forked from ClickHouse/clickhouse-kafka-connect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClickHouseWriter.java
More file actions
1504 lines (1361 loc) · 74.6 KB
/
Copy pathClickHouseWriter.java
File metadata and controls
1504 lines (1361 loc) · 74.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.clickhouse.kafka.connect.sink.db;
import com.clickhouse.client.ClickHouseClient;
import com.clickhouse.client.ClickHouseConfig;
import com.clickhouse.client.ClickHouseNode;
import com.clickhouse.client.ClickHouseNodeSelector;
import com.clickhouse.client.ClickHouseProtocol;
import com.clickhouse.client.ClickHouseRequest;
import com.clickhouse.client.ClickHouseResponse;
import com.clickhouse.client.ClickHouseResponseSummary;
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.ServerException;
import com.clickhouse.client.api.insert.InsertResponse;
import com.clickhouse.client.api.insert.InsertSettings;
import com.clickhouse.client.config.ClickHouseClientOption;
import com.clickhouse.data.ClickHouseDataStreamFactory;
import com.clickhouse.data.ClickHouseFormat;
import com.clickhouse.data.ClickHousePipedOutputStream;
import com.clickhouse.data.format.BinaryStreamUtils;
import com.clickhouse.kafka.connect.sink.ClickHouseSinkConfig;
import com.clickhouse.kafka.connect.sink.data.Data;
import com.clickhouse.kafka.connect.sink.data.Record;
import com.clickhouse.kafka.connect.sink.data.StructToJsonMap;
import com.clickhouse.kafka.connect.sink.db.helper.ClickHouseHelperClient;
import com.clickhouse.kafka.connect.sink.db.mapping.Column;
import com.clickhouse.kafka.connect.sink.db.mapping.Table;
import com.clickhouse.kafka.connect.sink.db.mapping.Type;
import com.clickhouse.kafka.connect.sink.dlq.ErrorReporter;
import com.clickhouse.kafka.connect.util.QueryIdentifier;
import com.clickhouse.kafka.connect.util.Utils;
import com.clickhouse.kafka.connect.util.jmx.SinkTaskStatistics;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.errors.DataException;
import org.apache.kafka.connect.errors.RetriableException;
import org.apache.kafka.connect.sink.SinkRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static com.clickhouse.kafka.connect.util.DataJson.OBJECT_MAPPER;
public class ClickHouseWriter implements DBWriter {
private static final Logger LOGGER = LoggerFactory.getLogger(ClickHouseWriter.class);
private static final long TIMEOUT_FOR_SHUTDOWN = 5; // seconds
private ClickHouseHelperClient chc = null;
private ClickHouseSinkConfig csc = null;
private final Map<String, Table> mapping;
private final AtomicBoolean isUpdateMappingRunning = new AtomicBoolean(false);
private final SinkTaskStatistics statistics;
private ScheduledExecutorService scheduledExecutor;
public ClickHouseWriter(SinkTaskStatistics statistics) {
this.mapping = new ConcurrentHashMap<>();
this.statistics = statistics;
}
protected Map<String, Table> getMapping() {
return mapping;
}
@Override
public boolean start(ClickHouseSinkConfig csc) {
LOGGER.trace("Starting ClickHouseWriter");
this.csc = csc;
String clientVersion = csc.getClientVersion();
boolean useClientV2 = clientVersion.equals("V1") ? false : true;
chc = new ClickHouseHelperClient.ClickHouseClientBuilder(csc.getHostname(), csc.getPort(), csc.getProxyType(), csc.getProxyHost(), csc.getProxyPort())
.setDatabase(csc.getDatabase())
.setUsername(csc.getUsername())
.setPassword(csc.getPassword())
.sslEnable(csc.isSslEnabled())
.setJdbcConnectionProperties(csc.getJdbcConnectionProperties())
.setTimeout(csc.getTimeout())
.setRetry(csc.getRetry())
.useClientV2(useClientV2)
.setSslSocketSni(csc.getSslSocketSni())
.build();
if (!chc.ping()) {
LOGGER.error("Unable to ping Clickhouse server.");
return false;
}
try {
String chVersion = chc.version();
LOGGER.info("Connected to ClickHouse version: {}", chVersion);
String[] versionParts = chVersion.split("\\.");
if (versionParts.length < 2) {
LOGGER.error("Unable to determine ClickHouse server version.");
return false;
}
int majorVersion = Integer.parseInt(versionParts[0]);
int minorVersion = Integer.parseInt(versionParts[1]);
if (majorVersion < 23 || (majorVersion == 23 && minorVersion < 3)) {
LOGGER.error("ClickHouse server version is too old to use this connector. Please upgrade to version 23.3 or newer.");
return false;
}
} catch (Exception e) {
LOGGER.error("Unable to determine ClickHouse server version.", e);
return false;
}
LOGGER.debug("Ping was successful.");
this.updateMapping(csc.getDatabase());
if (mapping.isEmpty()) {
LOGGER.error("Did not find any tables in destination Please create before running.");
return false;
}
startBackgroundTableSync(csc.getDatabase());
return true;
}
public boolean updateMapping(String database) {
// Do not start a new update cycle if one is already in progress
// Atomically compare and set isUpdateMappingRunning
if (!this.isUpdateMappingRunning.compareAndSet(false, true)) {
return false; // in progress
}
LOGGER.debug("Update table mapping.");
try {
// Getting tables from ClickHouse
List<Table> tableList = this.chc.extractTablesMapping(database, this.mapping);
// Adding new tables to mapping, or update existing tables
// TODO: check Kafka Connect's topics name or topics regex config and
// only add tables to in-memory mapping that matches the topics we consume.
for (Table table : tableList) {
this.mapping.put(table.getFullName(), table);
}
return true;
} finally {
this.isUpdateMappingRunning.set(false);
}
}
@Override
public void stop() {
LOGGER.debug("Stopping ClickHouseWriter");
if (scheduledExecutor != null) {
try {
scheduledExecutor.shutdownNow();
if (!scheduledExecutor.awaitTermination(TIMEOUT_FOR_SHUTDOWN, TimeUnit.SECONDS)) {
LOGGER.error("Failed to shutdown scheduled executor after " + TIMEOUT_FOR_SHUTDOWN + " seconds");
}
} catch (Exception e) {
LOGGER.error("Failed to shutdown scheduled executor", e);
} finally {
scheduledExecutor = null;
}
}
}
public ClickHouseNode getServer() {
return chc.getServer();
}
public void doInsert(List<Record> records, QueryIdentifier queryId) throws IOException, ExecutionException, InterruptedException {
doInsert(records, queryId, null);
}
@Override
public void doInsert(List<Record> records, QueryIdentifier queryId, ErrorReporter errorReporter) throws IOException, ExecutionException, InterruptedException {
if (records.isEmpty())
return;
Record first = records.get(0);
String topic = first.getTopic();
String database = first.getDatabase();
Table table = getTable(database, topic);
if (table == null) { return; }//We checked the error flag in getTable, so we don't need to check it again here
if (csc.isAutoEvolve()) {
// Check the last record's schema for new fields.
// Limitation: if a batch contains multiple schema versions, only the last one is checked.
// A full scan across all records can be implemented later if needed.
Record last = records.get(records.size() - 1);
Map<String, Schema> lastFields = new LinkedHashMap<>();
if (last.getFields() != null) {
for (Field f : last.getFields()) {
lastFields.put(f.name(), f.schema());
}
}
table = evolveTableSchema(table, lastFields);
}
doInsertBatch(records, table, queryId);
}
private void doInsertBatch(List<Record> records, Table table, QueryIdentifier queryId) throws IOException, ExecutionException, InterruptedException {
Record first = records.get(0);
LOGGER.debug("Trying to insert [{}] records to table name [{}] (QueryId: [{}])", records.size(), table.getName(), queryId.getQueryId());
switch (first.getSchemaType()) {
case SCHEMA:
if (csc.isBypassRowBinary()) {
doInsertJson(records, table, queryId);
} else {
doInsertRawBinary(records, table, queryId, table.hasDefaults(), true);
}
break;
case SCHEMA_LESS:
doInsertJson(records, table, queryId);
break;
case STRING_SCHEMA:
doInsertString(records, table, queryId);
break;
}
}
private static final Set<String> INT_TYPES = Set.of("INT8", "INT16", "INT32", "INT64", "UINT8", "UINT16", "UINT32", "UINT64");
protected boolean validateDataSchema(Table table, Record record, boolean onlyFieldsName) {
boolean validSchema = true;
for (Column col : table.getRootColumnsList()) {
String colName = col.getName();
Type type = col.getType();
boolean isNullable = col.isNullable();
boolean hasDefault = col.hasDefault();
// Variant has a native NULL discriminator (255) so it can accept missing values without Nullable or DEFAULT.
if (!isNullable && !hasDefault && type != Type.VARIANT) {
Map<String, Schema> schemaMap = record.getFields().stream().collect(Collectors.toMap(Field::name, Field::schema));
var objSchema = schemaMap.get(colName);
Data obj = record.getJsonMap().get(colName);
if (obj == null) {
validSchema = false;
LOGGER.error(String.format("Table column name [%s] was not found.", colName));
} else if (!onlyFieldsName) {
String colTypeName = type.name();
String dataTypeName = obj.getFieldType().getName().toUpperCase();
// TODO: make extra validation for Map/Array type
LOGGER.debug(String.format("Column type name [%s] and data type name [%s]", colTypeName, dataTypeName));
switch (colTypeName) {
case "Date":
case "Date32":
case "DateTime":
case "DateTime64":
case "UUID":
case "FIXED_STRING":
case "Enum8":
case "Enum16":
break;//I notice we just break here, rather than actually validate the type
case "STRING": {
if (dataTypeName.equals("BYTES")) {
continue;
} else if (obj.getFieldType().equals(Schema.Type.STRUCT)) {
for (Field field : objSchema.fields()) {
if (!(field.schema().type().equals(Schema.Type.STRING) || field.schema().type().equals(Schema.Type.BYTES))) {
validSchema = false;
break;
}
}
if (!validSchema) {
LOGGER.error(String.format("Cannot write field of union schema '%s' to column [%s] of `String`: only unions of `string` and `bytes` are allowed in this case",
objSchema.schema().fields(), colName));
}
}
break;
}
default:
if (!colTypeName.equals(dataTypeName)) {
LOGGER.debug("Data schema name: {}", objSchema.name());
if (colTypeName.equals("TUPLE") && dataTypeName.equals("STRUCT"))
continue;
if (colTypeName.equals("VARIANT") && dataTypeName.equals("STRUCT"))
continue;
if (INT_TYPES.contains(colTypeName)) {
continue;
}
if (colTypeName.equalsIgnoreCase("BOOLEAN") &&
INT_TYPES.contains(dataTypeName.toUpperCase())) {
continue;
}
if (("DECIMAL".equalsIgnoreCase(colTypeName) && objSchema.name().equals("org.apache.kafka.connect.data.Decimal")))
continue;
if (type == Type.JSON) {
if (csc.isBinaryFormatWrtiteJsonAsString() &&
(dataTypeName.equals("STRUCT") || dataTypeName.equals("STRING"))) {
// we will convert struct to a string
// suppose to have JSON already
continue;
}
}
validSchema = false;
LOGGER.error(String.format("Table column name [%s] type [%s] is not matching data column type [%s]", col.getName(), colTypeName, dataTypeName));
}
}
}
}
}
return validSchema;
}
/**
* BASES array maps precision levels to scaling factors for date/time values.
* The index corresponds to the precision (e.g., index 3 = precision 3).
* Value at each index is the scaling factor (e.g., value 1 = no scaling).
* Example: BASES[3] == 1 means precision 3 uses no scaling.
*/
private int[] BASES = new int[] { 1_000, 100, 10, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000 };
protected void doWriteDates(Type type, OutputStream stream, Data value, int precision, String columnName) throws IOException {
// TODO: develop more specific tests to have better coverage
if (value.getObject() == null) {
BinaryStreamUtils.writeNull(stream);
return;
}
LOGGER.trace("Writing date type: {}, value: {}, value class: {}", type, value.getObject(), value.getObject().getClass());
boolean unsupported = false;
switch (type) {
case Date:
if (value.getFieldType().equals(Schema.Type.INT32)) {
if (value.getObject().getClass().getName().endsWith(".Date")) {
Date date = (Date) value.getObject();
int timeInDays = (int) TimeUnit.MILLISECONDS.toDays(date.getTime());
BinaryStreamUtils.writeUnsignedInt16(stream, timeInDays);
} else {
BinaryStreamUtils.writeUnsignedInt16(stream, (Integer) value.getObject());
}
} else {
unsupported = true;
}
break;
case Date32:
if (value.getFieldType().equals(Schema.Type.INT32)) {
if (value.getObject().getClass().getName().endsWith(".Date")) {
Date date = (Date) value.getObject();
int timeInDays = (int) TimeUnit.MILLISECONDS.toDays(date.getTime());
BinaryStreamUtils.writeInt32(stream, timeInDays);
} else {
BinaryStreamUtils.writeInt32(stream, (Integer) value.getObject());
}
} else {
unsupported = true;
}
break;
case DateTime:
if (value.getFieldType().equals(Schema.Type.INT32) || value.getFieldType().equals(Schema.Type.INT64)) {
if (value.getObject().getClass().getName().endsWith(".Date")) {
Date date = (Date) value.getObject();
BinaryStreamUtils.writeUnsignedInt32(stream, date.toInstant().getEpochSecond());
} else {
BinaryStreamUtils.writeUnsignedInt32(stream, Long.parseLong(String.valueOf(value.getObject())));
}
} else if (value.getFieldType().equals(Schema.Type.STRING)) {
try {
ZonedDateTime zonedDateTime = ZonedDateTime.parse((String) value.getObject());
BinaryStreamUtils.writeUnsignedInt32(stream, zonedDateTime.toInstant().getEpochSecond());
} catch (Exception e) {
LOGGER.error("Error parsing date time string: {}", value.getObject());
unsupported = true;
}
} else {
unsupported = true;
}
break;
case DateTime64:
if ( value.getFieldType().equals(Schema.Type.INT64)) {
if (value.getObject() instanceof Date) {
doWriteDate(stream, (Date) value.getObject(), precision);
} else {
BinaryStreamUtils.writeInt64(stream, (Long) value.getObject());
}
} else if (value.getFieldType().equals(Schema.Type.INT32) && value.getObject() instanceof Date) {
doWriteDate(stream, (Date) value.getObject(), precision);
} else if (value.getFieldType().equals(Schema.Type.STRING)) {
try {
long seconds;
long milliSeconds;
long microSeconds;
long nanoSeconds;
if (!csc.getDateTimeFormats().isEmpty()) {
Map<String, DateTimeFormatter> formats = csc.getDateTimeFormats();
DateTimeFormatter formatter = formats.get(columnName);
LOGGER.trace("Using custom date time format: {}", formatter);
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse((String) value.getObject()));
seconds = localDateTime.toInstant(ZoneOffset.UTC).getEpochSecond();
milliSeconds = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
microSeconds = TimeUnit.MICROSECONDS.convert(seconds, TimeUnit.SECONDS) + localDateTime.get(ChronoField.MICRO_OF_SECOND);
nanoSeconds = TimeUnit.NANOSECONDS.convert(seconds, TimeUnit.SECONDS) + localDateTime.getNano();
} else {
ZonedDateTime zonedDateTime = ZonedDateTime.parse((String) value.getObject());
seconds = zonedDateTime.toInstant().getEpochSecond();
milliSeconds = zonedDateTime.toInstant().toEpochMilli();
microSeconds = TimeUnit.MICROSECONDS.convert(seconds, TimeUnit.SECONDS) + zonedDateTime.get(ChronoField.MICRO_OF_SECOND);
nanoSeconds = TimeUnit.NANOSECONDS.convert(seconds, TimeUnit.SECONDS) + zonedDateTime.getNano();
}
if (precision == 3) {
LOGGER.trace("Writing epoch milliseconds: {}", milliSeconds);
BinaryStreamUtils.writeInt64(stream, milliSeconds);
} else if (precision == 6) {
LOGGER.trace("Writing epoch microseconds: {}", microSeconds);
BinaryStreamUtils.writeInt64(stream, microSeconds);
} else if (precision == 9) {
LOGGER.trace("Writing epoch nanoseconds: {}", nanoSeconds);
BinaryStreamUtils.writeInt64(stream, nanoSeconds);
} else {
LOGGER.trace("Writing epoch seconds: {}", seconds);
BinaryStreamUtils.writeInt64(stream, seconds);
}
} catch (Exception e) {
LOGGER.error("Error parsing date time string: {}, exception: {}", value.getObject(), e.getMessage());
unsupported = true;
}
} else {
unsupported = true;
}
break;
}
if (unsupported) {
String msg = String.format("(Potentially) Not implemented conversion from %s to %s", value.getFieldType(), type);
LOGGER.error(msg);
throw new DataException(msg);
}
}
private void doWriteDate(OutputStream stream, Date date, int precision ) throws IOException {
long ts = date.getTime();
if (precision > 3) {
ts *= BASES[precision];
} else if (precision < 3) {
ts /= BASES[precision];
}
BinaryStreamUtils.writeInt64(stream, ts);
}
protected void doWriteColValue(Column col, OutputStream stream, Data value, boolean defaultsSupport) throws IOException {
Type columnType = col.getType();
try {
switch (columnType) {
case INT8:
case INT16:
case INT32:
case INT64:
case UINT8:
case UINT16:
case UINT32:
case UINT64:
case FLOAT32:
case FLOAT64:
case BOOLEAN:
case UUID:
case STRING:
case Enum8:
case Enum16:
doWritePrimitive(columnType, value.getFieldType(), stream, value.getObject(), col);
break;
case FIXED_STRING:
doWriteFixedString(columnType, stream, value.getObject(), col.getPrecision());
break;
case Date:
case Date32:
case DateTime:
case DateTime64:
doWriteDates(columnType, stream, value, col.getPrecision(), col.getName());
break;
case Decimal:
if (value.getObject() == null) {
BinaryStreamUtils.writeNull(stream);
return;
} else {
BigDecimal decimal = (BigDecimal) value.getObject();
BinaryStreamUtils.writeDecimal(stream, decimal, col.getPrecision(), col.getScale());
}
break;
case MAP:
Map<?, ?> mapTmp = (Map<?, ?>) value.getObject();
int mapSize = mapTmp.size();
BinaryStreamUtils.writeVarInt(stream, mapSize);
mapTmp.forEach((key, mapValue) -> {
try {
doWritePrimitive(col.getMapKeyType(), value.getMapKeySchema().type(), stream, key, col);
if (col.getMapValueType() != null && col.getMapValueType().isNullable() && mapValue != null) {
BinaryStreamUtils.writeNonNull(stream);
}
doWriteColValue(col.getMapValueType(), stream, new Data(value.getNestedValueSchema(), mapValue), defaultsSupport);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
break;
case ARRAY:
List<?> arrObject = (List<?>) value.getObject();
if (arrObject == null) {
if (defaultsSupport) {
BinaryStreamUtils.writeNonNull(stream);
}
} else {
int sizeArrObject = arrObject.size();
BinaryStreamUtils.writeVarInt(stream, sizeArrObject);
arrObject.forEach(v -> {
try {
if (col.getArrayType().isNullable() && v != null) {
BinaryStreamUtils.writeNonNull(stream);
}
doWriteColValue(col.getArrayType(), stream, new Data(value.getNestedValueSchema(), v), defaultsSupport);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
break;
case TUPLE:
Map<?, ?> jsonMapValues;
Object underlyingObject = value.getObject();
if (underlyingObject.getClass() != Struct.class) {
// Tuples in the root structure are parsed using StructToJsonMap
jsonMapValues = (Map<?, ?>) underlyingObject;
} else {
jsonMapValues = StructToJsonMap.toJsonMap((Struct) underlyingObject);
}
col.getTupleFields().forEach(column -> {
String[] colNameSplit = column.getName().split("\\.");
String fieldName = colNameSplit.length > 0 ? colNameSplit[colNameSplit.length - 1] : column.getName();
Data innerData = (Data) jsonMapValues.get(fieldName);
try {
// we need to apply here the default and nullable logic
doWriteCol(innerData, jsonMapValues.containsKey(fieldName), column, stream, false);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
break;
case VARIANT:
// https://github.com/ClickHouse/ClickHouse/pull/58047/files#diff-f56b7f61d5a82c440bb1a078ea8e5dcf2679dc92adbbc28bd89638cbe499363dR368-R384
// https://github.com/ClickHouse/ClickHouse/blob/658a8e9a9b1658cd12c78365f9829b35d016f1b2/src/Columns/ColumnVariant.h#L10-L56
mapTmp = (Map<?, ?>) value.getObject();
Optional<Data> variantValueOption = mapTmp.values().stream()
.map(o -> (Data) o)
.filter(data -> data.getObject() != null)
.findFirst();
// Null Discriminator (https://github.com/ClickHouse/ClickHouse/blob/658a8e9a9b1658cd12c78365f9829b35d016f1b2/src/Columns/ColumnVariant.h#L65)
int nullDiscriminator = 255;
if (variantValueOption.isEmpty()) {
BinaryStreamUtils.writeUnsignedInt8(stream, nullDiscriminator);
} else {
Data variantValue = variantValueOption.get();
String fieldTypeName = variantValue.getFieldType().getName();
Optional<Integer> globalDiscriminator = col.getVariantGlobalDiscriminator(fieldTypeName);
if (globalDiscriminator.isEmpty()) {
LOGGER.error("Unable to determine the global discriminator of {} variant! Writing NULL variant instead.", fieldTypeName);
BinaryStreamUtils.writeUnsignedInt8(stream, nullDiscriminator);
return;
}
BinaryStreamUtils.writeUnsignedInt8(stream, globalDiscriminator.get());
// Variants support parametrized types, such as Decimal(x, y). Because of that, we can't use
// the doWritePrimitive method.
doWriteColValue(
col.getVariantGlobalDiscriminators().get(globalDiscriminator.get()).getT1(),
stream,
variantValue,
defaultsSupport
);
}
break;
case JSON:
if (csc.isBinaryFormatWrtiteJsonAsString()) {
if (value.getFieldType() == Schema.Type.STRUCT) {
byte[] jsonBytes = OBJECT_MAPPER.writeValueAsBytes(value);
BinaryStreamUtils.writeString(stream, jsonBytes);
} else if (value.getFieldType() == Schema.Type.STRING) {
BinaryStreamUtils.writeString(stream, ((String) value.getObject()).getBytes(StandardCharsets.UTF_8));
} else {
throw new RuntimeException("Unsupported field type: " + value.getFieldType() + " for column type [JSON]");
}
break;
} else {
throw new RuntimeException("Writing JSON in binary is not supported yet. Use `input_format_binary_read_json_as_string=1` in clickhouse settings to allow writing as string");
}
default:
// If you wonder, how NESTED works in JDBC:
// https://github.com/ClickHouse/clickhouse-java/blob/6cbbd8fe3f86ac26d12a95e0c2b964f3a3755fc9/clickhouse-data/src/main/java/com/clickhouse/data/format/ClickHouseRowBinaryProcessor.java#L159
LOGGER.error("Cannot serialize unsupported type {}", columnType);
}
} catch (Exception e) {
LOGGER.error("Error writing value of " + (value == null ? "<value null>" : value.getFieldType() ) + " to the column `" + col.getName() + "` of type " + columnType, e);
throw e;
}
}
protected void doWriteFixedString(Type columnType, OutputStream stream, Object value, int length) throws IOException {
LOGGER.trace("Writing fixed string type: {}, value: {}", columnType, value);
if (value == null) {
BinaryStreamUtils.writeNull(stream);
return;
}
if (Objects.requireNonNull(columnType) == Type.FIXED_STRING) {
if (value instanceof String) {
BinaryStreamUtils.writeFixedString(stream, (String) value, length, StandardCharsets.UTF_8);
} else if (value instanceof byte[]) {
byte[] bytes = (byte[]) value;
BinaryStreamUtils.writeFixedString(stream, new String(bytes, StandardCharsets.UTF_8), length, StandardCharsets.UTF_8);
} else {
String msg = String.format("Not implemented conversion from %s to %s", value.getClass(), columnType);
LOGGER.error(msg);
throw new DataException(msg);
}
}
}
protected void doWritePrimitive(Type columnType, Schema.Type dataType, OutputStream stream, Object value, Column col) throws IOException {
LOGGER.trace("Writing primitive type: {}, value: {}", columnType, value);
if (value == null) {
BinaryStreamUtils.writeNull(stream);
return;
}
if (value instanceof Boolean && columnType != Type.BOOLEAN) {
Long boolVal = (Boolean) value ? 1L : 0L;
switch (columnType) {
case INT8:
BinaryStreamUtils.writeInt8(stream, boolVal.byteValue());
break;
case INT16:
BinaryStreamUtils.writeInt16(stream, boolVal.shortValue());
break;
case INT32:
BinaryStreamUtils.writeInt32(stream, boolVal.intValue());
break;
case INT64:
BinaryStreamUtils.writeInt64(stream, boolVal.longValue());
break;
case UINT8:
BinaryStreamUtils.writeUnsignedInt8(stream, boolVal.byteValue());
break;
case UINT16:
BinaryStreamUtils.writeUnsignedInt16(stream, boolVal.shortValue());
break;
case UINT32:
BinaryStreamUtils.writeUnsignedInt32(stream, boolVal.intValue());
break;
case UINT64:
BinaryStreamUtils.writeUnsignedInt64(stream, boolVal.longValue());
break;
default:
throw new DataException("Not implemented conversion from Boolean to " + columnType);
}
} else {
switch (columnType) {
case INT8:
BinaryStreamUtils.writeInt8(stream, (Byte) value);
break;
case INT16:
BinaryStreamUtils.writeInt16(stream, (Short) value);
break;
case INT32:
if (value.getClass().getName().endsWith(".Date")) {
Date date = (Date) value;
int time = (int) date.getTime();
BinaryStreamUtils.writeInt32(stream, time);
} else {
BinaryStreamUtils.writeInt32(stream, (Integer) value);
}
break;
case DateTime64:
case INT64:
if (value.getClass().getName().endsWith(".Date")) {
Date date = (Date) value;
long time = date.getTime();
BinaryStreamUtils.writeInt64(stream, time);
} else {
BinaryStreamUtils.writeInt64(stream, (Long) value);
}
break;
case UINT8:
BinaryStreamUtils.writeUnsignedInt8(stream, (Byte) value);
break;
case UINT16:
BinaryStreamUtils.writeUnsignedInt16(stream, ((Number) value).shortValue());
break;
case UINT32:
BinaryStreamUtils.writeUnsignedInt32(stream, ((Number) value).intValue());
break;
case UINT64:
BinaryStreamUtils.writeUnsignedInt64(stream, ((Number) value).longValue());
break;
case FLOAT32:
BinaryStreamUtils.writeFloat32(stream, (Float) value);
break;
case FLOAT64:
BinaryStreamUtils.writeFloat64(stream, (Double) value);
break;
case BOOLEAN:
if (value instanceof Number) {
BinaryStreamUtils.writeBoolean(stream, ((Number) value).longValue() != 0);
} else {
BinaryStreamUtils.writeBoolean(stream, (Boolean) value);
}
break;
case STRING:
if (Schema.Type.BYTES.equals(dataType)) {
BinaryStreamUtils.writeString(stream, (byte[]) value);
} else if (Schema.Type.STRUCT.equals(dataType)) {
Map<String, Data> map = (Map<String, Data>) value;
for (Data unionData : map.values()) {
if (unionData != null && unionData.getObject() != null) {
if (unionData.getObject() instanceof String) {
BinaryStreamUtils.writeString(stream, ((String) unionData.getObject()).getBytes(StandardCharsets.UTF_8));
} else if (unionData.getObject() instanceof byte[]) {
BinaryStreamUtils.writeString(stream, (byte[]) unionData.getObject());
} else {
BinaryStreamUtils.writeString(stream, unionData.getObject().toString().getBytes(StandardCharsets.UTF_8));
}
break;
}
}
} else {
BinaryStreamUtils.writeString(stream, ((String) value).getBytes(StandardCharsets.UTF_8));
}
break;
case UUID:
BinaryStreamUtils.writeUuid(stream, UUID.fromString((String) value));
break;
case Enum8:
BinaryStreamUtils.writeEnum8(stream, col.convertEnumValues((String) value).byteValue());
break;
case Enum16:
BinaryStreamUtils.writeEnum16(stream, col.convertEnumValues((String) value).intValue());
break;
}
}
}
/**
* Write records to ClickHouse using RowBinary/RowBinaryWithDefaults format.
*
* Note: RowBinaryWithDefaults writes an extra byte 01 to indicate default, and 00
* to indicate actual value. But that only applies to top level columns.
* @param value The data to write
* @param fieldExists Indecate if the field exists
* @param col Internal Column object (represent type and name of the column)
* @param stream Stream to write the data
* @param defaultsSupport Indicate if the defaults values in fields at the level
* @throws IOException
*/
protected void doWriteCol(Data value, boolean fieldExists, Column col, OutputStream stream, boolean defaultsSupport) throws IOException {
LOGGER.trace("Writing column {} to stream", col.getName());
LOGGER.trace("Column type is {}", col.getType());
String name = col.getName();
Type colType = col.getType();
if (fieldExists) {
LOGGER.trace("Column value is {}", value);
// TODO: the mapping need to be more efficient
if (defaultsSupport) {
if (value.getObject() != null) {//Because we now support defaults, we have to send nonNull
BinaryStreamUtils.writeNonNull(stream);//Write 0 for no default
if (col.isNullable()) {//If the column is nullable
BinaryStreamUtils.writeNonNull(stream);//Write 0 for not null
}
} else {//So if the object is null
if (col.hasDefault()) {
BinaryStreamUtils.writeNull(stream);//Send 1 for default
return;
} else if (col.isNullable()) {//And the column is nullable
BinaryStreamUtils.writeNonNull(stream);
BinaryStreamUtils.writeNull(stream);//Then we send null, write 1
return;//And we're done
} else if (colType == Type.ARRAY) {//If the column is an array
BinaryStreamUtils.writeNonNull(stream);//Then we send nonNull
} else if (colType == Type.VARIANT) {
BinaryStreamUtils.writeNonNull(stream);
BinaryStreamUtils.writeUnsignedInt8(stream, 255);
return;
} else {
throw new RuntimeException(String.format("An attempt to write null into not nullable column '%s'", name));
}
}
} else {
// If column is nullable && the object is also null add the not null marker
if (col.isNullable() && value.getObject() != null) {
BinaryStreamUtils.writeNonNull(stream);
}
if (!col.isNullable() && value.getObject() == null) {
if (colType == Type.ARRAY)
BinaryStreamUtils.writeNonNull(stream);
else if (colType == Type.VARIANT) {
BinaryStreamUtils.writeUnsignedInt8(stream, 255);
return;
} else
throw new RuntimeException(String.format("An attempt to write null into not nullable column '%s'", name));
}
}
doWriteColValue(col, stream, value, defaultsSupport);
} else {
if (col.hasDefault()) {
BinaryStreamUtils.writeNull(stream);
} else if (col.isNullable()) {
// set null since there is no value
if (defaultsSupport) {//Only set this if we're using defaults
BinaryStreamUtils.writeNonNull(stream);
}
BinaryStreamUtils.writeNull(stream);
} else if (col.getType() == Type.VARIANT) {
// Variant has a native NULL discriminator (255) — no Nullable/DEFAULT needed.
if (defaultsSupport) {
BinaryStreamUtils.writeNonNull(stream);
}
BinaryStreamUtils.writeUnsignedInt8(stream, 255);
} else {
// no filled and not nullable
LOGGER.error("Column {} is not nullable and no value is provided", name);
throw new RuntimeException();
}
}
}
protected Table evolveTableSchema(Table table, Map<String, Schema> allFields) throws InterruptedException {
if (allFields.isEmpty()) {
throw new RuntimeException(
"auto.evolve requires a Connect schema (Avro, Protobuf, or JSON Schema). " +
"Schemaless or string records are not supported with auto.evolve=true.");
}
Set<String> missingColumns = table.getMissingColumns(allFields.keySet());
if (missingColumns.isEmpty()) {
return table;
}
LOGGER.info("Detected {} new field(s) not present in table {}: {}", missingColumns.size(), table.getName(), missingColumns);
List<String> columnDefs = new ArrayList<>();
for (String fieldName : missingColumns) {
Schema fieldSchema = allFields.get(fieldName);
if (fieldSchema == null) {
continue;
}
String chType = Column.connectTypeToClickHouseType(fieldSchema, csc.isAutoEvolveStructToJson());
String defaultExpr = Column.defaultExpressionForType(chType);
columnDefs.add(String.format("%s %s%s", Utils.escapeName(fieldName), chType, defaultExpr));
}
if (!columnDefs.isEmpty()) {
chc.alterTableAddColumns(table.getDatabase(), table.getCleanName(), columnDefs, csc.getClickhouseSettings());
LOGGER.info("Schema evolution complete for table {}. Added columns: {}", table.getName(), columnDefs);
table = refreshTableAfterDDL(table, missingColumns);
}
return table;
}
private static final long DDL_REFRESH_BACKOFF_MS = 200;
private Table refreshTableAfterDDL(Table table, Set<String> expectedNewColumns) throws InterruptedException {
int maxRetries = csc.getAutoEvolveDdlRefreshRetries();
for (int attempt = 0; attempt < maxRetries; attempt++) {
Table refreshed = urgentTableUpdate(table);
Set<String> stillMissing = refreshed.getMissingColumns(expectedNewColumns);
if (stillMissing.isEmpty()) {
return refreshed;
}
LOGGER.warn("DDL refresh attempt {}/{}: columns {} not yet visible, retrying in {}ms",
attempt + 1, maxRetries, stillMissing, DDL_REFRESH_BACKOFF_MS);
Thread.sleep(DDL_REFRESH_BACKOFF_MS);
}
throw new RetriableException(String.format(
"DDL propagation timeout: columns not visible after %d retries", maxRetries));
}
protected void doInsertRawBinary(List<Record> records, Table table, QueryIdentifier queryId, boolean supportDefaults, boolean retry) throws IOException, ExecutionException, InterruptedException {
try {
if (chc.isUseClientV2()) {
doInsertRawBinaryV2(records, table, queryId, supportDefaults);
} else {
doInsertRawBinaryV1(records, table, queryId, supportDefaults);
}
} catch (ServerException e) {
LOGGER.error("Error inserting records can cause by schema changes", e);
if (e.getCode() == 33 && retry == true) {
LOGGER.error("Error code 33: ClickHouse server error. Trying to update table mapping.");
Table tableTmp = urgentTableUpdate(table);
doInsertRawBinary(records, tableTmp, queryId, tableTmp.hasDefaults(), false);
} else {
throw e;
}
} catch (Exception e) {
// Note: this part will be removed once V1 is deprecated
LOGGER.error("Error inserting records", e);
if (e.getMessage().indexOf("ClickHouseException: Code: 33") != -1 && retry == true) {
LOGGER.error("Error code 33: ClickHouse server error. Trying to update table mapping.");
Table tableTmp = urgentTableUpdate(table);
doInsertRawBinary(records, tableTmp, queryId, tableTmp.hasDefaults(), false);
} else {
throw e;
}
}
}
private Table urgentTableUpdate(Table table) {
Table tableTmp;
if (updateMapping(table.getDatabase())) {
LOGGER.debug("urgentTableUpdate({}): update complete", table.getName());
tableTmp = getTable(table.getDatabase(), table.getName());
} else {
LOGGER.debug("urgentTableUpdate({}): update still running", table.getName());
tableTmp = chc.describeTable(table.getDatabase(), table.getCleanName());
if (tableTmp == null) {
LOGGER.error("Failed to describe table {}.{} via ClickHouseHelperClient.describeTable(); falling back to existing mapping.",
table.getDatabase(), table.getCleanName());
tableTmp = getTable(table.getDatabase(), table.getName());
}
}
if (tableTmp == null) {
throw new IllegalStateException("Unable to refresh table mapping for " + table.getDatabase() + "." + table.getName());
}
return tableTmp;
}
protected void doInsertRawBinaryV2(List<Record> records, Table table, QueryIdentifier queryId, boolean supportDefaults) throws IOException, ExecutionException, InterruptedException {
long s1 = System.currentTimeMillis();
Record first = records.get(0);
String database = first.getDatabase();
String topic = first.getSinkRecord().topic();
String partition = first.getSinkRecord().kafkaPartition().toString();
if (!csc.isBypassSchemaValidation() && !validateDataSchema(table, first, false))
throw new RuntimeException("Data schema validation failed.");
// Let's test first record
// Do we have all elements from the table inside the record
long s2 = System.currentTimeMillis();
// get or create client
Client client = chc.getClient();
InsertSettings insertSettings = new InsertSettings();
insertSettings.setDatabase(database);
String deduplicationToken = queryId.getDeduplicationToken();
if (deduplicationToken != null) {
insertSettings.setDeduplicationToken(deduplicationToken);
}
insertSettings.setQueryId(queryId.getQueryId());
for (String clickhouseSetting : csc.getClickhouseSettings().keySet()) {//THIS ASSUMES YOU DON'T ADD insert_deduplication_token
insertSettings.serverSetting(clickhouseSetting, csc.getClickhouseSettings().get(clickhouseSetting));