This repository was archived by the owner on Mar 23, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathBigQueryDatabaseMetaData.java
More file actions
5289 lines (4787 loc) · 193 KB
/
BigQueryDatabaseMetaData.java
File metadata and controls
5289 lines (4787 loc) · 193 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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery.jdbc;
import com.google.api.gax.paging.Page;
import com.google.cloud.Tuple;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQuery.DatasetListOption;
import com.google.cloud.bigquery.BigQuery.RoutineListOption;
import com.google.cloud.bigquery.BigQuery.TableListOption;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.Field.Mode;
import com.google.cloud.bigquery.FieldList;
import com.google.cloud.bigquery.FieldValue;
import com.google.cloud.bigquery.FieldValueList;
import com.google.cloud.bigquery.Routine;
import com.google.cloud.bigquery.RoutineArgument;
import com.google.cloud.bigquery.RoutineId;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLDataType;
import com.google.cloud.bigquery.StandardSQLField;
import com.google.cloud.bigquery.StandardSQLTableType;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.Table;
import com.google.cloud.bigquery.TableDefinition;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* An implementation of {@link java.sql.DatabaseMetaData}. This interface is implemented by driver
* vendors to let users know the capabilities of a Database Management System (DBMS) in combination
* with the driver based on JDBC™ technology ("JDBC driver") that is used with it.
*
* @see BigQueryStatement
*/
// TODO(neenu): test and verify after post MVP implementation.
class BigQueryDatabaseMetaData implements DatabaseMetaData {
final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(this.toString());
private static final String DATABASE_PRODUCT_NAME = "Google BigQuery";
private static final String DATABASE_PRODUCT_VERSION = "2.0";
private static final String DRIVER_NAME = "GoogleJDBCDriverForGoogleBigQuery";
private static final String DRIVER_DEFAULT_VERSION = "0.0.0";
private static final String SCHEMA_TERM = "Dataset";
private static final String CATALOG_TERM = "Project";
private static final String PROCEDURE_TERM = "Procedure";
private static final String GET_PRIMARY_KEYS_SQL = "DatabaseMetaData_GetPrimaryKeys.sql";
private static final String GET_IMPORTED_KEYS_SQL = "DatabaseMetaData_GetImportedKeys.sql";
private static final String GET_EXPORTED_KEYS_SQL = "DatabaseMetaData_GetExportedKeys.sql";
private static final String GET_CROSS_REFERENCE_SQL = "DatabaseMetaData_GetCrossReference.sql";
private static final int API_EXECUTOR_POOL_SIZE = 50;
private static final int DEFAULT_PAGE_SIZE = 500;
private static final int DEFAULT_QUEUE_CAPACITY = 5000;
// Declared package-private for testing.
static final String GOOGLE_SQL_QUOTED_IDENTIFIER = "`";
// Does not include SQL:2003 Keywords as per JDBC spec.
// https://en.wikipedia.org/wiki/List_of_SQL_reserved_words
static final String GOOGLE_SQL_RESERVED_KEYWORDS =
"ASC,ASSERT_ROWS_MODIFIED,DESC,ENUM,EXCLUDE,FOLLOWING,HASH,IF,"
+ "IGNORE,LIMIT,LOOKUP,NULLS,PRECEDING,PROTO,QUALIFY,RESPECT,STRUCT,UNBOUNDED";
static final String GOOGLE_SQL_NUMERIC_FNS =
"ABS,ACOS,ACOSH,ASIN,ASINH,ATAN,ATAN2,ATANH,CBRT,CEIL,CEILING,COS"
+ ",COSH,COSINE_DISTANCE,COT,COTH,CSC,CSCH,DIV,EXP,EUCLIDEAN_DISTANCE,FLOOR"
+ ",GREATEST,IS_INF,LEAST,LN,LOG,LOG10,MOD,POW,RAND,RANGE_BUCKET,ROUND,"
+ ",SAFE_ADD,SAFE_DIVIDE,SAFE_MULTIPLY,SAFE_NEGATE,SAFE_SUBTRACT,SEC,SECH,"
+ "SIGN,SIN,SINH,SQRT,TAN,TANH,TRUNC";
static final String GOOGLE_SQL_STRING_FNS =
"ASCII,BYTE_LENGTH,CHAR_LENGTH,CHARACTER_LENGTH,CHR,CODE_POINTS_TO_BYTES,"
+ "CODE_POINTS_TO_STRING,COLLATE,CONCAT,CONTAINS_SUBSTR,EDIT_DISTANCE,ENDS_WITH,"
+ "FORMAT,FROM_BASE32,FROM_BASE64,FROM_HEX,INITCAP,INSTR,LEFT,LENGTH,LOWER,"
+ "LPAD,LTRIM,NORMALIZ,NORMALIZE_AND_CASEFOLD,OCTET_LENGTH,REGEXP_CONTAINS,"
+ "REGEXP_EXTRACT,REGEXP_EXTRACT_ALL,REGEXP_INSTR,REGEXP_REPLACE,REGEXP_SUBSTR,"
+ "REPEAT,REPLACE,REVERSE,RIGHT,RPAD,RTRIM,SAFE_CONVERT_BYTES_TO_STRING,SOUNDEX,"
+ "SPLIT,STARTS_WITH,STRPOS,SUBSTR,SUBSTRING,TO_BASE32,TO_BASE64,TO_CODE_POINTS,"
+ "TO_HEX,TRANSLATE,TRIMunicode,UNICODE,UPPER";
static final String GOOGLE_SQL_TIME_DATE_FNS =
"DATE,DATE_ADD,DATE_BUCKET,DATE_DIFF,DATE_FROM_UNIX_DATE,"
+ "DATE_SUB,DATE_TRUNC,DATETIME,DATETIME_ADD.,DATETIME_BUCKET,"
+ "DATETIME_DIFF,DATETIME_SUB,DATETIME_TRUNC,CURRENT_DATE,CURRENT_DATETIME,"
+ "CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_TIME,EXTRACT,FORMAT_TIME,PARSE_TIME,"
+ "TIME,TIME_ADD,TIME_DIFF,TIME_SUB,TIME_TRUNC,CURRENT_TIMESTAMP,EXTRACT,"
+ "FORMAT_TIMESTAMP,GENERATE_TIMESTAMP_ARRAY,PARSE_TIMESTAMP,TIMESTAMP,"
+ "TIMESTAMP_ADD,TIMESTAMP_DIFF,TIMESTAMP_MICROS,TIMESTAMP_MILLIS,TIMESTAMP_SECONDS,"
+ "TIMESTAMP_SUB,TIMESTAMP_TRUNC,UNIX_MICROS,UNIX_MILLIS,UNIX_SECONDS";
static final String GOOGLE_SQL_ESCAPE = "\\";
static final String GOOGLE_SQL_CATALOG_SEPARATOR = ".";
static final int GOOGLE_SQL_MAX_COL_NAME_LEN = 300;
static final int GOOGLE_SQL_MAX_COLS_PER_TABLE = 10000;
String URL;
BigQueryConnection connection;
private final BigQueryStatement statement;
private final BigQuery bigquery;
private final int metadataFetchThreadCount;
private static final AtomicReference<String> parsedDriverVersion = new AtomicReference<>(null);
private static final AtomicReference<Integer> parsedDriverMajorVersion =
new AtomicReference<>(null);
private static final AtomicReference<Integer> parsedDriverMinorVersion =
new AtomicReference<>(null);
BigQueryDatabaseMetaData(BigQueryConnection connection) throws SQLException {
this.URL = connection.getConnectionUrl();
this.connection = connection;
this.statement = connection.createStatement().unwrap(BigQueryStatement.class);
this.bigquery = connection.getBigQuery();
this.metadataFetchThreadCount = connection.getMetadataFetchThreadCount();
loadDriverVersionProperties();
}
@Override
public boolean allProceduresAreCallable() {
// Returns false because BigQuery's IAM permissions can allow a user
// to discover a procedure's existence without having rights to execute it.
return false;
}
@Override
public boolean allTablesAreSelectable() {
// Returns true to ensure maximum compatibility with client applications
// that expect a positive response to discover and list all available tables.
return true;
}
@Override
public String getURL() {
return this.URL;
}
@Override
public String getUserName() {
return null;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public boolean nullsAreSortedHigh() {
return false;
}
@Override
public boolean nullsAreSortedLow() {
return false;
}
@Override
public boolean nullsAreSortedAtStart() {
return false;
}
@Override
public boolean nullsAreSortedAtEnd() {
return false;
}
@Override
public String getDatabaseProductName() {
return DATABASE_PRODUCT_NAME;
}
@Override
public String getDatabaseProductVersion() {
return DATABASE_PRODUCT_VERSION;
}
@Override
public String getDriverName() {
return DRIVER_NAME;
}
@Override
public String getDriverVersion() {
return parsedDriverVersion.get() != null ? parsedDriverVersion.get() : DRIVER_DEFAULT_VERSION;
}
@Override
public int getDriverMajorVersion() {
return parsedDriverMajorVersion.get() != null ? parsedDriverMajorVersion.get() : 0;
}
@Override
public int getDriverMinorVersion() {
return parsedDriverMinorVersion.get() != null ? parsedDriverMinorVersion.get() : 0;
}
@Override
public boolean usesLocalFiles() {
return false;
}
@Override
public boolean usesLocalFilePerTable() {
return false;
}
@Override
public boolean supportsMixedCaseIdentifiers() {
return false;
}
@Override
public boolean storesUpperCaseIdentifiers() {
return false;
}
@Override
public boolean storesLowerCaseIdentifiers() {
return false;
}
@Override
public boolean storesMixedCaseIdentifiers() {
return false;
}
@Override
public boolean supportsMixedCaseQuotedIdentifiers() {
return false;
}
@Override
public boolean storesUpperCaseQuotedIdentifiers() {
return false;
}
@Override
public boolean storesLowerCaseQuotedIdentifiers() {
return false;
}
@Override
public boolean storesMixedCaseQuotedIdentifiers() {
return false;
}
@Override
public String getIdentifierQuoteString() {
return GOOGLE_SQL_QUOTED_IDENTIFIER;
}
@Override
public String getSQLKeywords() {
return GOOGLE_SQL_RESERVED_KEYWORDS;
}
@Override
public String getNumericFunctions() {
return GOOGLE_SQL_NUMERIC_FNS;
}
@Override
public String getStringFunctions() {
return GOOGLE_SQL_STRING_FNS;
}
@Override
// GoogleSQL has UDF (user defined functions).
// System functions like DATABASE(), USER() are not supported.
public String getSystemFunctions() {
return null;
}
@Override
public String getTimeDateFunctions() {
return GOOGLE_SQL_TIME_DATE_FNS;
}
@Override
public String getSearchStringEscape() {
return GOOGLE_SQL_ESCAPE;
}
@Override
// No extra characters beyond a-z, A-Z, 0-9 and _
public String getExtraNameCharacters() {
return null;
}
@Override
public boolean supportsAlterTableWithAddColumn() {
return true;
}
@Override
public boolean supportsAlterTableWithDropColumn() {
return true;
}
@Override
public boolean supportsColumnAliasing() {
return true;
}
@Override
public boolean nullPlusNonNullIsNull() {
return true;
}
@Override
public boolean supportsConvert() {
return false;
}
@Override
public boolean supportsConvert(int fromType, int toType) {
return false;
}
@Override
public boolean supportsTableCorrelationNames() {
return true;
}
@Override
public boolean supportsDifferentTableCorrelationNames() {
return false;
}
@Override
public boolean supportsExpressionsInOrderBy() {
return true;
}
@Override
public boolean supportsOrderByUnrelated() {
return true;
}
@Override
public boolean supportsGroupBy() {
return true;
}
@Override
public boolean supportsGroupByUnrelated() {
return true;
}
@Override
public boolean supportsGroupByBeyondSelect() {
return true;
}
@Override
public boolean supportsLikeEscapeClause() {
return false;
}
@Override
public boolean supportsMultipleResultSets() {
return false;
}
@Override
public boolean supportsMultipleTransactions() {
return false;
}
@Override
public boolean supportsNonNullableColumns() {
return false;
}
@Override
public boolean supportsMinimumSQLGrammar() {
return false;
}
@Override
public boolean supportsCoreSQLGrammar() {
return false;
}
@Override
public boolean supportsExtendedSQLGrammar() {
return false;
}
@Override
public boolean supportsANSI92EntryLevelSQL() {
return false;
}
@Override
public boolean supportsANSI92IntermediateSQL() {
return false;
}
@Override
public boolean supportsANSI92FullSQL() {
return false;
}
@Override
public boolean supportsIntegrityEnhancementFacility() {
return false;
}
@Override
public boolean supportsOuterJoins() {
return false;
}
@Override
public boolean supportsFullOuterJoins() {
return false;
}
@Override
public boolean supportsLimitedOuterJoins() {
return false;
}
@Override
public String getSchemaTerm() {
return SCHEMA_TERM;
}
@Override
public String getProcedureTerm() {
return PROCEDURE_TERM;
}
@Override
public String getCatalogTerm() {
return CATALOG_TERM;
}
@Override
public boolean isCatalogAtStart() {
return true;
}
@Override
public String getCatalogSeparator() {
return GOOGLE_SQL_CATALOG_SEPARATOR;
}
@Override
public boolean supportsSchemasInDataManipulation() {
return false;
}
@Override
public boolean supportsSchemasInProcedureCalls() {
return false;
}
@Override
public boolean supportsSchemasInTableDefinitions() {
return false;
}
@Override
public boolean supportsSchemasInIndexDefinitions() {
return false;
}
@Override
public boolean supportsSchemasInPrivilegeDefinitions() {
return false;
}
@Override
public boolean supportsCatalogsInDataManipulation() {
return false;
}
@Override
public boolean supportsCatalogsInProcedureCalls() {
return false;
}
@Override
public boolean supportsCatalogsInTableDefinitions() {
return false;
}
@Override
public boolean supportsCatalogsInIndexDefinitions() {
return false;
}
@Override
public boolean supportsCatalogsInPrivilegeDefinitions() {
return false;
}
@Override
public boolean supportsPositionedDelete() {
return false;
}
@Override
public boolean supportsPositionedUpdate() {
return false;
}
@Override
public boolean supportsSelectForUpdate() {
return false;
}
@Override
public boolean supportsStoredProcedures() {
return false;
}
@Override
public boolean supportsSubqueriesInComparisons() {
return false;
}
@Override
public boolean supportsSubqueriesInExists() {
return false;
}
@Override
public boolean supportsSubqueriesInIns() {
return false;
}
@Override
public boolean supportsSubqueriesInQuantifieds() {
return false;
}
@Override
public boolean supportsCorrelatedSubqueries() {
return false;
}
@Override
public boolean supportsUnion() {
return true;
}
@Override
public boolean supportsUnionAll() {
return true;
}
@Override
public boolean supportsOpenCursorsAcrossCommit() {
return false;
}
@Override
public boolean supportsOpenCursorsAcrossRollback() {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossCommit() {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossRollback() {
return false;
}
@Override
// No limit
public int getMaxBinaryLiteralLength() {
return 0;
}
@Override
// No Limit
public int getMaxCharLiteralLength() {
return 0;
}
@Override
// GoogleSQL documentation says 300.
// https://cloud.google.com/bigquery/quotas#all_tables
public int getMaxColumnNameLength() {
return GOOGLE_SQL_MAX_COL_NAME_LEN;
}
@Override
// No specific limits for group by.
public int getMaxColumnsInGroupBy() {
return 0;
}
@Override
// No specific limits for index.
public int getMaxColumnsInIndex() {
return 0;
}
@Override
// No specific limit for Order By.
public int getMaxColumnsInOrderBy() {
return 0;
}
@Override
// All columns can be selected. No specific limits.
public int getMaxColumnsInSelect() {
return 0;
}
@Override
public int getMaxColumnsInTable() {
return GOOGLE_SQL_MAX_COLS_PER_TABLE;
}
@Override
public int getMaxConnections() {
// Per JDBC spec, returns 0 as there is no connection limit or is unknown.
return 0;
}
@Override
public int getMaxCursorNameLength() {
// BigQuery does not support named cursors or positioned updates/deletes.
return 0;
}
@Override
public int getMaxIndexLength() {
// Per the JDBC spec, 0 indicates this feature is not supported.
return 0;
}
@Override
public int getMaxSchemaNameLength() {
// Dataset IDs can be up to 1024 characters long.
// See: https://cloud.google.com/bigquery/docs/datasets#dataset-naming
return 1024;
}
@Override
public int getMaxProcedureNameLength() {
// Routine IDs can be up to 256 characters long.
// See:
// https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#RoutineReference.FIELDS.routine_id
return 256;
}
@Override
public int getMaxCatalogNameLength() {
// Corresponds to the BigQuery Project ID, which can be a maximum of 30 characters.
// See:
// https://cloud.google.com/resource-manager/docs/creating-managing-projects#before_you_begin
return 30;
}
@Override
public int getMaxRowSize() {
// Per JDBC spec, returns 0 as there is no fixed limit or is unknown.
return 0;
}
@Override
public boolean doesMaxRowSizeIncludeBlobs() {
return false;
}
@Override
public int getMaxStatementLength() {
// Per JDBC spec, returns 0 as there is no fixed limit or is unknown.
// See: https://cloud.google.com/bigquery/quotas#query_jobs
return 0;
}
@Override
public int getMaxStatements() {
// Per JDBC spec, returns 0 as there is no fixed limit or is unknown.
return 0;
}
@Override
public int getMaxTableNameLength() {
// Table IDs can be up to 1024 characters long.
// See: https://cloud.google.com/bigquery/docs/tables#table-naming
return 1024;
}
@Override
public int getMaxTablesInSelect() {
// BigQuery allows up to 1,000 tables to be referenced per query.
// See: https://cloud.google.com/bigquery/quotas#query_jobs
return 1000;
}
@Override
public int getMaxUserNameLength() {
return 0;
}
@Override
public int getDefaultTransactionIsolation() {
return Connection.TRANSACTION_SERIALIZABLE;
}
@Override
public boolean supportsTransactions() {
return true;
}
@Override
public boolean supportsTransactionIsolationLevel(int level) {
return level == Connection.TRANSACTION_SERIALIZABLE;
}
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions() {
return false;
}
@Override
public boolean supportsDataManipulationTransactionsOnly() {
return false;
}
@Override
public boolean dataDefinitionCausesTransactionCommit() {
return false;
}
@Override
public boolean dataDefinitionIgnoredInTransactions() {
return false;
}
@Override
public ResultSet getProcedures(
String catalog, String schemaPattern, String procedureNamePattern) {
if ((catalog == null || catalog.isEmpty())
|| (schemaPattern != null && schemaPattern.isEmpty())
|| (procedureNamePattern != null && procedureNamePattern.isEmpty())) {
LOG.warning("Returning empty ResultSet as catalog is null/empty or a pattern is empty.");
return new BigQueryJsonResultSet();
}
LOG.info(
"getProcedures called for catalog: %s, schemaPattern: %s, procedureNamePattern: %s",
catalog, schemaPattern, procedureNamePattern);
final Pattern schemaRegex = compileSqlLikePattern(schemaPattern);
final Pattern procedureNameRegex = compileSqlLikePattern(procedureNamePattern);
final Schema resultSchema = defineGetProceduresSchema();
final FieldList resultSchemaFields = resultSchema.getFields();
final BlockingQueue<BigQueryFieldValueListWrapper> queue =
new LinkedBlockingQueue<>(DEFAULT_QUEUE_CAPACITY);
final List<FieldValueList> collectedResults = Collections.synchronizedList(new ArrayList<>());
final List<Future<?>> processingTaskFutures = new ArrayList<>();
final String catalogParam = catalog;
Runnable procedureFetcher =
() -> {
ExecutorService apiExecutor = null;
ExecutorService routineProcessorExecutor = null;
final FieldList localResultSchemaFields = resultSchemaFields;
final List<Future<List<Routine>>> apiFutures = new ArrayList<>();
try {
List<Dataset> datasetsToScan =
findMatchingBigQueryObjects(
"Dataset",
() ->
bigquery.listDatasets(
catalogParam, DatasetListOption.pageSize(DEFAULT_PAGE_SIZE)),
(name) -> bigquery.getDataset(DatasetId.of(catalogParam, name)),
(ds) -> ds.getDatasetId().getDataset(),
schemaPattern,
schemaRegex,
LOG);
if (datasetsToScan.isEmpty()) {
LOG.info("Fetcher thread found no matching datasets. Finishing.");
return;
}
apiExecutor = Executors.newFixedThreadPool(API_EXECUTOR_POOL_SIZE);
routineProcessorExecutor = Executors.newFixedThreadPool(this.metadataFetchThreadCount);
LOG.fine("Submitting parallel findMatchingRoutines tasks...");
for (Dataset dataset : datasetsToScan) {
if (Thread.currentThread().isInterrupted()) {
LOG.warning("Fetcher interrupted during dataset iteration submission.");
break;
}
final DatasetId currentDatasetId = dataset.getDatasetId();
Callable<List<Routine>> apiCallable =
() ->
findMatchingBigQueryObjects(
"Routine",
() ->
bigquery.listRoutines(
currentDatasetId, RoutineListOption.pageSize(DEFAULT_PAGE_SIZE)),
(name) ->
bigquery.getRoutine(
RoutineId.of(
currentDatasetId.getProject(),
currentDatasetId.getDataset(),
name)),
(rt) -> rt.getRoutineId().getRoutine(),
procedureNamePattern,
procedureNameRegex,
LOG);
Future<List<Routine>> apiFuture = apiExecutor.submit(apiCallable);
apiFutures.add(apiFuture);
}
LOG.fine("Finished submitting " + apiFutures.size() + " findMatchingRoutines tasks.");
apiExecutor.shutdown();
LOG.fine("Processing results from findMatchingRoutines tasks...");
for (Future<List<Routine>> apiFuture : apiFutures) {
if (Thread.currentThread().isInterrupted()) {
LOG.warning("Fetcher interrupted while processing API futures.");
break;
}
try {
List<Routine> routinesResult = apiFuture.get();
if (routinesResult != null) {
for (Routine routine : routinesResult) {
if (Thread.currentThread().isInterrupted()) break;
if ("PROCEDURE".equalsIgnoreCase(routine.getRoutineType())) {
LOG.fine(
"Submitting processing task for procedure: " + routine.getRoutineId());
final Routine finalRoutine = routine;
Future<?> processFuture =
routineProcessorExecutor.submit(
() ->
processProcedureInfo(
finalRoutine, collectedResults, localResultSchemaFields));
processingTaskFutures.add(processFuture);
} else {
LOG.finer("Skipping non-procedure routine: " + routine.getRoutineId());
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.warning("Fetcher thread interrupted while waiting for API future result.");
break;
} catch (ExecutionException e) {
LOG.warning(
"Error executing findMatchingRoutines task: "
+ e.getMessage()
+ ". Cause: "
+ e.getCause());
} catch (CancellationException e) {
LOG.warning("A findMatchingRoutines task was cancelled.");
}
}
LOG.fine(
"Finished submitting "
+ processingTaskFutures.size()
+ " processProcedureInfo tasks.");
if (Thread.currentThread().isInterrupted()) {
LOG.warning(
"Fetcher interrupted before waiting for processing tasks; cancelling remaining.");
processingTaskFutures.forEach(f -> f.cancel(true));
} else {
LOG.fine("Waiting for processProcedureInfo tasks to complete...");
waitForTasksCompletion(processingTaskFutures);
LOG.fine("All processProcedureInfo tasks completed or handled.");
}
if (!Thread.currentThread().isInterrupted()) {
Comparator<FieldValueList> comparator =
defineGetProceduresComparator(localResultSchemaFields);
sortResults(collectedResults, comparator, "getProcedures", LOG);
}
if (!Thread.currentThread().isInterrupted()) {
populateQueue(collectedResults, queue, localResultSchemaFields);
}
} catch (Throwable t) {
LOG.severe("Unexpected error in procedure fetcher runnable: " + t.getMessage());
apiFutures.forEach(f -> f.cancel(true));
processingTaskFutures.forEach(f -> f.cancel(true));
} finally {
signalEndOfData(queue, localResultSchemaFields);
shutdownExecutor(apiExecutor);
shutdownExecutor(routineProcessorExecutor);
LOG.info("Procedure fetcher thread finished.");
}
};
Thread fetcherThread = new Thread(procedureFetcher, "getProcedures-fetcher-" + catalog);
BigQueryJsonResultSet resultSet =
BigQueryJsonResultSet.of(
resultSchema, -1, queue, this.statement, new Thread[] {fetcherThread});
fetcherThread.start();
LOG.info("Started background thread for getProcedures");
return resultSet;
}
Schema defineGetProceduresSchema() {
List<Field> fields = new ArrayList<>(9);
fields.add(
Field.newBuilder("PROCEDURE_CAT", StandardSQLTypeName.STRING)
.setMode(Field.Mode.NULLABLE)
.build());
fields.add(
Field.newBuilder("PROCEDURE_SCHEM", StandardSQLTypeName.STRING)
.setMode(Field.Mode.NULLABLE)
.build());
fields.add(
Field.newBuilder("PROCEDURE_NAME", StandardSQLTypeName.STRING)
.setMode(Field.Mode.REQUIRED)
.build());
fields.add(
Field.newBuilder("reserved1", StandardSQLTypeName.INT64)
.setMode(Field.Mode.NULLABLE)
.build());
fields.add(
Field.newBuilder("reserved2", StandardSQLTypeName.INT64)
.setMode(Field.Mode.NULLABLE)
.build());
fields.add(
Field.newBuilder("reserved3", StandardSQLTypeName.INT64)
.setMode(Field.Mode.NULLABLE)
.build());
fields.add(
Field.newBuilder("REMARKS", StandardSQLTypeName.STRING)
.setMode(Field.Mode.NULLABLE)
.build());
fields.add(
Field.newBuilder("PROCEDURE_TYPE", StandardSQLTypeName.INT64)
.setMode(Field.Mode.REQUIRED)
.build());
fields.add(
Field.newBuilder("SPECIFIC_NAME", StandardSQLTypeName.STRING)
.setMode(Field.Mode.REQUIRED)
.build());
return Schema.of(fields);
}
void processProcedureInfo(
Routine routine, List<FieldValueList> collectedResults, FieldList resultSchemaFields) {
RoutineId routineId = routine.getRoutineId();
LOG.fine("Processing procedure info for: " + routineId);