sqlalchemy-bigquery 1.14.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1442 @@
1
+ # Copyright (c) 2017 The sqlalchemy-bigquery Authors
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ # this software and associated documentation files (the "Software"), to deal in
5
+ # the Software without restriction, including without limitation the rights to
6
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ # the Software, and to permit persons to whom the Software is furnished to do so,
8
+ # subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ """Integration between SQLAlchemy and BigQuery."""
21
+
22
+ import datetime
23
+ from decimal import Decimal
24
+ import random
25
+ import operator
26
+ import uuid
27
+
28
+ from google import auth
29
+ import google.api_core.exceptions
30
+ from google.cloud.bigquery import dbapi, ConnectionProperty
31
+ from google.cloud.bigquery.table import (
32
+ RangePartitioning,
33
+ TableReference,
34
+ TimePartitioning,
35
+ )
36
+ from google.api_core.exceptions import NotFound
37
+ import packaging.version
38
+ import sqlalchemy
39
+ import sqlalchemy.sql.expression
40
+ import sqlalchemy.sql.functions
41
+ import sqlalchemy.sql.sqltypes
42
+ import sqlalchemy.sql.type_api
43
+ from sqlalchemy.exc import NoSuchTableError, NoSuchColumnError
44
+ from sqlalchemy import util
45
+ from sqlalchemy.ext.compiler import compiles
46
+ from sqlalchemy.sql.compiler import (
47
+ SQLCompiler,
48
+ GenericTypeCompiler,
49
+ DDLCompiler,
50
+ IdentifierPreparer,
51
+ )
52
+ from sqlalchemy.sql.sqltypes import Integer, String, NullType, Numeric
53
+ from sqlalchemy.engine.default import DefaultDialect, DefaultExecutionContext
54
+ from sqlalchemy.engine.base import Engine
55
+ from sqlalchemy.sql.schema import Column
56
+ from sqlalchemy.sql.schema import Table
57
+ from sqlalchemy.sql.selectable import CTE
58
+ from sqlalchemy.sql import elements, selectable
59
+ import re
60
+
61
+ from .parse_url import parse_url
62
+ from . import _helpers, _struct, _types
63
+ import sqlalchemy_bigquery_vendored.sqlalchemy.postgresql.base as vendored_postgresql
64
+ from google.cloud.bigquery import QueryJobConfig
65
+
66
+ # Illegal characters is intended to be all characters that are not explicitly
67
+ # allowed as part of the flexible column names.
68
+ # https://cloud.google.com/bigquery/docs/schemas#flexible-column-names
69
+ FIELD_ILLEGAL_CHARACTERS = re.compile(r'[!"$()*,./;?@[\\\]^{}~\n]+', re.ASCII)
70
+
71
+ TABLE_VALUED_ALIAS_ALIASES = "bigquery_table_valued_alias_aliases"
72
+
73
+
74
+ def assert_(cond, message="Assertion failed"): # pragma: NO COVER
75
+ if not cond:
76
+ raise AssertionError(message)
77
+
78
+
79
+ class BigQueryIdentifierPreparer(IdentifierPreparer):
80
+ """
81
+ Set containing everything
82
+ https://github.com/dropbox/PyHive/blob/master/pyhive/sqlalchemy_presto.py
83
+ """
84
+
85
+ def __init__(self, dialect):
86
+ super(BigQueryIdentifierPreparer, self).__init__(
87
+ dialect,
88
+ initial_quote="`",
89
+ )
90
+
91
+ def quote_column(self, value):
92
+ """
93
+ Quote a column.
94
+ Fields are quoted separately from the record name.
95
+ """
96
+
97
+ parts = value.split(".")
98
+ return ".".join(self.quote_identifier(x) for x in parts)
99
+
100
+ def quote(self, ident, force=None, column=False):
101
+ """
102
+ Conditionally quote an identifier.
103
+ """
104
+
105
+ force = getattr(ident, "quote", None)
106
+ if force is None or force:
107
+ return self.quote_column(ident) if column else self.quote_identifier(ident)
108
+ else:
109
+ return ident
110
+
111
+ def format_label(self, label, name=None):
112
+ name = name or label.name
113
+
114
+ # Fields must start with a letter or underscore
115
+ if not name[0].isalpha() and name[0] != "_":
116
+ name = "_" + name
117
+
118
+ # Fields must contain only letters, numbers, and underscores
119
+ name = FIELD_ILLEGAL_CHARACTERS.sub("_", name)
120
+
121
+ result = self.quote(name)
122
+ return result
123
+
124
+
125
+ class BigQueryExecutionContext(DefaultExecutionContext):
126
+ def create_cursor(self):
127
+ # Set arraysize
128
+ c = super(BigQueryExecutionContext, self).create_cursor()
129
+ if self.dialect.arraysize:
130
+ c.arraysize = self.dialect.arraysize
131
+ return c
132
+
133
+ def get_insert_default(self, column): # pragma: NO COVER
134
+ # Only used by compliance tests
135
+ if isinstance(column.type, Integer):
136
+ return random.randint(-9223372036854775808, 9223372036854775808) # 1<<63
137
+ elif isinstance(column.type, String):
138
+ return str(uuid.uuid4())
139
+
140
+ __remove_type_from_empty_in = _helpers.substitute_string_re_method(
141
+ r"""
142
+ \sIN\sUNNEST\(\[\s # ' IN UNNEST([ '
143
+ (
144
+ (?:NULL|\(NULL(?:,\sNULL)+\))\) # '(NULL)' or '((NULL, NULL, ...))'
145
+ \s(?:AND|OR)\s\(1\s!?=\s1 # ' and 1 != 1' or ' or 1 = 1'
146
+ )
147
+ (?:[:][A-Z0-9]+)? # Maybe ':TYPE' (e.g. ':INT64')
148
+ \s\]\) # Close: ' ])'
149
+ """,
150
+ flags=re.IGNORECASE | re.VERBOSE,
151
+ repl=r" IN(\1)",
152
+ )
153
+
154
+ @_helpers.substitute_re_method(
155
+ r"""
156
+ \sIN\sUNNEST\(\[\s # ' IN UNNEST([ '
157
+ ( # Placeholders. See below.
158
+ %\([^)]+_\d+\)s # Placeholder '%(foo_1)s'
159
+ (?:,\s # 0 or more placeholders
160
+ %\([^)]+_\d+\)s
161
+ )*
162
+ )?
163
+ :([A-Z0-9]+) # Type ':TYPE' (e.g. ':INT64')
164
+ \s\]\) # Close: ' ])'
165
+ """,
166
+ flags=re.IGNORECASE | re.VERBOSE,
167
+ )
168
+ def __distribute_types_to_expanded_placeholders(self, m): # pragma: NO COVER
169
+ # If we have an in parameter, it sometimes gets expaned to 0 or more
170
+ # parameters and we need to move the type marker to each
171
+ # parameter.
172
+ # (The way SQLAlchemy handles this is a bit awkward for our
173
+ # purposes.)
174
+
175
+ # In the placeholder part of the regex above, the `_\d+
176
+ # suffixes refect that when an array parameter is expanded,
177
+ # numeric suffixes are added. For example, a placeholder like
178
+ # `%(foo)s` gets expaneded to `%(foo_0)s, `%(foo_1)s, ...`.
179
+
180
+ # Coverage: despite our best efforts, never recognized this segment of code as being tested.
181
+ placeholders, type_ = m.groups()
182
+ if placeholders:
183
+ placeholders = placeholders.replace(")", f":{type_})")
184
+ else:
185
+ placeholders = ""
186
+ return f" IN UNNEST([ {placeholders} ])"
187
+
188
+ def pre_exec(self):
189
+ self.statement = self.__distribute_types_to_expanded_placeholders(
190
+ self.__remove_type_from_empty_in(self.statement)
191
+ )
192
+
193
+
194
+ class BigQueryCompiler(_struct.SQLCompiler, vendored_postgresql.PGCompiler):
195
+ compound_keywords = SQLCompiler.compound_keywords.copy()
196
+ compound_keywords[selectable.CompoundSelect.UNION] = "UNION DISTINCT"
197
+ compound_keywords[selectable.CompoundSelect.UNION_ALL] = "UNION ALL"
198
+ compound_keywords[selectable.CompoundSelect.EXCEPT] = "EXCEPT DISTINCT"
199
+ compound_keywords[selectable.CompoundSelect.INTERSECT] = "INTERSECT DISTINCT"
200
+
201
+ def __init__(self, dialect, statement, *args, **kwargs):
202
+ if isinstance(statement, Column):
203
+ kwargs["compile_kwargs"] = util.immutabledict({"include_table": False})
204
+ super(BigQueryCompiler, self).__init__(dialect, statement, *args, **kwargs)
205
+
206
+ def visit_insert(self, insert_stmt, asfrom=False, **kw):
207
+ # The (internal) documentation for `inline` is confusing, but
208
+ # having `inline` be true prevents us from generating default
209
+ # primary-key values when we're doing executemany, which seem broken.
210
+
211
+ # We can probably do this in the constructor, but I want to
212
+ # make sure this only affects insert, because I'm paranoid. :)
213
+
214
+ self.inline = False
215
+
216
+ return super(BigQueryCompiler, self).visit_insert(
217
+ insert_stmt, asfrom=False, **kw
218
+ )
219
+
220
+ def visit_table_valued_alias(self, element, **kw):
221
+ # When using table-valued functions, like UNNEST, BigQuery requires a
222
+ # FROM for any table referenced in the function, including expressions
223
+ # in function arguments.
224
+ #
225
+ # For example, given SQLAlchemy code:
226
+ #
227
+ # print(
228
+ # select(func.unnest(foo.c.objects).alias('foo_objects').column)
229
+ # .compile(engine))
230
+ #
231
+ # Left to it's own devices, SQLAlchemy would outout:
232
+ #
233
+ # SELECT `foo_objects`
234
+ # FROM unnest(`foo`.`objects`) AS `foo_objects`
235
+ #
236
+ # But BigQuery diesn't understand the `foo` reference unless
237
+ # we add as reference to `foo` in the FROM:
238
+ #
239
+ # SELECT foo_objects
240
+ # FROM `foo`, UNNEST(`foo`.`objects`) as foo_objects
241
+ #
242
+ # This is tricky because:
243
+ # 1. We have to find the table references.
244
+ # 2. We can't know practically if there's already a FROM for a table.
245
+ #
246
+ # We leverage visit_column to find a table reference. Whenever we find
247
+ # one, we create an alias for it, so as not to conflict with an existing
248
+ # reference if one is present.
249
+ #
250
+ # This requires communicating between this function and visit_column.
251
+ # We do this by sticking a dictionary in the keyword arguments.
252
+ # This dictionary:
253
+ # a. Tells visit_column that it's an a table-valued alias expresssion, and
254
+ # b. Gives it a place to record the aliases it creates.
255
+ #
256
+ # This function creates aliases in the FROM list for any aliases recorded
257
+ # by visit_column.
258
+
259
+ kw[TABLE_VALUED_ALIAS_ALIASES] = {}
260
+ ret = super().visit_table_valued_alias(element, **kw)
261
+ aliases = kw.pop(TABLE_VALUED_ALIAS_ALIASES)
262
+ if aliases:
263
+ aliases = ", ".join(
264
+ f"{self.preparer.quote(tablename)} {self.preparer.quote(alias)}"
265
+ for tablename, alias in aliases.items()
266
+ )
267
+ ret = f"{aliases}, {ret}"
268
+ return ret
269
+
270
+ def _known_tables(self):
271
+ known_tables = set()
272
+
273
+ for from_ in self.compile_state.froms:
274
+ if isinstance(from_, Table):
275
+ known_tables.add(from_.name)
276
+ elif isinstance(from_, CTE):
277
+ known_tables.add(from_.name)
278
+ for column in from_.original.selected_columns:
279
+ table = getattr(column, "table", None)
280
+ if table is not None:
281
+ known_tables.add(table.name)
282
+
283
+ # If we have the table in the `from` of our parent, do not add the alias
284
+ # as this will add the table twice and cause an implicit JOIN for that
285
+ # table on itself
286
+ asfrom_froms = self.stack[-1].get("asfrom_froms", [])
287
+ for from_ in asfrom_froms:
288
+ if isinstance(from_, Table):
289
+ known_tables.add(from_.name)
290
+
291
+ return known_tables
292
+
293
+ def visit_column(
294
+ self,
295
+ column,
296
+ add_to_result_map=None,
297
+ include_table=True,
298
+ result_map_targets=(),
299
+ **kwargs,
300
+ ):
301
+ name = orig_name = column.name
302
+ if name is None:
303
+ name = self._fallback_column_name(column)
304
+
305
+ is_literal = column.is_literal
306
+ if not is_literal and isinstance(name, elements._truncated_label):
307
+ name = self._truncated_identifier("colident", name)
308
+
309
+ if add_to_result_map is not None:
310
+ targets = (column, name, column.key) + result_map_targets
311
+ if getattr(column, "_tq_label", None):
312
+ # _tq_label was added in SQLAlchemy 1.4
313
+ targets += (column._tq_label,)
314
+
315
+ add_to_result_map(name, orig_name, targets, column.type)
316
+
317
+ if is_literal:
318
+ name = self.escape_literal_column(name)
319
+ else:
320
+ name = self.preparer.quote(name, column=True)
321
+ table = column.table
322
+ if table is None or not include_table or not table.named_with_column:
323
+ return name
324
+ else:
325
+ tablename = table.name
326
+ if isinstance(tablename, elements._truncated_label):
327
+ tablename = self._truncated_identifier("alias", tablename)
328
+ elif TABLE_VALUED_ALIAS_ALIASES in kwargs:
329
+ if tablename not in self._known_tables():
330
+ aliases = kwargs[TABLE_VALUED_ALIAS_ALIASES]
331
+ if tablename not in aliases:
332
+ aliases[tablename] = self.anon_map[
333
+ f"{TABLE_VALUED_ALIAS_ALIASES} {tablename}"
334
+ ]
335
+ tablename = aliases[tablename]
336
+
337
+ return self.preparer.quote(tablename) + "." + name
338
+
339
+ def visit_label(self, *args, within_group_by=False, **kwargs):
340
+ # Use labels in GROUP BY clause.
341
+ #
342
+ # Flag set in the group_by_clause method. Works around missing
343
+ # equivalent to supports_simple_order_by_label for group by.
344
+ if within_group_by:
345
+ column_label = args[0]
346
+ sql_keywords = {"GROUPING SETS", "ROLLUP", "CUBE"}
347
+ label_str = column_label.compile(dialect=self.dialect).string
348
+ if not any(keyword in label_str for keyword in sql_keywords):
349
+ kwargs["render_label_as_label"] = column_label
350
+
351
+ return super(BigQueryCompiler, self).visit_label(*args, **kwargs)
352
+
353
+ def group_by_clause(self, select, **kw):
354
+ return super(BigQueryCompiler, self).group_by_clause(
355
+ select, **kw, within_group_by=True
356
+ )
357
+
358
+ ############################################################################
359
+ # Handle parameters in in
360
+
361
+ # Due to details in the way sqlalchemy arranges the compilation we
362
+ # expect the bind parameter as an array and unnest it.
363
+
364
+ # As it happens, bigquery can handle arrays directly, but there's
365
+ # no way to tell sqlalchemy that, so it works harder than
366
+ # necessary and makes us do the same.
367
+
368
+ __sqlalchemy_version_info = packaging.version.parse(sqlalchemy.__version__)
369
+
370
+ __expanding_text = "POSTCOMPILE"
371
+
372
+ # https://github.com/sqlalchemy/sqlalchemy/commit/f79df12bd6d99b8f6f09d4bf07722638c4b4c159
373
+ __expanding_conflict = (
374
+ "" if __sqlalchemy_version_info < packaging.version.parse("1.4.27") else "__"
375
+ )
376
+
377
+ __in_expanding_bind = _helpers.substitute_string_re_method(
378
+ rf"""
379
+ \sIN\s\( # ' IN ('
380
+ (
381
+ {__expanding_conflict}\[ # Expanding placeholder
382
+ {__expanding_text} # e.g. [EXPANDING_foo_1]
383
+ _[^\]]+ #
384
+ \]
385
+ (:[A-Z0-9]+)? # type marker (e.g. ':INT64'
386
+ )
387
+ \)$ # close w ending )
388
+ """,
389
+ flags=re.IGNORECASE | re.VERBOSE,
390
+ repl=r" IN UNNEST([ \1 ])",
391
+ )
392
+
393
+ def visit_in_op_binary(self, binary, operator_, **kw):
394
+ return self.__in_expanding_bind(
395
+ self._generate_generic_binary(binary, " IN ", **kw)
396
+ )
397
+
398
+ def visit_not_in_op_binary(self, binary, operator, **kw):
399
+ return (
400
+ "("
401
+ + self.__in_expanding_bind(
402
+ self._generate_generic_binary(binary, " NOT IN ", **kw)
403
+ )
404
+ + ")"
405
+ )
406
+
407
+ ############################################################################
408
+
409
+ ############################################################################
410
+ # Correct for differences in the way that SQLAlchemy escape % and _ (/)
411
+ # and BigQuery does (\\).
412
+
413
+ @staticmethod
414
+ def _maybe_reescape(binary):
415
+ binary = binary._clone()
416
+ escape = binary.modifiers.pop("escape", None)
417
+ if escape and escape != "\\":
418
+ binary.right.value = escape.join(
419
+ v.replace(escape, "\\")
420
+ for v in binary.right.value.split(escape + escape)
421
+ )
422
+ return binary
423
+
424
+ def visit_contains_op_binary(self, binary, operator, **kw):
425
+ return super(BigQueryCompiler, self).visit_contains_op_binary(
426
+ self._maybe_reescape(binary), operator, **kw
427
+ )
428
+
429
+ def visit_not_contains_op_binary(self, binary, operator, **kw):
430
+ return super(BigQueryCompiler, self).visit_not_contains_op_binary(
431
+ self._maybe_reescape(binary), operator, **kw
432
+ )
433
+
434
+ def visit_startswith_op_binary(self, binary, operator, **kw):
435
+ return super(BigQueryCompiler, self).visit_startswith_op_binary(
436
+ self._maybe_reescape(binary), operator, **kw
437
+ )
438
+
439
+ def visit_not_startswith_op_binary(self, binary, operator, **kw):
440
+ return super(BigQueryCompiler, self).visit_not_startswith_op_binary(
441
+ self._maybe_reescape(binary), operator, **kw
442
+ )
443
+
444
+ def visit_endswith_op_binary(self, binary, operator, **kw):
445
+ return super(BigQueryCompiler, self).visit_endswith_op_binary(
446
+ self._maybe_reescape(binary), operator, **kw
447
+ )
448
+
449
+ def visit_not_endswith_op_binary(self, binary, operator, **kw):
450
+ return super(BigQueryCompiler, self).visit_not_endswith_op_binary(
451
+ self._maybe_reescape(binary), operator, **kw
452
+ )
453
+
454
+ ############################################################################
455
+
456
+ __placeholder = re.compile(r"%\(([^\]:]+)(:[^\]:]+)?\)s$").match
457
+
458
+ __expanded_param = re.compile(
459
+ rf"\({__expanding_conflict}\[" rf"{__expanding_text}" rf"_[^\]]+\]\)$"
460
+ ).match
461
+
462
+ __remove_type_parameter = _helpers.substitute_string_re_method(
463
+ r"""
464
+ (STRING|BYTES|NUMERIC|BIGNUMERIC) # Base type
465
+ \( # Dimensions e.g. '(42)', '(4, 2)':
466
+ \s*\d+\s* # First dimension
467
+ (?:,\s*\d+\s*)* # Remaining dimensions
468
+ \)
469
+ """,
470
+ repl=r"\1",
471
+ flags=re.VERBOSE | re.IGNORECASE,
472
+ )
473
+
474
+ def visit_bindparam(
475
+ self,
476
+ bindparam,
477
+ within_columns_clause=False,
478
+ literal_binds=False,
479
+ skip_bind_expression=False,
480
+ **kwargs,
481
+ ):
482
+ type_ = bindparam.type
483
+ unnest = False
484
+ if (
485
+ bindparam.expanding
486
+ and not isinstance(type_, NullType)
487
+ and not literal_binds
488
+ ):
489
+ # Normally, when performing an IN operation, like:
490
+ #
491
+ # foo IN (some_sequence)
492
+ #
493
+ # SQAlchemy passes `foo` as a parameter and unpacks
494
+ # `some_sequence` and passes each element as a parameter.
495
+ # This mechanism is refered to as "expanding". It's
496
+ # inefficient and can't handle large arrays. (It's also
497
+ # very complicated, but that's not the issue we care about
498
+ # here. :) ) BigQuery lets us use arrays directly in this
499
+ # context, we just need to call UNNEST on an array when
500
+ # it's used in IN.
501
+ #
502
+ # So, if we get an `expanding` flag, and if we have a known type
503
+ # (and don't have literal binds, which are implemented in-line in
504
+ # in the SQL), we turn off expanding and we set an unnest flag
505
+ # so that we add an UNNEST() call (below).
506
+ #
507
+ # The NullType/known-type check has to do with some extreme
508
+ # edge cases having to do with empty in-lists that get special
509
+ # hijinks from SQLAlchemy that we don't want to disturb. :)
510
+ #
511
+ # Note that we do *not* want to overwrite the "real" bindparam
512
+ # here, because then we can't do a recompile later (e.g., first
513
+ # print the statment, then execute it). See issue #357.
514
+ #
515
+ # Coverage: despite our best efforts, never recognized this segment of code as being tested.
516
+ if getattr(bindparam, "expand_op", None) is not None: # pragma: NO COVER
517
+ assert bindparam.expand_op.__name__.endswith("in_op") # in in
518
+ bindparam = bindparam._clone(maintain_key=True)
519
+ bindparam.expanding = False
520
+ unnest = True
521
+
522
+ param = super(BigQueryCompiler, self).visit_bindparam(
523
+ bindparam,
524
+ within_columns_clause,
525
+ literal_binds,
526
+ skip_bind_expression,
527
+ **kwargs,
528
+ )
529
+
530
+ if literal_binds or isinstance(type_, NullType):
531
+ return param
532
+
533
+ if (
534
+ isinstance(type_, Numeric)
535
+ and (type_.precision is None or type_.scale is None)
536
+ and isinstance(bindparam.value, Decimal)
537
+ ):
538
+ t = bindparam.value.as_tuple()
539
+
540
+ if type_.precision is None:
541
+ type_.precision = len(t.digits)
542
+
543
+ if type_.scale is None and t.exponent < 0:
544
+ type_.scale = -t.exponent
545
+
546
+ bq_type = self.dialect.type_compiler.process(type_)
547
+ bq_type = self.__remove_type_parameter(bq_type)
548
+
549
+ assert_(param != "%s", f"Unexpected param: {param}")
550
+
551
+ if bindparam.expanding: # pragma: NO COVER
552
+ assert_(self.__expanded_param(param), f"Unexpected param: {param}")
553
+ if self.__sqlalchemy_version_info < packaging.version.parse("1.4.27"):
554
+ param = param.replace(")", f":{bq_type})")
555
+
556
+ else:
557
+ m = self.__placeholder(param)
558
+ if m:
559
+ name, type_ = m.groups()
560
+ assert_(type_ is None)
561
+ param = f"%({name}:{bq_type})s"
562
+
563
+ if unnest:
564
+ param = f"UNNEST({param})"
565
+
566
+ return param
567
+
568
+ def visit_getitem_binary(self, binary, operator_, **kw):
569
+ left = self.process(binary.left, **kw)
570
+ right = self.process(binary.right, **kw)
571
+ return f"{left}[OFFSET({right})]"
572
+
573
+ def _get_regexp_args(self, binary, kw):
574
+ string = self.process(binary.left, **kw)
575
+ pattern = self.process(binary.right, **kw)
576
+ return string, pattern
577
+
578
+ def visit_regexp_match_op_binary(self, binary, operator, **kw):
579
+ string, pattern = self._get_regexp_args(binary, kw)
580
+ return "REGEXP_CONTAINS(%s, %s)" % (string, pattern)
581
+
582
+ def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
583
+ return "NOT %s" % self.visit_regexp_match_op_binary(binary, operator, **kw)
584
+
585
+ def visit_mod_binary(self, binary, operator, **kw):
586
+ return f"MOD({self.process(binary.left, **kw)}, {self.process(binary.right, **kw)})"
587
+
588
+
589
+ class BigQueryTypeCompiler(GenericTypeCompiler):
590
+ def visit_INTEGER(self, type_, **kw):
591
+ return "INT64"
592
+
593
+ visit_BIGINT = visit_SMALLINT = visit_INTEGER
594
+
595
+ def visit_BOOLEAN(self, type_, **kw):
596
+ return "BOOL"
597
+
598
+ def visit_FLOAT(self, type_, **kw):
599
+ return "FLOAT64"
600
+
601
+ visit_REAL = visit_FLOAT
602
+
603
+ def visit_STRING(self, type_, **kw):
604
+ if (type_.length is not None) and isinstance(
605
+ kw.get("type_expression"), Column
606
+ ): # column def
607
+ return f"STRING({type_.length})"
608
+ return "STRING"
609
+
610
+ visit_CHAR = visit_NCHAR = visit_STRING
611
+ visit_VARCHAR = visit_NVARCHAR = visit_TEXT = visit_STRING
612
+
613
+ def visit_ARRAY(self, type_, **kw):
614
+ return "ARRAY<{}>".format(self.process(type_.item_type, **kw))
615
+
616
+ def visit_BINARY(self, type_, **kw):
617
+ if type_.length is not None:
618
+ return f"BYTES({type_.length})"
619
+ return "BYTES"
620
+
621
+ visit_VARBINARY = visit_BLOB = visit_BINARY
622
+
623
+ def visit_NUMERIC(self, type_, **kw):
624
+ if (type_.precision is not None) and isinstance(
625
+ kw.get("type_expression"), Column
626
+ ): # column def
627
+ if type_.scale is not None:
628
+ suffix = f"({type_.precision}, {type_.scale})"
629
+ else:
630
+ suffix = f"({type_.precision})"
631
+ else:
632
+ suffix = ""
633
+
634
+ return (
635
+ "BIGNUMERIC"
636
+ if (type_.precision is not None and type_.precision > 38)
637
+ or (type_.scale is not None and type_.scale > 9)
638
+ else "NUMERIC"
639
+ ) + suffix
640
+
641
+ visit_DECIMAL = visit_NUMERIC
642
+
643
+
644
+ class BigQueryDDLCompiler(DDLCompiler):
645
+ option_datatype_mapping = {
646
+ "friendly_name": str,
647
+ "expiration_timestamp": datetime.datetime,
648
+ "require_partition_filter": bool,
649
+ "default_rounding_mode": str,
650
+ }
651
+
652
+ # BigQuery has no support for foreign keys.
653
+ def visit_foreign_key_constraint(self, constraint, **kw):
654
+ return None
655
+
656
+ # BigQuery has no support for primary keys.
657
+ def visit_primary_key_constraint(self, constraint, **kw):
658
+ return None
659
+
660
+ # BigQuery has no support for unique constraints.
661
+ def visit_unique_constraint(self, constraint, **kw):
662
+ return None
663
+
664
+ def get_column_specification(self, column, **kwargs):
665
+ colspec = super(BigQueryDDLCompiler, self).get_column_specification(
666
+ column, **kwargs
667
+ )
668
+ if column.comment is not None:
669
+ colspec = "{} OPTIONS(description={})".format(
670
+ colspec, process_string_literal(column.comment)
671
+ )
672
+ return colspec
673
+
674
+ def post_create_table(self, table):
675
+ """
676
+ Constructs additional SQL clauses for table creation in BigQuery.
677
+
678
+ This function processes the BigQuery dialect-specific options and generates SQL clauses for partitioning,
679
+ clustering, and other table options.
680
+
681
+ Args:
682
+ table (Table): The SQLAlchemy Table object for which the SQL is being generated.
683
+
684
+ Returns:
685
+ str: A string composed of SQL clauses for time partitioning, clustering, and other BigQuery specific
686
+ options, each separated by a newline. Returns an empty string if no such options are specified.
687
+
688
+ Raises:
689
+ TypeError: If the time_partitioning option is not a `TimePartitioning` object or if the clustering_fields option is not a list.
690
+ NoSuchColumnError: If any field specified in clustering_fields does not exist in the table.
691
+ """
692
+
693
+ bq_opts = table.dialect_options["bigquery"]
694
+
695
+ options = {}
696
+ clauses = []
697
+
698
+ if (
699
+ bq_opts.get("time_partitioning") is not None
700
+ and bq_opts.get("range_partitioning") is not None
701
+ ):
702
+ raise ValueError(
703
+ "biquery_time_partitioning and bigquery_range_partitioning"
704
+ " dialect options are mutually exclusive."
705
+ )
706
+
707
+ if (time_partitioning := bq_opts.get("time_partitioning")) is not None:
708
+ self._raise_for_type(
709
+ "time_partitioning",
710
+ time_partitioning,
711
+ TimePartitioning,
712
+ )
713
+
714
+ if time_partitioning.expiration_ms:
715
+ _24hours = 1000 * 60 * 60 * 24
716
+ options["partition_expiration_days"] = (
717
+ time_partitioning.expiration_ms / _24hours
718
+ )
719
+
720
+ partition_by_clause = self._process_time_partitioning(
721
+ table,
722
+ time_partitioning,
723
+ )
724
+
725
+ clauses.append(partition_by_clause)
726
+
727
+ if (range_partitioning := bq_opts.get("range_partitioning")) is not None:
728
+ self._raise_for_type(
729
+ "range_partitioning",
730
+ range_partitioning,
731
+ RangePartitioning,
732
+ )
733
+
734
+ partition_by_clause = self._process_range_partitioning(
735
+ table,
736
+ range_partitioning,
737
+ )
738
+
739
+ clauses.append(partition_by_clause)
740
+
741
+ if (clustering_fields := bq_opts.get("clustering_fields")) is not None:
742
+ self._raise_for_type("clustering_fields", clustering_fields, list)
743
+
744
+ for field in clustering_fields:
745
+ if field not in table.c:
746
+ raise NoSuchColumnError(field)
747
+
748
+ clauses.append(f"CLUSTER BY {', '.join(clustering_fields)}")
749
+
750
+ if ("description" in bq_opts) or table.comment:
751
+ description = bq_opts.get("description", table.comment)
752
+ self._validate_option_value_type("description", description)
753
+ options["description"] = description
754
+
755
+ for option in self.option_datatype_mapping:
756
+ if option in bq_opts:
757
+ options[option] = bq_opts.get(option)
758
+
759
+ if options:
760
+ individual_option_statements = [
761
+ "{}={}".format(k, self._process_option_value(v))
762
+ for (k, v) in options.items()
763
+ if self._validate_option_value_type(k, v)
764
+ ]
765
+ clauses.append(f"OPTIONS({', '.join(individual_option_statements)})")
766
+
767
+ return " " + "\n".join(clauses)
768
+
769
+ def visit_set_table_comment(self, create, **kw):
770
+ table_name = self.preparer.format_table(create.element)
771
+ description = self.sql_compiler.render_literal_value(
772
+ create.element.comment, sqlalchemy.sql.sqltypes.String()
773
+ )
774
+ return f"ALTER TABLE {table_name} SET OPTIONS(description={description})"
775
+
776
+ def visit_drop_table_comment(self, drop, **kw):
777
+ table_name = self.preparer.format_table(drop.element)
778
+ return f"ALTER TABLE {table_name} SET OPTIONS(description=null)"
779
+
780
+ def _validate_option_value_type(self, option: str, value):
781
+ """
782
+ Validates the type of the given option value against the expected data type.
783
+
784
+ Args:
785
+ option (str): The name of the option to be validated.
786
+ value: The value of the dialect option whose type is to be checked. The type of this parameter
787
+ is dynamic and is verified against the expected type in `self.option_datatype_mapping`.
788
+
789
+ Returns:
790
+ bool: True if the type of the value matches the expected type, or if the option is not found in
791
+ `self.option_datatype_mapping`.
792
+
793
+ Raises:
794
+ TypeError: If the type of the provided value does not match the expected type as defined in
795
+ `self.option_datatype_mapping`.
796
+ """
797
+ if option in self.option_datatype_mapping:
798
+ self._raise_for_type(
799
+ option,
800
+ value,
801
+ self.option_datatype_mapping[option],
802
+ )
803
+
804
+ return True
805
+
806
+ def _raise_for_type(self, option, value, expected_type):
807
+ if type(value) is not expected_type:
808
+ raise TypeError(
809
+ f"bigquery_{option} dialect option accepts only {expected_type},"
810
+ f" provided {repr(value)}"
811
+ )
812
+
813
+ def _process_time_partitioning(
814
+ self,
815
+ table: Table,
816
+ time_partitioning: TimePartitioning,
817
+ ):
818
+ """
819
+ Generates a SQL 'PARTITION BY' clause for partitioning a table,
820
+
821
+ Args:
822
+ - table (Table): The SQLAlchemy table object representing the BigQuery
823
+ table to be partitioned.
824
+ - time_partitioning (TimePartitioning): The time partitioning details,
825
+ including the field to be used for partitioning.
826
+
827
+ Returns:
828
+ - str: A SQL 'PARTITION BY' clause.
829
+
830
+ Example:
831
+ - Given a table with an 'event_timestamp' and setting time_partitioning.type
832
+ as DAY and by setting 'time_partitioning.field' as 'event_timestamp', the
833
+ function returns:
834
+ "PARTITION BY TIMESTAMP_TRUNC(event_timestamp, DAY)".
835
+
836
+ Current inputs allowed by BQ and covered by this function include:
837
+ * _PARTITIONDATE
838
+ * DATETIME_TRUNC(<datetime_column>, DAY/HOUR/MONTH/YEAR)
839
+ * TIMESTAMP_TRUNC(<timestamp_column>, DAY/HOUR/MONTH/YEAR)
840
+ * DATE_TRUNC(<date_column>, MONTH/YEAR)
841
+
842
+ Additional options allowed by BQ but not explicitly covered by this
843
+ function include:
844
+ * DATE(_PARTITIONTIME)
845
+ * DATE(<timestamp_column>)
846
+ * DATE(<datetime_column>)
847
+ * DATE column
848
+ """
849
+
850
+ sqltypes = {
851
+ "_PARTITIONDATE": ("_PARTITIONDATE", None),
852
+ "TIMESTAMP": ("TIMESTAMP_TRUNC", {"DAY", "HOUR", "MONTH", "YEAR"}),
853
+ "DATETIME": ("DATETIME_TRUNC", {"DAY", "HOUR", "MONTH", "YEAR"}),
854
+ "DATE": ("DATE_TRUNC", {"MONTH", "YEAR"}),
855
+ }
856
+
857
+ # Extract field (i.e <column_name> or _PARTITIONDATE)
858
+ # AND extract the name of the column_type (i.e. "TIMESTAMP", "DATE",
859
+ # "DATETIME", "_PARTITIONDATE")
860
+ if time_partitioning.field is not None:
861
+ field = time_partitioning.field
862
+ column_type = table.columns[field].type.__visit_name__.upper()
863
+
864
+ else:
865
+ field = "_PARTITIONDATE"
866
+ column_type = "_PARTITIONDATE"
867
+
868
+ # Extract time_partitioning.type_ (DAY, HOUR, MONTH, YEAR)
869
+ # i.e. generates one partition per type (1/DAY, 1/HOUR)
870
+ # NOTE: if time_partitioning.type_ == None, it gets
871
+ # immediately overwritten by python-bigquery to a default of DAY.
872
+ partitioning_period = time_partitioning.type_
873
+
874
+ # Extract the truncation_function (i.e. DATE_TRUNC)
875
+ # and the set of allowable partition_periods
876
+ # that can be used in that function
877
+ trunc_fn, allowed_partitions = sqltypes[column_type]
878
+
879
+ # Create output:
880
+ # Special Case: _PARTITIONDATE does NOT use a function or partitioning_period
881
+ if trunc_fn == "_PARTITIONDATE":
882
+ return f"PARTITION BY {field}"
883
+
884
+ # Special Case: BigQuery will not accept DAY as partitioning_period for
885
+ # DATE_TRUNC.
886
+ # However, the default argument in python-bigquery for TimePartioning
887
+ # is DAY. This case overwrites that to avoid making a breaking change in
888
+ # python-bigquery.
889
+ # https://github.com/googleapis/python-bigquery/blob/a4d9534a900f13ae7355904cda05097d781f27e3/google/cloud/bigquery/table.py#L2916
890
+ if trunc_fn == "DATE_TRUNC" and partitioning_period == "DAY":
891
+ raise ValueError(
892
+ "The TimePartitioning.type_ must be one of: "
893
+ f"{allowed_partitions}, received {partitioning_period}."
894
+ "NOTE: the `default` value for TimePartioning.type_ as set in "
895
+ "python-bigquery is 'DAY', if you wish to use 'DATE_TRUNC' "
896
+ "ensure that you overwrite the default TimePartitioning.type_. "
897
+ )
898
+
899
+ # Generic Case
900
+ if partitioning_period not in allowed_partitions:
901
+ raise ValueError(
902
+ "The TimePartitioning.type_ must be one of: "
903
+ f"{allowed_partitions}, received {partitioning_period}."
904
+ )
905
+
906
+ return f"PARTITION BY {trunc_fn}({field}, {partitioning_period})"
907
+
908
+ def _process_range_partitioning(
909
+ self, table: Table, range_partitioning: RangePartitioning
910
+ ):
911
+ """
912
+ Generates a SQL 'PARTITION BY' clause for partitioning a table by a range of integers.
913
+
914
+ Args:
915
+ - table (Table): The SQLAlchemy table object representing the BigQuery table to be partitioned.
916
+ - range_partitioning (RangePartitioning): The RangePartitioning object containing the
917
+ partitioning field, range start, range end, and interval.
918
+
919
+ Returns:
920
+ - str: A SQL string for range partitioning using RANGE_BUCKET and GENERATE_ARRAY functions.
921
+
922
+ Raises:
923
+ - AttributeError: If the partitioning field is not defined.
924
+ - ValueError: If the partitioning field (i.e. column) data type is not an integer.
925
+ - TypeError: If the partitioning range start/end values are not integers.
926
+
927
+ Example:
928
+ "PARTITION BY RANGE_BUCKET(zipcode, GENERATE_ARRAY(0, 100000, 10))"
929
+ """
930
+ if range_partitioning.field is None:
931
+ raise AttributeError(
932
+ "bigquery_range_partitioning expects field to be defined"
933
+ )
934
+
935
+ if not isinstance(
936
+ table.columns[range_partitioning.field].type,
937
+ sqlalchemy.sql.sqltypes.INT,
938
+ ):
939
+ raise ValueError(
940
+ "bigquery_range_partitioning expects field (i.e. column) data type to be INTEGER"
941
+ )
942
+
943
+ range_ = range_partitioning.range_
944
+
945
+ if not isinstance(range_.start, int):
946
+ raise TypeError(
947
+ "bigquery_range_partitioning expects range_.start to be an int,"
948
+ f" provided {repr(range_.start)}"
949
+ )
950
+
951
+ if not isinstance(range_.end, int):
952
+ raise TypeError(
953
+ "bigquery_range_partitioning expects range_.end to be an int,"
954
+ f" provided {repr(range_.end)}"
955
+ )
956
+
957
+ default_interval = 1
958
+
959
+ return f"PARTITION BY RANGE_BUCKET({range_partitioning.field}, GENERATE_ARRAY({range_.start}, {range_.end}, {range_.interval or default_interval}))"
960
+
961
+ def _process_option_value(self, value):
962
+ """
963
+ Transforms the given option value into a literal representation suitable for SQL queries in BigQuery.
964
+
965
+ Args:
966
+ value: The value to be transformed.
967
+
968
+ Returns:
969
+ The processed value in a format suitable for inclusion in a SQL query.
970
+
971
+ Raises:
972
+ NotImplementedError: When there is no transformation registered for a data type.
973
+ """
974
+ option_casting = {
975
+ # Mapping from option type to its casting method
976
+ str: lambda x: process_string_literal(x),
977
+ int: lambda x: x,
978
+ float: lambda x: x,
979
+ bool: lambda x: "true" if x else "false",
980
+ datetime.datetime: lambda x: BQTimestamp.process_timestamp_literal(x),
981
+ }
982
+
983
+ if (option_cast := option_casting.get(type(value))) is not None:
984
+ return option_cast(value)
985
+
986
+ raise NotImplementedError(f"No transformation registered for {repr(value)}")
987
+
988
+
989
+ def process_string_literal(value):
990
+ return repr(value.replace("%", "%%"))
991
+
992
+
993
+ class BQString(String):
994
+ def literal_processor(self, dialect):
995
+ return process_string_literal
996
+
997
+
998
+ class BQBinary(sqlalchemy.sql.sqltypes._Binary):
999
+ @staticmethod
1000
+ def __process_bytes_literal(value):
1001
+ return repr(value.replace(b"%", b"%%"))
1002
+
1003
+ def literal_processor(self, dialect):
1004
+ return self.__process_bytes_literal
1005
+
1006
+
1007
+ class BQClassTaggedStr(sqlalchemy.sql.type_api.TypeEngine):
1008
+ """Type that can get literals via str"""
1009
+
1010
+ @staticmethod
1011
+ def process_literal_as_class_tagged_str(value):
1012
+ return f"{value.__class__.__name__.upper()} {repr(str(value))}"
1013
+
1014
+ def literal_processor(self, dialect):
1015
+ return self.process_literal_as_class_tagged_str
1016
+
1017
+
1018
+ class BQTimestamp(sqlalchemy.sql.type_api.TypeEngine):
1019
+ """Type that can get literals via str"""
1020
+
1021
+ @staticmethod
1022
+ def process_timestamp_literal(value):
1023
+ return f"TIMESTAMP {process_string_literal(str(value))}"
1024
+
1025
+ def literal_processor(self, dialect):
1026
+ return self.process_timestamp_literal
1027
+
1028
+
1029
+ class BQArray(sqlalchemy.sql.sqltypes.ARRAY):
1030
+ def literal_processor(self, dialect):
1031
+ item_processor = self.item_type._cached_literal_processor(dialect)
1032
+ if not item_processor:
1033
+ raise NotImplementedError(
1034
+ f"Don't know how to literal-quote values of type {self.item_type}"
1035
+ )
1036
+
1037
+ def process_array_literal(value):
1038
+ return "[" + ", ".join(item_processor(v) for v in value) + "]"
1039
+
1040
+ return process_array_literal
1041
+
1042
+
1043
+ class BigQueryDialect(DefaultDialect):
1044
+ name = "bigquery"
1045
+ driver = "bigquery"
1046
+ preparer = BigQueryIdentifierPreparer
1047
+ statement_compiler = BigQueryCompiler
1048
+ type_compiler = BigQueryTypeCompiler
1049
+ ddl_compiler = BigQueryDDLCompiler
1050
+ execution_ctx_cls = BigQueryExecutionContext
1051
+ cte_follows_insert = True
1052
+ supports_alter = False
1053
+ supports_comments = True
1054
+ inline_comments = True
1055
+ supports_pk_autoincrement = False
1056
+ supports_default_values = False
1057
+ supports_empty_insert = False
1058
+ supports_multivalues_insert = True
1059
+ supports_statement_cache = False
1060
+ supports_unicode_statements = True
1061
+ supports_unicode_binds = True
1062
+ supports_native_decimal = True
1063
+ description_encoding = None
1064
+ supports_native_boolean = True
1065
+ supports_simple_order_by_label = True
1066
+ postfetch_lastrowid = False
1067
+ preexecute_autoincrement_sequences = False
1068
+
1069
+ colspecs = {
1070
+ String: BQString,
1071
+ sqlalchemy.sql.sqltypes._Binary: BQBinary,
1072
+ sqlalchemy.sql.sqltypes.Date: BQClassTaggedStr,
1073
+ sqlalchemy.sql.sqltypes.DateTime: BQClassTaggedStr,
1074
+ sqlalchemy.sql.sqltypes.Time: BQClassTaggedStr,
1075
+ sqlalchemy.sql.sqltypes.TIMESTAMP: BQTimestamp,
1076
+ sqlalchemy.sql.sqltypes.ARRAY: BQArray,
1077
+ sqlalchemy.sql.sqltypes.Enum: sqlalchemy.sql.sqltypes.Enum,
1078
+ }
1079
+
1080
+ def __init__(
1081
+ self,
1082
+ arraysize=5000,
1083
+ credentials_path=None,
1084
+ billing_project_id=None,
1085
+ location=None,
1086
+ credentials_info=None,
1087
+ credentials_base64=None,
1088
+ list_tables_page_size=1000,
1089
+ *args,
1090
+ **kwargs,
1091
+ ):
1092
+ super(BigQueryDialect, self).__init__(*args, **kwargs)
1093
+ self.arraysize = arraysize
1094
+ self.credentials_path = credentials_path
1095
+ self.credentials_info = credentials_info
1096
+ self.credentials_base64 = credentials_base64
1097
+ self.project_id = None
1098
+ self.billing_project_id = billing_project_id
1099
+ self.location = location
1100
+ self.identifier_preparer = self.preparer(self)
1101
+ self.dataset_id = None
1102
+ self.list_tables_page_size = list_tables_page_size
1103
+
1104
+ @classmethod
1105
+ def dbapi(cls):
1106
+ """
1107
+ Use `import_dbapi()` instead.
1108
+ Maintained for backward compatibility.
1109
+ """
1110
+ return dbapi
1111
+
1112
+ @classmethod
1113
+ def import_dbapi(cls):
1114
+ return dbapi
1115
+
1116
+ @staticmethod
1117
+ def _build_formatted_table_id(table):
1118
+ """Build '<dataset_id>.<table_id>' string using given table."""
1119
+ return "{}.{}".format(table.reference.dataset_id, table.table_id)
1120
+
1121
+ def create_job_config(self, provided_config: QueryJobConfig):
1122
+ project_id = self.project_id
1123
+ if self.dataset_id is None and project_id == self.billing_project_id:
1124
+ return provided_config
1125
+ job_config = provided_config or QueryJobConfig()
1126
+ if project_id != self.billing_project_id:
1127
+ job_config.connection_properties = [
1128
+ ConnectionProperty(key="dataset_project_id", value=project_id)
1129
+ ]
1130
+ if self.dataset_id:
1131
+ if not project_id:
1132
+ _, project_id = auth.default()
1133
+ job_config.default_dataset = "{}.{}".format(project_id, self.dataset_id)
1134
+ return job_config
1135
+
1136
+ def do_execute(self, cursor, statement, parameters, context=None):
1137
+ kwargs = {}
1138
+ if context is not None and context.execution_options.get("job_config"):
1139
+ kwargs["job_config"] = context.execution_options.get("job_config")
1140
+ cursor.execute(statement, parameters, **kwargs)
1141
+
1142
+ def create_connect_args(self, url):
1143
+ (
1144
+ self.project_id,
1145
+ location,
1146
+ dataset_id,
1147
+ arraysize,
1148
+ credentials_path,
1149
+ credentials_base64,
1150
+ provided_job_config,
1151
+ list_tables_page_size,
1152
+ user_supplied_client,
1153
+ ) = parse_url(url)
1154
+
1155
+ self.arraysize = arraysize or self.arraysize
1156
+ self.list_tables_page_size = list_tables_page_size or self.list_tables_page_size
1157
+ self.location = location or self.location
1158
+ self.credentials_path = credentials_path or self.credentials_path
1159
+ self.credentials_base64 = credentials_base64 or self.credentials_base64
1160
+ self.dataset_id = dataset_id
1161
+ self.billing_project_id = self.billing_project_id or self.project_id
1162
+
1163
+ default_query_job_config = self.create_job_config(provided_job_config)
1164
+
1165
+ if user_supplied_client:
1166
+ # The user is expected to supply a client with
1167
+ # create_engine('...', connect_args={'client': bq_client})
1168
+ return ([], {})
1169
+ else:
1170
+ client = _helpers.create_bigquery_client(
1171
+ credentials_path=self.credentials_path,
1172
+ credentials_info=self.credentials_info,
1173
+ credentials_base64=self.credentials_base64,
1174
+ project_id=self.billing_project_id,
1175
+ location=self.location,
1176
+ default_query_job_config=default_query_job_config,
1177
+ )
1178
+ # If the user specified `bigquery://` we need to set the project_id
1179
+ # from the client
1180
+ self.project_id = self.project_id or client.project
1181
+ self.billing_project_id = self.billing_project_id or client.project
1182
+ return ([], {"client": client})
1183
+
1184
+ def _get_table_or_view_names(self, connection, item_types, schema=None):
1185
+ current_schema = schema or self.dataset_id
1186
+ get_table_name = (
1187
+ self._build_formatted_table_id
1188
+ if self.dataset_id is None
1189
+ else operator.attrgetter("table_id")
1190
+ )
1191
+
1192
+ client = connection.connection._client
1193
+ datasets = client.list_datasets(self.project_id)
1194
+
1195
+ result = []
1196
+ for dataset in datasets:
1197
+ if current_schema is not None and current_schema != dataset.dataset_id:
1198
+ continue
1199
+
1200
+ try:
1201
+ tables = client.list_tables(
1202
+ dataset.reference, page_size=self.list_tables_page_size
1203
+ )
1204
+ for table in tables:
1205
+ if table.table_type in item_types:
1206
+ result.append(get_table_name(table))
1207
+ except google.api_core.exceptions.NotFound:
1208
+ # It's possible that the dataset was deleted between when we
1209
+ # fetched the list of datasets and when we try to list the
1210
+ # tables from it. See:
1211
+ # https://github.com/googleapis/python-bigquery-sqlalchemy/issues/105
1212
+ pass
1213
+ return result
1214
+
1215
+ @staticmethod
1216
+ def _split_table_name(full_table_name):
1217
+ # Split full_table_name to get project, dataset and table name
1218
+ dataset = None
1219
+ table_name = None
1220
+ project = None
1221
+
1222
+ table_name_split = full_table_name.split(".")
1223
+ if len(table_name_split) == 1:
1224
+ table_name = full_table_name
1225
+ elif len(table_name_split) == 2:
1226
+ dataset, table_name = table_name_split
1227
+ elif len(table_name_split) == 3:
1228
+ project, dataset, table_name = table_name_split
1229
+ else:
1230
+ raise ValueError(
1231
+ "Did not understand table_name: {}".format(full_table_name)
1232
+ )
1233
+
1234
+ return (project, dataset, table_name)
1235
+
1236
+ def _table_reference(
1237
+ self, provided_schema_name, provided_table_name, client_project
1238
+ ):
1239
+ project_id_from_table, dataset_id_from_table, table_id = self._split_table_name(
1240
+ provided_table_name
1241
+ )
1242
+ project_id_from_schema = None
1243
+ dataset_id_from_schema = None
1244
+ if provided_schema_name is not None:
1245
+ provided_schema_name_split = provided_schema_name.split(".")
1246
+ if len(provided_schema_name_split) == 1:
1247
+ if dataset_id_from_table:
1248
+ project_id_from_schema = provided_schema_name_split[0]
1249
+ else:
1250
+ dataset_id_from_schema = provided_schema_name_split[0]
1251
+ elif len(provided_schema_name_split) == 2:
1252
+ project_id_from_schema = provided_schema_name_split[0]
1253
+ dataset_id_from_schema = provided_schema_name_split[1]
1254
+ else:
1255
+ raise ValueError(
1256
+ "Did not understand schema: {}".format(provided_schema_name)
1257
+ )
1258
+ if (
1259
+ dataset_id_from_schema
1260
+ and dataset_id_from_table
1261
+ and dataset_id_from_schema != dataset_id_from_table
1262
+ ):
1263
+ raise ValueError(
1264
+ "dataset_id specified in schema and table_name disagree: "
1265
+ "got {} in schema, and {} in table_name".format(
1266
+ dataset_id_from_schema, dataset_id_from_table
1267
+ )
1268
+ )
1269
+ if (
1270
+ project_id_from_schema
1271
+ and project_id_from_table
1272
+ and project_id_from_schema != project_id_from_table
1273
+ ):
1274
+ raise ValueError(
1275
+ "project_id specified in schema and table_name disagree: "
1276
+ "got {} in schema, and {} in table_name".format(
1277
+ project_id_from_schema, project_id_from_table
1278
+ )
1279
+ )
1280
+ project_id = project_id_from_schema or project_id_from_table or client_project
1281
+ dataset_id = dataset_id_from_schema or dataset_id_from_table or self.dataset_id
1282
+
1283
+ table_ref = TableReference.from_string(
1284
+ "{}.{}.{}".format(project_id, dataset_id, table_id)
1285
+ )
1286
+ return table_ref
1287
+
1288
+ def _get_table(self, connection, table_name, schema=None):
1289
+ if isinstance(connection, Engine):
1290
+ connection = connection.connect()
1291
+
1292
+ client = connection.connection._client
1293
+
1294
+ # table_ref = self._table_reference(schema, table_name, client.project)
1295
+ table_ref = self._table_reference(schema, table_name, self.project_id)
1296
+ try:
1297
+ table = client.get_table(table_ref)
1298
+ except NotFound:
1299
+ raise NoSuchTableError(table_name)
1300
+ return table
1301
+
1302
+ def has_table(self, connection, table_name, schema=None, **kw):
1303
+ """Checks whether a table exists in BigQuery.
1304
+
1305
+ Args:
1306
+ connection (google.cloud.bigquery.client.Client): The client
1307
+ object used to interact with BigQuery.
1308
+ table_name (str): The name of the table to check for.
1309
+ schema (str, optional): The name of the schema to which the table
1310
+ belongs. Defaults to the default schema.
1311
+ **kw (dict): Any extra keyword arguments will be ignored.
1312
+
1313
+ Returns:
1314
+ bool: True if the table exists, False otherwise.
1315
+
1316
+ """
1317
+ try:
1318
+ self._get_table(connection, table_name, schema)
1319
+ return True
1320
+ except NoSuchTableError:
1321
+ return False
1322
+
1323
+ def get_columns(self, connection, table_name, schema=None, **kw):
1324
+ table = self._get_table(connection, table_name, schema)
1325
+ return _types.get_columns(table.schema)
1326
+
1327
+ def get_table_comment(self, connection, table_name, schema=None, **kw):
1328
+ table = self._get_table(connection, table_name, schema)
1329
+ return {
1330
+ "text": table.description,
1331
+ }
1332
+
1333
+ def get_foreign_keys(self, connection, table_name, schema=None, **kw):
1334
+ # BigQuery has no support for foreign keys.
1335
+ return []
1336
+
1337
+ def get_pk_constraint(self, connection, table_name, schema=None, **kw):
1338
+ # BigQuery has no support for primary keys.
1339
+ return {"constrained_columns": []}
1340
+
1341
+ def get_indexes(self, connection, table_name, schema=None, **kw):
1342
+ # BigQuery has no support for indexes.
1343
+ return []
1344
+
1345
+ def get_schema_names(self, connection, **kw):
1346
+ if isinstance(connection, Engine):
1347
+ connection = connection.connect()
1348
+
1349
+ datasets = connection.connection._client.list_datasets(self.project_id)
1350
+ return [d.dataset_id for d in datasets]
1351
+
1352
+ def get_table_names(self, connection, schema=None, **kw):
1353
+ if isinstance(connection, Engine):
1354
+ connection = connection.connect()
1355
+
1356
+ item_types = ["TABLE", "EXTERNAL"]
1357
+ return self._get_table_or_view_names(connection, item_types, schema)
1358
+
1359
+ def get_view_names(self, connection, schema=None, **kw):
1360
+ if isinstance(connection, Engine):
1361
+ connection = connection.connect()
1362
+
1363
+ item_types = ["VIEW", "MATERIALIZED_VIEW"]
1364
+ return self._get_table_or_view_names(connection, item_types, schema)
1365
+
1366
+ def do_rollback(self, dbapi_connection):
1367
+ # BigQuery has no support for transactions.
1368
+ pass
1369
+
1370
+ def get_view_definition(self, connection, view_name, schema=None, **kw):
1371
+ if isinstance(connection, Engine):
1372
+ connection = connection.connect()
1373
+ client = connection.connection._client
1374
+ if self.dataset_id:
1375
+ view_name = f"{self.dataset_id}.{view_name}"
1376
+ view = client.get_table(view_name)
1377
+ return view.view_query
1378
+
1379
+
1380
+ class unnest(sqlalchemy.sql.functions.GenericFunction):
1381
+ def __init__(self, *args, **kwargs):
1382
+ expr = kwargs.pop("expr", None)
1383
+ if expr is not None:
1384
+ args = (expr,) + args
1385
+ if len(args) != 1:
1386
+ raise TypeError("The unnest function requires a single argument.")
1387
+ arg = args[0]
1388
+ if isinstance(arg, sqlalchemy.sql.expression.ColumnElement):
1389
+ if not (
1390
+ isinstance(arg.type, sqlalchemy.sql.sqltypes.ARRAY)
1391
+ or (
1392
+ hasattr(arg.type, "impl")
1393
+ and isinstance(arg.type.impl, sqlalchemy.sql.sqltypes.ARRAY)
1394
+ )
1395
+ ):
1396
+ raise TypeError("The argument to unnest must have an ARRAY type.")
1397
+ self.type = arg.type.item_type
1398
+ super().__init__(*args, **kwargs)
1399
+
1400
+
1401
+ dialect = BigQueryDialect
1402
+
1403
+ try:
1404
+ import alembic # noqa
1405
+ except ImportError: # pragma: NO COVER
1406
+ pass
1407
+ else:
1408
+ from alembic.ddl import impl
1409
+ from alembic.ddl.base import (
1410
+ ColumnName,
1411
+ ColumnType,
1412
+ format_column_name,
1413
+ format_type,
1414
+ alter_table,
1415
+ alter_column,
1416
+ )
1417
+
1418
+ class SqlalchemyBigqueryImpl(impl.DefaultImpl):
1419
+ __dialect__ = "bigquery"
1420
+
1421
+ @compiles(ColumnName, "bigquery")
1422
+ def visit_column_name(element: ColumnName, compiler: DDLCompiler, **kw) -> str:
1423
+ """Replaces the visit_column_name() function in alembic/alembic/ddl/base.py.
1424
+ See https://github.com/googleapis/python-bigquery-sqlalchemy/issues/1097"""
1425
+
1426
+ return "%s RENAME COLUMN %s TO %s" % (
1427
+ alter_table(compiler, element.table_name, element.schema),
1428
+ format_column_name(compiler, element.column_name),
1429
+ format_column_name(compiler, element.newname),
1430
+ )
1431
+
1432
+ @compiles(ColumnType, "bigquery")
1433
+ def visit_column_type(element: ColumnType, compiler: DDLCompiler, **kw) -> str:
1434
+ """Replaces the visit_column_type() function in alembic/alembic/ddl/base.py.
1435
+ The alembic version ends in TYPE <element type>, but bigquery requires this syntax:
1436
+ SET DATA TYPE <element type>"""
1437
+
1438
+ return "%s %s %s" % (
1439
+ alter_table(compiler, element.table_name, element.schema),
1440
+ alter_column(compiler, element.column_name),
1441
+ "SET DATA TYPE %s" % format_type(compiler, element.type_),
1442
+ )