sqlalchemy-bigquery 1.17.2__tar.gz → 1.18.0__tar.gz

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.
Files changed (69) hide show
  1. {sqlalchemy_bigquery-1.17.2/sqlalchemy_bigquery.egg-info → sqlalchemy_bigquery-1.18.0}/PKG-INFO +28 -11
  2. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/README.rst +20 -4
  3. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/setup.py +1 -0
  4. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/__init__.py +4 -2
  5. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/base.py +48 -10
  6. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/geography.py +28 -1
  7. sqlalchemy_bigquery-1.18.0/sqlalchemy_bigquery/provision.py +95 -0
  8. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/version.py +1 -1
  9. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0/sqlalchemy_bigquery.egg-info}/PKG-INFO +28 -11
  10. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery.egg-info/SOURCES.txt +2 -0
  11. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/sqlalchemy_dialect_compliance/conftest.py +59 -15
  12. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/sqlalchemy_dialect_compliance/test_dialect_compliance.py +43 -16
  13. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/conftest.py +1 -1
  14. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/fauxdbi.py +1 -2
  15. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_comments.py +1 -1
  16. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_compiler.py +124 -5
  17. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_compliance.py +2 -2
  18. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_geography.py +40 -2
  19. sqlalchemy_bigquery-1.18.0/tests/unit/test_provision.py +128 -0
  20. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_select.py +1 -1
  21. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/AUTHORS +0 -0
  22. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/LICENSE +0 -0
  23. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/MANIFEST.in +0 -0
  24. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/pyproject.toml +0 -0
  25. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/setup.cfg +0 -0
  26. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/_helpers.py +2 -2
  27. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/_struct.py +1 -1
  28. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/_types.py +1 -1
  29. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/parse_url.py +0 -0
  30. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery/requirements.py +0 -0
  31. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery.egg-info/dependency_links.txt +0 -0
  32. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery.egg-info/entry_points.txt +0 -0
  33. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery.egg-info/requires.txt +5 -5
  34. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/sqlalchemy_bigquery.egg-info/top_level.txt +0 -0
  35. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/__init__.py +0 -0
  36. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/conftest.py +0 -0
  37. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/sqlalchemy_dialect_compliance/README.rst +0 -0
  38. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/__init__.py +0 -0
  39. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/conftest.py +2 -2
  40. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/data/sample.json +0 -0
  41. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/data/sample_one_row.json +0 -0
  42. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/data/schema.json +0 -0
  43. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/test__struct.py +0 -0
  44. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/test_alembic.py +1 -1
  45. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/test_geography.py +0 -0
  46. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/test_helpers.py +0 -0
  47. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/test_sqlalchemy_bigquery.py +1 -1
  48. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/system/test_sqlalchemy_bigquery_remote.py +0 -0
  49. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/__init__.py +0 -0
  50. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test__struct.py +0 -0
  51. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test__types.py +1 -1
  52. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_alembic.py +0 -0
  53. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_catalog_functions.py +0 -0
  54. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_dialect_types.py +0 -0
  55. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_engine.py +0 -0
  56. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_helpers.py +1 -1
  57. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_like_reescape.py +0 -0
  58. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_parse_url.py +1 -1
  59. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_sqlalchemy_bigquery.py +2 -2
  60. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_table_options.py +2 -2
  61. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_version.py +0 -0
  62. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/tests/unit/test_view.py +0 -0
  63. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/third_party/sqlalchemy_bigquery_vendored/__init__.py +0 -0
  64. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/third_party/sqlalchemy_bigquery_vendored/py.typed +0 -0
  65. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/third_party/sqlalchemy_bigquery_vendored/sqlalchemy/AUTHORS +0 -0
  66. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/third_party/sqlalchemy_bigquery_vendored/sqlalchemy/LICENSE +0 -0
  67. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/third_party/sqlalchemy_bigquery_vendored/sqlalchemy/__init__.py +0 -0
  68. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/third_party/sqlalchemy_bigquery_vendored/sqlalchemy/postgresql/__init__.py +0 -0
  69. {sqlalchemy_bigquery-1.17.2 → sqlalchemy_bigquery-1.18.0}/third_party/sqlalchemy_bigquery_vendored/sqlalchemy/postgresql/base.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlalchemy-bigquery
3
- Version: 1.17.2
3
+ Version: 1.18.0
4
4
  Summary: SQLAlchemy dialect for BigQuery
5
5
  Home-page: https://github.com/googleapis/google-cloud-python/tree/main/packages/sqlalchemy-bigquery
