-
Notifications
You must be signed in to change notification settings - Fork 624
Expand file tree
/
Copy pathPreparedStatementImpl.java
More file actions
1022 lines (889 loc) · 37.6 KB
/
PreparedStatementImpl.java
File metadata and controls
1022 lines (889 loc) · 37.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.jdbc;
import com.clickhouse.client.api.DataTypeUtils;
import com.clickhouse.client.api.metadata.TableSchema;
import com.clickhouse.client.api.sql.SQLUtils;
import com.clickhouse.data.ClickHouseColumn;
import com.clickhouse.data.ClickHouseDataType;
import com.clickhouse.data.Tuple;
import com.clickhouse.jdbc.internal.ExceptionUtils;
import com.clickhouse.jdbc.internal.JdbcUtils;
import com.clickhouse.jdbc.internal.ParsedPreparedStatement;
import com.clickhouse.jdbc.metadata.ParameterMetaDataImpl;
import com.clickhouse.jdbc.metadata.ResultSetMetaDataImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.JDBCType;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLType;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Struct;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PreparedStatementImpl extends StatementImpl implements PreparedStatement, JdbcV2Wrapper {
private static final Logger LOG = LoggerFactory.getLogger(PreparedStatementImpl.class);
protected final Calendar defaultCalendar;
private final String originalSql;
private final String[] values; // temp value holder (set can be called > once)
private final List<StringBuilder> batchValues; // composed value statements
private final ParsedPreparedStatement parsedPreparedStatement;
private final boolean insertStmtWithValues;
private final String valueListTmpl;
private final int[] paramPositionsInDataClause;
private final int argCount;
private final ParameterMetaData parameterMetaData;
private ResultSetMetaData resultSetMetaData = null;
public PreparedStatementImpl(ConnectionImpl connection, String sql, ParsedPreparedStatement parsedStatement) throws SQLException {
super(connection);
this.isPoolable = true; // PreparedStatement is poolable by default
this.originalSql = sql;
this.parsedPreparedStatement = parsedStatement;
this.argCount = parsedStatement.getArgCount();
this.defaultCalendar = connection.defaultCalendar;
this.values = new String[argCount];
this.parameterMetaData = new ParameterMetaDataImpl(this.values.length);
int valueListStartPos = parsedStatement.getAssignValuesListStartPosition();
int valueListStopPos = parsedStatement.getAssignValuesListStopPosition();
if (parsedStatement.getAssignValuesGroups() == 1 && valueListStartPos > -1 && valueListStopPos > -1) {
int[] positions = parsedStatement.getParamPositions();
paramPositionsInDataClause = new int[argCount];
for (int i = 0; i < argCount; i++) {
int p = positions[i] - valueListStartPos;
paramPositionsInDataClause[i] = p;
}
valueListTmpl = originalSql.substring(valueListStartPos, valueListStopPos + 1);
insertStmtWithValues = true;
batchValues = new ArrayList<>();
} else {
paramPositionsInDataClause = new int[0];
batchValues = Collections.emptyList();
valueListTmpl = "";
insertStmtWithValues = false;
}
}
private String buildSQL() throws SQLException {
StringBuilder compiledSql = new StringBuilder(originalSql);
int posOffset = 0;
int[] positions = parsedPreparedStatement.getParamPositions();
for (int i = 0; i < argCount; i++) {
int p = positions[i] + posOffset;
String val = values[i];
if (val == null) {
throw new SQLException("Parameter at position '" + (i + 1) + "' is not set");
}
compiledSql.replace(p, p+1, val);
posOffset += val.length() - 1;
}
return compiledSql.toString();
}
@Override
public ResultSet executeQuery() throws SQLException {
ensureOpen();
String buildSQL = buildSQL();
return super.executeQuery(buildSQL);
}
@Override
public int executeUpdate() throws SQLException {
ensureOpen();
return (int) super.executeUpdateImpl(buildSQL(), localSettings);
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
ensureOpen();
setNull(parameterIndex, sqlType, null);
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
setDate(parameterIndex, x, defaultCalendar);
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
setTime(parameterIndex, x, defaultCalendar);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
setTimestamp(parameterIndex, x, defaultCalendar);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
ensureOpen();
setAsciiStream(parameterIndex, x, (long)length);
}
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x, (long) length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
ensureOpen();
setBinaryStream(parameterIndex, x, (long)length);
}
@Override
public void clearParameters() throws SQLException {
ensureOpen();
Arrays.fill(this.values, null);
}
int getParametersCount() {
return argCount;
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
ensureOpen();
isValidForTargetType(x, targetSqlType);
values[parameterIndex-1] = encodeObject(x);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
ensureOpen();
isValidForTargetType(x, targetSqlType);
values[parameterIndex-1] = encodeObject(x, (long) scaleOrLength);
}
@Override
public void setObject(int parameterIndex, Object x, SQLType targetSqlType) throws SQLException {
ensureOpen();
isValidForTargetType(x, targetSqlType.getVendorTypeNumber());
values[parameterIndex-1] = encodeObject(x);
}
@Override
public void setObject(int parameterIndex, Object x, SQLType targetSqlType, int scaleOrLength) throws SQLException {
ensureOpen();
isValidForTargetType(x, targetSqlType.getVendorTypeNumber());
values[parameterIndex-1] = encodeObject(x, (long) scaleOrLength);
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public boolean execute() throws SQLException {
ensureOpen();
currentUpdateCount = -1;
if (parsedPreparedStatement.isHasResultSet()) {
currentResultSet = super.executeQueryImpl(buildSQL(), localSettings);
return currentResultSet != null;
} else {
currentUpdateCount = super.executeUpdateImpl(buildSQL(), localSettings);
return false;
}
}
@Override
public void addBatch() throws SQLException {
ensureOpen();
if (insertStmtWithValues) {
StringBuilder valuesClause = new StringBuilder(valueListTmpl);
int posOffset = 0;
for (int i = 0; i < argCount; i++) {
int p = paramPositionsInDataClause[i] + posOffset;
valuesClause.replace(p, p + 1, values[i]);
posOffset += values[i].length() - 1;
}
batchValues.add(valuesClause);
} else {
super.addBatch(buildSQL());
}
}
@Override
public int[] executeBatch() throws SQLException {
ensureOpen();
return executeBatchImpl().stream().mapToInt(Integer::intValue).toArray();
}
@Override
public long[] executeLargeBatch() throws SQLException {
ensureOpen();
return executeBatchImpl().stream().mapToLong(Integer::longValue).toArray();
}
private List<Integer> executeBatchImpl() throws SQLException {
List<Integer> results;
if (insertStmtWithValues) {
results = executeInsertBatch();
} else {
results = new ArrayList<>();
for (String sql : batch) {
results.add((int) executeUpdateImpl(sql, localSettings));
}
}
clearBatch();
return results;
}
@Override
public void clearBatch() throws SQLException {
super.clearBatch(); /// clear super#batch
batchValues.clear();
}
private List<Integer> executeInsertBatch() throws SQLException {
StringBuilder insertSql = new StringBuilder(originalSql.substring(0,
parsedPreparedStatement.getAssignValuesListStartPosition()));
for (StringBuilder valuesList : batchValues) {
insertSql.append(valuesList).append(',');
}
insertSql.setLength(insertSql.length() - 1);
int updateCount = (int) super.executeUpdateImpl(insertSql.toString(), localSettings);
if (updateCount == batchValues.size()) {
return Collections.nCopies(batchValues.size(), 1);
} else {
return Collections.nCopies(batchValues.size(), Statement.SUCCESS_NO_INFO);
}
}
@Override
public void setCharacterStream(int parameterIndex, Reader x, int length) throws SQLException {
ensureOpen();
setCharacterStream(parameterIndex, x, (long)length);
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
ensureOpen();
if (!connection.config.isIgnoreUnsupportedRequests()) {
throw new SQLFeatureNotSupportedException("Ref is not supported.", ExceptionUtils.SQL_STATE_FEATURE_NOT_SUPPORTED);
}
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
ensureOpen();
if (resultSetMetaData == null && currentResultSet == null) {
// before execution
if (parsedPreparedStatement.isHasResultSet()) {
try {
// Replace '?' with NULL to make SQL valid for DESCRIBE
String sql = replaceQuestionMarks(originalSql, NULL_LITERAL);
TableSchema tSchema = connection.getClient().getTableSchemaFromQuery(sql);
resultSetMetaData = new ResultSetMetaDataImpl(tSchema.getColumns(),
connection.getSchema(), connection.getCatalog(),
tSchema.getTableName(), JdbcUtils.DATA_TYPE_CLASS_MAP, connection.getTypeMap());
} catch (Exception e) {
LOG.warn("Failed to get schema for statement '{}'", originalSql);
}
}
if (resultSetMetaData == null) {
List<ClickHouseColumn> columns = IntStream.range(0, argCount)
.mapToObj(value -> ClickHouseColumn.of("v_" + value, "Nothing"))
.collect(Collectors.toList());
resultSetMetaData = new ResultSetMetaDataImpl(columns,
connection.getSchema(), connection.getCatalog(),
"", JdbcUtils.DATA_TYPE_CLASS_MAP, connection.getTypeMap());
}
} else if (currentResultSet != null) {
resultSetMetaData = currentResultSet.getMetaData();
}
return resultSetMetaData;
}
public static final String NULL_LITERAL = "NULL";
private static final Pattern REPLACE_Q_MARK_PATTERN = Pattern.compile("(\"[^\"]*\"|`[^`]*`|'[^']*')|(\\?)");
public static String replaceQuestionMarks(String sql, final String replacement) {
Matcher matcher = REPLACE_Q_MARK_PATTERN.matcher(sql);
StringBuilder result = new StringBuilder();
int lastPos = 0;
while (matcher.find()) {
String text;
if ((text = matcher.group(1)) != null) {
// Quoted string — keep as-is
String str = Matcher.quoteReplacement(text);
result.append(sql, lastPos, matcher.start()).append(str);
lastPos = matcher.end();
} else if (matcher.group(2) != null) {
// Question mark outside quotes — replace it
String str = Matcher.quoteReplacement(replacement);
result.append(sql, lastPos, matcher.start()).append(str);
lastPos = matcher.end();
}
}
// Add rest of the `sql`
result.append(sql, lastPos, sql.length());
return result.toString();
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
ensureOpen();
TimeZone tz = (cal == null ? defaultCalendar : cal).getTimeZone();
values[parameterIndex - 1] = encodeObject(DataTypeUtils.toLocalDate(x, tz));
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
ensureOpen();
TimeZone tz = (cal == null ? defaultCalendar : cal).getTimeZone();
values[parameterIndex - 1] = encodeObject(DataTypeUtils.toLocalTime(x, tz));
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
ensureOpen();
TimeZone tz = (cal == null ? defaultCalendar : cal).getTimeZone();
values[parameterIndex - 1] = encodeObject(DataTypeUtils.toZonedDateTime(x, tz));
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(null);
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
/**
* Returned metadata has only minimal information about parameters. Currently only their count.
* Current implementation do not parse SQL to detect type of each parameter.
*
* @see ParameterMetaDataImpl
* @return {@link ParameterMetaDataImpl}
* @throws SQLException if the statement is close
*/
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
ensureOpen();
return parameterMetaData;
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
ensureOpen();
throw new SQLException("ROWID type is not supported by ClickHouse.",
ExceptionUtils.SQL_STATE_FEATURE_NOT_SUPPORTED);
}
@Override
public void setNString(int parameterIndex, String x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader x, long length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x, length);
}
@Override
public void setNClob(int parameterIndex, NClob x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setClob(int parameterIndex, Reader x, long length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setBlob(int parameterIndex, InputStream x, long length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setNClob(int parameterIndex, Reader x, long length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setSQLXML(int parameterIndex, SQLXML x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x, length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader x, long length) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x, length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setCharacterStream(int parameterIndex, Reader x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setClob(int parameterIndex, Reader x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setBlob(int parameterIndex, InputStream x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public void setNClob(int parameterIndex, Reader x) throws SQLException {
ensureOpen();
values[parameterIndex - 1] = encodeObject(x);
}
@Override
public long executeLargeUpdate() throws SQLException {
return executeUpdate();
}
@Override
public final void addBatch(String sql) throws SQLException {
ensureOpen();
throw new SQLException(
"addBatch(String) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final boolean execute(String sql) throws SQLException {
ensureOpen();
throw new SQLException(
"execute(String) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
ensureOpen();
throw new SQLException(
"execute(String, int) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final boolean execute(String sql, int[] columnIndexes) throws SQLException {
ensureOpen();
throw new SQLException(
"execute(String, int[]) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final boolean execute(String sql, String[] columnNames) throws SQLException {
ensureOpen();
throw new SQLException(
"execute(String, String[]) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final long executeLargeUpdate(String sql) throws SQLException {
ensureOpen();
throw new SQLException(
"executeLargeUpdate(String) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
ensureOpen();
throw new SQLException(
"executeLargeUpdate(String, int) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
ensureOpen();
throw new SQLException(
"executeLargeUpdate(String, int[]) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final long executeLargeUpdate(String sql, String[] columnNames) throws SQLException {
ensureOpen();
throw new SQLException(
"executeLargeUpdate(String, String[]) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final ResultSet executeQuery(String sql) throws SQLException {
ensureOpen();
throw new SQLException(
"executeQuery(String) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final int executeUpdate(String sql) throws SQLException {
ensureOpen();
throw new SQLException(
"executeUpdate(String) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
ensureOpen();
throw new SQLException(
"executeUpdate(String, int) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
ensureOpen();
throw new SQLException(
"executeUpdate(String, int[]) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
@Override
public final int executeUpdate(String sql, String[] columnNames) throws SQLException {
ensureOpen();
throw new SQLException(
"executeUpdate(String, String[]) cannot be called in PreparedStatement or CallableStatement!",
ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE);
}
private String encodeObject(Object x) throws SQLException {
return encodeObject(x, null);
}
private static final char QUOTE = '\'';
private static final char O_BRACKET = '[';
private static final char C_BRACKET = ']';
private String encodeObject(Object x, Long length) throws SQLException {
LOG.trace("Encoding object: {}", x);
try {
if (x == null) {
return "NULL";
} else if (x instanceof String) {
return QUOTE + SQLUtils.escapeSingleQuotes((String) x) + QUOTE;
} else if (x instanceof Boolean) {
return (Boolean) x ? "1" : "0";
} else if (x instanceof Date) {
return QUOTE + DataTypeUtils.DATE_FORMATTER.format(((Date) x).toLocalDate()) + QUOTE;
} else if (x instanceof LocalDate) {
return QUOTE + DataTypeUtils.DATE_FORMATTER.format((LocalDate) x) + QUOTE;
} else if (x instanceof Time) {
return QUOTE + DataTypeUtils.TIME_FORMATTER.format(((Time) x).toLocalTime()) + QUOTE;
} else if (x instanceof LocalTime) {
return QUOTE + DataTypeUtils.TIME_WITH_NANOS_FORMATTER.format((LocalTime) x) + QUOTE;
} else if (x instanceof Timestamp) {
return QUOTE + DataTypeUtils.DATE_TIME_WITH_OPTIONAL_NANOS.format(((Timestamp) x).toLocalDateTime()) + QUOTE;
} else if (x instanceof LocalDateTime) {
return "fromUnixTimestamp64Nano(" + DataTypeUtils.toUnixTimestampString((LocalDateTime) x, defaultCalendar.getTimeZone()) + ")";
} else if (x instanceof OffsetDateTime) {
return encodeObject(((OffsetDateTime) x).toInstant());
} else if (x instanceof ZonedDateTime) {
return encodeObject(((ZonedDateTime) x).toInstant());
} else if (x instanceof Instant) {
return "fromUnixTimestamp64Nano(" + DataTypeUtils.toUnixTimestampString((Instant) x) + ")";
} else if (x instanceof Duration) {
return QUOTE + DataTypeUtils.durationToTimeString((Duration) x, 9) + QUOTE;
} else if (x instanceof InetAddress) {
return QUOTE + ((InetAddress) x).getHostAddress() + QUOTE;
} else if (x instanceof byte[]) {
return JdbcUtils.convertToUnhexExpression((byte[]) x);
} else if (x instanceof java.sql.Array) {
com.clickhouse.jdbc.types.Array array = (com.clickhouse.jdbc.types.Array) x;
int nestedLevel = Math.max(1, array.getNestedLevel());
return encodeArray((Object[]) array.getArray(), nestedLevel, array.getBaseDataType());
} else if (x instanceof Object[]) {
StringBuilder arrayString = new StringBuilder();
arrayString.append(O_BRACKET);
appendArrayElements((Object[]) x, arrayString);
arrayString.append(C_BRACKET);
return arrayString.toString();
} else if (x.getClass().isArray()) {
StringBuilder listString = new StringBuilder();
listString.append(O_BRACKET);
if (x.getClass().getComponentType().isPrimitive()) {
int len = java.lang.reflect.Array.getLength(x);
for (int i = 0; i < len; i++) {
listString.append(encodeObject(java.lang.reflect.Array.get(x, i))).append(',');
}
if (len > 0) {
listString.setLength(listString.length() - 1);
}
} else {
appendArrayElements((Object[]) x, listString);
}
listString.append(C_BRACKET);
return listString.toString();
} else if (x instanceof Collection) {
StringBuilder listString = new StringBuilder();
listString.append(O_BRACKET);
Collection<?> collection = (Collection<?>) x;
for (Object item : collection) {
listString.append(encodeObject(item)).append(',');
}
if (!collection.isEmpty()) {
listString.setLength(listString.length() - 1);
}
listString.append(C_BRACKET);
return listString.toString();
} else if (x instanceof Map) {
Map<?, ?> tmpMap = (Map<?, ?>) x;
StringBuilder mapString = new StringBuilder();
mapString.append('{');
for (Object key : tmpMap.keySet()) {
mapString.append(encodeObject(key)).append(": ").append(encodeObject(tmpMap.get(key))).append(',');
}
if (!tmpMap.isEmpty()) {
mapString.setLength(mapString.length() - 1);
}
mapString.append('}');
return mapString.toString();
} else if (x instanceof Reader) {
return encodeCharacterStream((Reader) x, length);
} else if (x instanceof InputStream) {
return encodeCharacterStream((InputStream) x, length);
} else if (x instanceof Tuple) {
return encodeTuple(((Tuple)x).getValues());
} else if (x instanceof Struct) {
return encodeTuple(((Struct)x).getAttributes());
} else if (x instanceof UUID) {
return QUOTE + ((UUID) x).toString() + QUOTE;
}
return SQLUtils.escapeSingleQuotes(x.toString()); //Escape single quotes
} catch (Exception e) {
LOG.error("Error encoding object", e);
throw new SQLException("Error encoding object", ExceptionUtils.SQL_STATE_SQL_ERROR, e);
}
}
private void appendArrayElements(Object[] array, StringBuilder sb) throws SQLException {
appendArrayElements(array, sb, null);
}
private void appendArrayElements(Object[] array, StringBuilder sb, ClickHouseDataType elementType) throws SQLException {
if (array == null) {
return;
}
for (Object item : array) {
if (elementType == ClickHouseDataType.Tuple && item != null && item.getClass().isArray()) {
sb.append(encodeTuple((Object[]) item));
} else {
sb.append(encodeObject(item)).append(',');
}
}
if (array.length > 0) {
sb.setLength(sb.length() - 1);
}
}
public String encodeArray(Object[] elements, int levels, ClickHouseDataType elementType) throws SQLException {
if (elements == null) {
return "[]";
}
StringBuilder arraySb = new StringBuilder();
Stack<ArrayProcessingCursor> stack = new Stack<>();
ArrayProcessingCursor cursor = new ArrayProcessingCursor(elements, 0, levels);
arraySb.append(O_BRACKET);
while (cursor != null) {
if (cursor.pos >= cursor.array.length) {
if (cursor.array.length > 0) {
arraySb.setLength(arraySb.length() - 1);
}
arraySb.append(C_BRACKET);
cursor = stack.isEmpty() ? null : stack.pop();
if (cursor != null) {
arraySb.append(',');
}
continue;
}
Object element = cursor.array[cursor.pos];
if (element == null) {
if (cursor.level == 1) {
arraySb.append("NULL");
} else {
arraySb.append("[]");
}
arraySb.append(',');
cursor.pos++;
} else if (cursor.arrayObjAsTuple) {
arraySb.append(encodeTuple((Object[]) ((Array)element).getArray())).append(',');
cursor.pos++;
} else if (cursor.arrayAsTuple) {
arraySb.append(encodeTuple((Object[]) element)).append(',');
cursor.pos++;
} else if (cursor.level == 1 && isTupleType(elementType) && element instanceof Array ) {
cursor.arrayObjAsTuple = true;
} else if (cursor.level == 1 && isTupleType(elementType) && element instanceof Object[] ) {
cursor.arrayAsTuple = true;
} else if (cursor.level == 1) {
arraySb.append(encodeObject(element)).append(',');
cursor.pos++;
} else {
cursor.pos++;
stack.push(cursor);
cursor = new ArrayProcessingCursor((Object[]) element, 0, cursor.level - 1);
arraySb.append(O_BRACKET);
}
}
return arraySb.toString();
}
private static boolean isTupleType(ClickHouseDataType type ) {
return type == ClickHouseDataType.Tuple || type == ClickHouseDataType.Point;
}
private static final class ArrayProcessingCursor {
Object[] array; // current array
int pos; // processing position
int level;
boolean arrayAsTuple = false;
boolean arrayObjAsTuple = false;
public ArrayProcessingCursor(Object[] array, int pos, int level) {
this.array = array;
this.pos = pos;
this.level = level;
}
}
private String encodeTuple(Object[] array) throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append('(');
if (array != null) {
appendArrayElements(array, sb);
}
sb.append(')');
return sb.toString();
}
private static String encodeCharacterStream(InputStream stream, Long length) throws SQLException {
return encodeCharacterStream(new InputStreamReader(stream, StandardCharsets.UTF_8), length);
}
private static String encodeCharacterStream(Reader reader, Long length) throws SQLException {
if (reader == null) {
throw new SQLException("Source cannot be null");
}
StringBuilder sb = new StringBuilder();
try {
char[] buffer = new char[1024];
int len;
while ((len = reader.read(buffer)) != -1) {
sb.append(buffer, 0, len);
}
reader.close();
} catch (IOException e) {
LOG.error("Error reading string from input stream", e);
throw new SQLException("Error reading string from input stream", ExceptionUtils.SQL_STATE_SQL_ERROR, e);
}
if (length == null) {
return "'" + SQLUtils.escapeSingleQuotes(sb.toString()) + "'";
} else {
return "'" + SQLUtils.escapeSingleQuotes(sb.substring(0, length.intValue())) + "'";
}
}
private void isValidForTargetType(Object value, int targetType) throws SQLException {
if (value == null) {
return; // NULL is handled in encoding and server checks if value can be NULL
}
Class<?> vClass = value.getClass();
// Here we validate only specific types
switch (targetType) {
case Types.DATE:
if (vClass == LocalDate.class || vClass == java.sql.Date.class) {