-
Notifications
You must be signed in to change notification settings - Fork 579
/
ConnectionImpl.java
5553 lines (4482 loc) · 211 KB
/
ConnectionImpl.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 (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this
program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.jdbc;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.sql.Blob;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLPermission;
import java.sql.SQLWarning;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Stack;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import com.mysql.jdbc.PreparedStatement.ParseInfo;
import com.mysql.jdbc.log.Log;
import com.mysql.jdbc.log.LogFactory;
import com.mysql.jdbc.log.LogUtils;
import com.mysql.jdbc.log.NullLogger;
import com.mysql.jdbc.profiler.ProfilerEvent;
import com.mysql.jdbc.profiler.ProfilerEventHandler;
import com.mysql.jdbc.util.LRUCache;
/**
* A Connection represents a session with a specific database. Within the context of a Connection, SQL statements are executed and results are returned.
*
* <P>
* A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this
* connection, etc. This information is obtained with the getMetaData method.
* </p>
*/
public class ConnectionImpl extends ConnectionPropertiesImpl implements MySQLConnection {
private static final long serialVersionUID = 2877471301981509474L;
private static final SQLPermission SET_NETWORK_TIMEOUT_PERM = new SQLPermission("setNetworkTimeout");
private static final SQLPermission ABORT_PERM = new SQLPermission("abort");
public static final String JDBC_LOCAL_CHARACTER_SET_RESULTS = "jdbc.local.character_set_results";
public String getHost() {
return this.host;
}
public String getHostPortPair() {
return this.hostPortPair != null ? this.hostPortPair : this.host + ":" + this.port;
}
private MySQLConnection proxy = null;
private InvocationHandler realProxy = null;
public boolean isProxySet() {
return this.proxy != null;
}
public void setProxy(MySQLConnection proxy) {
this.proxy = proxy;
this.realProxy = this.proxy instanceof MultiHostMySQLConnection ? ((MultiHostMySQLConnection) proxy).getThisAsProxy() : null;
}
// this connection has to be proxied when using multi-host settings so that statements get routed to the right physical connection
// (works as "logical" connection)
private MySQLConnection getProxy() {
return (this.proxy != null) ? this.proxy : (MySQLConnection) this;
}
/**
* @deprecated replaced by <code>getMultiHostSafeProxy()</code>
*/
@Deprecated
public MySQLConnection getLoadBalanceSafeProxy() {
return getMultiHostSafeProxy();
}
public MySQLConnection getMultiHostSafeProxy() {
return this.getProxy();
}
public Object getConnectionMutex() {
return (this.realProxy != null) ? this.realProxy : getProxy();
}
public class ExceptionInterceptorChain implements ExceptionInterceptor {
private List<Extension> interceptors;
ExceptionInterceptorChain(String interceptorClasses) throws SQLException {
this.interceptors = Util.loadExtensions(ConnectionImpl.this, ConnectionImpl.this.props, interceptorClasses, "Connection.BadExceptionInterceptor",
this);
}
void addRingZero(ExceptionInterceptor interceptor) throws SQLException {
this.interceptors.add(0, interceptor);
}
public SQLException interceptException(SQLException sqlEx, Connection conn) {
if (this.interceptors != null) {
Iterator<Extension> iter = this.interceptors.iterator();
while (iter.hasNext()) {
sqlEx = ((ExceptionInterceptor) iter.next()).interceptException(sqlEx, ConnectionImpl.this);
}
}
return sqlEx;
}
public void destroy() {
if (this.interceptors != null) {
Iterator<Extension> iter = this.interceptors.iterator();
while (iter.hasNext()) {
((ExceptionInterceptor) iter.next()).destroy();
}
}
}
public void init(Connection conn, Properties properties) throws SQLException {
if (this.interceptors != null) {
Iterator<Extension> iter = this.interceptors.iterator();
while (iter.hasNext()) {
((ExceptionInterceptor) iter.next()).init(conn, properties);
}
}
}
public List<Extension> getInterceptors() {
return this.interceptors;
}
}
/**
* Used as a key for caching callable statements which (may) depend on
* current catalog...In 5.0.x, they don't (currently), but stored procedure
* names soon will, so current catalog is a (hidden) component of the name.
*/
static class CompoundCacheKey {
String componentOne;
String componentTwo;
int hashCode;
CompoundCacheKey(String partOne, String partTwo) {
this.componentOne = partOne;
this.componentTwo = partTwo;
// Handle first component (in most cases, currentCatalog being NULL....
this.hashCode = (((this.componentOne != null) ? this.componentOne : "") + this.componentTwo).hashCode();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof CompoundCacheKey) {
CompoundCacheKey another = (CompoundCacheKey) obj;
boolean firstPartEqual = false;
if (this.componentOne == null) {
firstPartEqual = (another.componentOne == null);
} else {
firstPartEqual = this.componentOne.equals(another.componentOne);
}
return (firstPartEqual && this.componentTwo.equals(another.componentTwo));
}
return false;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.hashCode;
}
}
/**
* Marker for character set converter not being available (not written,
* multibyte, etc) Used to prevent multiple instantiation requests.
*/
private static final Object CHARSET_CONVERTER_NOT_AVAILABLE_MARKER = new Object();
/**
* The mapping between MySQL charset names and Java charset names.
* Initialized by loadCharacterSetMapping()
*/
public static Map<?, ?> charsetMap;
/** Default logger class name */
protected static final String DEFAULT_LOGGER_CLASS = "com.mysql.jdbc.log.StandardLogger";
private final static int HISTOGRAM_BUCKETS = 20;
/** Logger instance name */
private static final String LOGGER_INSTANCE_NAME = "MySQL";
/**
* Map mysql transaction isolation level name to
* java.sql.Connection.TRANSACTION_XXX
*/
private static Map<String, Integer> mapTransIsolationNameToValue = null;
/** Null logger shared by all connections at startup */
private static final Log NULL_LOGGER = new NullLogger(LOGGER_INSTANCE_NAME);
protected static Map<?, ?> roundRobinStatsMap;
/**
* Actual collation index to collation name map for given server URLs.
*/
private static final Map<String, Map<Number, String>> dynamicIndexToCollationMapByUrl = new HashMap<String, Map<Number, String>>();
/**
* Actual collation index to mysql charset name map for given server URLs.
*/
private static final Map<String, Map<Integer, String>> dynamicIndexToCharsetMapByUrl = new HashMap<String, Map<Integer, String>>();
/**
* Actual collation index to mysql charset name map of user defined charsets for given server URLs.
*/
private static final Map<String, Map<Integer, String>> customIndexToCharsetMapByUrl = new HashMap<String, Map<Integer, String>>();
/**
* Actual mysql charset name to mblen map of user defined charsets for given server URLs.
*/
private static final Map<String, Map<String, Integer>> customCharsetToMblenMapByUrl = new HashMap<String, Map<String, Integer>>();
private CacheAdapter<String, Map<String, String>> serverConfigCache;
private long queryTimeCount;
private double queryTimeSum;
private double queryTimeSumSquares;
private double queryTimeMean;
private transient Timer cancelTimer;
private List<Extension> connectionLifecycleInterceptors;
private static final Constructor<?> JDBC_4_CONNECTION_CTOR;
private static final int DEFAULT_RESULT_SET_TYPE = ResultSet.TYPE_FORWARD_ONLY;
private static final int DEFAULT_RESULT_SET_CONCURRENCY = ResultSet.CONCUR_READ_ONLY;
static {
mapTransIsolationNameToValue = new HashMap<String, Integer>(8);
mapTransIsolationNameToValue.put("READ-UNCOMMITED", TRANSACTION_READ_UNCOMMITTED);
mapTransIsolationNameToValue.put("READ-UNCOMMITTED", TRANSACTION_READ_UNCOMMITTED);
mapTransIsolationNameToValue.put("READ-COMMITTED", TRANSACTION_READ_COMMITTED);
mapTransIsolationNameToValue.put("REPEATABLE-READ", TRANSACTION_REPEATABLE_READ);
mapTransIsolationNameToValue.put("SERIALIZABLE", TRANSACTION_SERIALIZABLE);
if (Util.isJdbc4()) {
try {
JDBC_4_CONNECTION_CTOR = Class.forName("com.mysql.jdbc.JDBC4Connection")
.getConstructor(new Class[] { String.class, Integer.TYPE, Properties.class, String.class, String.class });
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
JDBC_4_CONNECTION_CTOR = null;
}
}
protected static SQLException appendMessageToException(SQLException sqlEx, String messageToAppend, ExceptionInterceptor interceptor) {
String origMessage = sqlEx.getMessage();
String sqlState = sqlEx.getSQLState();
int vendorErrorCode = sqlEx.getErrorCode();
StringBuilder messageBuf = new StringBuilder(origMessage.length() + messageToAppend.length());
messageBuf.append(origMessage);
messageBuf.append(messageToAppend);
SQLException sqlExceptionWithNewMessage = SQLError.createSQLException(messageBuf.toString(), sqlState, vendorErrorCode, interceptor);
//
// Try and maintain the original stack trace, only works on JDK-1.4 and newer
//
try {
// Have to do this with reflection, otherwise older JVMs croak
Method getStackTraceMethod = null;
Method setStackTraceMethod = null;
Object theStackTraceAsObject = null;
Class<?> stackTraceElementClass = Class.forName("java.lang.StackTraceElement");
Class<?> stackTraceElementArrayClass = Array.newInstance(stackTraceElementClass, new int[] { 0 }).getClass();
getStackTraceMethod = Throwable.class.getMethod("getStackTrace", new Class[] {});
setStackTraceMethod = Throwable.class.getMethod("setStackTrace", new Class[] { stackTraceElementArrayClass });
if (getStackTraceMethod != null && setStackTraceMethod != null) {
theStackTraceAsObject = getStackTraceMethod.invoke(sqlEx, new Object[0]);
setStackTraceMethod.invoke(sqlExceptionWithNewMessage, new Object[] { theStackTraceAsObject });
}
} catch (NoClassDefFoundError noClassDefFound) {
} catch (NoSuchMethodException noSuchMethodEx) {
} catch (Throwable catchAll) {
}
return sqlExceptionWithNewMessage;
}
public Timer getCancelTimer() {
synchronized (getConnectionMutex()) {
if (this.cancelTimer == null) {
boolean createdNamedTimer = false;
// Use reflection magic to try this on JDK's 1.5 and newer, fallback to non-named timer on older VMs.
try {
Constructor<Timer> ctr = Timer.class.getConstructor(new Class[] { String.class, Boolean.TYPE });
this.cancelTimer = ctr.newInstance(new Object[] { "MySQL Statement Cancellation Timer", Boolean.TRUE });
createdNamedTimer = true;
} catch (Throwable t) {
createdNamedTimer = false;
}
if (!createdNamedTimer) {
this.cancelTimer = new Timer(true);
}
}
return this.cancelTimer;
}
}
/**
* Creates a connection instance -- We need to provide factory-style methods
* so we can support both JDBC3 (and older) and JDBC4 runtimes, otherwise
* the class verifier complains when it tries to load JDBC4-only interface
* classes that are present in JDBC4 method signatures.
*/
protected static Connection getInstance(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url)
throws SQLException {
if (!Util.isJdbc4()) {
return new ConnectionImpl(hostToConnectTo, portToConnectTo, info, databaseToConnectTo, url);
}
return (Connection) Util.handleNewInstance(JDBC_4_CONNECTION_CTOR,
new Object[] { hostToConnectTo, Integer.valueOf(portToConnectTo), info, databaseToConnectTo, url }, null);
}
private static final Random random = new Random();
/**
* @param url
* @param hostList
*/
protected static synchronized int getNextRoundRobinHostIndex(String url, List<?> hostList) {
// we really do "random" here, because you don't get even distribution when this is coupled with connection pools
int indexRange = hostList.size();
int index = random.nextInt(indexRange);
return index;
}
private static boolean nullSafeCompare(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
}
if (s1 == null && s2 != null) {
return false;
}
return s1 != null && s1.equals(s2);
}
/** Are we in autoCommit mode? */
private boolean autoCommit = true;
/** A cache of SQL to parsed prepared statement parameters. */
private CacheAdapter<String, ParseInfo> cachedPreparedStatementParams;
/**
* For servers > 4.1.0, what character set is the metadata returned in?
*/
private String characterSetMetadata = null;
/**
* The character set we want results and result metadata returned in (null ==
* results in any charset, metadata in UTF-8).
*/
private String characterSetResultsOnServer = null;
/**
* Holds cached mappings to charset converters to avoid static
* synchronization and at the same time save memory (each charset converter
* takes approx 65K of static data).
*/
private Map<String, Object> charsetConverterMap = new HashMap<String, Object>(CharsetMapping.getNumberOfCharsetsConfigured());
/** The point in time when this connection was created */
private long connectionCreationTimeMillis = 0;
/** ID used when profiling */
private long connectionId;
/** The database we're currently using (called Catalog in JDBC terms). */
private String database = null;
/** Internal DBMD to use for various database-version specific features */
private DatabaseMetaData dbmd = null;
private TimeZone defaultTimeZone;
/** The event sink to use for profiling */
private ProfilerEventHandler eventSink;
/** Why was this connection implicitly closed, if known? (for diagnostics) */
private Throwable forceClosedReason;
/** Does the server support isolation levels? */
private boolean hasIsolationLevels = false;
/** Does this version of MySQL support quoted identifiers? */
private boolean hasQuotedIdentifiers = false;
/** The hostname we're connected to */
private String host = null;
/**
* We need this 'bootstrapped', because 4.1 and newer will send fields back
* with this even before we fill this dynamically from the server.
*/
public Map<Integer, String> indexToMysqlCharset = new HashMap<Integer, String>();
public Map<Integer, String> indexToCustomMysqlCharset = null; //new HashMap<Integer, String>();
private Map<String, Integer> mysqlCharsetToCustomMblen = null; //new HashMap<String, Integer>();
/** The I/O abstraction interface (network conn to MySQL server */
private transient MysqlIO io = null;
private boolean isClientTzUTC = false;
/** Has this connection been closed? */
private boolean isClosed = true;
/** Is this connection associated with a global tx? */
private boolean isInGlobalTx = false;
/** Is this connection running inside a JDK-1.3 VM? */
private boolean isRunningOnJDK13 = false;
/** isolation level */
private int isolationLevel = java.sql.Connection.TRANSACTION_READ_COMMITTED;
private boolean isServerTzUTC = false;
/** When did the last query finish? */
private long lastQueryFinishedTime = 0;
/** The logger we're going to use */
private transient Log log = NULL_LOGGER;
/**
* If gathering metrics, what was the execution time of the longest query so
* far ?
*/
private long longestQueryTimeMs = 0;
/** Is the server configured to use lower-case table names only? */
private boolean lowerCaseTableNames = false;
/** When did the master fail? */
// private long masterFailTimeMillis = 0L;
private long maximumNumberTablesAccessed = 0;
/** The max-rows setting for current session */
private int sessionMaxRows = -1;
/** When was the last time we reported metrics? */
private long metricsLastReportedMs;
private long minimumNumberTablesAccessed = Long.MAX_VALUE;
/** The JDBC URL we're using */
private String myURL = null;
/** Does this connection need to be tested? */
private boolean needsPing = false;
private int netBufferLength = 16384;
private boolean noBackslashEscapes = false;
private long numberOfPreparedExecutes = 0;
private long numberOfPrepares = 0;
private long numberOfQueriesIssued = 0;
private long numberOfResultSetsCreated = 0;
private long[] numTablesMetricsHistBreakpoints;
private int[] numTablesMetricsHistCounts;
private long[] oldHistBreakpoints = null;
private int[] oldHistCounts = null;
/**
* An array of currently open statements.
* Copy-on-write used here to avoid ConcurrentModificationException when statements unregister themselves while we iterate over the list.
*/
private final CopyOnWriteArrayList<Statement> openStatements = new CopyOnWriteArrayList<Statement>();
private LRUCache parsedCallableStatementCache;
private boolean parserKnowsUnicode = false;
/** The password we used */
private String password = null;
private long[] perfMetricsHistBreakpoints;
private int[] perfMetricsHistCounts;
/** Point of origin where this Connection was created */
private String pointOfOrigin;
/** The port number we're connected to (defaults to 3306) */
private int port = 3306;
/** Properties for this connection specified by user */
protected Properties props = null;
/** Should we retrieve 'info' messages from the server? */
private boolean readInfoMsg = false;
/** Are we in read-only mode? */
private boolean readOnly = false;
/** Cache of ResultSet metadata */
protected LRUCache resultSetMetadataCache;
/** The timezone of the server */
private TimeZone serverTimezoneTZ = null;
/** The map of server variables that we retrieve at connection init. */
private Map<String, String> serverVariables = null;
private long shortestQueryTimeMs = Long.MAX_VALUE;
private double totalQueryTimeMs = 0;
/** Are transactions supported by the MySQL server we are connected to? */
private boolean transactionsSupported = false;
/**
* The type map for UDTs (not implemented, but used by some third-party
* vendors, most notably IBM WebSphere)
*/
private Map<String, Class<?>> typeMap;
/** Has ANSI_QUOTES been enabled on the server? */
private boolean useAnsiQuotes = false;
/** The user we're connected as */
private String user = null;
/**
* Should we use server-side prepared statements? (auto-detected, but can be
* disabled by user)
*/
private boolean useServerPreparedStmts = false;
private LRUCache serverSideStatementCheckCache;
private LRUCache serverSideStatementCache;
private Calendar sessionCalendar;
private Calendar utcCalendar;
private String origHostToConnectTo;
// we don't want to be able to publicly clone this...
private int origPortToConnectTo;
private String origDatabaseToConnectTo;
private String errorMessageEncoding = "Cp1252"; // to begin with, changes after we talk to the server
private boolean usePlatformCharsetConverters;
/*
* For testing failover scenarios
*/
private boolean hasTriedMasterFlag = false;
/**
* The comment (if any) that we'll prepend to all statements
* sent to the server (to show up in "SHOW PROCESSLIST")
*/
private String statementComment = null;
private boolean storesLowerCaseTableName;
private List<StatementInterceptorV2> statementInterceptors;
/**
* If a CharsetEncoder is required for escaping. Needed for SJIS and related
* problems with \u00A5.
*/
private boolean requiresEscapingEncoder;
private String hostPortPair;
/**
* '
* For the delegate only
*/
protected ConnectionImpl() {
}
/**
* Creates a connection to a MySQL Server.
*
* @param hostToConnectTo
* the hostname of the database server
* @param portToConnectTo
* the port number the server is listening on
* @param info
* a Properties[] list holding the user and password
* @param databaseToConnectTo
* the database to connect to
* @param url
* the URL of the connection
* @param d
* the Driver instantation of the connection
* @exception SQLException
* if a database access error occurs
*/
public ConnectionImpl(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url) throws SQLException {
this.connectionCreationTimeMillis = System.currentTimeMillis();
if (databaseToConnectTo == null) {
databaseToConnectTo = "";
}
// Stash away for later, used to clone this connection for Statement.cancel and Statement.setQueryTimeout().
//
this.origHostToConnectTo = hostToConnectTo;
this.origPortToConnectTo = portToConnectTo;
this.origDatabaseToConnectTo = databaseToConnectTo;
try {
Blob.class.getMethod("truncate", new Class[] { Long.TYPE });
this.isRunningOnJDK13 = false;
} catch (NoSuchMethodException nsme) {
this.isRunningOnJDK13 = true;
}
this.sessionCalendar = new GregorianCalendar();
this.utcCalendar = new GregorianCalendar();
this.utcCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
//
// Normally, this code would be in initializeDriverProperties, but we need to do this as early as possible, so we can start logging to the 'correct'
// place as early as possible...this.log points to 'NullLogger' for every connection at startup to avoid NPEs and the overhead of checking for NULL at
// every logging call.
//
// We will reset this to the configured logger during properties initialization.
//
this.log = LogFactory.getLogger(getLogger(), LOGGER_INSTANCE_NAME, getExceptionInterceptor());
if (NonRegisteringDriver.isHostPropertiesList(hostToConnectTo)) {
Properties hostSpecificProps = NonRegisteringDriver.expandHostKeyValues(hostToConnectTo);
Enumeration<?> propertyNames = hostSpecificProps.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = propertyNames.nextElement().toString();
String propertyValue = hostSpecificProps.getProperty(propertyName);
info.setProperty(propertyName, propertyValue);
}
} else {
if (hostToConnectTo == null) {
this.host = "localhost";
this.hostPortPair = this.host + ":" + portToConnectTo;
} else {
this.host = hostToConnectTo;
if (hostToConnectTo.indexOf(":") == -1) {
this.hostPortPair = this.host + ":" + portToConnectTo;
} else {
this.hostPortPair = this.host;
}
}
}
this.port = portToConnectTo;
this.database = databaseToConnectTo;
this.myURL = url;
this.user = info.getProperty(NonRegisteringDriver.USER_PROPERTY_KEY);
this.password = info.getProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY);
if ((this.user == null) || this.user.equals("")) {
this.user = "";
}
if (this.password == null) {
this.password = "";
}
this.props = info;
initializeDriverProperties(info);
// We store this per-connection, due to static synchronization issues in Java's built-in TimeZone class...
this.defaultTimeZone = TimeUtil.getDefaultTimeZone(getCacheDefaultTimezone());
this.isClientTzUTC = !this.defaultTimeZone.useDaylightTime() && this.defaultTimeZone.getRawOffset() == 0;
if (getUseUsageAdvisor()) {
this.pointOfOrigin = LogUtils.findCallingClassAndMethod(new Throwable());
} else {
this.pointOfOrigin = "";
}
try {
this.dbmd = getMetaData(false, false);
initializeSafeStatementInterceptors();
createNewIO(false);
unSafeStatementInterceptors();
} catch (SQLException ex) {
cleanup(ex);
// don't clobber SQL exceptions
throw ex;
} catch (Exception ex) {
cleanup(ex);
StringBuilder mesg = new StringBuilder(128);
if (!getParanoid()) {
mesg.append("Cannot connect to MySQL server on ");
mesg.append(this.host);
mesg.append(":");
mesg.append(this.port);
mesg.append(".\n\n");
mesg.append("Make sure that there is a MySQL server ");
mesg.append("running on the machine/port you are trying ");
mesg.append("to connect to and that the machine this software is running on ");
mesg.append("is able to connect to this host/port (i.e. not firewalled). ");
mesg.append("Also make sure that the server has not been started with the --skip-networking ");
mesg.append("flag.\n\n");
} else {
mesg.append("Unable to connect to database.");
}
SQLException sqlEx = SQLError.createSQLException(mesg.toString(), SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE, getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
}
NonRegisteringDriver.trackConnection(this);
}
public void unSafeStatementInterceptors() throws SQLException {
ArrayList<StatementInterceptorV2> unSafedStatementInterceptors = new ArrayList<StatementInterceptorV2>(this.statementInterceptors.size());
for (int i = 0; i < this.statementInterceptors.size(); i++) {
NoSubInterceptorWrapper wrappedInterceptor = (NoSubInterceptorWrapper) this.statementInterceptors.get(i);
unSafedStatementInterceptors.add(wrappedInterceptor.getUnderlyingInterceptor());
}
this.statementInterceptors = unSafedStatementInterceptors;
if (this.io != null) {
this.io.setStatementInterceptors(this.statementInterceptors);
}
}
public void initializeSafeStatementInterceptors() throws SQLException {
this.isClosed = false;
List<Extension> unwrappedInterceptors = Util.loadExtensions(this, this.props, getStatementInterceptors(), "MysqlIo.BadStatementInterceptor",
getExceptionInterceptor());
this.statementInterceptors = new ArrayList<StatementInterceptorV2>(unwrappedInterceptors.size());
for (int i = 0; i < unwrappedInterceptors.size(); i++) {
Extension interceptor = unwrappedInterceptors.get(i);
// adapt older versions of statement interceptors, handle the case where something wants v2 functionality but wants to run with an older driver
if (interceptor instanceof StatementInterceptor) {
if (ReflectiveStatementInterceptorAdapter.getV2PostProcessMethod(interceptor.getClass()) != null) {
this.statementInterceptors.add(new NoSubInterceptorWrapper(new ReflectiveStatementInterceptorAdapter((StatementInterceptor) interceptor)));
} else {
this.statementInterceptors.add(new NoSubInterceptorWrapper(new V1toV2StatementInterceptorAdapter((StatementInterceptor) interceptor)));
}
} else {
this.statementInterceptors.add(new NoSubInterceptorWrapper((StatementInterceptorV2) interceptor));
}
}
}
public List<StatementInterceptorV2> getStatementInterceptorsInstances() {
return this.statementInterceptors;
}
private void addToHistogram(int[] histogramCounts, long[] histogramBreakpoints, long value, int numberOfTimes, long currentLowerBound,
long currentUpperBound) {
if (histogramCounts == null) {
createInitialHistogram(histogramBreakpoints, currentLowerBound, currentUpperBound);
} else {
for (int i = 0; i < HISTOGRAM_BUCKETS; i++) {
if (histogramBreakpoints[i] >= value) {
histogramCounts[i] += numberOfTimes;
break;
}
}
}
}
private void addToPerformanceHistogram(long value, int numberOfTimes) {
checkAndCreatePerformanceHistogram();
addToHistogram(this.perfMetricsHistCounts, this.perfMetricsHistBreakpoints, value, numberOfTimes,
this.shortestQueryTimeMs == Long.MAX_VALUE ? 0 : this.shortestQueryTimeMs, this.longestQueryTimeMs);
}
private void addToTablesAccessedHistogram(long value, int numberOfTimes) {
checkAndCreateTablesAccessedHistogram();
addToHistogram(this.numTablesMetricsHistCounts, this.numTablesMetricsHistBreakpoints, value, numberOfTimes,
this.minimumNumberTablesAccessed == Long.MAX_VALUE ? 0 : this.minimumNumberTablesAccessed, this.maximumNumberTablesAccessed);
}
/**
* Builds the map needed for 4.1.0 and newer servers that maps field-level
* charset/collation info to a java character encoding name.
*
* @throws SQLException
*/
private void buildCollationMapping() throws SQLException {
Map<Integer, String> indexToCharset = null;
Map<Number, String> sortedCollationMap = null;
Map<Integer, String> customCharset = null;
Map<String, Integer> customMblen = null;
if (getCacheServerConfiguration()) {
synchronized (dynamicIndexToCharsetMapByUrl) {
indexToCharset = dynamicIndexToCharsetMapByUrl.get(getURL());
sortedCollationMap = dynamicIndexToCollationMapByUrl.get(getURL());
customCharset = customIndexToCharsetMapByUrl.get(getURL());
customMblen = customCharsetToMblenMapByUrl.get(getURL());
}
}
if (indexToCharset == null) {
indexToCharset = new HashMap<Integer, String>();
if (versionMeetsMinimum(4, 1, 0) && getDetectCustomCollations()) {
java.sql.Statement stmt = null;
java.sql.ResultSet results = null;
try {
sortedCollationMap = new TreeMap<Number, String>();
customCharset = new HashMap<Integer, String>();
customMblen = new HashMap<String, Integer>();
stmt = getMetadataSafeStatement();
try {
results = stmt.executeQuery("SHOW COLLATION");
if (versionMeetsMinimum(5, 0, 0)) {
Util.resultSetToMap(sortedCollationMap, results, 3, 2);
} else {
while (results.next()) {
sortedCollationMap.put(results.getLong(3), results.getString(2));
}
}
} catch (SQLException ex) {
if (ex.getErrorCode() != MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD || getDisconnectOnExpiredPasswords()) {
throw ex;
}
}
for (Iterator<Map.Entry<Number, String>> indexIter = sortedCollationMap.entrySet().iterator(); indexIter.hasNext();) {
Map.Entry<Number, String> indexEntry = indexIter.next();
int collationIndex = indexEntry.getKey().intValue();
String charsetName = indexEntry.getValue();
indexToCharset.put(collationIndex, charsetName);
// if no static map for charsetIndex or server has a different mapping then our static map, adding it to custom map
if (collationIndex >= CharsetMapping.MAP_SIZE
|| !charsetName.equals(CharsetMapping.getMysqlCharsetNameForCollationIndex(collationIndex))) {
customCharset.put(collationIndex, charsetName);
}
// if no static map for charsetName adding to custom map
if (!CharsetMapping.CHARSET_NAME_TO_CHARSET.containsKey(charsetName)) {
customMblen.put(charsetName, null);
}
}
// if there is a number of custom charsets we should execute SHOW CHARACTER SET to know theirs mblen
if (customMblen.size() > 0) {
try {
results = stmt.executeQuery("SHOW CHARACTER SET");
while (results.next()) {
String charsetName = results.getString("Charset");
if (customMblen.containsKey(charsetName)) {
customMblen.put(charsetName, results.getInt("Maxlen"));
}
}