-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
JdbcConnection.java
1526 lines (1410 loc) · 63.8 KB
/
JdbcConnection.java
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
/*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.jdbc;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.apache.kafka.connect.errors.ConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.DebeziumException;
import io.debezium.annotation.NotThreadSafe;
import io.debezium.annotation.ThreadSafe;
import io.debezium.config.CommonConnectorConfig;
import io.debezium.config.Configuration;
import io.debezium.config.Field;
import io.debezium.relational.Column;
import io.debezium.relational.ColumnEditor;
import io.debezium.relational.RelationalDatabaseConnectorConfig;
import io.debezium.relational.Table;
import io.debezium.relational.TableId;
import io.debezium.relational.Tables;
import io.debezium.relational.Tables.ColumnNameFilter;
import io.debezium.relational.Tables.TableFilter;
import io.debezium.schema.DatabaseSchema;
import io.debezium.util.BoundedConcurrentHashMap;
import io.debezium.util.BoundedConcurrentHashMap.Eviction;
import io.debezium.util.BoundedConcurrentHashMap.EvictionListener;
import io.debezium.util.Collect;
import io.debezium.util.ColumnUtils;
import io.debezium.util.Strings;
/**
* A utility that simplifies using a JDBC connection and executing transactions composed of multiple statements.
*
* @author Randall Hauch
*/
@NotThreadSafe
public class JdbcConnection implements AutoCloseable {
private static final int WAIT_FOR_CLOSE_SECONDS = 10;
private static final char STATEMENT_DELIMITER = ';';
private static final int STATEMENT_CACHE_CAPACITY = 10_000;
private final static Logger LOGGER = LoggerFactory.getLogger(JdbcConnection.class);
private static final int CONNECTION_VALID_CHECK_TIMEOUT_IN_SEC = 3;
private final Map<String, PreparedStatement> statementCache = new BoundedConcurrentHashMap<>(STATEMENT_CACHE_CAPACITY, 16, Eviction.LIRS,
new EvictionListener<String, PreparedStatement>() {
@Override
public void onEntryEviction(Map<String, PreparedStatement> evicted) {
}
@Override
public void onEntryChosenForEviction(PreparedStatement statement) {
cleanupPreparedStatement(statement);
}
});
/**
* Establishes JDBC connections.
*/
@FunctionalInterface
@ThreadSafe
public static interface ConnectionFactory {
/**
* Establish a connection to the database denoted by the given configuration.
*
* @param config the configuration with JDBC connection information
* @return the JDBC connection; may not be null
* @throws SQLException if there is an error connecting to the database
*/
Connection connect(JdbcConfiguration config) throws SQLException;
}
private class ConnectionFactoryDecorator implements ConnectionFactory {
private final ConnectionFactory defaultConnectionFactory;
private final Supplier<ClassLoader> classLoaderSupplier;
private ConnectionFactory customConnectionFactory;
private ConnectionFactoryDecorator(ConnectionFactory connectionFactory, Supplier<ClassLoader> classLoaderSupplier) {
this.defaultConnectionFactory = connectionFactory;
this.classLoaderSupplier = classLoaderSupplier;
}
@Override
public Connection connect(JdbcConfiguration config) throws SQLException {
if (Strings.isNullOrEmpty(config.getConnectionFactoryClassName())) {
return defaultConnectionFactory.connect(config);
}
if (customConnectionFactory == null) {
customConnectionFactory = config.getInstance(JdbcConfiguration.CONNECTION_FACTORY_CLASS,
ConnectionFactory.class, classLoaderSupplier);
}
return customConnectionFactory.connect(config);
}
}
/**
* Defines multiple JDBC operations.
*/
@FunctionalInterface
public static interface Operations {
/**
* Apply a series of operations against the given JDBC statement.
*
* @param statement the JDBC statement to use to execute one or more operations
* @throws SQLException if there is an error connecting to the database or executing the statements
*/
void apply(Statement statement) throws SQLException;
}
/**
* Extracts a data of resultset..
*/
@FunctionalInterface
public static interface ResultSetExtractor<T> {
T apply(ResultSet rs) throws SQLException;
}
/**
* Create a {@link ConnectionFactory} that replaces variables in the supplied URL pattern. Variables include:
* <ul>
* <li><code>${hostname}</code></li>
* <li><code>${port}</code></li>
* <li><code>${dbname}</code></li>
* <li><code>${username}</code></li>
* <li><code>${password}</code></li>
* </ul>
*
* @param urlPattern the URL pattern string; may not be null
* @param variables any custom or overridden configuration variables
* @return the connection factory
*/
public static ConnectionFactory patternBasedFactory(String urlPattern, Field... variables) {
return (config) -> {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Config: {}", propsWithMaskedPassword(config.asProperties()));
}
Properties props = config.asProperties();
Field[] varsWithDefaults = combineVariables(variables,
JdbcConfiguration.HOSTNAME,
JdbcConfiguration.PORT,
JdbcConfiguration.USER,
JdbcConfiguration.PASSWORD,
JdbcConfiguration.DATABASE);
String url = findAndReplace(urlPattern, props, varsWithDefaults);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Props: {}", propsWithMaskedPassword(props));
}
LOGGER.trace("URL: {}", url);
Connection conn = DriverManager.getConnection(url, props);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Connected to {} with {}", url, propsWithMaskedPassword(props));
}
return conn;
};
}
/**
* Create a {@link ConnectionFactory} that uses the specific JDBC driver class loaded with the given class loader, and obtains the connection URL by replacing the following variables in the URL pattern:
* <ul>
* <li><code>${hostname}</code></li>
* <li><code>${port}</code></li>
* <li><code>${dbname}</code></li>
* <li><code>${username}</code></li>
* <li><code>${password}</code></li>
* </ul>
* <p>
* This method attempts to instantiate the JDBC driver class and use that instance to connect to the database.
* @param urlPattern the URL pattern string; may not be null
* @param driverClassName the name of the JDBC driver class; may not be null
* @param classloader the ClassLoader that should be used to load the JDBC driver class given by `driverClassName`; may be null if this class' class loader should be used
* @param variables any custom or overridden configuration variables
* @return the connection factory
*/
@SuppressWarnings("unchecked")
public static ConnectionFactory patternBasedFactory(String urlPattern, String driverClassName,
ClassLoader classloader, Field... variables) {
return (config) -> {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Config: {}", propsWithMaskedPassword(config.asProperties()));
}
Properties props = config.asProperties();
Field[] varsWithDefaults = combineVariables(variables,
JdbcConfiguration.HOSTNAME,
JdbcConfiguration.PORT,
JdbcConfiguration.USER,
JdbcConfiguration.PASSWORD,
JdbcConfiguration.DATABASE);
String url = findAndReplace(urlPattern, props, varsWithDefaults);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Props: {}", propsWithMaskedPassword(props));
}
LOGGER.trace("URL: {}", url);
Connection conn = null;
try {
ClassLoader driverClassLoader = classloader;
if (driverClassLoader == null) {
driverClassLoader = JdbcConnection.class.getClassLoader();
}
Class<java.sql.Driver> driverClazz = (Class<java.sql.Driver>) Class.forName(driverClassName, true, driverClassLoader);
java.sql.Driver driver = driverClazz.getDeclaredConstructor().newInstance();
conn = driver.connect(url, props);
}
catch (ClassNotFoundException | IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
throw new SQLException(e);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Connected to {} with {}", url, propsWithMaskedPassword(props));
}
return conn;
};
}
private static Properties propsWithMaskedPassword(Properties props) {
final Properties filtered = new Properties();
filtered.putAll(props);
if (props.containsKey(JdbcConfiguration.PASSWORD.name())) {
filtered.put(JdbcConfiguration.PASSWORD.name(), "***");
}
return filtered;
}
private static Field[] combineVariables(Field[] overriddenVariables,
Field... defaultVariables) {
Map<String, Field> fields = new HashMap<>();
if (defaultVariables != null) {
for (Field variable : defaultVariables) {
fields.put(variable.name(), variable);
}
}
if (overriddenVariables != null) {
for (Field variable : overriddenVariables) {
fields.put(variable.name(), variable);
}
}
return fields.values().toArray(new Field[fields.size()]);
}
private static String findAndReplace(String url, Properties props, Field... variables) {
for (Field field : variables) {
if (field != null) {
url = findAndReplace(url, field.name(), props, field.defaultValueAsString());
}
}
for (Object key : new HashSet<>(props.keySet())) {
if (key != null) {
url = findAndReplace(url, key.toString(), props, null);
}
}
return url;
}
private static String findAndReplace(String url, String name, Properties props, String defaultValue) {
if (name != null && url.contains("${" + name + "}")) {
{
// Otherwise, we have to remove it from the properties ...
String value = props.getProperty(name);
if (value != null) {
props.remove(name);
}
if (value == null) {
value = defaultValue;
}
if (value != null) {
// And replace the variable ...
url = url.replaceAll("\\$\\{" + name + "\\}", value);
}
}
}
return url;
}
private final Configuration config;
private final ConnectionFactory factory;
private final Operations initialOps;
private final String openingQuoteCharacter;
private final String closingQuoteCharacter;
private volatile Connection conn;
/**
* Create a new instance with the given configuration and connection factory.
*
* @param config the configuration; may not be null
* @param connectionFactory the connection factory; may not be null
*/
public JdbcConnection(Configuration config, ConnectionFactory connectionFactory, String openingQuoteCharacter, String closingQuoteCharacter) {
this(config, connectionFactory, null, null, null, openingQuoteCharacter, closingQuoteCharacter);
}
/**
* Create a new instance with the given configuration and connection factory.
*
* @param config the configuration; may not be null
* @param connectionFactory the connection factory; may not be null
*/
public JdbcConnection(Configuration config, ConnectionFactory connectionFactory, Supplier<ClassLoader> classLoaderSupplier, String openingQuoteCharacter,
String closingQuoteCharacter) {
this(config, connectionFactory, null, null, classLoaderSupplier, openingQuoteCharacter, closingQuoteCharacter);
}
/**
* Create a new instance with the given configuration and connection factory, and specify the operations that should be
* run against each newly-established connection.
*
* @param config the configuration; may not be null
* @param connectionFactory the connection factory; may not be null
* @param initialOperations the initial operations that should be run on each new connection; may be null
* @param adapter the function that can be called to update the configuration with defaults
*/
protected JdbcConnection(Configuration config, ConnectionFactory connectionFactory, Operations initialOperations,
Consumer<Configuration.Builder> adapter, String openingQuotingChar, String closingQuotingChar) {
this(config, connectionFactory, initialOperations, adapter, null, openingQuotingChar, closingQuotingChar);
}
/**
* Create a new instance with the given configuration and connection factory, and specify the operations that should be
* run against each newly-established connection.
*
* @param config the configuration; may not be null
* @param connectionFactory the connection factory; may not be null
* @param initialOperations the initial operations that should be run on each new connection; may be null
* @param adapter the function that can be called to update the configuration with defaults
* @param classLoaderSupplier class loader supplier
* @param openingQuotingChar the opening quoting character
* @param closingQuotingChar the closing quoting character
*/
protected JdbcConnection(Configuration config, ConnectionFactory connectionFactory, Operations initialOperations,
Consumer<Configuration.Builder> adapter, Supplier<ClassLoader> classLoaderSupplier, String openingQuotingChar, String closingQuotingChar) {
this.config = adapter == null ? config : config.edit().apply(adapter).build();
this.factory = classLoaderSupplier == null ? connectionFactory : new ConnectionFactoryDecorator(connectionFactory, classLoaderSupplier);
this.initialOps = initialOperations;
this.openingQuoteCharacter = openingQuotingChar;
this.closingQuoteCharacter = closingQuotingChar;
this.conn = null;
}
/**
* Obtain the configuration for this connection.
*
* @return the JDBC configuration; never null
*/
public JdbcConfiguration config() {
return JdbcConfiguration.adapt(config);
}
public JdbcConnection setAutoCommit(boolean autoCommit) throws SQLException {
connection().setAutoCommit(autoCommit);
return this;
}
public JdbcConnection commit() throws SQLException {
Connection conn = connection();
if (!conn.getAutoCommit()) {
conn.commit();
}
return this;
}
public synchronized JdbcConnection rollback() throws SQLException {
if (!isValid()) {
return this;
}
Connection conn = connection();
if (!conn.getAutoCommit()) {
conn.rollback();
}
return this;
}
/**
* Ensure a connection to the database is established.
*
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database
*/
public JdbcConnection connect() throws SQLException {
connection();
return this;
}
/**
* Execute a series of SQL statements as a single transaction.
*
* @param sqlStatements the SQL statements that are to be performed as a single transaction
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection execute(String... sqlStatements) throws SQLException {
return execute(statement -> {
for (String sqlStatement : sqlStatements) {
if (sqlStatement != null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("executing '{}'", sqlStatement);
}
statement.execute(sqlStatement);
}
}
});
}
/**
* Execute a series of operations as a single transaction.
*
* @param operations the function that will be called with a newly-created {@link Statement}, and that performs
* one or more operations on that statement object
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
*/
public JdbcConnection execute(Operations operations) throws SQLException {
Connection conn = connection();
try (Statement statement = conn.createStatement();) {
operations.apply(statement);
commit();
}
return this;
}
public static interface ResultSetConsumer {
void accept(ResultSet rs) throws SQLException;
}
public static interface ResultSetMapper<T> {
T apply(ResultSet rs) throws SQLException;
}
public static interface BlockingResultSetConsumer {
void accept(ResultSet rs) throws SQLException, InterruptedException;
}
public static interface ParameterResultSetConsumer {
void accept(List<?> parameters, ResultSet rs) throws SQLException;
}
public static interface MultiResultSetConsumer {
void accept(ResultSet[] rs) throws SQLException;
}
public static interface BlockingMultiResultSetConsumer {
void accept(ResultSet[] rs) throws SQLException, InterruptedException;
}
public static interface StatementPreparer {
void accept(PreparedStatement statement) throws SQLException;
}
@FunctionalInterface
public static interface CallPreparer {
void accept(CallableStatement statement) throws SQLException;
}
/**
* Execute a SQL query.
*
* @param query the SQL query
* @param resultConsumer the consumer of the query results
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection query(String query, ResultSetConsumer resultConsumer) throws SQLException {
return query(query, Connection::createStatement, resultConsumer);
}
/**
* Execute a SQL query and map the result set into an expected type.
* @param <T> type returned by the mapper
*
* @param query the SQL query
* @param mapper the function processing the query results
* @return the result of the mapper calculation
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public <T> T queryAndMap(String query, ResultSetMapper<T> mapper) throws SQLException {
return queryAndMap(query, Connection::createStatement, mapper);
}
/**
* Execute a stored procedure.
*
* @param sql the SQL query; may not be {@code null}
* @param callPreparer a {@link CallPreparer} instance which can be used to set additional parameters; may be null
* @param resultSetConsumer a {@link ResultSetConsumer} instance which can be used to process the results; may be null
* @return this object for chaining methods together
* @throws SQLException if anything unexpected fails
*/
public JdbcConnection call(String sql, CallPreparer callPreparer, ResultSetConsumer resultSetConsumer) throws SQLException {
Connection conn = connection();
try (CallableStatement callableStatement = conn.prepareCall(sql)) {
if (callPreparer != null) {
callPreparer.accept(callableStatement);
}
try (ResultSet rs = callableStatement.executeQuery()) {
if (resultSetConsumer != null) {
resultSetConsumer.accept(rs);
}
}
}
return this;
}
/**
* Execute a SQL query.
*
* @param query the SQL query
* @param statementFactory the function that should be used to create the statement from the connection; may not be null
* @param resultConsumer the consumer of the query results
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection query(String query, StatementFactory statementFactory, ResultSetConsumer resultConsumer) throws SQLException {
Connection conn = connection();
try (Statement statement = statementFactory.createStatement(conn);) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("running '{}'", query);
}
try (ResultSet resultSet = statement.executeQuery(query);) {
if (resultConsumer != null) {
resultConsumer.accept(resultSet);
}
}
}
return this;
}
/**
* Execute multiple SQL prepared queries where each query is executed with the same set of parameters.
*
* @param multiQuery the array of prepared queries
* @param preparer the function that supplies arguments to the prepared statement; may not be null
* @param resultConsumer the consumer of the query results
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection prepareQuery(String[] multiQuery, StatementPreparer preparer, BlockingMultiResultSetConsumer resultConsumer)
throws SQLException, InterruptedException {
final StatementPreparer[] preparers = new StatementPreparer[multiQuery.length];
Arrays.fill(preparers, preparer);
return prepareQuery(multiQuery, preparers, resultConsumer);
}
/**
* Execute multiple SQL prepared queries where each query is executed with the same set of parameters.
*
* @param multiQuery the array of prepared queries
* @param preparers the array of functions that supply arguments to the prepared statements; may not be null
* @param resultConsumer the consumer of the query results
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection prepareQuery(String[] multiQuery, StatementPreparer[] preparers, BlockingMultiResultSetConsumer resultConsumer)
throws SQLException, InterruptedException {
final ResultSet[] resultSets = new ResultSet[multiQuery.length];
final PreparedStatement[] preparedStatements = new PreparedStatement[multiQuery.length];
try {
for (int i = 0; i < multiQuery.length; i++) {
final String query = multiQuery[i];
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("running '{}'", query);
}
final PreparedStatement statement = createPreparedStatement(query);
preparedStatements[i] = statement;
preparers[i].accept(statement);
resultSets[i] = statement.executeQuery();
}
if (resultConsumer != null) {
resultConsumer.accept(resultSets);
}
}
finally {
for (ResultSet rs : resultSets) {
if (rs != null) {
try {
rs.close();
}
catch (Exception ei) {
}
}
}
}
return this;
}
/**
* Execute a SQL query and map the result set into an expected type.
* @param <T> type returned by the mapper
*
* @param query the SQL query
* @param statementFactory the function that should be used to create the statement from the connection; may not be null
* @param mapper the function processing the query results
* @return the result of the mapper calculation
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public <T> T queryAndMap(String query, StatementFactory statementFactory, ResultSetMapper<T> mapper) throws SQLException {
Objects.requireNonNull(mapper, "Mapper must be provided");
Connection conn = connection();
try (Statement statement = statementFactory.createStatement(conn);) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("running '{}'", query);
}
try (ResultSet resultSet = statement.executeQuery(query);) {
return mapper.apply(resultSet);
}
}
}
public JdbcConnection queryWithBlockingConsumer(String query, StatementFactory statementFactory, BlockingResultSetConsumer resultConsumer)
throws SQLException, InterruptedException {
Connection conn = connection();
try (Statement statement = statementFactory.createStatement(conn);) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("running '{}'", query);
}
try (ResultSet resultSet = statement.executeQuery(query);) {
if (resultConsumer != null) {
resultConsumer.accept(resultSet);
}
}
}
return this;
}
/**
* A function to create a statement from a connection.
* @author Randall Hauch
*/
@FunctionalInterface
public interface StatementFactory {
/**
* Use the given connection to create a statement.
* @param connection the JDBC connection; never null
* @return the statement
* @throws SQLException if there are problems creating a statement
*/
Statement createStatement(Connection connection) throws SQLException;
}
/**
* Execute a SQL prepared query.
*
* @param preparedQueryString the prepared query string
* @param preparer the function that supplied arguments to the prepared statement; may not be null
* @param resultConsumer the consumer of the query results
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection prepareQueryWithBlockingConsumer(String preparedQueryString, StatementPreparer preparer, BlockingResultSetConsumer resultConsumer)
throws SQLException, InterruptedException {
final PreparedStatement statement = createPreparedStatement(preparedQueryString);
preparer.accept(statement);
try (ResultSet resultSet = statement.executeQuery();) {
if (resultConsumer != null) {
resultConsumer.accept(resultSet);
}
}
return this;
}
/**
* Executes a SQL query, preparing it if encountering it for the first time.
*
* @param preparedQueryString the prepared query string
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
*/
public JdbcConnection prepareQuery(String preparedQueryString) throws SQLException {
final PreparedStatement statement = createPreparedStatement(preparedQueryString);
statement.executeQuery();
return this;
}
/**
* Execute a SQL prepared query.
*
* @param preparedQueryString the prepared query string
* @param preparer the function that supplied arguments to the prepared statement; may not be null
* @param resultConsumer the consumer of the query results
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection prepareQuery(String preparedQueryString, StatementPreparer preparer, ResultSetConsumer resultConsumer)
throws SQLException {
final PreparedStatement statement = createPreparedStatement(preparedQueryString);
preparer.accept(statement);
try (ResultSet resultSet = statement.executeQuery();) {
if (resultConsumer != null) {
resultConsumer.accept(resultSet);
}
}
return this;
}
/**
* Execute a SQL prepared query and map the result set into an expected type..
* @param <T> type returned by the mapper
*
* @param preparedQueryString the prepared query string
* @param preparer the function that supplied arguments to the prepared statement; may not be null
* @param mapper the function processing the query results
* @return the result of the mapper calculation
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public <T> T prepareQueryAndMap(String preparedQueryString, StatementPreparer preparer, ResultSetMapper<T> mapper)
throws SQLException {
Objects.requireNonNull(mapper, "Mapper must be provided");
final PreparedStatement statement = createPreparedStatement(preparedQueryString);
preparer.accept(statement);
try (ResultSet resultSet = statement.executeQuery();) {
return mapper.apply(resultSet);
}
}
/**
* Execute a SQL update via a prepared statement.
*
* @param stmt the statement string
* @param preparer the function that supplied arguments to the prepared stmt; may be null
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection prepareUpdate(String stmt, StatementPreparer preparer) throws SQLException {
final PreparedStatement statement = createPreparedStatement(stmt);
if (preparer != null) {
preparer.accept(statement);
}
LOGGER.trace("Executing statement '{}'", stmt);
statement.execute();
return this;
}
/**
* Execute a SQL prepared query.
*
* @param preparedQueryString the prepared query string
* @param parameters the list of values for parameters in the query; may not be null
* @param resultConsumer the consumer of the query results
* @return this object for chaining methods together
* @throws SQLException if there is an error connecting to the database or executing the statements
* @see #execute(Operations)
*/
public JdbcConnection prepareQuery(String preparedQueryString, List<?> parameters,
ParameterResultSetConsumer resultConsumer)
throws SQLException {
final PreparedStatement statement = createPreparedStatement(preparedQueryString);
int index = 1;
for (final Object parameter : parameters) {
statement.setObject(index++, parameter);
}
try (ResultSet resultSet = statement.executeQuery()) {
if (resultConsumer != null) {
resultConsumer.accept(parameters, resultSet);
}
}
return this;
}
public void print(ResultSet resultSet) {
// CHECKSTYLE:OFF
print(resultSet, System.out::println);
// CHECKSTYLE:ON
}
public void print(ResultSet resultSet, Consumer<String> lines) {
try {
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnCount = rsmd.getColumnCount();
int[] columnSizes = findMaxLength(resultSet);
lines.accept(delimiter(columnCount, columnSizes));
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
if (i > 1) {
sb.append(" | ");
}
sb.append(Strings.setLength(rsmd.getColumnLabel(i), columnSizes[i], ' '));
}
lines.accept(sb.toString());
sb.setLength(0);
lines.accept(delimiter(columnCount, columnSizes));
while (resultSet.next()) {
sb.setLength(0);
for (int i = 1; i <= columnCount; i++) {
if (i > 1) {
sb.append(" | ");
}
sb.append(Strings.setLength(resultSet.getString(i), columnSizes[i], ' '));
}
lines.accept(sb.toString());
sb.setLength(0);
}
lines.accept(delimiter(columnCount, columnSizes));
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
private String delimiter(int columnCount, int[] columnSizes) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
if (i > 1) {
sb.append("---");
}
sb.append(Strings.createString('-', columnSizes[i]));
}
return sb.toString();
}
private int[] findMaxLength(ResultSet resultSet) throws SQLException {
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnCount = rsmd.getColumnCount();
int[] columnSizes = new int[columnCount + 1];
for (int i = 1; i <= columnCount; i++) {
columnSizes[i] = Math.max(columnSizes[i], rsmd.getColumnLabel(i).length());
}
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
String value = resultSet.getString(i);
if (value != null) {
columnSizes[i] = Math.max(columnSizes[i], value.length());
}
}
}
resultSet.beforeFirst();
return columnSizes;
}
public synchronized boolean isConnected() throws SQLException {
if (conn == null) {
return false;
}
return !conn.isClosed();
}
public synchronized boolean isValid() throws SQLException {
return isConnected() && conn.isValid(CONNECTION_VALID_CHECK_TIMEOUT_IN_SEC);
}
public synchronized Connection connection() throws SQLException {
return connection(true);
}
public synchronized Connection connection(boolean executeOnConnect) throws SQLException {
if (!isValid()) {
conn = factory.connect(JdbcConfiguration.adapt(config));
if (!isValid()) {
throw new SQLException("Unable to obtain a JDBC connection");
}
// Always run the initial operations on this new connection
if (initialOps != null) {
execute(initialOps);
}
final String statements = config.getString(JdbcConfiguration.ON_CONNECT_STATEMENTS);
if (statements != null && executeOnConnect) {
final List<String> splitStatements = parseSqlStatementString(statements);
execute(splitStatements.toArray(new String[splitStatements.size()]));
}
}
return conn;
}
protected List<String> parseSqlStatementString(final String statements) {
final List<String> splitStatements = new ArrayList<>();
final char[] statementsChars = statements.toCharArray();
StringBuilder activeStatement = new StringBuilder();
for (int i = 0; i < statementsChars.length; i++) {
if (statementsChars[i] == STATEMENT_DELIMITER) {
if (i == statementsChars.length - 1) {
// last character so it is the delimiter
}
else if (statementsChars[i + 1] == STATEMENT_DELIMITER) {
// two semicolons in a row - escaped semicolon
activeStatement.append(STATEMENT_DELIMITER);
i++;
}
else {
// semicolon as a delimiter
final String trimmedStatement = activeStatement.toString().trim();
if (!trimmedStatement.isEmpty()) {
splitStatements.add(trimmedStatement);
}
activeStatement = new StringBuilder();
}
}
else {
activeStatement.append(statementsChars[i]);
}
}
final String trimmedStatement = activeStatement.toString().trim();
if (!trimmedStatement.isEmpty()) {
splitStatements.add(trimmedStatement);
}
return splitStatements;
}
/**
* Close the connection and release any resources.
*/
@Override
public synchronized void close() throws SQLException {
if (conn != null) {
try {
statementCache.values().forEach(this::cleanupPreparedStatement);
statementCache.clear();
LOGGER.trace("Closing database connection");
doClose();
}
finally {
conn = null;
}
}
}
private void doClose() throws SQLException {
ExecutorService executor = Executors.newSingleThreadExecutor();
// attempting to close the connection gracefully
Future<Object> futureClose = executor.submit(() -> {
conn.close();
LOGGER.info("Connection gracefully closed");
return null;
});
try {
futureClose.get(WAIT_FOR_CLOSE_SECONDS, TimeUnit.SECONDS);
}
catch (ExecutionException e) {
if (e.getCause() instanceof SQLException) {
throw (SQLException) e.getCause();
}
else if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new DebeziumException(e.getCause());
}
catch (TimeoutException | InterruptedException e) {
LOGGER.warn("Failed to close database connection by calling close(), attempting abort()");
conn.abort(Runnable::run);
}
finally {
executor.shutdownNow();
}
}
/**
* Get the names of all of the catalogs.
* @return the set of catalog names; never null but possibly empty
* @throws SQLException if an error occurs while accessing the database metadata
*/
public Set<String> readAllCatalogNames()
throws SQLException {
Set<String> catalogs = new HashSet<>();
DatabaseMetaData metadata = connection().getMetaData();
try (ResultSet rs = metadata.getCatalogs()) {
while (rs.next()) {
String catalogName = rs.getString(1);