6
6
  Author: The Sqlalchemy-Bigquery Authors
@@ -17,6 +17,7 @@ Classifier: Programming Language :: Python :: 3.11
17
17
  Classifier: Programming Language :: Python :: 3.12
18
18
  Classifier: Programming Language :: Python :: 3.13
19
19
  Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3.15
20
21
  Classifier: Operating System :: OS Independent
21
22
  Classifier: Topic :: Database :: Front-Ends
22
23
  Obsoletes: pybigquery
@@ -43,15 +44,15 @@ Requires-Dist: grpcio<2.0.0,>=1.59.0; extra == "bqstorage"
43
44
  Requires-Dist: grpcio<2.0.0,>=1.75.1; python_version >= "3.14" and extra == "bqstorage"
44
45
  Requires-Dist: pyarrow>=6.0.0; extra == "bqstorage"
45
46
  Provides-Extra: all
46
- Requires-Dist: grpcio<2.0.0,>=1.59.0; extra == "all"
47
- Requires-Dist: GeoAlchemy2; extra == "all"
48
- Requires-Dist: grpcio<2.0.0,>=1.75.1; python_version >= "3.14" and extra == "all"
49
- Requires-Dist: shapely; extra == "all"
50
- Requires-Dist: packaging; extra == "all"
51
47
  Requires-Dist: pyarrow>=6.0.0; extra == "all"
52
- Requires-Dist: pytz; extra == "all"
48
+ Requires-Dist: GeoAlchemy2; extra == "all"
53
49
  Requires-Dist: alembic; extra == "all"
54
50
  Requires-Dist: google-cloud-bigquery-storage<3.0.0,>=2.29.0; extra == "all"
51
+ Requires-Dist: grpcio<2.0.0,>=1.59.0; extra == "all"
52
+ Requires-Dist: packaging; extra == "all"
53
+ Requires-Dist: pytz; extra == "all"
54
+ Requires-Dist: shapely; extra == "all"
55
+ Requires-Dist: grpcio<2.0.0,>=1.75.1; python_version >= "3.14" and extra == "all"
55
56
  Dynamic: author
56
57
  Dynamic: author-email
57
58
  Dynamic: classifier
@@ -153,7 +154,7 @@ Installations when processing large datasets
153
154
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
154
155
 
155
156
  When handling large datasets, you may see speed increases by also installing the
156
- `bqstorage` dependencies. See the instructions above about creating a virtual
157
+ `bqstorage` dependencies. See the instructions above about creating a virtual
157
158
  environment and then install `sqlalchemy-bigquery` using the `bqstorage` extras:
158
159
 
159
160
  .. code-block:: console
@@ -186,7 +187,7 @@ Project
186
187
  Authentication
187
188
  ^^^^^^^^^^^^^^
188
189
 
189
- Follow the `Google Cloud library guide <https://google-cloud-python.readthedocs.io/en/latest/core/auth.html>`_ for authentication.
190
+ Follow the `Google Cloud library guide <https://google-cloud-python.readthedocs.io/en/latest/core/auth.html>`_ for authentication.
190
191
 
191
192
  Alternatively, you can choose either of the following approaches:
192
193
 
@@ -200,10 +201,10 @@ Alternatively, you can choose either of the following approaches:
200
201
  * pass the credentials in ``create_engine()`` as a Python dictionary using the ``credentials_info`` parameter:
201
202
 
202
203
  .. code-block:: python
203
-
204
+
204
205
  # provide credentials as a Python dictionary
205
206
  credentials_info = {
206
- "type": "service_account",
207
+ "type": "service_account",
207
208
  "project_id": "your-service-account-project-id"
208
209
  }
209
210
  engine = create_engine('bigquery://', credentials_info=credentials_info)
@@ -420,6 +421,22 @@ To create an integer-range partitioned table
420
421
  )
421
422
 
422
423
 
424
+ Casting with ``SAFE_CAST``
425
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
426
+
427
+ To generate a BigQuery ``SAFE_CAST`` expression (which returns ``NULL`` instead
428
+ of raising an error when a cast fails), use ``safe_cast`` from
429
+ ``sqlalchemy_bigquery`` (or ``sqlalchemy.try_cast`` on SQLAlchemy 2.0+):
430
+
431
+ .. code-block:: python
432
+
433
+ from sqlalchemy import Integer, select
434
+ from sqlalchemy_bigquery import safe_cast
435
+
436
+ stmt = select(safe_cast(table.c.string_col, Integer))
437
+
438
+
439
+
423
440
  Threading and Multiprocessing
424
441
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
425
442
 
