Repository navigation
Expand file tree
/
Copy pathLibsqlResultSetMetaData.java
More file actions
680 lines (612 loc) · 23.3 KB
/
Copy pathLibsqlResultSetMetaData.java
File metadata and controls
680 lines (612 loc) · 23.3 KB
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
package com.github.magnusp.libsql.jdbc;
import com.github.magnusp.libsql.hrana.codec.Col;
import com.github.magnusp.libsql.hrana.codec.Row;
import com.github.magnusp.libsql.hrana.codec.Stmt;
import com.github.magnusp.libsql.hrana.codec.StmtResult;
import com.github.magnusp.libsql.hrana.codec.Value;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LibsqlResultSetMetaData implements ResultSetMetaData {
private static final Pattern COLUMN_TYPENAME = Pattern.compile("([^\\(]*)");
private static final Pattern COLUMN_TYPECAST =
Pattern.compile("cast\\(.*?\\s+as\\s+(.*?)\\s*\\)");
private static final Pattern COLUMN_PRECISION = Pattern.compile(".*?\\((.*?)\\)");
private final List<Col> cols;
private final List<Row> rows;
private final String sql;
private final LibsqlConnection connection;
private final LibsqlResultSet resultSet;
private boolean tableContextResolved;
private SqlTableReference.Resolution columnOrigins;
private final Map<String, TableInfo> tableInfoCache = new LinkedHashMap<>();
public LibsqlResultSetMetaData(List<Col> cols) {
this(cols, List.of(), null, null, null);
}
LibsqlResultSetMetaData(List<Col> cols, List<Row> rows, String sql, LibsqlConnection connection) {
this(cols, rows, sql, connection, null);
}
LibsqlResultSetMetaData(
List<Col> cols, List<Row> rows, String sql, LibsqlConnection connection, LibsqlResultSet resultSet) {
this.cols = cols != null ? cols : List.of();
this.rows = rows != null ? rows : List.of();
this.sql = sql;
this.connection = connection;
this.resultSet = resultSet;
}
@Override
public int getColumnCount() throws SQLException {
return cols.size();
}
private Col getCol(int column) throws SQLException {
if (column < 1 || column > cols.size()) {
throw new SQLException("Invalid column index: " + column + ", must be between 1 and " + cols.size());
}
return cols.get(column - 1);
}
@Override
public boolean isAutoIncrement(int column) throws SQLException {
TableInfo table = tableForColumn(column);
ColumnInfo info = table != null ? table.columns().get(columnName(column)) : null;
return info != null && info.primaryKey() && isAutoIncrementColumn(table.createSql(), columnName(column));
}
static boolean isAutoIncrementColumn(String createSql, String columnName) {
if (createSql == null || columnName == null) {
return false;
}
List<List<SqlTokenizer.Token>> definitions = tableDefinitions(createSql);
if (definitions == null) {
return false;
}
for (List<SqlTokenizer.Token> definition : definitions) {
if (columnDefinitionIsAutoIncrement(definition, columnName)
|| tableConstraintIsAutoIncrement(definition, columnName)) {
return true;
}
}
return false;
}
@Override
public boolean isCaseSensitive(int column) throws SQLException {
getCol(column);
return true;
}
@Override
public boolean isSearchable(int column) throws SQLException {
getCol(column);
return true;
}
@Override
public boolean isCurrency(int column) throws SQLException {
getCol(column);
return false;
}
@Override
public int isNullable(int column) throws SQLException {
TableInfo table = tableForColumn(column);
if (table == null) {
return columnNullableUnknown;
}
ColumnInfo info = table.columns().get(columnName(column));
if (info == null) {
return columnNullable;
}
return info.notNull() ? columnNoNulls : columnNullable;
}
@Override
public boolean isSigned(int column) throws SQLException {
if (declType(column) != null) {
return switch (getColumnTypeName(column)) {
case "NUMERIC", "INTEGER", "REAL" -> true;
default -> false;
};
}
// An expression column has no declared type, so signedness follows the
// storage class of the current value, as xerial does.
return switch (storageType(runtimeValue(column))) {
case INTEGER, FLOAT, NULL -> true;
case TEXT, BLOB -> false;
};
}
@Override
public int getColumnDisplaySize(int column) throws SQLException {
getCol(column);
return Integer.MAX_VALUE;
}
@Override
public String getColumnLabel(int column) throws SQLException {
String name = getCol(column).name();
return name != null ? name : "";
}
@Override
public String getColumnName(int column) throws SQLException {
return getColumnLabel(column);
}
@Override
public String getSchemaName(int column) throws SQLException {
getCol(column);
return "";
}
@Override
public int getPrecision(int column) throws SQLException {
String declType = declType(column);
if (declType == null) {
return 0;
}
Matcher matcher = COLUMN_PRECISION.matcher(declType);
return matcher.find() ? Integer.parseInt(matcher.group(1).split(",")[0].trim()) : 0;
}
@Override
public int getScale(int column) throws SQLException {
String declType = declType(column);
if (declType == null) {
return 0;
}
Matcher matcher = COLUMN_PRECISION.matcher(declType);
if (matcher.find()) {
String[] parts = matcher.group(1).split(",");
if (parts.length == 2) {
return Integer.parseInt(parts[1].trim());
}
}
return 0;
}
@Override
public String getTableName(int column) throws SQLException {
TableInfo table = tableForColumn(column);
return table != null ? table.name() : "";
}
@Override
public String getCatalogName(int column) throws SQLException {
getCol(column);
return "";
}
@Override
public int getColumnType(int column) throws SQLException {
getCol(column);
String typeName = getColumnTypeName(column);
Value value = runtimeValue(column);
SampleType valueType = storageType(value);
if (valueType == SampleType.INTEGER || valueType == SampleType.NULL) {
if ("BOOLEAN".equals(typeName)) {
return Types.BOOLEAN;
}
if ("TINYINT".equals(typeName)) {
return Types.TINYINT;
}
if ("SMALLINT".equals(typeName) || "INT2".equals(typeName)) {
return Types.SMALLINT;
}
if ("BIGINT".equals(typeName)
|| "INT8".equals(typeName)
|| "UNSIGNED BIG INT".equals(typeName)) {
return Types.BIGINT;
}
if ("DATE".equals(typeName)) {
return Types.DATE;
}
if ("DATETIME".equals(typeName) || "TIMESTAMP".equals(typeName)) {
return Types.TIMESTAMP;
}
if (valueType == SampleType.INTEGER
|| "INT".equals(typeName)
|| "INTEGER".equals(typeName)
|| "MEDIUMINT".equals(typeName)) {
long val = integer(value);
return val > Integer.MAX_VALUE || val < Integer.MIN_VALUE ? Types.BIGINT : Types.INTEGER;
}
}
if (valueType == SampleType.FLOAT || valueType == SampleType.NULL) {
if ("DECIMAL".equals(typeName)) {
return Types.DECIMAL;
}
if ("DOUBLE".equals(typeName) || "DOUBLE PRECISION".equals(typeName)) {
return Types.DOUBLE;
}
if ("NUMERIC".equals(typeName)) {
return Types.NUMERIC;
}
if ("REAL".equals(typeName)) {
return Types.REAL;
}
if (valueType == SampleType.FLOAT || "FLOAT".equals(typeName)) {
return Types.FLOAT;
}
}
if (valueType == SampleType.TEXT || valueType == SampleType.NULL) {
if ("CHARACTER".equals(typeName)
|| "NCHAR".equals(typeName)
|| "NATIVE CHARACTER".equals(typeName)
|| "CHAR".equals(typeName)) {
return Types.CHAR;
}
if ("CLOB".equals(typeName)) {
return Types.CLOB;
}
if ("DATE".equals(typeName)) {
return Types.DATE;
}
if ("DATETIME".equals(typeName) || "TIMESTAMP".equals(typeName)) {
return Types.TIMESTAMP;
}
if (valueType == SampleType.TEXT
|| "VARCHAR".equals(typeName)
|| "VARYING CHARACTER".equals(typeName)
|| "NVARCHAR".equals(typeName)
|| "TEXT".equals(typeName)) {
return Types.VARCHAR;
}
}
if (valueType == SampleType.BLOB || valueType == SampleType.NULL) {
if ("BINARY".equals(typeName)) {
return Types.BINARY;
}
if (valueType == SampleType.BLOB || "BLOB".equals(typeName)) {
return Types.BLOB;
}
}
return Types.NUMERIC;
}
@Override
public String getColumnTypeName(int column) throws SQLException {
getCol(column);
String declType = declType(column);
if (declType != null) {
Matcher matcher = COLUMN_TYPENAME.matcher(declType);
matcher.find();
return matcher.group(1).toUpperCase(Locale.ENGLISH);
}
return "NUMERIC";
}
@Override
public boolean isReadOnly(int column) throws SQLException {
getCol(column);
return false;
}
@Override
public boolean isWritable(int column) throws SQLException {
getCol(column);
return true;
}
@Override
public boolean isDefinitelyWritable(int column) throws SQLException {
getCol(column);
return true;
}
@Override
public String getColumnClassName(int column) throws SQLException {
getCol(column);
return className(runtimeValue(column));
}
private static String className(Value value) {
if (value instanceof Value.Integer i) {
long val = i.value();
return val > Integer.MAX_VALUE || val < Integer.MIN_VALUE
? Long.class.getName()
: Integer.class.getName();
}
if (value instanceof Value.Float) {
return Double.class.getName();
}
if (value instanceof Value.Text) {
return String.class.getName();
}
return Object.class.getName();
}
private String declType(int column) throws SQLException {
Col col = getCol(column);
String declType = col.decltype();
if (declType == null) {
String name = col.name();
if (name != null) {
Matcher matcher = COLUMN_TYPECAST.matcher(name);
declType = matcher.find() ? matcher.group(1) : null;
}
}
return declType;
}
private String columnName(int column) throws SQLException {
String name = getCol(column).name();
return name != null ? name.toLowerCase(Locale.ROOT) : "";
}
private Value runtimeValue(int column) {
if (resultSet != null) {
return resultSet.valueForMetadata(column);
}
return sampleValue(column);
}
private Value sampleValue(int column) {
for (Row row : rows) {
List<Value> values = row.values();
if (values == null || column < 1 || column > values.size()) {
continue;
}
Value value = values.get(column - 1);
if (value != null && !(value instanceof Value.Null)) {
return value;
}
}
return null;
}
private static SampleType storageType(Value value) {
if (value instanceof Value.Integer) {
return SampleType.INTEGER;
}
if (value instanceof Value.Float) {
return SampleType.FLOAT;
}
if (value instanceof Value.Blob) {
return SampleType.BLOB;
}
if (value instanceof Value.Text) {
return SampleType.TEXT;
}
return SampleType.NULL;
}
private TableInfo tableForColumn(int column) throws SQLException {
getCol(column);
SqlTableReference.TableRef reference = originTable(column);
return reference != null ? tableInfo(reference) : null;
}
private SqlTableReference.TableRef originTable(int column) throws SQLException {
SqlTableReference.Resolution resolution = resolveColumnOrigins();
return resolution != null ? resolution.table(column - 1) : null;
}
private SqlTableReference.Resolution resolveColumnOrigins() throws SQLException {
if (!tableContextResolved) {
SqlTableReference.Resolution resolved = null;
if (connection != null && sql != null) {
resolved = SqlTableReference.resolve(sql, reference -> {
TableInfo info = tableInfo(reference);
if (info == null) {
return null;
}
return new SqlTableReference.TableDefinition(
info.createSql(), new ArrayList<>(info.columns().keySet()));
}, cols.size());
}
columnOrigins = resolved;
tableContextResolved = true;
}
return columnOrigins;
}
private TableInfo tableInfo(SqlTableReference.TableRef reference) throws SQLException {
String schema = reference.schema() != null ? reference.schema().toLowerCase(Locale.ROOT) : "";
String table = reference.table() != null ? reference.table().toLowerCase(Locale.ROOT) : "";
String key = schema + "." + table;
if (tableInfoCache.containsKey(key)) {
return tableInfoCache.get(key);
}
TableInfo info = loadTableInfo(reference);
tableInfoCache.put(key, info);
return info;
}
private TableInfo loadTableInfo(SqlTableReference.TableRef reference) throws SQLException {
String schema = reference.schema();
String table = reference.table();
if (schema == null) {
TableInfo temp = loadTableInfo("temp", table);
if (temp != null) {
return temp;
}
return loadTableInfo("main", table);
}
return switch (schema.toLowerCase(Locale.ROOT)) {
case "main" -> loadTableInfo("main", table);
case "temp" -> loadTableInfo("temp", table);
default -> loadAttachedTableInfo(schema, table);
};
}
private TableInfo loadTableInfo(String schema, String table) throws SQLException {
String master = schema.equals("temp") ? "sqlite_temp_master" : "sqlite_master";
String query = "SELECT m.name, m.sql, p.name, p.\"notnull\", p.pk "
+ "FROM " + master + " m JOIN pragma_table_xinfo(?, ?) p "
+ "WHERE m.type IN ('table', 'view') AND m.name COLLATE NOCASE = ? "
+ "AND p.hidden != 1 "
+ "ORDER BY p.cid";
StmtResult result = connection.executeStatement(
new Stmt(query, List.of(Value.of(table), Value.of(schema), Value.of(table))));
return toTableInfo(result, table);
}
private TableInfo loadAttachedTableInfo(String schema, String table) throws SQLException {
String actualSchema = findSchema(schema);
if (actualSchema == null) {
return null;
}
String quotedSchema = "\"" + actualSchema.replace("\"", "\"\"") + "\"";
String query = "SELECT m.name, m.sql, p.name, p.\"notnull\", p.pk "
+ "FROM " + quotedSchema + ".sqlite_master m JOIN pragma_table_xinfo(?, ?) p "
+ "WHERE m.type IN ('table', 'view') AND m.name COLLATE NOCASE = ? "
+ "AND p.hidden != 1 "
+ "ORDER BY p.cid";
StmtResult result = connection.executeStatement(new Stmt(
query, List.of(Value.of(table), Value.of(actualSchema), Value.of(table))));
return toTableInfo(result, table);
}
private String findSchema(String schema) throws SQLException {
StmtResult databases =
connection.executeStatement(new Stmt("SELECT name FROM pragma_database_list"));
if (databases == null || databases.rows() == null) {
return null;
}
for (Row row : databases.rows()) {
List<Value> values = row.values();
if (values == null || values.isEmpty()) {
continue;
}
String name = text(values.get(0));
if (name != null && name.equalsIgnoreCase(schema)) {
return name;
}
}
return null;
}
private static TableInfo toTableInfo(StmtResult result, String fallbackName) {
if (result == null || result.rows() == null || result.rows().isEmpty()) {
return null;
}
String tableName = null;
String createSql = null;
Map<String, ColumnInfo> columns = new LinkedHashMap<>();
for (Row row : result.rows()) {
List<Value> values = row.values();
if (values == null || values.size() < 5) {
continue;
}
if (tableName == null) {
tableName = text(values.get(0));
createSql = text(values.get(1));
}
String columnName = text(values.get(2));
if (columnName != null) {
columns.put(
columnName.toLowerCase(Locale.ROOT),
new ColumnInfo(integer(values.get(3)) != 0, integer(values.get(4)) != 0));
}
}
return new TableInfo(tableName != null ? tableName : fallbackName, createSql, columns);
}
private static List<List<SqlTokenizer.Token>> tableDefinitions(String createSql) {
List<SqlTokenizer.Token> tokens = SqlTokenizer.tokenize(createSql);
if (tokens == null) {
return null;
}
int open = -1;
for (int i = 0; i < tokens.size(); i++) {
if (tokens.get(i).isSymbol("(")) {
open = i;
break;
}
}
if (open < 0) {
return null;
}
List<List<SqlTokenizer.Token>> definitions = new ArrayList<>();
List<SqlTokenizer.Token> current = new ArrayList<>();
for (int i = open + 1; i < tokens.size(); i++) {
SqlTokenizer.Token token = tokens.get(i);
if (token.isSymbol(")") && token.depth() == 0) {
if (!current.isEmpty()) {
definitions.add(current);
}
return definitions;
}
if (token.isSymbol(",") && token.depth() == 1) {
definitions.add(current);
current = new ArrayList<>();
continue;
}
current.add(token);
}
return null;
}
private static boolean columnDefinitionIsAutoIncrement(
List<SqlTokenizer.Token> definition, String columnName) {
int start = skipConstraintName(definition);
if (start >= definition.size()) {
return false;
}
if (isConstraintKeyword(definition.get(start))) {
return false;
}
String name = definition.get(start).identifier();
if (name == null || !name.equalsIgnoreCase(columnName)) {
return false;
}
return containsKeyword(definition, start + 1, definition.size(), "AUTOINCREMENT", 1);
}
private static boolean tableConstraintIsAutoIncrement(
List<SqlTokenizer.Token> definition, String columnName) {
int start = skipConstraintName(definition);
if (start + 1 >= definition.size()
|| !definition.get(start).isWord("PRIMARY")
|| !definition.get(start + 1).isWord("KEY")) {
return false;
}
int open = -1;
for (int i = start + 2; i < definition.size(); i++) {
if (definition.get(i).isSymbol("(")) {
open = i;
break;
}
}
if (open < 0) {
return false;
}
int partStart = open + 1;
for (int i = open + 1; i < definition.size(); i++) {
SqlTokenizer.Token token = definition.get(i);
if ((token.isSymbol(",") && token.depth() == 2)
|| (token.isSymbol(")") && token.depth() == 1)) {
if (indexedColumnIsAutoIncrement(definition, partStart, i, columnName)) {
return true;
}
partStart = i + 1;
}
}
return false;
}
private static boolean indexedColumnIsAutoIncrement(
List<SqlTokenizer.Token> definition, int start, int end, String columnName) {
if (start >= end) {
return false;
}
String name = definition.get(start).identifier();
return name != null
&& name.equalsIgnoreCase(columnName)
&& containsKeyword(definition, start + 1, end, "AUTOINCREMENT", 2);
}
private static int skipConstraintName(List<SqlTokenizer.Token> definition) {
if (definition.size() >= 2 && definition.get(0).isWord("CONSTRAINT")) {
return 2;
}
return 0;
}
private static boolean isConstraintKeyword(SqlTokenizer.Token token) {
return token.isWord("PRIMARY")
|| token.isWord("UNIQUE")
|| token.isWord("CHECK")
|| token.isWord("FOREIGN");
}
private static boolean containsKeyword(
List<SqlTokenizer.Token> tokens, int start, int end, String keyword, int depth) {
for (int i = start; i < end; i++) {
SqlTokenizer.Token token = tokens.get(i);
if (token.depth() == depth && token.isWord(keyword)) {
return true;
}
}
return false;
}
private static String text(Value value) {
return value instanceof Value.Text t ? t.value() : null;
}
private static long integer(Value value) {
return value instanceof Value.Integer i ? i.value() : 0L;
}
private enum SampleType {
INTEGER,
FLOAT,
BLOB,
TEXT,
NULL
}
private record ColumnInfo(boolean notNull, boolean primaryKey) {}
private record TableInfo(String name, String createSql, Map<String, ColumnInfo> columns) {}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) return iface.cast(this);
throw new SQLException("Cannot unwrap to " + iface.getName());
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
}