-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
MySQLDatabase.java
670 lines (612 loc) · 18.6 KB
/
MySQLDatabase.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
package liquibase.database.core;
import liquibase.CatalogAndSchema;
import liquibase.Scope;
import liquibase.change.Change;
import liquibase.database.AbstractJdbcDatabase;
import liquibase.database.DatabaseConnection;
import liquibase.exception.DatabaseException;
import liquibase.exception.Warnings;
import liquibase.executor.ExecutorService;
import liquibase.statement.DatabaseFunction;
import liquibase.statement.core.RawSqlStatement;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Index;
import liquibase.structure.core.PrimaryKey;
import liquibase.util.StringUtil;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Encapsulates MySQL database support.
*/
public class MySQLDatabase extends AbstractJdbcDatabase {
private static final String PRODUCT_NAME = "MySQL";
private static final Set<String> RESERVED_WORDS = createReservedWords();
/** Pattern used to extract function precision like 3 in CURRENT_TIMESTAMP(3) */
public static final Pattern PRECISION_PATTERN = Pattern.compile("\\(\\d+\\)");
public MySQLDatabase() {
super.setCurrentDateTimeFunction("NOW()");
}
@Override
public String getShortName() {
return "mysql";
}
@Override
public String correctObjectName(String name, Class<? extends DatabaseObject> objectType) {
if (objectType.equals(PrimaryKey.class) && "PRIMARY".equals(name)) {
return null;
} else {
name = super.correctObjectName(name, objectType);
if (name == null) {
return null;
}
if (!this.isCaseSensitive()) {
return name.toLowerCase(Locale.US);
}
return name;
}
}
@Override
protected String getDefaultDatabaseProductName() {
return "MySQL";
}
@Override
public Integer getDefaultPort() {
return 3306;
}
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
@Override
public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException {
// If it looks like a MySQL, swims like a MySQL and quacks like a MySQL,
// it may still not be a MySQL, but a MariaDB.
return (
(PRODUCT_NAME.equalsIgnoreCase(conn.getDatabaseProductName()))
&& (!conn.getDatabaseProductVersion().toLowerCase().contains("mariadb") &&
!conn.getDatabaseProductVersion().toLowerCase().contains("clustrix"))
);
}
@Override
public String getDefaultDriver(String url) {
if (url != null && url.toLowerCase().startsWith("jdbc:mysql")) {
String cjDriverClassName = "com.mysql.cj.jdbc.Driver";
try {
//make sure we don't have an old jdbc driver that doesn't have this class
Class.forName(cjDriverClassName);
return cjDriverClassName;
} catch (ClassNotFoundException e) {
//
// Try to load the class again with the current thread classloader
//
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
Class.forName(cjDriverClassName, true, cl);
return cjDriverClassName;
} catch (ClassNotFoundException cnfe) {
return "com.mysql.jdbc.Driver";
}
}
}
return null;
}
@Override
public boolean supportsSequences() {
return false;
}
@Override
public boolean supportsInitiallyDeferrableColumns() {
return false;
}
@Override
protected boolean mustQuoteObjectName(String objectName, Class<? extends DatabaseObject> objectType) {
return super.mustQuoteObjectName(objectName, objectType) || (!objectName.contains("(") && !objectName.matches("\\w+"));
}
@Override
public String getLineComment() {
return "-- ";
}
@Override
protected String getAutoIncrementClause() {
return "AUTO_INCREMENT";
}
@Override
protected boolean generateAutoIncrementStartWith(final BigInteger startWith) {
// startWith not supported here. StartWith has to be set as table option.
return false;
}
public String getTableOptionAutoIncrementStartWithClause(BigInteger startWith) {
String startWithClause = String.format(getAutoIncrementStartWithClause(), (startWith == null) ? defaultAutoIncrementStartWith : startWith);
return getAutoIncrementClause() + startWithClause;
}
@Override
protected boolean generateAutoIncrementBy(BigInteger incrementBy) {
// incrementBy not supported
return false;
}
@Override
protected String getAutoIncrementOpening() {
return "";
}
@Override
protected String getAutoIncrementClosing() {
return "";
}
@Override
protected String getAutoIncrementStartWithClause() {
return "=%d";
}
@Override
public String getConcatSql(String... values) {
StringBuilder returnString = new StringBuilder();
returnString.append("CONCAT_WS(");
for (String value : values) {
returnString.append(value).append(", ");
}
return returnString.toString().replaceFirst(", $", ")");
}
@Override
public boolean supportsTablespaces() {
return false;
}
@Override
public boolean supportsSchemas() {
return false;
}
@Override
public boolean supportsCatalogs() {
return true;
}
@Override
public String escapeIndexName(String catalogName, String schemaName, String indexName) {
return escapeObjectName(indexName, Index.class);
}
@Override
public boolean supportsForeignKeyDisable() {
return true;
}
@Override
public boolean disableForeignKeyChecks() throws DatabaseException {
boolean enabled = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", this).queryForInt(new RawSqlStatement("SELECT @@FOREIGN_KEY_CHECKS")) == 1;
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", this).execute(new RawSqlStatement("SET FOREIGN_KEY_CHECKS=0"));
return enabled;
}
@Override
public void enableForeignKeyChecks() throws DatabaseException {
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", this).execute(new RawSqlStatement("SET FOREIGN_KEY_CHECKS=1"));
}
@Override
public CatalogAndSchema getSchemaFromJdbcInfo(String rawCatalogName, String rawSchemaName) {
return new CatalogAndSchema(rawCatalogName, null).customize(this);
}
@Override
public String escapeStringForDatabase(String string) {
string = super.escapeStringForDatabase(string);
if (string == null) {
return null;
}
return string.replace("\\", "\\\\");
}
@Override
public boolean createsIndexesForForeignKeys() {
return true;
}
@Override
public boolean isReservedWord(String string) {
if (RESERVED_WORDS.contains(string.toUpperCase())) {
return true;
}
return super.isReservedWord(string);
}
public int getDatabasePatchVersion() throws DatabaseException {
String databaseProductVersion = this.getDatabaseProductVersion();
if (databaseProductVersion == null) {
return 0;
}
String versionStrings[] = databaseProductVersion.split("\\.");
try {
return Integer.parseInt(versionStrings[2].replaceFirst("\\D.*", ""));
} catch (IndexOutOfBoundsException | NumberFormatException e) {
return 0;
}
}
@Override
public int getMaxFractionalDigitsForTimestamp() {
int major = 0;
int minor = 0;
int patch = 0;
try {
major = getDatabaseMajorVersion();
minor = getDatabaseMinorVersion();
patch = getDatabasePatchVersion();
} catch (DatabaseException x) {
Scope.getCurrentScope().getLog(getClass()).warning(
"Unable to determine exact database server version"
+ " - specified TIMESTAMP precision"
+ " will not be set: ", x);
return 0;
}
String minimumVersion = getMinimumVersionForFractionalDigitsForTimestamp();
if (StringUtil.isMinimumVersion(minimumVersion, major, minor, patch))
return 6;
else
return 0;
}
/**
*
* Check to see if this instance of a MySQL database is equal to or greater
* than the specified version
*
* @param minimumVersion
* @return boolean
*
*/
public boolean isMinimumMySQLVersion(String minimumVersion) {
int major = 0;
int minor = 0;
int patch = 0;
try {
major = getDatabaseMajorVersion();
minor = getDatabaseMinorVersion();
patch = getDatabasePatchVersion();
} catch (DatabaseException x) {
Scope.getCurrentScope().getLog(getClass()).warning(
"Unable to determine exact database server version");
return false;
}
return StringUtil.isMinimumVersion(minimumVersion, major, minor, patch);
}
protected String getMinimumVersionForFractionalDigitsForTimestamp() {
// MySQL 5.6.4 introduced fractional support...
// https://dev.mysql.com/doc/refman/5.7/en/data-types.html
return "5.6.4";
}
@Override
protected String getQuotingStartCharacter() {
return "`"; // objects in mysql are always case sensitive
}
@Override
protected String getQuotingEndCharacter() {
return "`"; // objects in mysql are always case sensitive
}
/**
* <p>Returns the default timestamp fractional digits if nothing is specified.</p>
* https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html :
* "The fsp value, if given, must be in the range 0 to 6. A value of 0 signifies that there is no fractional part.
* If omitted, the default precision is 0. (This differs from the STANDARD SQL default of 6, for compatibility
* with previous MySQL versions.)"
*
* @return always 0
*/
@Override
public int getDefaultFractionalDigitsForTimestamp() {
return 0;
}
/*
* list from http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
*/
private static Set<String> createReservedWords() {
return new HashSet<String>(Arrays.asList("ACCESSIBLE",
"ADD",
"ADMIN",
"ALL",
"ALTER",
"ANALYZE",
"AND",
"AS",
"ASC",
"ASENSITIVE",
"BEFORE",
"BETWEEN",
"BIGINT",
"BINARY",
"BLOB",
"BOTH",
"BUCKETS",
"BY",
"CALL",
"CASCADE",
"CASE",
"CHANGE",
"CHAR",
"CHARACTER",
"CHECK",
"COLLATE",
"COLUMN",
"CONDITION",
"CONSTRAINT",
"CONTINUE",
"CONVERT",
"CREATE",
"CROSS",
"CLONE",
"COMPONENT",
"CUBE",
"CUME_DIST",
"CURRENT_DATE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_USER",
"CURSOR",
"DATABASE",
"DATABASES",
"DAY_HOUR",
"DAY_MICROSECOND",
"DAY_MINUTE",
"DAY_SECOND",
"DEC",
"DECIMAL",
"DECLARE",
"DEFAULT",
"DEFINITION",
"DELAYED",
"DELETE",
"DENSE_RANK",
"DESC",
"DESCRIBE",
"DESCRIPTION",
"DETERMINISTIC",
"DISTINCT",
"DISTINCTROW",
"DIV",
"DOUBLE",
"DROP",
"DUAL",
"EACH",
"ELSE",
"ELSEIF",
"EMPTY",
"ENCLOSED",
"ESCAPED",
"EXCEPT",
"EXCLUDE",
"EXISTS",
"EXIT",
"EXPLAIN",
"FALSE",
"FETCH",
"FIRST_VALUE",
"FLOAT",
"FLOAT4",
"FLOAT8",
"FOLLOWING",
"FOR",
"FORCE",
"FOREIGN",
"FROM",
"FULLTEXT",
"GEOMCOLLECTION",
"GENERATED",
"GET",
"GET_MASTER_PUBLIC_KEY",
"GRANT",
"GROUP",
"GROUPING",
"GROUPS",
"HAVING",
"HIGH_PRIORITY",
"HISTOGRAM",
"HISTORY",
"HOUR_MICROSECOND",
"HOUR_MINUTE",
"HOUR_SECOND",
"IF",
"IGNORE",
"IN",
"INDEX",
"INFILE",
"INNER",
"INOUT",
"INSENSITIVE",
"INSERT",
"INT",
"INT1",
"INT2",
"INT3",
"INT4",
"INT8",
"INTEGER",
"INTERVAL",
"INTO",
"IS",
"ITERATE",
"INVISIBLE",
"JOIN",
"JSON_TABLE",
"KEY",
"KEYS",
"KILL",
"LAG",
"LAST_VALUE",
"LEAD",
"LEADING",
"LEAVE",
"LEFT",
"LIKE",
"LIMIT",
"LINEAR",
"LINES",
"LOAD",
"LOCALTIME",
"LOCALTIMESTAMP",
"LOCK",
"LOCKED",
"LONG",
"LONGBLOB",
"LONGTEXT",
"LOOP",
"LOW_PRIORITY",
"MASTER_PUBLIC_KEY_PATH",
"MASTER_SSL_VERIFY_SERVER_CERT",
"MATCH",
"MAXVALUE",
"MEDIUMBLOB",
"MEDIUMINT",
"MEDIUMTEXT",
"MIDDLEINT",
"MINUTE_MICROSECOND",
"MINUTE_SECOND",
"MOD",
"MODIFIES",
"NATURAL",
"NESTED",
"NOT",
"NOWAIT",
"NO_WRITE_TO_BINLOG",
"NTH_VALUE",
"NTILE",
"NULL",
"NULLS",
"NUMERIC",
"OF",
"ON",
"OPTIMIZE",
"OPTIMIZER_COSTS",
"OPTION",
"OPTIONALLY",
"OR",
"ORDER",
"ORDINALITY",
"ORGANIZATION",
"OUT",
"OUTER",
"OUTFILE",
"OTHERS",
"OVER",
"PARTITION",
"PATH",
"PERCENT_RANK",
"PERSIST",
"PERSIST_ONLY",
"PRECEDING",
"PRECISION",
"PRIMARY",
"PROCEDURE",
"PROCESS",
"PURGE",
"RANGE",
"RANK",
"READ",
"READS",
"READ_WRITE",
"REAL",
"RECURSIVE",
"REFERENCE",
"REFERENCES",
"REGEXP",
"RELEASE",
"REMOTE",
"RENAME",
"REPEAT",
"REPLACE",
"REQUIRE",
"RESIGNAL",
"RESOURCE",
"RESPECT",
"RESTART",
"RESTRICT",
"RETURN",
"REUSE",
"REVOKE",
"RIGHT",
"RLIKE",
"ROLE",
"ROW_NUMBER",
"SCHEMA",
"SCHEMAS",
"SECOND_MICROSECOND",
"SELECT",
"SENSITIVE",
"SEPARATOR",
"SET",
"SHOW",
"SIGNAL",
"SKIP",
"SMALLINT",
"SPATIAL",
"SPECIFIC",
"SQL",
"SQLEXCEPTION",
"SQLSTATE",
"SQLWARNING",
"SQL_BIG_RESULT",
"SQL_CALC_FOUND_ROWS",
"SQL_SMALL_RESULT",
"SRID",
"SSL",
"STARTING",
"STORED",
"STRAIGHT_JOIN",
"SYSTEM",
"TABLE",
"TERMINATED",
"THEN",
"THREAD_PRIORITY",
"TIES",
"TINYBLOB",
"TINYINT",
"TINYTEXT",
"TO",
"TRAILING",
"TRIGGER",
"TRUE",
"UNBOUNDED",
"UNDO",
"UNION",
"UNIQUE",
"UNLOCK",
"UNSIGNED",
"UPDATE",
"USAGE",
"USE",
"USING",
"UTC_DATE",
"UTC_TIME",
"UTC_TIMESTAMP",
"VALUES",
"VARBINARY",
"VARCHAR",
"VARCHARACTER",
"VARYING",
"VCPU",
"VISIBLE",
"VIRTUAL",
"WHEN",
"WHERE",
"WHILE",
"WINDOW",
"WITH",
"WRITE",
"XOR",
"YEAR_MONTH",
"ZEROFILL"
));
}
protected String getCurrentDateTimeFunction(int precision) {
return currentDateTimeFunction.replace("()", "("+precision+")");
}
@Override
public String generateDatabaseFunctionValue(DatabaseFunction databaseFunction) {
if (databaseFunction.getValue() != null && isCurrentTimeFunction(databaseFunction.getValue().toLowerCase())) {
int precision = extractPrecision(databaseFunction);
return precision != 0 ? getCurrentDateTimeFunction(precision) : getCurrentDateTimeFunction();
}
return super.generateDatabaseFunctionValue(databaseFunction);
}
private int extractPrecision(DatabaseFunction databaseFunction) {
int precision = 0;
Matcher precisionMatcher = PRECISION_PATTERN.matcher(databaseFunction.getValue());
if (precisionMatcher.find()) {
precision = Integer.parseInt(precisionMatcher.group().replaceAll("[(,)]", ""));
}
return precision;
}
public void warnAboutAlterColumn(String changeName, Warnings warnings ) {
warnings.addWarning("Due to " + this.getShortName() + " SQL limitations, " + changeName + " will lose primary key/autoincrement/not null/comment settings explicitly redefined in the change. Use <sql> or <modifySql> to re-specify all configuration if this is the case");
}
}