@@ -84,7 +84,7 @@ Installations when processing large datasets
84
84
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
85
85
 
86
86
  When handling large datasets, you may see speed increases by also installing the
87
- `bqstorage` dependencies. See the instructions above about creating a virtual
87
+ `bqstorage` dependencies. See the instructions above about creating a virtual
88
88
  environment and then install `sqlalchemy-bigquery` using the `bqstorage` extras:
89
89
 
90
90
  .. code-block:: console
@@ -117,7 +117,7 @@ Project
117
117
  Authentication
118
118
  ^^^^^^^^^^^^^^
119
119
 
120
- Follow the `Google Cloud library guide <https://google-cloud-python.readthedocs.io/en/latest/core/auth.html>`_ for authentication.
120
+ Follow the `Google Cloud library guide <https://google-cloud-python.readthedocs.io/en/latest/core/auth.html>`_ for authentication.
121
121
 
122
122
  Alternatively, you can choose either of the following approaches:
123
123
 
@@ -131,10 +131,10 @@ Alternatively, you can choose either of the following approaches:
131
131
  * pass the credentials in ``create_engine()`` as a Python dictionary using the ``credentials_info`` parameter:
132
132
 
133
133
  .. code-block:: python
134
-
134
+
135
135
  # provide credentials as a Python dictionary
136
136
  credentials_info = {
137
- "type": "service_account",
137
+ "type": "service_account",
138
138
  "project_id": "your-service-account-project-id"
139
139
  }
140
140
  engine = create_engine('bigquery://', credentials_info=credentials_info)
@@ -351,6 +351,22 @@ To create an integer-range partitioned table
351
351
  )
352
352
 
353
353
 
354
+ Casting with ``SAFE_CAST``
355
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
356
+
357
+ To generate a BigQuery ``SAFE_CAST`` expression (which returns ``NULL`` instead
358
+ of raising an error when a cast fails), use ``safe_cast`` from
359
+ ``sqlalchemy_bigquery`` (or ``sqlalchemy.try_cast`` on SQLAlchemy 2.0+):
360
+
361
+ .. code-block:: python
362
+
363
+ from sqlalchemy import Integer, select
364
+ from sqlalchemy_bigquery import safe_cast
365
+
366
+ stmt = select(safe_cast(table.c.string_col, Integer))
367
+
368
+
369
+
354
370
  Threading and Multiprocessing
355
371
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
356
372
 
@@ -105,6 +105,7 @@ setup(
105
105
  "Programming Language :: Python :: 3.12",
106
106
  "Programming Language :: Python :: 3.13",
107
107
  "Programming Language :: Python :: 3.14",
108
+ "Programming Language :: Python :: 3.15",
108
109
  "Operating System :: OS Independent",
109
110
  "Topic :: Database :: Front-Ends",
110
111
  ],
@@ -20,6 +20,7 @@
20
20
  SQLAlchemy dialect for Google BigQuery
