/
BaseTest.java
1119 lines (1006 loc) · 34.9 KB
/
BaseTest.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
/*
*
* MariaDB Client for Java
*
* Copyright (c) 2012-2014 Monty Program Ab.
* Copyright (c) 2015-2017 MariaDB Ab.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to Monty Program Ab info@montyprogram.com.
*
* This particular MariaDB Client for Java file is work
* derived from a Drizzle-JDBC. Drizzle-JDBC file which is covered by subject to
* the following copyright and notice provisions:
*
* Copyright (c) 2009-2011, Marcus Eriksson
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of the driver nor the names of its contributors may not be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
package org.mariadb.jdbc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.sun.jna.Platform;
import java.io.IOException;
import java.lang.Thread.State;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.mariadb.jdbc.failover.TcpProxy;
import org.mariadb.jdbc.internal.failover.AbstractMastersListener;
import org.mariadb.jdbc.internal.protocol.Protocol;
import org.mariadb.jdbc.internal.util.Options;
/**
* Base util class. For testing mvn test -DdbUrl=jdbc:mariadb://localhost:3306/testj?user=root
* -DlogLevel=FINEST
*/
@Ignore
@SuppressWarnings("Annotator")
public class BaseTest {
protected static final String mDefUrl = "jdbc:mariadb://localhost:3306/testj?user=root";
private static final Set<String> tempTableList = new HashSet<>();
private static final Set<String> tempViewList = new HashSet<>();
private static final Set<String> tempProcedureList = new HashSet<>();
private static final Set<String> tempFunctionList = new HashSet<>();
private static final NumberFormat numberFormat = DecimalFormat.getInstance(Locale.ROOT);
protected static String connU;
protected static String connUri;
protected static String connDnsUri;
protected static String hostname;
protected static int port;
protected static String database;
protected static String username;
protected static String password;
protected static String parameters;
protected static boolean testSingleHost;
protected static Connection sharedConnection;
protected static boolean runLongTest = false;
protected static boolean doPrecisionTest = true;
private static TcpProxy proxy = null;
private static UrlParser urlParser;
@Rule
public TestRule watcher = new TestWatcher() {
private long ttime;
protected void starting(Description description) {
if (testSingleHost) {
System.out.println(
"start test : " + description.getClassName() + "." + description.getMethodName());
ttime = System.nanoTime();
}
}
//execute another query to ensure connection is stable
protected void finished(Description description) {
if (testSingleHost) {
Random random = new Random();
int randInt = random.nextInt();
try (PreparedStatement preparedStatement = sharedConnection
.prepareStatement("SELECT " + randInt)) {
ResultSet rs = preparedStatement.executeQuery();
assertTrue(rs.next());
assertEquals(randInt, rs.getInt(1));
} catch (SQLNonTransientConnectionException connFail) {
connFail.printStackTrace();
try {
beforeClassBaseTest();
} catch (SQLException e) {
System.out.println("ERROR reconnecting");
e.printStackTrace();
}
fail("Prepare after test fail for " + description.getClassName() + "." + description
.getMethodName());
} catch (Exception e) {
e.printStackTrace();
fail("Prepare after test fail for " + description.getClassName() + "." + description
.getMethodName());
}
}
}
protected void succeeded(Description description) {
if (testSingleHost) {
System.out.println(
"finished test success : " + description.getClassName() + "." + description
.getMethodName()
+ " after " + numberFormat.format(((double) System.nanoTime() - ttime) / 1000000)
+ " ms");
}
}
protected void failed(Throwable throwable, Description description) {
if (testSingleHost) {
System.out.println(
"finished test failed : " + description.getClassName() + "." + description
.getMethodName()
+ " after " + numberFormat.format(((double) System.nanoTime() - ttime) / 1000000)
+ " ms");
}
}
};
/**
* Initialization.
*
* @throws SQLException exception
*/
@BeforeClass()
public static void beforeClassBaseTest() throws SQLException {
String url = System.getProperty("dbUrl", mDefUrl);
runLongTest = Boolean.parseBoolean(System.getProperty("runLongTest", "false"));
testSingleHost = Boolean.parseBoolean(System.getProperty("testSingleHost", "true"));
if (testSingleHost) {
urlParser = UrlParser.parse(url + "&pool=true&maxPoolSize=2&minPoolSize=1");
if (urlParser.getHostAddresses().size() > 0) {
hostname = urlParser.getHostAddresses().get(0).host;
port = urlParser.getHostAddresses().get(0).port;
} else {
hostname = null;
port = 3306;
}
database = urlParser.getDatabase();
username = urlParser.getUsername();
password = urlParser.getPassword();
int separator = url.indexOf("//");
String urlSecondPart = url.substring(separator + 2);
int dbIndex = urlSecondPart.indexOf("/");
int paramIndex = urlSecondPart.indexOf("?");
String additionalParameters;
if ((dbIndex < paramIndex && dbIndex < 0) || (dbIndex > paramIndex && paramIndex > -1)) {
additionalParameters = urlSecondPart.substring(paramIndex);
} else if ((dbIndex < paramIndex && dbIndex > -1) || (dbIndex > paramIndex
&& paramIndex < 0)) {
additionalParameters = urlSecondPart.substring(dbIndex);
} else {
additionalParameters = null;
}
if (additionalParameters != null) {
String regex = "(\\/[^\\?]*)(\\?.+)*|(\\?[^\\/]*)(\\/.+)*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(additionalParameters);
if (matcher.find()) {
String options1 = (matcher.group(2) != null) ? matcher.group(2).substring(1) : "";
String options2 = (matcher.group(3) != null) ? matcher.group(3).substring(1) : "";
parameters = (options1.isEmpty()) ? options2 : options1;
}
} else {
parameters = null;
}
setUri();
urlParser.auroraPipelineQuirks();
try {
sharedConnection = MariaDbConnection.newConnection(urlParser, null);
} catch (SQLException sqle) {
System.out.println("Connection from pool fail :" + sqle.getMessage());
sharedConnection = DriverManager.getConnection(url);
}
String dbVersion = sharedConnection.getMetaData().getDatabaseProductVersion();
doPrecisionTest =
isMariadbServer() || !dbVersion.startsWith("5.5"); //MySQL 5.5 doesn't support precision
}
}
private static void setUri() {
connU = "jdbc:mariadb://" + ((hostname == null) ? "localhost" : hostname) + ":" + port + "/"
+ ((database == null) ? "" : database);
connUri = connU + "?" + parameters
+ (password != null && !"".equals(password) ? "&password=" + password : "");
connDnsUri = "jdbc:mariadb://mariadb.example.com:" + port + "/" + database + "?" + parameters
+ (password != null && !"".equals(password) ? "&password=" + password : "");
}
/**
* Destroy the test tables.
*
* @throws SQLException exception
*/
@AfterClass
public static void afterClassBaseTest() throws SQLException {
if (testSingleHost && sharedConnection != null && !sharedConnection.isClosed()) {
if (!tempViewList.isEmpty()) {
Statement stmt = sharedConnection.createStatement();
for (String viewName : tempViewList) {
try {
stmt.execute("DROP VIEW IF EXISTS " + viewName);
} catch (SQLException e) {
//eat exception
}
}
}
if (!tempTableList.isEmpty()) {
Statement stmt = sharedConnection.createStatement();
for (String tableName : tempTableList) {
try {
stmt.execute("DROP TABLE IF EXISTS " + tableName);
} catch (SQLException e) {
//eat exception
}
}
}
if (!tempProcedureList.isEmpty()) {
Statement stmt = sharedConnection.createStatement();
for (String procedureName : tempProcedureList) {
try {
stmt.execute("DROP procedure IF EXISTS " + procedureName);
} catch (SQLException e) {
//eat exception
}
}
}
if (!tempFunctionList.isEmpty()) {
Statement stmt = sharedConnection.createStatement();
for (String functionName : tempFunctionList) {
try {
stmt.execute("DROP FUNCTION IF EXISTS " + functionName);
} catch (SQLException e) {
//eat exception
}
}
}
try {
sharedConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (!Platform.isWindows()) {
Iterator<Thread> it = Thread.getAllStackTraces().keySet().iterator();
Thread thread;
while (it.hasNext()) {
thread = it.next();
if (thread.getName().contains("MariaDb-bulk-")) {
if (thread.getState() != State.WAITING) {
//print stack trace to console.
for (StackTraceElement ste : thread.getStackTrace()) {
System.out.println(ste);
}
}
assertEquals(State.WAITING, thread.getState());
}
}
}
}
// common function for logging information
static void logInfo(String message) {
System.out.println(message);
}
/**
* Create a table that will be detroyed a the end of tests.
*
* @param tableName table name
* @param tableColumns table columns
* @throws SQLException exception
*/
public static void createTable(String tableName, String tableColumns) throws SQLException {
createTable(tableName, tableColumns, null);
}
/**
* Create a table that will be detroyed a the end of tests.
*
* @param tableName table name
* @param tableColumns table columns
* @param engine engine type
* @throws SQLException exception
*/
public static void createTable(String tableName, String tableColumns, String engine)
throws SQLException {
if (testSingleHost) {
Statement stmt = sharedConnection.createStatement();
stmt.execute("drop table if exists " + tableName);
stmt.execute(
"create table " + tableName + " (" + tableColumns + ") " + ((engine != null) ? engine
: ""));
if (!tempFunctionList.contains(tableName)) {
tempTableList.add(tableName);
}
}
}
/**
* Create a view that will be detroyed a the end of tests.
*
* @param viewName table name
* @param tableColumns table columns
* @throws SQLException exception
*/
public static void createView(String viewName, String tableColumns) throws SQLException {
if (testSingleHost) {
Statement stmt = sharedConnection.createStatement();
stmt.execute("drop view if exists " + viewName);
stmt.execute("create view " + viewName + " AS (" + tableColumns + ") ");
tempViewList.add(viewName);
}
}
/**
* Create procedure that will be delete on end of test.
*
* @param name procedure name
* @param body procecure body
* @throws SQLException exception
*/
public static void createProcedure(String name, String body) throws SQLException {
if (testSingleHost) {
Statement stmt = sharedConnection.createStatement();
stmt.execute("drop procedure IF EXISTS " + name);
stmt.execute("create procedure " + name + body);
tempProcedureList.add(name);
}
}
/**
* Create function that will be delete on end of test.
*
* @param name function name
* @param body function body
* @throws SQLException exception
*/
public static void createFunction(String name, String body) throws SQLException {
if (testSingleHost) {
Statement stmt = sharedConnection.createStatement();
stmt.execute("drop function IF EXISTS " + name);
stmt.execute("create function " + name + body);
tempFunctionList.add(name);
}
}
/**
* Check if current DB server is MariaDB.
*
* @return true if DB is mariadb
* @throws SQLException exception
*/
static boolean isMariadbServer() throws SQLException {
if (testSingleHost) {
DatabaseMetaData md = sharedConnection.getMetaData();
return md.getDatabaseProductVersion().contains("MariaDB");
}
return false;
}
/**
* List current connections to server.
*
* @return number of thread connected.
* @throws SQLException if queries failed
*/
public static int getCurrentConnections() {
try {
Statement stmt = sharedConnection.createStatement();
ResultSet rs = stmt.executeQuery("show status where `variable_name` = 'Threads_connected'");
assertTrue(rs.next());
return rs.getInt(2);
} catch (SQLException e) {
return -1;
}
}
/**
* Indicate if there is a anonymous user.
*
* @return true if anonymous user exist
* @throws SQLException if any error occur
*/
public boolean anonymousUser() throws SQLException {
if (testSingleHost) {
Statement stmt = sharedConnection.createStatement();
ResultSet rs = stmt
.executeQuery("SELECT * FROM mysql.user u where u.Host='localhost' and u.User=''");
return rs.next();
}
return false;
}
/**
* Create a connection with proxy.
*
* @param info additionnal properties
* @return a proxyfied connection
* @throws SQLException if any error occur
*/
public Connection createProxyConnection(Properties info) throws SQLException {
UrlParser tmpUrlParser = UrlParser.parse(connUri);
username = tmpUrlParser.getUsername();
hostname = tmpUrlParser.getHostAddresses().get(0).host;
String sockethosts = "";
HostAddress hostAddress;
try {
hostAddress = tmpUrlParser.getHostAddresses().get(0);
proxy = new TcpProxy(hostAddress.host, hostAddress.port);
sockethosts += "address=(host=localhost)(port=" + proxy.getLocalPort() + ")"
+ ((hostAddress.type != null) ? "(type=" + hostAddress.type + ")" : "");
} catch (IOException e) {
e.printStackTrace();
}
return openConnection("jdbc:mariadb://" + sockethosts + "/" + connUri.split("/")[3], info);
}
/**
* Stop proxy, and restart it after a certain amount of time.
*
* @param millissecond milliseconds
*/
public void stopProxy(long millissecond) {
proxy.restart(millissecond);
}
/**
* Stop proxy.
*/
public void stopProxy() {
proxy.stop();
}
public void delayProxy(int millissecond) {
proxy.setDelay(millissecond);
}
public void removeDelayProxy() {
proxy.removeDelay();
}
/**
* Restart proxy.
*/
public void restartProxy() {
proxy.restart();
}
/**
* Clean proxies.
*/
public void closeProxy() {
try {
proxy.stop();
proxy = null;
} catch (Exception e) {
//Eat exception
}
}
@Before
public void init() {
Assume.assumeTrue(testSingleHost);
}
/**
* Permit to assure that host are not in a blacklist after a test.
*
* @param connection connection
*/
public void assureBlackList(Connection connection) {
AbstractMastersListener.clearBlacklist();
}
protected Protocol getProtocolFromConnection(Connection conn) throws Throwable {
Method getProtocol = MariaDbConnection.class.getDeclaredMethod("getProtocol");
getProtocol.setAccessible(true);
Object obj = getProtocol.invoke(conn);
return (Protocol) obj;
}
protected void setHostname(String hostname) throws SQLException {
BaseTest.hostname = hostname;
setUri();
setConnection();
}
protected void setPort(int port) throws SQLException {
BaseTest.port = port;
setUri();
setConnection();
}
protected void setDatabase(String database) throws SQLException {
BaseTest.database = database;
BaseTest.setUri();
setConnection();
}
protected void setUsername(String username) throws SQLException {
BaseTest.username = username;
setUri();
setConnection();
}
protected void setPassword(String password) throws SQLException {
BaseTest.password = password;
setUri();
setConnection();
}
protected Connection setBlankConnection(String parameters) throws SQLException {
return openConnection(connU
+ "?user=" + username
+ (password != null && !"".equals(password) ? "&password=" + password : "")
+ parameters, null);
}
protected Connection setConnection() throws SQLException {
return openConnection(connUri, null);
}
protected Connection setConnection(Map<String, String> props) throws SQLException {
Properties info = new Properties();
for (String key : props.keySet()) {
info.setProperty(key, props.get(key));
}
return openConnection(connU, info);
}
protected Connection setConnection(Properties info) throws SQLException {
return openConnection(connUri, info);
}
protected Connection setConnection(String parameters) throws SQLException {
return openConnection(connUri + parameters, null);
}
protected Connection setConnection(String additionalParameters, String database)
throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("jdbc:mariadb://");
if (hostname == null) {
sb.append("localhost");
} else {
sb.append(hostname);
}
sb.append(":").append(port).append("/");
if (database != null) {
sb.append(database);
}
sb.append("?user=").append(username);
if (password != null && !password.isEmpty()) {
sb.append("&password=").append(password);
}
if (parameters != null && !parameters.isEmpty()) {
sb.append("&").append(parameters);
}
sb.append(additionalParameters);
return openConnection(sb.toString(), null);
}
protected Connection setDnsConnection(String parameters) throws SQLException {
String connU = "jdbc:mariadb://mariadb.example.com:" + port + "/"
+ ((database == null) ? "" : database);
String connUri = connU + "?user=" + username
+ (password != null && !"".equals(password) ? "&password=" + password : "")
+ (parameters != null ? "&" + parameters : "");
return openConnection(connUri + parameters, null);
}
/**
* Permit to reconstruct a connection.
*
* @param uri base uri
* @param info additionnal properties
* @return A connection
* @throws SQLException is any error occur
*/
public Connection openConnection(String uri, Properties info) throws SQLException {
if (info == null) {
return DriverManager.getConnection(uri);
} else {
return DriverManager.getConnection(uri, info);
}
}
protected Connection openNewConnection(String url) throws SQLException {
return DriverManager.getConnection(url);
}
protected Connection openNewConnection(String url, Properties info) throws SQLException {
return DriverManager.getConnection(url, info);
}
protected boolean isGalera() {
try {
Statement st = sharedConnection.createStatement();
ResultSet rs = st.executeQuery("show status like 'wsrep_cluster_size'");
if (rs.next()) {
return rs.getInt(2) > 0;
}
} catch (SQLException sqle) {
//skip
}
return false;
}
/**
* Check if max_allowed_packet value is equal or greater then 8m.
*
* @param testName test method name
* @return true if max_allowed_packet value is equal or greater then 8m.
* @throws SQLException if connection fail
*/
public boolean checkMaxAllowedPacketMore8m(String testName) throws SQLException {
Statement st = sharedConnection.createStatement();
ResultSet rs = st.executeQuery("select @@max_allowed_packet");
assertTrue(rs.next());
long maxAllowedPacket = rs.getLong(1);
if (maxAllowedPacket < 8 * 1024 * 1024L) {
System.out.println(
"test '" + testName + "' skipped due to server variable max_allowed_packet < 8M");
return false;
}
return true;
}
/**
* Check if max_allowed_packet value is equal or greater then 20m.
*
* @param testName test method name
* @return true if max_allowed_packet value is equal or greater then 20m.
* @throws SQLException if connection fail
*/
public boolean checkMaxAllowedPacketMore20m(String testName) throws SQLException {
return checkMaxAllowedPacketMore20m(testName, true);
}
/**
* Check if max_allowed_packet value is equal or greater then 20m.
*
* @param testName test method name
* @param displayMessage message to display in case of error.
* @return true if max_allowed_packet value is equal or greater then 20m.
* @throws SQLException if connection fail
*/
public boolean checkMaxAllowedPacketMore20m(String testName, boolean displayMessage)
throws SQLException {
Statement st = sharedConnection.createStatement();
ResultSet rs = st.executeQuery("select @@max_allowed_packet");
assertTrue(rs.next());
long maxAllowedPacket = rs.getLong(1);
if (maxAllowedPacket < 20 * 1024 * 1024L) {
if (displayMessage) {
System.out.println(
"test '" + testName + "' skipped due to server variable max_allowed_packet < 20M");
}
return false;
}
return true;
}
/**
* Check if max_allowed_packet value is equal or greater then 40m.
*
* @param testName test method name
* @return true if max_allowed_packet value is equal or greater then 40m.
* @throws SQLException if connection fail
*/
public boolean checkMaxAllowedPacketMore40m(String testName) throws SQLException {
return checkMaxAllowedPacketMore40m(testName, true);
}
/**
* Check if max_allowed_packet value is equal or greater then 40m.
*
* @param testName test method name
* @param displayMsg message to display in case of error.
* @return true if max_allowed_packet value is equal or greater then 40m.
* @throws SQLException if connection fail
*/
public boolean checkMaxAllowedPacketMore40m(String testName, boolean displayMsg)
throws SQLException {
Statement st = sharedConnection.createStatement();
ResultSet rs = st.executeQuery("select @@max_allowed_packet");
assertTrue(rs.next());
long maxAllowedPacket = rs.getLong(1);
if (maxAllowedPacket < 40 * 1024 * 1024L) {
if (displayMsg) {
System.out.println(
"test '" + testName + "' skipped due to server variable max_allowed_packet < 40M");
}
return false;
}
return true;
}
/**
* Does the user have super privileges.
*
* @param testName test name
* @return true if super user
* @throws SQLException in any connection occur
*/
public boolean hasSuperPrivilege(String testName) throws SQLException {
boolean superPrivilege = false;
try (Statement st = sharedConnection.createStatement()) {
// first test for specific user and host combination
try (ResultSet rs = st.executeQuery(
"SELECT Super_Priv FROM mysql.user WHERE user = '" + username + "' AND host = '"
+ hostname + "'")) {
if (rs.next()) {
superPrivilege = (rs.getString(1).equals("Y"));
} else {
// then check for user on whatever (%) host
try (ResultSet rs2 = st.executeQuery(
"SELECT Super_Priv FROM mysql.user WHERE user = '" + username + "' AND host = '%'")) {
if (rs2.next()) {
superPrivilege = (rs2.getString(1).equals("Y"));
}
}
}
}
}
if (!superPrivilege) {
System.out.println("test '" + testName + "' skipped because user '" + username
+ "' doesn't have SUPER privileges");
}
return superPrivilege;
}
/**
* Is the connection local.
*
* @param testName test method name
* @return true if local
*/
public boolean isLocalConnection(String testName) {
boolean isLocal = false;
try {
if (InetAddress.getByName(hostname).isAnyLocalAddress() || InetAddress.getByName(hostname)
.isLoopbackAddress()) {
isLocal = true;
}
} catch (UnknownHostException e) {
// for some reason it wasn't possible to parse the hostname
// do nothing
}
if (!isLocal) {
System.out.println("test '" + testName + "' skipped because connection is not local");
}
return isLocal;
}
/**
* Indicate if server has ssl configured.
*
* @param connection connection to check
* @return true if SSL is enabled
*/
public boolean haveSsl(Connection connection) {
try {
ResultSet rs = connection.createStatement().executeQuery("select @@have_ssl");
assertTrue(rs.next());
return "YES".equals(rs.getString(1));
} catch (Exception e) {
return false; /* maybe 4.x ? */
}
}
/**
* Check if version if at minimum the version asked.
*
* @param major database major version
* @param minor database minor version
* @throws SQLException exception
*/
public boolean minVersion(int major, int minor) throws SQLException {
DatabaseMetaData md = sharedConnection.getMetaData();
int dbMajor = md.getDatabaseMajorVersion();
int dbMinor = md.getDatabaseMinorVersion();
return (dbMajor > major
|| (dbMajor == major && dbMinor >= minor));
}
/**
* Check if version if at minimum the version asked.
*
* @param major database major version
* @param minor database minor version
* @param patch database patch version
* @throws SQLException exception
*/
public static boolean minVersion(int major, int minor, int patch) {
return ((MariaDbConnection) sharedConnection).versionGreaterOrEqual(major, minor, patch);
}
/**
* Check if version if before the version asked.
*
* @param major database major version
* @param minor database minor version
* @throws SQLException exception
*/
public boolean strictBeforeVersion(int major, int minor) throws SQLException {
DatabaseMetaData md = sharedConnection.getMetaData();
int dbMajor = md.getDatabaseMajorVersion();
int dbMinor = md.getDatabaseMinorVersion();
return (dbMajor < major || (dbMajor == major && dbMinor < minor));
}
/**
* Cancel if database version match.
*
* @param major db major version
* @param minor db minor version
* @throws SQLException exception
*/
public void cancelForVersion(int major, int minor) throws SQLException {
String dbVersion = sharedConnection.getMetaData().getDatabaseProductVersion();
Assume.assumeFalse(dbVersion.startsWith(major + "." + minor));
}
/**
* Cancel if database version match.
*
* @param major db major version
* @param minor db minor version
* @param patch db patch version
* @throws SQLException exception
*/
public void cancelForVersion(int major, int minor, int patch) throws SQLException {
String dbVersion = sharedConnection.getMetaData().getDatabaseProductVersion();
Assume.assumeFalse(dbVersion.startsWith(major + "." + minor + "." + patch));
}
public void requireMinimumVersion(int major, int minor) throws SQLException {
Assume.assumeTrue(minVersion(major, minor));
}
/**
* Cancel if Maxscale version isn't required minimum.
*
* @param major minimum maxscale major version
* @param minor minimum maxscale minor version
*/
public void ifMaxscaleRequireMinimumVersion(int major, int minor) {
String maxscaleVersion = System.getenv("MAXSCALE_VERSION");
if (maxscaleVersion == null) {
return;
}
String[] versionArray = maxscaleVersion.split("[^0-9]");
int majorVersion = 0;
int minorVersion = 0;
//standard version
if (versionArray.length > 2) {
majorVersion = Integer.parseInt(versionArray[0]);
minorVersion = Integer.parseInt(versionArray[1]);
} else {
if (versionArray.length > 0) {
majorVersion = Integer.parseInt(versionArray[0]);
}
if (versionArray.length > 1) {
minorVersion = Integer.parseInt(versionArray[1]);
}
}
Assume.assumeTrue(majorVersion > major
|| (majorVersion == major && minorVersion >= minor));
}
/**
* Change session time zone.
*
* @param connection connection
* @param timeZone timezone to set
* @throws SQLException exception
*/
public void setSessionTimeZone(Connection connection, String timeZone) throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.execute("set @@session.time_zone = '" + timeZone + "'");
}
}
/**
* Get row number.
*
* @param tableName table name
* @return resultset number in this table
* @throws SQLException if error occur
*/
public int getRowCount(String tableName) throws SQLException {
ResultSet rs = sharedConnection.createStatement()