/
MariaDbDatabaseMetaData.java
3943 lines (3674 loc) · 146 KB
/
MariaDbDatabaseMetaData.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 java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PseudoColumnUsage;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.mariadb.jdbc.internal.ColumnType;
import org.mariadb.jdbc.internal.com.read.resultset.ColumnInformation;
import org.mariadb.jdbc.internal.com.read.resultset.SelectResultSet;
import org.mariadb.jdbc.internal.io.input.StandardPacketInputStream;
import org.mariadb.jdbc.internal.util.Options;
import org.mariadb.jdbc.internal.util.Utils;
import org.mariadb.jdbc.internal.util.constant.Version;
import org.mariadb.jdbc.internal.util.dao.Identifier;
public class MariaDbDatabaseMetaData implements DatabaseMetaData {
public static final String DRIVER_NAME = "MariaDB Connector/J";
private final MariaDbConnection connection;
private final UrlParser urlParser;
private boolean datePrecisionColumnExist = true;
/**
* Constructor.
*
* @param connection connection
* @param urlParser Url parser
*/
public MariaDbDatabaseMetaData(Connection connection, UrlParser urlParser) {
this.connection = (MariaDbConnection) connection;
this.urlParser = urlParser;
}
private static String columnTypeClause(Options options) {
String upperCaseWithoutSize =
" UCASE(IF( COLUMN_TYPE LIKE '%(%)%', CONCAT(SUBSTRING( COLUMN_TYPE,1, LOCATE('(',"
+ "COLUMN_TYPE) - 1 ), SUBSTRING(COLUMN_TYPE ,1+locate(')', COLUMN_TYPE))), "
+ "COLUMN_TYPE))";
if (options.tinyInt1isBit) {
upperCaseWithoutSize =
" IF(COLUMN_TYPE like 'tinyint(1)%', 'BIT', " + upperCaseWithoutSize + ")";
}
if (!options.yearIsDateType) {
return " IF(COLUMN_TYPE IN ('year(2)', 'year(4)'), 'SMALLINT', " + upperCaseWithoutSize + ")";
}
return upperCaseWithoutSize;
}
// Extract identifier quoted string from input String.
// Return new position, or -1 on error
private static int skipWhite(char[] part, int startPos) {
for (int i = startPos; i < part.length; i++) {
if (!Character.isWhitespace(part[i])) {
return i;
}
}
return part.length;
}
private static int parseIdentifier(char[] part, int startPos, Identifier identifier)
throws ParseException {
int pos = skipWhite(part, startPos);
if (part[pos] != '`') {
throw new ParseException(new String(part), pos);
}
pos++;
StringBuilder sb = new StringBuilder();
int quotes = 0;
for (; pos < part.length; pos++) {
char ch = part[pos];
if (ch == '`') {
quotes++;
} else {
for (int j = 0; j < quotes / 2; j++) {
sb.append('`');
}
if (quotes % 2 == 1) {
if (ch == '.') {
if (identifier.schema != null) {
throw new ParseException(new String(part), pos);
}
identifier.schema = sb.toString();
return parseIdentifier(part, pos + 1, identifier);
}
identifier.name = sb.toString();
return pos;
}
quotes = 0;
sb.append(ch);
}
}
throw new ParseException(new String(part), startPos);
}
private static int parseIdentifierList(char[] part, int startPos, List<Identifier> list)
throws ParseException {
int pos = skipWhite(part, startPos);
if (part[pos] != '(') {
throw new ParseException(new String(part), pos);
}
pos++;
for (; ; ) {
pos = skipWhite(part, pos);
char ch = part[pos];
switch (ch) {
case ')':
return pos + 1;
case '`':
Identifier id = new Identifier();
pos = parseIdentifier(part, pos, id);
list.add(id);
break;
case ',':
pos++;
break;
default:
throw new ParseException(new String(part, startPos, part.length - startPos), startPos);
}
}
}
private static int skipKeyword(char[] part, int startPos, String keyword) throws ParseException {
int pos = skipWhite(part, startPos);
for (int i = 0; i < keyword.length(); i++, pos++) {
if (part[pos] != keyword.charAt(i)) {
throw new ParseException(new String(part), pos);
}
}
return pos;
}
private static int getImportedKeyAction(String actionKey) {
if (actionKey == null) {
return DatabaseMetaData.importedKeyRestrict;
}
switch (actionKey) {
case "NO ACTION":
return DatabaseMetaData.importedKeyNoAction;
case "CASCADE":
return DatabaseMetaData.importedKeyCascade;
case "SET NULL":
return DatabaseMetaData.importedKeySetNull;
case "SET DEFAULT":
return DatabaseMetaData.importedKeySetDefault;
case "RESTRICT":
return DatabaseMetaData.importedKeyRestrict;
default:
throw new IllegalArgumentException("Illegal key action '" + actionKey + "' specified.");
}
}
/**
* Get imported keys.
*
* @param tableDef table definition
* @param tableName table name
* @param catalog catalog
* @param connection connection
* @return resultset resultset
* @throws ParseException exception
*/
private static ResultSet getImportedKeys(
String tableDef, String tableName, String catalog, MariaDbConnection connection)
throws ParseException {
String[] columnNames = {
"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME",
"PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM",
"FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
"UPDATE_RULE", "DELETE_RULE", "FK_NAME",
"PK_NAME", "DEFERRABILITY"
};
ColumnType[] columnTypes = {
ColumnType.VARCHAR, ColumnType.NULL, ColumnType.VARCHAR,
ColumnType.VARCHAR, ColumnType.VARCHAR, ColumnType.NULL,
ColumnType.VARCHAR, ColumnType.VARCHAR, ColumnType.SMALLINT,
ColumnType.SMALLINT, ColumnType.SMALLINT, ColumnType.VARCHAR,
ColumnType.NULL, ColumnType.SMALLINT
};
String[] parts = tableDef.split("\n");
List<String[]> data = new ArrayList<>();
for (String part : parts) {
part = part.trim();
if (!part.startsWith("CONSTRAINT") && !part.contains("FOREIGN KEY")) {
continue;
}
char[] partChar = part.toCharArray();
Identifier constraintName = new Identifier();
int pos = skipKeyword(partChar, 0, "CONSTRAINT");
pos = parseIdentifier(partChar, pos, constraintName);
pos = skipKeyword(partChar, pos, "FOREIGN KEY");
List<Identifier> foreignKeyCols = new ArrayList<>();
pos = parseIdentifierList(partChar, pos, foreignKeyCols);
pos = skipKeyword(partChar, pos, "REFERENCES");
Identifier pkTable = new Identifier();
pos = parseIdentifier(partChar, pos, pkTable);
List<Identifier> primaryKeyCols = new ArrayList<>();
parseIdentifierList(partChar, pos, primaryKeyCols);
if (primaryKeyCols.size() != foreignKeyCols.size()) {
throw new ParseException(tableDef, 0);
}
int onUpdateReferenceAction = DatabaseMetaData.importedKeyRestrict;
int onDeleteReferenceAction = DatabaseMetaData.importedKeyRestrict;
for (String referenceAction : new String[] {"RESTRICT", "CASCADE", "SET NULL", "NO ACTION"}) {
if (part.contains("ON UPDATE " + referenceAction)) {
onUpdateReferenceAction = getImportedKeyAction(referenceAction);
}
if (part.contains("ON DELETE " + referenceAction)) {
onDeleteReferenceAction = getImportedKeyAction(referenceAction);
}
}
for (int i = 0; i < primaryKeyCols.size(); i++) {
String[] row = new String[columnNames.length];
row[0] = pkTable.schema;
if (row[0] == null) {
row[0] = catalog;
}
row[1] = null;
row[2] = pkTable.name;
row[3] = primaryKeyCols.get(i).name;
row[4] = catalog;
row[5] = null;
row[6] = tableName;
row[7] = foreignKeyCols.get(i).name;
row[8] = Integer.toString(i + 1);
row[9] = Integer.toString(onUpdateReferenceAction);
row[10] = Integer.toString(onDeleteReferenceAction);
row[11] = constraintName.name;
row[12] = null;
row[13] = Integer.toString(DatabaseMetaData.importedKeyNotDeferrable);
data.add(row);
}
}
String[][] arr = data.toArray(new String[0][]);
/* Sort array by PKTABLE_CAT, PKTABLE_NAME, and KEY_SEQ.*/
Arrays.sort(
arr,
(row1, row2) -> {
int result = row1[0].compareTo(row2[0]); // PKTABLE_CAT
if (result == 0) {
result = row1[2].compareTo(row2[2]); // PKTABLE_NAME
if (result == 0) {
result = row1[8].length() - row2[8].length(); // KEY_SEQ
if (result == 0) {
result = row1[8].compareTo(row2[8]);
}
}
}
return result;
});
return SelectResultSet.createResultSet(columnNames, columnTypes, arr, connection.getProtocol());
}
/**
* Retrieves a description of the primary key columns that are referenced by the given table's
* foreign key columns (the primary keys imported by a table). They are ordered by PKTABLE_CAT,
* PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ.
*
* <p>Each primary key column description has the following columns:
*
* <OL>
* <LI><B>PKTABLE_CAT</B> String {@code =>} primary key table catalog being imported (may be
* <code>null</code>)
* <LI><B>PKTABLE_SCHEM</B> String {@code =>} primary key table schema being imported (may be
* <code>null</code>)
* <LI><B>PKTABLE_NAME</B> String {@code =>} primary key table name being imported
* <LI><B>PKCOLUMN_NAME</B> String {@code =>} primary key column name being imported
* <LI><B>FKTABLE_CAT</B> String {@code =>} foreign key table catalog (may be <code>null</code>)
* <LI><B>FKTABLE_SCHEM</B> String {@code =>} foreign key table schema (may be <code>null</code>
* )
* <LI><B>FKTABLE_NAME</B> String {@code =>} foreign key table name
* <LI><B>FKCOLUMN_NAME</B> String {@code =>} foreign key column name
* <LI><B>KEY_SEQ</B> short {@code =>} sequence number within a foreign key( a value of 1
* represents the first column of the foreign key, a value of 2 would represent the second
* column within the foreign key).
* <LI><B>UPDATE_RULE</B> short {@code =>} What happens to a foreign key when the primary key is
* updated:
* <UL>
* <LI>importedNoAction - do not allow update of primary key if it has been imported
* <LI>importedKeyCascade - change imported key to agree with primary key update
* <LI>importedKeySetNull - change imported key to <code>NULL</code> if its primary key
* has been updated
* <LI>importedKeySetDefault - change imported key to default values if its primary key
* has been updated
* <LI>importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
* </UL>
* <LI><B>DELETE_RULE</B> short {@code =>} What happens to the foreign key when primary is
* deleted.
* <UL>
* <LI>importedKeyNoAction - do not allow delete of primary key if it has been imported
* <LI>importedKeyCascade - delete rows that import a deleted key
* <LI>importedKeySetNull - change imported key to NULL if its primary key has been
* deleted
* <LI>importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
* <LI>importedKeySetDefault - change imported key to default if its primary key has been
* deleted
* </UL>
* <LI><B>FK_NAME</B> String {@code =>} foreign key name (may be <code>null</code>)
* <LI><B>PK_NAME</B> String {@code =>} primary key name (may be <code>null</code>)
* <LI><B>DEFERRABILITY</B> short {@code =>} can the evaluation of foreign key constraints be
* deferred until commit
* <UL>
* <LI>importedKeyInitiallyDeferred - see SQL92 for definition
* <LI>importedKeyInitiallyImmediate - see SQL92 for definition
* <LI>importedKeyNotDeferrable - see SQL92 for definition
* </UL>
* </OL>
*
* @param catalog a catalog name; must match the catalog name as it is stored in the database; ""
* retrieves those without a catalog; <code>null</code> means that the catalog name should not
* be used to narrow the search
* @param schema a schema name; must match the schema name as it is stored in the database; ""
* retrieves those without a schema; <code>null</code> means that the schema name should not
* be used to narrow the search
* @param table a table name; must match the table name as it is stored in the database
* @return <code>ResultSet</code> - each row is a primary key column description
* @throws SQLException if a database access error occurs
* @see #getExportedKeys
*/
public ResultSet getImportedKeys(String catalog, String schema, String table)
throws SQLException {
String database = catalog;
// We avoid using information schema queries by default, because this appears to be an expensive
// query (CONJ-41).
if (table == null) {
throw new SQLException("'table' parameter in getImportedKeys cannot be null");
}
if (database == null && connection.nullCatalogMeansCurrent) {
/* Treat null catalog as current */
return getImportedKeysUsingInformationSchema("", table);
}
if (database == null) {
return getImportedKeysUsingInformationSchema(null, table);
}
if (database.isEmpty()) {
database = connection.getCatalog();
if (database == null || database.isEmpty()) {
return getImportedKeysUsingInformationSchema(database, table);
}
}
try {
return getImportedKeysUsingShowCreateTable(database, table);
} catch (Exception e) {
// Likely, parsing failed, try out I_S query.
return getImportedKeysUsingInformationSchema(database, table);
}
}
private String dataTypeClause(String fullTypeColumnName) {
Options options = urlParser.getOptions();
return " CASE data_type"
+ " WHEN 'bit' THEN "
+ Types.BIT
+ " WHEN 'tinyblob' THEN "
+ Types.VARBINARY
+ " WHEN 'mediumblob' THEN "
+ Types.LONGVARBINARY
+ " WHEN 'longblob' THEN "
+ Types.LONGVARBINARY
+ " WHEN 'blob' THEN "
+ Types.LONGVARBINARY
+ " WHEN 'tinytext' THEN "
+ Types.VARCHAR
+ " WHEN 'mediumtext' THEN "
+ Types.LONGVARCHAR
+ " WHEN 'longtext' THEN "
+ Types.LONGVARCHAR
+ " WHEN 'text' THEN "
+ Types.LONGVARCHAR
+ " WHEN 'date' THEN "
+ Types.DATE
+ " WHEN 'datetime' THEN "
+ Types.TIMESTAMP
+ " WHEN 'decimal' THEN "
+ Types.DECIMAL
+ " WHEN 'double' THEN "
+ Types.DOUBLE
+ " WHEN 'enum' THEN "
+ Types.VARCHAR
+ " WHEN 'float' THEN "
+ Types.REAL
+ " WHEN 'int' THEN IF( "
+ fullTypeColumnName
+ " like '%unsigned%', "
+ Types.INTEGER
+ ","
+ Types.INTEGER
+ ")"
+ " WHEN 'bigint' THEN "
+ Types.BIGINT
+ " WHEN 'mediumint' THEN "
+ Types.INTEGER
+ " WHEN 'null' THEN "
+ Types.NULL
+ " WHEN 'set' THEN "
+ Types.VARCHAR
+ " WHEN 'smallint' THEN IF( "
+ fullTypeColumnName
+ " like '%unsigned%', "
+ Types.SMALLINT
+ ","
+ Types.SMALLINT
+ ")"
+ " WHEN 'varchar' THEN "
+ Types.VARCHAR
+ " WHEN 'varbinary' THEN "
+ Types.VARBINARY
+ " WHEN 'char' THEN "
+ Types.CHAR
+ " WHEN 'binary' THEN "
+ Types.BINARY
+ " WHEN 'time' THEN "
+ Types.TIME
+ " WHEN 'timestamp' THEN "
+ Types.TIMESTAMP
+ " WHEN 'tinyint' THEN "
+ (options.tinyInt1isBit
? "IF("
+ fullTypeColumnName
+ " like 'tinyint(1)%',"
+ Types.BIT
+ ","
+ Types.TINYINT
+ ") "
: Types.TINYINT)
+ " WHEN 'year' THEN "
+ (options.yearIsDateType ? Types.DATE : Types.SMALLINT)
+ " ELSE "
+ Types.OTHER
+ " END ";
}
private ResultSet executeQuery(String sql) throws SQLException {
Statement stmt =
new MariaDbStatement(connection, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
SelectResultSet rs = (SelectResultSet) stmt.executeQuery(sql);
rs.setStatement(null); // bypass Hibernate statement tracking (CONJ-49)
rs.setForceTableAlias();
return rs;
}
private String escapeQuote(String value) {
if (value == null) {
return "NULL";
}
return "'" + Utils.escapeString(value, connection.getProtocol().noBackslashEscapes()) + "'";
}
/**
* Generate part of the information schema query that restricts catalog names In the driver,
* catalogs is the equivalent to MariaDB schemas.
*
* @param columnName - column name in the information schema table
* @param catalog - catalog name. This driver does not (always) follow JDBC standard for following
* special values, due to ConnectorJ compatibility 1. empty string ("") - matches current
* catalog (i.e database). JDBC standard says only tables without catalog should be returned -
* such tables do not exist in MariaDB. If there is no current catalog, then empty string
* matches any catalog. 2. null - if nullCatalogMeansCurrent=true (which is the default), then
* the handling is the same as for "" . i.e return current catalog.JDBC-conforming way would
* be to match any catalog with null parameter. This can be switched with
* nullCatalogMeansCurrent=false in the connection URL.
* @return part of SQL query ,that restricts search for the catalog.
*/
private String catalogCond(String columnName, String catalog) {
if (catalog == null) {
/* Treat null catalog as current */
if (connection.nullCatalogMeansCurrent) {
return "(ISNULL(database()) OR (" + columnName + " = database()))";
}
return "(1 = 1)";
}
if (catalog.isEmpty()) {
return "(ISNULL(database()) OR (" + columnName + " = database()))";
}
return "(" + columnName + " = " + escapeQuote(catalog) + ")";
}
// Helper to generate information schema queries with "like" or "equals" condition (typically on
// table name)
private String patternCond(String columnName, String tableName) {
if (tableName == null) {
return "(1 = 1)";
}
String predicate =
(tableName.indexOf('%') == -1 && tableName.indexOf('_') == -1) ? "=" : "LIKE";
return "(" + columnName + " " + predicate + " '" + Utils.escapeString(tableName, true) + "')";
}
/**
* Retrieves a description of the given table's primary key columns. They are ordered by
* COLUMN_NAME.
*
* <p>Each primary key column description has the following columns:
*
* <OL>
* <li><B>TABLE_CAT</B> String {@code =>} table catalog
* <li><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
* <li><B>TABLE_NAME</B> String {@code =>} table name
* <li><B>COLUMN_NAME</B> String {@code =>} column name
* <li><B>KEY_SEQ</B> short {@code =>} sequence number within primary key( a value of 1
* represents the first column of the primary key, a value of 2 would represent the second
* column within the primary key).
* <li><B>PK_NAME</B> String {@code =>} primary key name
* </OL>
*
* @param catalog a catalog name; must match the catalog name as it is stored in the database; ""
* retrieves those without a catalog; <code>null</code> means that the catalog name should not
* be used to narrow the search
* @param schema a schema name; must match the schema name as it is stored in the database; ""
* retrieves those without a schema; <code>null</code> means that the schema name should not
* be used to narrow the search
* @param table a table name; must match the table name as it is stored in the database
* @return <code>ResultSet</code> - each row is a primary key column description
* @throws SQLException if a database access error occurs
*/
public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
// MySQL 8 now use 'PRI' in place of 'pri'
String sql =
"SELECT A.TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, A.TABLE_NAME, A.COLUMN_NAME, B.SEQ_IN_INDEX KEY_SEQ, B.INDEX_NAME PK_NAME "
+ " FROM INFORMATION_SCHEMA.COLUMNS A, INFORMATION_SCHEMA.STATISTICS B"
+ " WHERE A.COLUMN_KEY in ('PRI','pri') AND B.INDEX_NAME='PRIMARY' "
+ " AND "
+ catalogCond("A.TABLE_SCHEMA", catalog)
+ " AND "
+ catalogCond("B.TABLE_SCHEMA", catalog)
+ " AND "
+ patternCond("A.TABLE_NAME", table)
+ " AND "
+ patternCond("B.TABLE_NAME", table)
+ " AND A.TABLE_SCHEMA = B.TABLE_SCHEMA AND A.TABLE_NAME = B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME "
+ " ORDER BY A.COLUMN_NAME";
return executeQuery(sql);
}
/**
* Maps standard table types to MariaDB ones - helper since table type is never "table" in
* MariaDB, it is "base table".
*
* @param tableType the table type defined by user
* @return the internal table type.
*/
private String mapTableTypes(String tableType) {
if ("TABLE".equals(tableType)) {
return "BASE TABLE";
}
return tableType;
}
/**
* Retrieves a description of the tables available in the given catalog. Only table descriptions
* matching the catalog, schema, table name and type criteria are returned. They are ordered by
* <code>TABLE_TYPE</code>, <code>TABLE_CAT</code>, <code>TABLE_SCHEM</code> and <code>TABLE_NAME
* </code>. Each table description has the following columns:
*
* <OL>
* <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
* <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
* <LI><B>TABLE_NAME</B> String {@code =>} table name
* <LI><B>TABLE_TYPE</B> String {@code =>} table type. Typical types are "TABLE", "VIEW",
* "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
* <LI><B>REMARKS</B> String {@code =>} explanatory comment on the table
* <LI><B>TYPE_CAT</B> String {@code =>} the types catalog (may be <code>null</code>)
* <LI><B>TYPE_SCHEM</B> String {@code =>} the types schema (may be <code>null</code>)
* <LI><B>TYPE_NAME</B> String {@code =>} type name (may be <code>null</code>)
* <LI><B>SELF_REFERENCING_COL_NAME</B> String {@code =>} name of the designated "identifier"
* column of a typed table (may be <code>null</code>)
* <LI><B>REF_GENERATION</B> String {@code =>} specifies how values in SELF_REFERENCING_COL_NAME
* are created. Values are "SYSTEM", "USER", "DERIVED". (may be <code>null</code>)
* </OL>
*
* <p><B>Note:</B> Some databases may not return information for all tables.
*
* @param catalog a catalog name; must match the catalog name as it is stored in the database; ""
* retrieves those without a catalog; <code>null</code> means that the catalog name should not
* be used to narrow the search
* @param schemaPattern a schema name pattern; must match the schema name as it is stored in the
* database; "" retrieves those without a schema; <code>null</code> means that the schema name
* should not be used to narrow the search
* @param tableNamePattern a table name pattern; must match the table name as it is stored in the
* database
* @param types a list of table types, which must be from the list of table types returned from
* {@link #getTableTypes},to include; <code>null</code> returns all types
* @return <code>ResultSet</code> - each row is a table description
* @throws SQLException if a database access error occurs
* @see #getSearchStringEscape
*/
public ResultSet getTables(
String catalog, String schemaPattern, String tableNamePattern, String[] types)
throws SQLException {
StringBuilder sql =
new StringBuilder(
"SELECT TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, TABLE_NAME,"
+ " IF(TABLE_TYPE='BASE TABLE', 'TABLE', TABLE_TYPE) as TABLE_TYPE,"
+ " TABLE_COMMENT REMARKS, NULL TYPE_CAT, NULL TYPE_SCHEM, NULL TYPE_NAME, NULL SELF_REFERENCING_COL_NAME, "
+ " NULL REF_GENERATION"
+ " FROM INFORMATION_SCHEMA.TABLES "
+ " WHERE "
+ catalogCond("TABLE_SCHEMA", catalog)
+ " AND "
+ patternCond("TABLE_NAME", tableNamePattern));
if (types != null && types.length > 0) {
sql.append(" AND TABLE_TYPE IN (");
for (int i = 0; i < types.length; i++) {
if (types[i] == null) {
continue;
}
String type = escapeQuote(mapTableTypes(types[i]));
if (i == types.length - 1) {
sql.append(type).append(")");
} else {
sql.append(type).append(",");
}
}
}
sql.append(" ORDER BY TABLE_TYPE, TABLE_SCHEMA, TABLE_NAME");
return executeQuery(sql.toString());
}
/**
* Retrieves a description of table columns available in the specified catalog.
*
* <p>Only column descriptions matching the catalog, schema, table and column name criteria are
* returned. They are ordered by <code>TABLE_CAT</code>,<code>TABLE_SCHEM</code>, <code>TABLE_NAME
* </code>, and <code>ORDINAL_POSITION</code>.
*
* <p>Each column description has the following columns:
*
* <OL>
* <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
* <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
* <LI><B>TABLE_NAME</B> String {@code =>} table name
* <LI><B>COLUMN_NAME</B> String {@code =>} column name
* <LI><B>DATA_TYPE</B> int {@code =>} SQL type from java.sql.Types
* <LI><B>TYPE_NAME</B> String {@code =>} Data source dependent type name, for a UDT the type
* name is fully qualified
* <LI><B>COLUMN_SIZE</B> int {@code =>} column size.
* <LI><B>BUFFER_LENGTH</B> is not used.
* <LI><B>DECIMAL_DIGITS</B> int {@code =>} the number of fractional digits. Null is returned
* for data types where DECIMAL_DIGITS is not applicable.
* <LI><B>NUM_PREC_RADIX</B> int {@code =>} Radix (typically either 10 or 2)
* <LI><B>NULLABLE</B> int {@code =>} is NULL allowed.
* <UL>
* <LI>columnNoNulls - might not allow <code>NULL</code> values
* <LI>columnNullable - definitely allows <code>NULL</code> values
* <LI>columnNullableUnknown - nullability unknown
* </UL>
* <LI><B>REMARKS</B> String {@code =>} comment describing column (may be <code>null</code>)
* <LI><B>COLUMN_DEF</B> String {@code =>} default value for the column, which should be
* interpreted as a string when the value is enclosed in single quotes (may be <code>null
* </code>)
* <LI><B>SQL_DATA_TYPE</B> int {@code =>} unused
* <LI><B>SQL_DATETIME_SUB</B> int {@code =>} unused
* <LI><B>CHAR_OCTET_LENGTH</B> int {@code =>} for char types the maximum number of bytes in the
* column
* <LI><B>ORDINAL_POSITION</B> int {@code =>} index of column in table (starting at 1)
* <LI><B>IS_NULLABLE</B> String {@code =>} ISO rules are used to determine the nullability for
* a column.
* <UL>
* <LI>YES --- if the column can include NULLs
* <LI>NO --- if the column cannot include NULLs
* <LI>empty string --- if the nullability for the column is unknown
* </UL>
* <LI><B>SCOPE_CATALOG</B> String {@code =>} catalog of table that is the scope of a reference
* attribute (<code>null</code> if DATA_TYPE isn't REF)
* <LI><B>SCOPE_SCHEMA</B> String {@code =>} schema of table that is the scope of a reference
* attribute (<code>null</code> if the DATA_TYPE isn't REF)
* <LI><B>SCOPE_TABLE</B> String {@code =>} table name that this the scope of a reference
* attribute (<code>null</code> if the DATA_TYPE isn't REF)
* <LI><B>SOURCE_DATA_TYPE</B> short {@code =>} source type of a distinct type or user-generated
* Ref type, SQL type from java.sql.Types (<code>null</code> if DATA_TYPE isn't DISTINCT or
* user-generated REF)
* <LI><B>IS_AUTOINCREMENT</B> String {@code =>} Indicates whether this column is auto
* incremented
* <UL>
* <LI>YES --- if the column is auto incremented
* <LI>NO --- if the column is not auto incremented
* <LI>empty string --- if it cannot be determined whether the column is auto incremented
* </UL>
* <LI><B>IS_GENERATEDCOLUMN</B> String {@code =>} Indicates whether this is a generated column
* <UL>
* <LI>YES --- if this a generated column
* <LI>NO --- if this not a generated column
* <LI>empty string --- if it cannot be determined whether this is a generated column
* </UL>
* </OL>
*
* <p>The COLUMN_SIZE column specifies the column size for the given column. For numeric data,
* this is the maximum precision. For character data, this is the length in characters. For
* datetime datatypes, this is the length in characters of the String representation (assuming the
* maximum allowed precision of the fractional seconds component). For binary data, this is the
* length in bytes. For the ROWID datatype, this is the length in bytes. Null is returned for data
* types where the column size is not applicable.
*
* @param catalog a catalog name; must match the catalog name as it is stored in the database; ""
* retrieves those without a catalog; <code>null</code> means that the catalog name should not
* be used to narrow the search
* @param schemaPattern a schema name pattern; must match the schema name as it is stored in the
* database; "" retrieves those without a schema; <code>null</code> means that the schema name
* should not be used to narrow the search
* @param tableNamePattern a table name pattern; must match the table name as it is stored in the
* database
* @param columnNamePattern a column name pattern; must match the column name as it is stored in
* the database
* @return <code>ResultSet</code> - each row is a column description
* @throws SQLException if a database access error occurs
* @see #getSearchStringEscape
*/
public ResultSet getColumns(
String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
throws SQLException {
Options options = urlParser.getOptions();
String sql =
"SELECT TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, TABLE_NAME, COLUMN_NAME,"
+ dataTypeClause("COLUMN_TYPE")
+ " DATA_TYPE,"
+ columnTypeClause(options)
+ " TYPE_NAME, "
+ " CASE DATA_TYPE"
+ " WHEN 'time' THEN "
+ (datePrecisionColumnExist
? "IF(DATETIME_PRECISION = 0, 10, CAST(11 + DATETIME_PRECISION as signed integer))"
: "10")
+ " WHEN 'date' THEN 10"
+ " WHEN 'datetime' THEN "
+ (datePrecisionColumnExist
? "IF(DATETIME_PRECISION = 0, 19, CAST(20 + DATETIME_PRECISION as signed integer))"
: "19")
+ " WHEN 'timestamp' THEN "
+ (datePrecisionColumnExist
? "IF(DATETIME_PRECISION = 0, 19, CAST(20 + DATETIME_PRECISION as signed integer))"
: "19")
+ (options.yearIsDateType ? "" : " WHEN 'year' THEN 5")
+ " ELSE "
+ " IF(NUMERIC_PRECISION IS NULL, LEAST(CHARACTER_MAXIMUM_LENGTH,"
+ Integer.MAX_VALUE
+ "), NUMERIC_PRECISION) "
+ " END"
+ " COLUMN_SIZE, 65535 BUFFER_LENGTH, "
+ " CONVERT (CASE DATA_TYPE"
+ " WHEN 'year' THEN "
+ (options.yearIsDateType ? "NUMERIC_SCALE" : "0")
+ " WHEN 'tinyint' THEN "
+ (options.tinyInt1isBit ? "0" : "NUMERIC_SCALE")
+ " ELSE NUMERIC_SCALE END, UNSIGNED INTEGER) DECIMAL_DIGITS,"
+ " 10 NUM_PREC_RADIX, IF(IS_NULLABLE = 'yes',1,0) NULLABLE,COLUMN_COMMENT REMARKS,"
+ " COLUMN_DEFAULT COLUMN_DEF, 0 SQL_DATA_TYPE, 0 SQL_DATETIME_SUB, "
+ " LEAST(CHARACTER_OCTET_LENGTH,"
+ Integer.MAX_VALUE
+ ") CHAR_OCTET_LENGTH,"
+ " ORDINAL_POSITION, IS_NULLABLE, NULL SCOPE_CATALOG, NULL SCOPE_SCHEMA, NULL SCOPE_TABLE, NULL SOURCE_DATA_TYPE,"
+ " IF(EXTRA = 'auto_increment','YES','NO') IS_AUTOINCREMENT, "
+ " IF(EXTRA in ('VIRTUAL', 'PERSISTENT', 'VIRTUAL GENERATED', 'STORED GENERATED') ,'YES','NO') IS_GENERATEDCOLUMN "
+ " FROM INFORMATION_SCHEMA.COLUMNS WHERE "
+ catalogCond("TABLE_SCHEMA", catalog)
+ " AND "
+ patternCond("TABLE_NAME", tableNamePattern)
+ " AND "
+ patternCond("COLUMN_NAME", columnNamePattern)
+ " ORDER BY TABLE_CAT, TABLE_SCHEM, TABLE_NAME, ORDINAL_POSITION";
try {
return executeQuery(sql);
} catch (SQLException sqlException) {
if (sqlException.getMessage().contains("Unknown column 'DATETIME_PRECISION'")) {
datePrecisionColumnExist = false;
return getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern);
}
throw sqlException;
}
}
/**
* Retrieves a description of the foreign key columns that reference the given table's primary key
* columns (the foreign keys exported by a table). They are ordered by FKTABLE_CAT, FKTABLE_SCHEM,
* FKTABLE_NAME, and KEY_SEQ.
*
* <p>Each foreign key column description has the following columns:
*
* <OL>
* <LI><B>PKTABLE_CAT</B> String {@code =>} primary key table catalog (may be <code>null</code>)
* <LI><B>PKTABLE_SCHEM</B> String {@code =>} primary key table schema (may be <code>null</code>
* )
* <LI><B>PKTABLE_NAME</B> String {@code =>} primary key table name
* <LI><B>PKCOLUMN_NAME</B> String {@code =>} primary key column name
* <LI><B>FKTABLE_CAT</B> String {@code =>} foreign key table catalog (may be <code>null</code>)
* being exported (may be <code>null</code>)
* <LI><B>FKTABLE_SCHEM</B> String {@code =>} foreign key table schema (may be <code>null</code>
* ) being exported (may be <code>null</code>)
* <LI><B>FKTABLE_NAME</B> String {@code =>} foreign key table name being exported
* <LI><B>FKCOLUMN_NAME</B> String {@code =>} foreign key column name being exported
* <LI><B>KEY_SEQ</B> short {@code =>} sequence number within foreign key( a value of 1
* represents the first column of the foreign key, a value of 2 would represent the second
* column within the foreign key).
* <LI><B>UPDATE_RULE</B> short {@code =>} What happens to foreign key when primary is updated:
* <UL>
* <LI>importedNoAction - do not allow update of primary key if it has been imported
* <LI>importedKeyCascade - change imported key to agree with primary key update
* <LI>importedKeySetNull - change imported key to <code>NULL</code> if its primary key
* has been updated
* <LI>importedKeySetDefault - change imported key to default values if its primary key
* has been updated
* <LI>importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
* </UL>
* <LI><B>DELETE_RULE</B> short {@code =>} What happens to the foreign key when primary is
* deleted.
* <UL>
* <LI>importedKeyNoAction - do not allow delete of primary key if it has been imported
* <LI>importedKeyCascade - delete rows that import a deleted key
* <LI>importedKeySetNull - change imported key to <code>NULL</code> if its primary key
* has been deleted
* <LI>importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
* <LI>importedKeySetDefault - change imported key to default if its primary key has been
* deleted
* </UL>
* <LI><B>FK_NAME</B> String {@code =>} foreign key name (may be <code>null</code>)
* <LI><B>PK_NAME</B> String {@code =>} primary key name (may be <code>null</code>)
* <LI><B>DEFERRABILITY</B> short {@code =>} can the evaluation of foreign key constraints be
* deferred until commit
* <UL>
* <LI>importedKeyInitiallyDeferred - see SQL92 for definition
* <LI>importedKeyInitiallyImmediate - see SQL92 for definition
* <LI>importedKeyNotDeferrable - see SQL92 for definition
* </UL>
* </OL>
*
* @param catalog a catalog name; must match the catalog name as it is stored in this database; ""
* retrieves those without a catalog; <code>null</code> means that the catalog name should not
* be used to narrow the search
* @param schema a schema name; must match the schema name as it is stored in the database; ""
* retrieves those without a schema; <code>null</code> means that the schema name should not
* be used to narrow the search
* @param table a table name; must match the table name as it is stored in this database
* @return a <code>ResultSet</code> object in which each row is a foreign key column description
* @throws SQLException if a database access error occurs
* @see #getImportedKeys
*/
public ResultSet getExportedKeys(String catalog, String schema, String table)
throws SQLException {
if (table == null) {
throw new SQLException("'table' parameter in getExportedKeys cannot be null");
}
String sql =
"SELECT KCU.REFERENCED_TABLE_SCHEMA PKTABLE_CAT, NULL PKTABLE_SCHEM, KCU.REFERENCED_TABLE_NAME PKTABLE_NAME,"
+ " KCU.REFERENCED_COLUMN_NAME PKCOLUMN_NAME, KCU.TABLE_SCHEMA FKTABLE_CAT, NULL FKTABLE_SCHEM, "
+ " KCU.TABLE_NAME FKTABLE_NAME, KCU.COLUMN_NAME FKCOLUMN_NAME, KCU.POSITION_IN_UNIQUE_CONSTRAINT KEY_SEQ,"
+ " CASE update_rule "
+ " WHEN 'RESTRICT' THEN 1"
+ " WHEN 'NO ACTION' THEN 3"
+ " WHEN 'CASCADE' THEN 0"
+ " WHEN 'SET NULL' THEN 2"
+ " WHEN 'SET DEFAULT' THEN 4"
+ " END UPDATE_RULE,"
+ " CASE DELETE_RULE"
+ " WHEN 'RESTRICT' THEN 1"
+ " WHEN 'NO ACTION' THEN 3"
+ " WHEN 'CASCADE' THEN 0"
+ " WHEN 'SET NULL' THEN 2"
+ " WHEN 'SET DEFAULT' THEN 4"
+ " END DELETE_RULE,"
+ " RC.CONSTRAINT_NAME FK_NAME,"
+ " NULL PK_NAME,"
+ importedKeyNotDeferrable
+ " DEFERRABILITY"
+ " FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU"
+ " INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC"
+ " ON KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA"
+ " AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME"
+ " WHERE "
+ catalogCond("KCU.REFERENCED_TABLE_SCHEMA", catalog)
+ " AND "
+ " KCU.REFERENCED_TABLE_NAME = "
+ escapeQuote(table)
+ " ORDER BY FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, KEY_SEQ";
return executeQuery(sql);
}
/**
* GetImportedKeysUsingInformationSchema.
*
* @param catalog catalog
* @param table table
* @return resultset
* @throws SQLException exception
*/
public ResultSet getImportedKeysUsingInformationSchema(String catalog, String table)
throws SQLException {
if (table == null) {
throw new SQLException("'table' parameter in getImportedKeys cannot be null");
}
String sql =
"SELECT KCU.REFERENCED_TABLE_SCHEMA PKTABLE_CAT, NULL PKTABLE_SCHEM, KCU.REFERENCED_TABLE_NAME PKTABLE_NAME,"
+ " KCU.REFERENCED_COLUMN_NAME PKCOLUMN_NAME, KCU.TABLE_SCHEMA FKTABLE_CAT, NULL FKTABLE_SCHEM, "
+ " KCU.TABLE_NAME FKTABLE_NAME, KCU.COLUMN_NAME FKCOLUMN_NAME, KCU.POSITION_IN_UNIQUE_CONSTRAINT KEY_SEQ,"
+ " CASE update_rule "
+ " WHEN 'RESTRICT' THEN 1"
+ " WHEN 'NO ACTION' THEN 3"
+ " WHEN 'CASCADE' THEN 0"
+ " WHEN 'SET NULL' THEN 2"
+ " WHEN 'SET DEFAULT' THEN 4"
+ " END UPDATE_RULE,"
+ " CASE DELETE_RULE"
+ " WHEN 'RESTRICT' THEN 1"
+ " WHEN 'NO ACTION' THEN 3"
+ " WHEN 'CASCADE' THEN 0"
+ " WHEN 'SET NULL' THEN 2"
+ " WHEN 'SET DEFAULT' THEN 4"
+ " END DELETE_RULE,"
+ " RC.CONSTRAINT_NAME FK_NAME,"
+ " NULL PK_NAME,"
+ importedKeyNotDeferrable
+ " DEFERRABILITY"