21
21
  """
22
22
 
23
+ import sys
23
24
  import warnings
24
25
 
25
26
  from ._types import (
@@ -41,9 +42,8 @@ from ._types import (
41
42
  TIME,
42
43
  TIMESTAMP,
43
44
  )
44
- from .base import BigQueryDialect, dialect
45
+ from .base import BigQueryDialect, SafeCast, dialect, safe_cast
45
46
  from .version import __version__
46
- import sys
47
47
 
48
48
  # Now that support for Python 3.7, 3.8 and 3.9 has been removed, we don't expect the
49
49
  # following check to succeed. The warning is only included for robustness.
@@ -77,8 +77,10 @@ __all__ = [
77
77
  "RECORD",
78
78
  "STRING",
79
79
  "STRUCT",
80
+ "SafeCast",
80
81
  "TIME",
81
82
  "TIMESTAMP",
83
+ "safe_cast",
82
84
  ]
83
85
 
84
86
  try:
@@ -20,14 +20,22 @@
20
20
  """Integration between SQLAlchemy and BigQuery."""
21
21
 
22
22
  import datetime
23
- from decimal import Decimal
24
23
  import operator
25
24
  import random
26
25
  import re
27
26
  import uuid
27
+ from decimal import Decimal
28
+ from typing import Any
28
29
 
29
- from google import auth
30
30
  import google.api_core.exceptions
31
+ import packaging.version
32
+ import sqlalchemy
33
+ import sqlalchemy.sql.expression
34
+ import sqlalchemy.sql.functions
35
+ import sqlalchemy.sql.sqltypes
36
+ import sqlalchemy.sql.type_api
37
+ import sqlalchemy_bigquery_vendored.sqlalchemy.postgresql.base as vendored_postgresql
38
+ from google import auth
31
39
  from google.api_core.exceptions import NotFound
32
40
  from google.cloud.bigquery import ConnectionProperty, QueryJobConfig, dbapi
33
41
  from google.cloud.bigquery.table import (
@@ -35,8 +43,6 @@ from google.cloud.bigquery.table import (
35
43
  TableReference,
36
44
  TimePartitioning,
37
45
  )
38
- import packaging.version
39
- import sqlalchemy
40
46
  from sqlalchemy import util
41
47
  from sqlalchemy.engine.base import Engine
42
48
  from sqlalchemy.engine.default import DefaultDialect, DefaultExecutionContext
@@ -49,14 +55,9 @@ from sqlalchemy.sql.compiler import (
49
55
  IdentifierPreparer,
50
56
  SQLCompiler,
51
57
  )
52
- import sqlalchemy.sql.expression
53
- import sqlalchemy.sql.functions
54
58
  from sqlalchemy.sql.schema import Column, Table
55
59
  from sqlalchemy.sql.selectable import CTE
56
- import sqlalchemy.sql.sqltypes
57
60
  from sqlalchemy.sql.sqltypes import Integer, NullType, Numeric, String
58
- import sqlalchemy.sql.type_api
59
- import sqlalchemy_bigquery_vendored.sqlalchemy.postgresql.base as vendored_postgresql
60
61
 
61
62
  from . import _helpers, _types
62
63
  from .parse_url import parse_url
@@ -587,6 +588,17 @@ class BigQueryCompiler(vendored_postgresql.PGCompiler, SQLCompiler):
587
588
  def visit_mod_binary(self, binary, operator, **kw):
588
589
  return f"MOD({self.process(binary.left, **kw)}, {self.process(binary.right, **kw)})"
589
590
 
591
+ def visit_now_func(self, fn, **kw):
592
+ # BigQuery has no NOW() function, use CURRENT_TIMESTAMP instead.
593
+ return "CURRENT_TIMESTAMP"
594
+
595
+ def visit_try_cast(self, cast: elements.Cast, **kwargs: Any) -> str:
596
+ """Compile a ``SAFE_CAST`` / ``try_cast`` expression for BigQuery."""
597
+ return "SAFE_CAST(%s AS %s)" % (
598
+ self.process(cast.clause, **kwargs),
599
+ self.process(cast.typeclause, **kwargs),
600
+ )
601
+
590
602
 
591
603
  class BigQueryTypeCompiler(GenericTypeCompiler):
592
604
  def visit_INTEGER(self, type_, **kw):
@@ -600,7 +612,7 @@ class BigQueryTypeCompiler(GenericTypeCompiler):
600
612
  def visit_FLOAT(self, type_, **kw):
601
613
  return "FLOAT64"
602
614
 
603
- visit_REAL = visit_FLOAT
615
+ visit_REAL = visit_DOUBLE = visit_DOUBLE_PRECISION = visit_FLOAT
604
616
 
605
617
  def visit_STRING(self, type_, **kw):
606
618
  if (type_.length is not None) and isinstance(
@@ -1382,6 +1394,32 @@ class BigQueryDialect(DefaultDialect):
1382
1394
  return view.view_query
1383
1395
 
1384
1396
 
1397
+ _BaseTryCast = getattr(elements, "TryCast", elements.Cast)
1398
+
1399
+
1400
+ class SafeCast(_BaseTryCast):
1401
+ """Represent a BigQuery ``SAFE_CAST`` expression."""
1402
+
1403
+ __visit_name__ = "try_cast"
1404
+ inherit_cache = True
1405
+
1406
+
1407
+ def safe_cast(expression: Any, type_: Any) -> SafeCast:
1408
+ """Produce a BigQuery ``SAFE_CAST`` expression.
1409
+
1410
+ ``SAFE_CAST`` is identical to ``CAST``, except that it returns ``NULL``
1411
+ instead of raising an error when a cast fails.
1412
+
1413
+ Args:
1414
+ expression: A SQL expression, column, or literal to be cast.
1415
+ type_: The target SQLAlchemy ``TypeEngine`` class or instance.
1416
+
1417
+ Returns:
1418
+ A ``SafeCast`` clause element that compiles to ``SAFE_CAST(...)``.
1419
+ """
1420
+ return SafeCast(expression, type_)
1421
+
1422
+
1385
1423
  class unnest(sqlalchemy.sql.functions.GenericFunction):
1386
1424
  def __init__(self, *args, **kwargs):
1387
1425
  expr = kwargs.pop("expr", None)
@@ -19,9 +19,9 @@
19
19
 
20
20
  import geoalchemy2
21
21
  import geoalchemy2.functions
22
+ import sqlalchemy.ext.compiler
22
23
  from geoalchemy2.shape import to_shape
23
24
  from shapely import wkb, wkt
24
- import sqlalchemy.ext.compiler
25
25
  from sqlalchemy.sql.elements import BindParameter
26
26
 
27
27
  SRID = 4326 # WGS84, https://spatialreference.org/ref/epsg/wgs-84/
@@ -180,6 +180,17 @@ def _fixup_st_arguments(element, compiler, **kw):
180
180
 
181
181
  This is not a user-facing function.
182
182
  """
183
+ # GeoAlchemy2 >= 0.21.0 wraps raw string arguments in an _UntypedString(NullType)
184
+ # bindparam for PostgreSQL compatibility. Restore String() for string bindparams
185
+ # so BigQueryCompiler.visit_bindparam emits typed %(...:STRING)s placeholders.
186
+ for argument in element.clauses.clauses:
187
+ if (
188
+ isinstance(argument, BindParameter)
189
+ and isinstance(argument.type, sqlalchemy.types.NullType)
190
+ and isinstance(argument.value, str)
191
+ ):
192
+ argument.type = sqlalchemy.types.String()
193
+
183
194
  argument_types = _argument_types.get(element.name.lower())
184
195
  if argument_types:
185
196
  for argument_type, argument in zip(argument_types, element.clauses.clauses):
@@ -191,6 +202,22 @@ def _fixup_st_arguments(element, compiler, **kw):
191
202
  return compiler.visit_function(element, **kw)
192
203
 
193
204
 
205
+ def _get_all_subclasses(cls):
206
+ subclasses = set(cls.__subclasses__())
207
+ for sub in list(subclasses):
208
+ subclasses.update(_get_all_subclasses(sub))
209
+ return subclasses
210
+
211
+
212
+ # GeoAlchemy2 registers dialect-specific @compiles handlers (e.g. for "mssql")
213
+ # on several GenericFunction subclasses such as ST_GeogFromText, which gives
214
+ # those subclasses their own _compiler_dispatcher that shadows GenericFunction's.
215
+ # Register _fixup_st_arguments on each subclass so the "bigquery" compiler
216
+ # hook is invoked for all spatial functions.
217
+ for _cls in _get_all_subclasses(geoalchemy2.functions.GenericFunction):
218
+ sqlalchemy.ext.compiler.compiles(_cls, "bigquery")(_fixup_st_arguments)
219
+
220
+
194
221
  _argument_types = dict(
195
222
  st_area=(GEOGRAPHY,),
196
223
  st_asbinary=(GEOGRAPHY,),
@@ -0,0 +1,95 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import contextlib
16
+ import datetime
17
+ import os
18
+ import uuid
19
+
20
+ import google.cloud.bigquery
21
+ from sqlalchemy.engine import make_url
22
+ from sqlalchemy.testing.provision import (
23
+ create_db,
24
+ drop_db,
25
+ follower_url_from_main,
26
+ generate_driver_url,
27
+ )
28
+
29
+ try:
30
+ import test_utils.prefixer # pragma: NO COVER
31
+
32
+ prefixer = test_utils.prefixer.Prefixer( # pragma: NO COVER
33
+ "python-bigquery-sqlalchemy", "tests/compliance"
34
+ )
35
+ except ImportError:
36
+ prefixer = None
37
+
38
+
39
+ def _dataset_id_from_ident(ident: str) -> str:
40
+ """Derive a deterministic BigQuery dataset ID for an xdist follower ident."""
41
+ run_prefix = os.environ.get("COMPLIANCE_RUN_PREFIX")
42
+ if not run_prefix:
43
+ if prefixer:
44
+ run_prefix = prefixer.create_prefix()
45
+ else:
46
+ now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M%S")
47
+ run_prefix = f"python_bigquery_sqlalchemy_tests_compliance_{now}_{uuid.uuid4().hex[:6]}"
48
+ os.environ["COMPLIANCE_RUN_PREFIX"] = run_prefix
49
+ return f"{run_prefix}_{ident}"
50
+
51
+
52
+ @generate_driver_url.for_db("bigquery")
53
+ def _bigquery_generate_driver_url(url, driver, query_str):
54
+ url = make_url(url)
55
+ if driver and driver != "bigquery":
56
+ new_url = url.set(drivername=f"bigquery+{driver}")
57
+ else:
58
+ new_url = url.set(drivername="bigquery")
59
+ if query_str:
60
+ new_url = new_url.update_query_string(query_str)
61
+ return new_url
62
+
63
+
64
+ @follower_url_from_main.for_db("bigquery")
65
+ def _bigquery_follower_url_from_main(url, ident):
66
+ url = make_url(url)
67
+ dataset_id = _dataset_id_from_ident(ident)
68
+ return url.set(database=dataset_id)
69
+
70
+
71
+ def ensure_dataset(dataset_id: str) -> None:
72
+ """Ensure a BigQuery dataset exists with a 1-hour expiration safety net."""
73
+ with contextlib.closing(google.cloud.bigquery.Client()) as client:
74
+ dataset_ref = google.cloud.bigquery.DatasetReference(client.project, dataset_id)
75
+ dataset = google.cloud.bigquery.Dataset(dataset_ref)
76
+ dataset.default_table_expiration_ms = 3600 * 1000
77
+ client.create_dataset(dataset, exists_ok=True)
78
+
79
+
80
+ def drop_dataset(dataset_id: str) -> None:
81
+ """Drop a BigQuery dataset and its contents if it exists."""
82
+ with contextlib.closing(google.cloud.bigquery.Client()) as client:
83
+ client.delete_dataset(dataset_id, delete_contents=True, not_found_ok=True)
84
+
85
+
86
+ @create_db.for_db("bigquery")
87
+ def _bigquery_create_db(cfg, eng, ident):
88
+ dataset_id = _dataset_id_from_ident(ident)
89
+ ensure_dataset(dataset_id)
90
+
91
+
92
+ @drop_db.for_db("bigquery")
93
+ def _bigquery_drop_db(cfg, eng, ident):
94
+ dataset_id = _dataset_id_from_ident(ident)
95
+ drop_dataset(dataset_id)
@@ -17,4 +17,4 @@
17
17
  # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
18
  # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
19
 
20
- __version__ = "1.17.2"
20
+ __version__ = "1.18.0"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlalchemy-bigquery
3
- Version: 1.17.2
3
+ Version: 1.18.0
4
4
  Summary: SQLAlchemy dialect for BigQuery
5
5
  Home-page: https://github.com/googleapis/google-cloud-python/tree/main/packages/sqlalchemy-bigquery
6
6
  Author: The Sqlalchemy-Bigquery Authors
@@ -17,6 +17,7 @@ Classifier: Programming Language :: Python :: 3.11
17
17
  Classifier: Programming Language :: Python :: 3.12
18
18
  Classifier: Programming Language :: Python :: 3.13
19
19
  Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3.15
20
21
  Classifier: Operating System :: OS Independent
21
22
  Classifier: Topic :: Database :: Front-Ends
22
23
  Obsoletes: pybigquery
@@ -43,15 +44,15 @@ Requires-Dist: grpcio<2.0.0,>=1.59.0; extra == "bqstorage"
43
44
  Requires-Dist: grpcio<2.0.0,>=1.75.1; python_version >= "3.14" and extra == "bqstorage"
44
45
  Requires-Dist: pyarrow>=6.0.0; extra == "bqstorage"
45
46
  Provides-Extra: all
46
- Requires-Dist: grpcio<2.0.0,>=1.59.0; extra == "all"
47
- Requires-Dist: GeoAlchemy2; extra == "all"
48
- Requires-Dist: grpcio<2.0.0,>=1.75.1; python_version >= "3.14" and extra == "all"
49
- Requires-Dist: shapely; extra == "all"
50
- Requires-Dist: packaging; extra == "all"
51
47
  Requires-Dist: pyarrow>=6.0.0; extra == "all"
52
- Requires-Dist: pytz; extra == "all"
48
+ Requires-Dist: GeoAlchemy2; extra == "all"
53
49
  Requires-Dist: alembic; extra == "all"
54
50
  Requires-Dist: google-cloud-bigquery-storage<3.0.0,>=2.29.0; extra == "all"
51
+ Requires-Dist: grpcio<2.0.0,>=1.59.0; extra == "all"
52
+ Requires-Dist: packaging; extra == "all"
53
+ Requires-Dist: pytz; extra == "all"
54
+ Requires-Dist: shapely; extra == "all"
55
+ Requires-Dist: grpcio<2.0.0,>=1.75.1; python_version >= "3.14" and extra == "all"
55
56
  Dynamic: author
56
57
  Dynamic: author-email
57
58
  Dynamic: classifier
@@ -153,7 +154,7 @@ Installations when processing large datasets
153
154
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
154
155
 
155
156
  When handling large datasets, you may see speed increases by also installing the
156
- `bqstorage` dependencies. See the instructions above about creating a virtual
157
+ `bqstorage` dependencies. See the instructions above about creating a virtual
157
158
  environment and then install `sqlalchemy-bigquery` using the `bqstorage` extras:
158
159
 
159
160
  .. code-block:: console
@@ -186,7 +187,7 @@ Project
186
187
  Authentication
187
188
  ^^^^^^^^^^^^^^
188
189
 
189
- Follow the `Google Cloud library guide <https://google-cloud-python.readthedocs.io/en/latest/core/auth.html>`_ for authentication.
190
+ Follow the `Google Cloud library guide <https://google-cloud-python.readthedocs.io/en/latest/core/auth.html>`_ for authentication.
190
191
 
191
192
  Alternatively, you can choose either of the following approaches:
192
193
 
@@ -200,10 +201,10 @@ Alternatively, you can choose either of the following approaches:
200
201
  * pass the credentials in ``create_engine()`` as a Python dictionary using the ``credentials_info`` parameter:
201
202
 
202
203
  .. code-block:: python
203
-
204
+
204
205
  # provide credentials as a Python dictionary
205
206
  credentials_info = {
206
- "type": "service_account",
207
+ "type": "service_account",
207
208
  "project_id": "your-service-account-project-id"
208
209
  }
209
210
  engine = create_engine('bigquery://', credentials_info=credentials_info)
@@ -420,6 +421,22 @@ To create an integer-range partitioned table
420
421
  )
421
422
 
422
423
 
424
+ Casting with ``SAFE_CAST``
425
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
426
+
427
+ To generate a BigQuery ``SAFE_CAST`` expression (which returns ``NULL`` instead
428
+ of raising an error when a cast fails), use ``safe_cast`` from
429
+ ``sqlalchemy_bigquery`` (or ``sqlalchemy.try_cast`` on SQLAlchemy 2.0+):
430
+
431
+ .. code-block:: python
432
+
433
+ from sqlalchemy import Integer, select
434
+ from sqlalchemy_bigquery import safe_cast
435
+
436
+ stmt = select(safe_cast(table.c.string_col, Integer))
437
+
438
+
439
+
423
440
  Threading and Multiprocessing
424
441
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
425
442
 
@@ -12,6 +12,7 @@ sqlalchemy_bigquery/_types.py
12
12
  sqlalchemy_bigquery/base.py
13
13
  sqlalchemy_bigquery/geography.py
14
14
  sqlalchemy_bigquery/parse_url.py
15
+ sqlalchemy_bigquery/provision.py
15
16
  sqlalchemy_bigquery/requirements.py
16
17
  sqlalchemy_bigquery/version.py
17
18
  sqlalchemy_bigquery.egg-info/PKG-INFO
@@ -52,6 +53,7 @@ tests/unit/test_geography.py
52
53
  tests/unit/test_helpers.py
53
54
  tests/unit/test_like_reescape.py
54
55
  tests/unit/test_parse_url.py
56
+ tests/unit/test_provision.py
55
57
  tests/unit/test_select.py
56
58
  tests/unit/test_sqlalchemy_bigquery.py
57
59
  tests/unit/test_table_options.py
@@ -18,21 +18,21 @@
18
18
  # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
19
 
20
20
  import contextlib
21
+ import os
21
22
  import re
22
23
  import traceback
23
24
 
24
25
  import google.cloud.bigquery.dbapi.connection
25
- from sqlalchemy.testing import config
26
- from sqlalchemy.testing.plugin.pytestplugin import * # noqa
27
- from sqlalchemy.testing.plugin.pytestplugin import (
28
- pytest_sessionfinish as _pytest_sessionfinish,
29
- )
30
- from sqlalchemy.testing.plugin.pytestplugin import (
31
- pytest_sessionstart as _pytest_sessionstart,
32
- )
33
26
  import test_utils.prefixer
27
+ from sqlalchemy.testing import config
28
+ from sqlalchemy.testing.plugin import pytestplugin
29
+
30
+ # flake8: F401, F403 are ignored because SQLAlchemy requires importing its testing
31
+ # plugin fixtures and hooks directly into the pytest conftest namespace.
32
+ from sqlalchemy.testing.plugin.pytestplugin import * # noqa: F401, F403
34
33
 
35
34
  import sqlalchemy_bigquery.base
35
+ import sqlalchemy_bigquery.provision
36
36
 
37
37
  sqlalchemy_bigquery.BigQueryDialect.preexecute_autoincrement_sequences = True
38
38
 
@@ -54,6 +54,7 @@ _where = re.compile(r"\s+WHERE\s+", re.IGNORECASE).search
54
54
 
55
55
 
56
56
  def visit_delete(self, delete_stmt, *args, **kw):
57
+ """Compile DELETE statements, appending WHERE true during test teardown."""
57
58
  text = super(sqlalchemy_bigquery.base.BigQueryCompiler, self).visit_delete(
58
59
  delete_stmt, *args, **kw
59
60
  )
@@ -69,19 +70,62 @@ def visit_delete(self, delete_stmt, *args, **kw):
69
70
  sqlalchemy_bigquery.base.BigQueryCompiler.visit_delete = visit_delete
70
71
 
71
72
 
73
+ def _resolve_dataset_id(cfg) -> str:
74
+ """Resolve the dataset ID for the current runner process (worker or master)."""
75
+ run_prefix = os.environ["COMPLIANCE_RUN_PREFIX"]
76
+ if hasattr(cfg, "workerinput"):
77
+ ident = cfg.workerinput.get("follower_ident")
78
+ if ident:
79
+ return sqlalchemy_bigquery.provision._dataset_id_from_ident(ident)
80
+ return f"{run_prefix}_worker"
81
+ return f"{run_prefix}_master"
82
+
83
+
84
+ def pytest_configure(config):
85
+ """Configure pytest session, establishing compliance run prefix and target dburi."""
86
+ if hasattr(config, "workerinput"):
87
+ prefix = config.workerinput.get("compliance_run_prefix")
88
+ if prefix:
89
+ os.environ["COMPLIANCE_RUN_PREFIX"] = prefix
90
+ else:
91
+ if "COMPLIANCE_RUN_PREFIX" not in os.environ:
92
+ os.environ["COMPLIANCE_RUN_PREFIX"] = prefixer.create_prefix()
93
+
94
+ dataset_id = _resolve_dataset_id(config)
95
+ config.option.dburi = [f"bigquery:///{dataset_id}"]
96
+ pytestplugin.pytest_configure(config)
97
+
98
+
99
+ def pytest_configure_node(node):
100
+ """Propagate the compliance run prefix from the controller to worker nodes."""
101
+ node.workerinput["compliance_run_prefix"] = os.environ.get("COMPLIANCE_RUN_PREFIX")
102
+
103
+
72
104
  def pytest_sessionstart(session):
73
- dataset_id = prefixer.create_prefix()
105
+ """Ensure the target dataset exists before running compliance tests in the session."""
106
+ dataset_id = _resolve_dataset_id(session.config)
74
107
  session.config.option.dburi = [f"bigquery:///{dataset_id}"]
75
- with contextlib.closing(google.cloud.bigquery.Client()) as client:
76
- client.create_dataset(dataset_id)
77
- _pytest_sessionstart(session)
108
+ sqlalchemy_bigquery.provision.ensure_dataset(dataset_id)
109
+ pytestplugin.pytest_sessionstart(session)
78
110
 
79
111
 
80
112
  def pytest_sessionfinish(session):
81
- dataset_id = config.db.dialect.dataset_id
82
- _pytest_sessionfinish(session)
113
+ """Tear down datasets and clean up leaked test datasets after session completion."""
114
+ if hasattr(session.config, "workerinput"):
115
+ # Worker dataset teardown is handled by provision.drop_follower_db
116
+ # on the controller node.
117
+ pytestplugin.pytest_sessionfinish(session)
118
+ return
119
+
120
+ pytestplugin.pytest_sessionfinish(session)
121
+ run_prefix = os.environ.get("COMPLIANCE_RUN_PREFIX")
122
+ db = getattr(session.config, "db", None) or getattr(config, "db", None)
123
+ if db is not None and hasattr(db.dialect, "dataset_id"):
124
+ sqlalchemy_bigquery.provision.drop_dataset(db.dialect.dataset_id)
125
+ elif run_prefix:
126
+ sqlalchemy_bigquery.provision.drop_dataset(f"{run_prefix}_master")
127
+
83
128
  with contextlib.closing(google.cloud.bigquery.Client()) as client:
84
- client.delete_dataset(dataset_id, delete_contents=True, not_found_ok=True)
85
129
  for dataset in client.list_datasets():
86
130
  if prefixer.should_cleanup(dataset.dataset_id):
87
131
  client.delete_dataset(dataset, delete_contents=True, not_found_ok=True)