sqlalchemy-bigquery 1.9.0__tar.gz → 1.10.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 (57) hide show
  1. {sqlalchemy-bigquery-1.9.0/sqlalchemy_bigquery.egg-info → sqlalchemy-bigquery-1.10.0}/PKG-INFO +57 -6
  2. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/README.rst +52 -1
  3. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/base.py +255 -33
  4. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/version.py +1 -1
  5. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0/sqlalchemy_bigquery.egg-info}/PKG-INFO +57 -6
  6. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery.egg-info/SOURCES.txt +1 -0
  7. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/test_alembic.py +7 -10
  8. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/test_sqlalchemy_bigquery.py +11 -11
  9. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/conftest.py +7 -0
  10. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_catalog_functions.py +1 -12
  11. sqlalchemy-bigquery-1.10.0/tests/unit/test_compiler.py +280 -0
  12. sqlalchemy-bigquery-1.10.0/tests/unit/test_table_options.py +474 -0
  13. sqlalchemy-bigquery-1.9.0/tests/unit/test_compiler.py +0 -116
  14. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/AUTHORS +0 -0
  15. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/LICENSE +0 -0
  16. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/MANIFEST.in +0 -0
  17. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/setup.cfg +0 -0
  18. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/setup.py +0 -0
  19. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/__init__.py +0 -0
  20. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/_helpers.py +0 -0
  21. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/_struct.py +0 -0
  22. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/_types.py +0 -0
  23. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/geography.py +0 -0
  24. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/parse_url.py +0 -0
  25. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery/requirements.py +0 -0
  26. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery.egg-info/dependency_links.txt +0 -0
  27. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery.egg-info/entry_points.txt +0 -0
  28. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery.egg-info/requires.txt +3 -3
  29. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/sqlalchemy_bigquery.egg-info/top_level.txt +0 -0
  30. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/__init__.py +0 -0
  31. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/conftest.py +0 -0
  32. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/sqlalchemy_dialect_compliance/README.rst +0 -0
  33. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/sqlalchemy_dialect_compliance/conftest.py +0 -0
  34. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/sqlalchemy_dialect_compliance/test_dialect_compliance.py +0 -0
  35. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/__init__.py +0 -0
  36. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/conftest.py +0 -0
  37. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/data/sample.json +0 -0
  38. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/data/sample_one_row.json +0 -0
  39. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/data/schema.json +0 -0
  40. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/test__struct.py +0 -0
  41. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/test_geography.py +0 -0
  42. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/system/test_helpers.py +0 -0
  43. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/__init__.py +0 -0
  44. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/fauxdbi.py +0 -0
  45. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test__struct.py +0 -0
  46. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_comments.py +0 -0
  47. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_compliance.py +0 -0
  48. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_dialect_types.py +0 -0
  49. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_engine.py +0 -0
  50. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_geography.py +0 -0
  51. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_helpers.py +0 -0
  52. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_like_reescape.py +0 -0
  53. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_parse_url.py +0 -0
  54. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_select.py +0 -0
  55. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_sqlalchemy_bigquery.py +0 -0
  56. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_version.py +0 -0
  57. {sqlalchemy-bigquery-1.9.0 → sqlalchemy-bigquery-1.10.0}/tests/unit/test_view.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlalchemy-bigquery
3
- Version: 1.9.0
3
+ Version: 1.10.0
4
4
  Summary: SQLAlchemy dialect for BigQuery
5
5
  Home-page: https://github.com/googleapis/python-bigquery-sqlalchemy
6
6
  Author: The Sqlalchemy-Bigquery Authors
@@ -44,14 +44,14 @@ Requires-Dist: grpcio<2.0dev,>=1.49.1; python_version >= "3.11" and extra == "bq
44
44
  Requires-Dist: pyarrow>=3.0.0; extra == "bqstorage"
45
45
  Provides-Extra: all
46
46
  Requires-Dist: alembic; extra == "all"
47
- Requires-Dist: GeoAlchemy2; extra == "all"
48
47
  Requires-Dist: google-cloud-bigquery-storage<3.0.0dev,>=2.0.0; extra == "all"
49
- Requires-Dist: grpcio<2.0dev,>=1.47.0; extra == "all"
50
48
  Requires-Dist: shapely; extra == "all"
49
+ Requires-Dist: pyarrow>=3.0.0; extra == "all"
50
+ Requires-Dist: grpcio<2.0dev,>=1.49.1; python_version >= "3.11" and extra == "all"
51
51
  Requires-Dist: packaging; extra == "all"
52
52
  Requires-Dist: pytz; extra == "all"
53
- Requires-Dist: grpcio<2.0dev,>=1.49.1; python_version >= "3.11" and extra == "all"
54
- Requires-Dist: pyarrow>=3.0.0; extra == "all"
53
+ Requires-Dist: GeoAlchemy2; extra == "all"
54
+ Requires-Dist: grpcio<2.0dev,>=1.47.0; extra == "all"
55
55
 
56
56
  SQLAlchemy Dialect for BigQuery
57
57
  ===============================
@@ -347,7 +347,12 @@ To add metadata to a table:
347
347
 
348
348
  .. code-block:: python
349
349
 
350
- table = Table('mytable', ..., bigquery_description='my table description', bigquery_friendly_name='my table friendly name')
350
+ table = Table('mytable', ...,
351
+ bigquery_description='my table description',
352
+ bigquery_friendly_name='my table friendly name',
353
+ bigquery_default_rounding_mode="ROUND_HALF_EVEN",
354
+ bigquery_expiration_timestamp=datetime.datetime.fromisoformat("2038-01-01T00:00:00+00:00"),
355
+ )
351
356
 
352
357
  To add metadata to a column:
353
358
 
@@ -355,6 +360,52 @@ To add metadata to a column:
355
360
 
356
361
  Column('mycolumn', doc='my column description')
357
362
 
363
+ To create a clustered table:
364
+
365
+ .. code-block:: python
366
+
367
+ table = Table('mytable', ..., bigquery_clustering_fields=["a", "b", "c"])
368
+
369
+ To create a time-unit column-partitioned table:
370
+
371
+ .. code-block:: python
372
+
373
+ from google.cloud import bigquery
374
+
375
+ table = Table('mytable', ...,
376
+ bigquery_time_partitioning=bigquery.TimePartitioning(
377
+ field="mytimestamp",
378
+ type_="MONTH",
379
+ expiration_ms=1000 * 60 * 60 * 24 * 30 * 6, # 6 months
380
+ ),
381
+ bigquery_require_partition_filter=True,
382
+ )
383
+
384
+ To create an ingestion-time partitioned table:
385
+
386
+ .. code-block:: python
387
+
388
+ from google.cloud import bigquery
389
+
390
+ table = Table('mytable', ...,
391
+ bigquery_time_partitioning=bigquery.TimePartitioning(),
392
+ bigquery_require_partition_filter=True,
393
+ )
394
+
395
+ To create an integer-range partitioned table
396
+
397
+ .. code-block:: python
398
+
399
+ from google.cloud import bigquery
400
+
401
+ table = Table('mytable', ...,
402
+ bigquery_range_partitioning=bigquery.RangePartitioning(
403
+ field="zipcode",
404
+ range_=bigquery.PartitionRange(start=0, end=100000, interval=10),
405
+ ),
406
+ bigquery_require_partition_filter=True,
407
+ )
408
+
358
409
 
359
410
  Threading and Multiprocessing
360
411
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -292,7 +292,12 @@ To add metadata to a table:
292
292
 
293
293
  .. code-block:: python
294
294
 
295
- table = Table('mytable', ..., bigquery_description='my table description', bigquery_friendly_name='my table friendly name')
295
+ table = Table('mytable', ...,
296
+ bigquery_description='my table description',
297
+ bigquery_friendly_name='my table friendly name',
298
+ bigquery_default_rounding_mode="ROUND_HALF_EVEN",
299
+ bigquery_expiration_timestamp=datetime.datetime.fromisoformat("2038-01-01T00:00:00+00:00"),
300
+ )
296
301
 
297
302
  To add metadata to a column:
298
303
 
@@ -300,6 +305,52 @@ To add metadata to a column:
300
305
 
301
306
  Column('mycolumn', doc='my column description')
302
307
 
308
+ To create a clustered table:
309
+
310
+ .. code-block:: python
311
+
312
+ table = Table('mytable', ..., bigquery_clustering_fields=["a", "b", "c"])
313
+
314
+ To create a time-unit column-partitioned table:
315
+
316
+ .. code-block:: python
317
+
318
+ from google.cloud import bigquery
319
+
320
+ table = Table('mytable', ...,
321
+ bigquery_time_partitioning=bigquery.TimePartitioning(
322
+ field="mytimestamp",
323
+ type_="MONTH",
324
+ expiration_ms=1000 * 60 * 60 * 24 * 30 * 6, # 6 months
325
+ ),
326
+ bigquery_require_partition_filter=True,
327
+ )
328
+
329
+ To create an ingestion-time partitioned table:
330
+
331
+ .. code-block:: python
332
+
333
+ from google.cloud import bigquery
334
+
335
+ table = Table('mytable', ...,
336
+ bigquery_time_partitioning=bigquery.TimePartitioning(),
337
+ bigquery_require_partition_filter=True,
338
+ )
339
+
340
+ To create an integer-range partitioned table
341
+
342
+ .. code-block:: python
343
+
344
+ from google.cloud import bigquery
345
+
346
+ table = Table('mytable', ...,
347
+ bigquery_range_partitioning=bigquery.RangePartitioning(
348
+ field="zipcode",
349
+ range_=bigquery.PartitionRange(start=0, end=100000, interval=10),
350
+ ),
351
+ bigquery_require_partition_filter=True,
352
+ )
353
+
303
354
 
304
355
  Threading and Multiprocessing
305
356
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -19,6 +19,7 @@
19
19
 
20
20
  """Integration between SQLAlchemy and BigQuery."""
21
21
 
22
+ import datetime
22
23
  from decimal import Decimal
23
24
  import random
24
25
  import operator
@@ -27,7 +28,11 @@ import uuid
27
28
  from google import auth
28
29
  import google.api_core.exceptions
29
30
  from google.cloud.bigquery import dbapi
30
- from google.cloud.bigquery.table import TableReference
31
+ from google.cloud.bigquery.table import (
32
+ RangePartitioning,
33
+ TableReference,
34
+ TimePartitioning,
35
+ )
31
36
  from google.api_core.exceptions import NotFound
32
37
  import packaging.version
33
38
  import sqlalchemy
@@ -35,7 +40,7 @@ import sqlalchemy.sql.expression
35
40
  import sqlalchemy.sql.functions
36
41
  import sqlalchemy.sql.sqltypes
37
42
  import sqlalchemy.sql.type_api
38
- from sqlalchemy.exc import NoSuchTableError
43
+ from sqlalchemy.exc import NoSuchTableError, NoSuchColumnError
39
44
  from sqlalchemy import util
40
45
  from sqlalchemy.ext.compiler import compiles
41
46
  from sqlalchemy.sql.compiler import (
@@ -269,6 +274,14 @@ class BigQueryCompiler(_struct.SQLCompiler, SQLCompiler):
269
274
  if table is not None:
270
275
  known_tables.add(table.name)
271
276
 
277
+ # If we have the table in the `from` of our parent, do not add the alias
278
+ # as this will add the table twice and cause an implicit JOIN for that
279
+ # table on itself
280
+ asfrom_froms = self.stack[-1].get("asfrom_froms", [])
281
+ for from_ in asfrom_froms:
282
+ if isinstance(from_, Table):
283
+ known_tables.add(from_.name)
284
+
272
285
  return known_tables
273
286
 
274
287
  def visit_column(
@@ -623,6 +636,13 @@ class BigQueryTypeCompiler(GenericTypeCompiler):
623
636
 
624
637
 
625
638
  class BigQueryDDLCompiler(DDLCompiler):
639
+ option_datatype_mapping = {
640
+ "friendly_name": str,
641
+ "expiration_timestamp": datetime.datetime,
642
+ "require_partition_filter": bool,
643
+ "default_rounding_mode": str,
644
+ }
645
+
626
646
  # BigQuery has no support for foreign keys.
627
647
  def visit_foreign_key_constraint(self, constraint):
628
648
  return None
@@ -646,26 +666,99 @@ class BigQueryDDLCompiler(DDLCompiler):
646
666
  return colspec
647
667
 
648
668
  def post_create_table(self, table):
669
+ """
670
+ Constructs additional SQL clauses for table creation in BigQuery.
671
+
672
+ This function processes the BigQuery dialect-specific options and generates SQL clauses for partitioning,
673
+ clustering, and other table options.
674
+
675
+ Args:
676
+ table (Table): The SQLAlchemy Table object for which the SQL is being generated.
677
+
678
+ Returns:
679
+ str: A string composed of SQL clauses for time partitioning, clustering, and other BigQuery specific
680
+ options, each separated by a newline. Returns an empty string if no such options are specified.
681
+
682
+ Raises:
683
+ TypeError: If the time_partitioning option is not a `TimePartitioning` object or if the clustering_fields option is not a list.
684
+ NoSuchColumnError: If any field specified in clustering_fields does not exist in the table.
685
+ """
686
+
649
687
  bq_opts = table.dialect_options["bigquery"]
650
- opts = []
651
688
 
652
- if ("description" in bq_opts) or table.comment:
653
- description = process_string_literal(
654
- bq_opts.get("description", table.comment)
689
+ options = {}
690
+ clauses = []
691
+
692
+ if (
693
+ bq_opts.get("time_partitioning") is not None
694
+ and bq_opts.get("range_partitioning") is not None
695
+ ):
696
+ raise ValueError(
697
+ "biquery_time_partitioning and bigquery_range_partitioning"
698
+ " dialect options are mutually exclusive."
699
+ )
700
+
701
+ if (time_partitioning := bq_opts.get("time_partitioning")) is not None:
702
+ self._raise_for_type(
703
+ "time_partitioning",
704
+ time_partitioning,
705
+ TimePartitioning,
655
706
  )
656
- opts.append(f"description={description}")
657
707
 
658
- if "friendly_name" in bq_opts:
659
- opts.append(
660
- "friendly_name={}".format(
661
- process_string_literal(bq_opts["friendly_name"])
708
+ if time_partitioning.expiration_ms:
709
+ _24hours = 1000 * 60 * 60 * 24
710
+ options["partition_expiration_days"] = (
711
+ time_partitioning.expiration_ms / _24hours
662
712
  )
713
+
714
+ partition_by_clause = self._process_time_partitioning(
715
+ table,
716
+ time_partitioning,
663
717
  )
664
718
 
665
- if opts:
666
- return "\nOPTIONS({})".format(", ".join(opts))
719
+ clauses.append(partition_by_clause)
667
720
 
668
- return ""
721
+ if (range_partitioning := bq_opts.get("range_partitioning")) is not None:
722
+ self._raise_for_type(
723
+ "range_partitioning",
724
+ range_partitioning,
725
+ RangePartitioning,
726
+ )
727
+
728
+ partition_by_clause = self._process_range_partitioning(
729
+ table,
730
+ range_partitioning,
731
+ )
732
+
733
+ clauses.append(partition_by_clause)
734
+
735
+ if (clustering_fields := bq_opts.get("clustering_fields")) is not None:
736
+ self._raise_for_type("clustering_fields", clustering_fields, list)
737
+
738
+ for field in clustering_fields:
739
+ if field not in table.c:
740
+ raise NoSuchColumnError(field)
741
+
742
+ clauses.append(f"CLUSTER BY {', '.join(clustering_fields)}")
743
+
744
+ if ("description" in bq_opts) or table.comment:
745
+ description = bq_opts.get("description", table.comment)
746
+ self._validate_option_value_type("description", description)
747
+ options["description"] = description
748
+
749
+ for option in self.option_datatype_mapping:
750
+ if option in bq_opts:
751
+ options[option] = bq_opts.get(option)
752
+
753
+ if options:
754
+ individual_option_statements = [
755
+ "{}={}".format(k, self._process_option_value(v))
756
+ for (k, v) in options.items()
757
+ if self._validate_option_value_type(k, v)
758
+ ]
759
+ clauses.append(f"OPTIONS({', '.join(individual_option_statements)})")
760
+
761
+ return " " + "\n".join(clauses)
669
762
 
670
763
  def visit_set_table_comment(self, create):
671
764
  table_name = self.preparer.format_table(create.element)
@@ -678,6 +771,152 @@ class BigQueryDDLCompiler(DDLCompiler):
678
771
  table_name = self.preparer.format_table(drop.element)
679
772
  return f"ALTER TABLE {table_name} SET OPTIONS(description=null)"
680
773
 
774
+ def _validate_option_value_type(self, option: str, value):
775
+ """
776
+ Validates the type of the given option value against the expected data type.
777
+
778
+ Args:
779
+ option (str): The name of the option to be validated.
780
+ value: The value of the dialect option whose type is to be checked. The type of this parameter
781
+ is dynamic and is verified against the expected type in `self.option_datatype_mapping`.
782
+
783
+ Returns:
784
+ bool: True if the type of the value matches the expected type, or if the option is not found in
785
+ `self.option_datatype_mapping`.
786
+
787
+ Raises:
788
+ TypeError: If the type of the provided value does not match the expected type as defined in
789
+ `self.option_datatype_mapping`.
790
+ """
791
+ if option in self.option_datatype_mapping:
792
+ self._raise_for_type(
793
+ option,
794
+ value,
795
+ self.option_datatype_mapping[option],
796
+ )
797
+
798
+ return True
799
+
800
+ def _raise_for_type(self, option, value, expected_type):
801
+ if type(value) is not expected_type:
802
+ raise TypeError(
803
+ f"bigquery_{option} dialect option accepts only {expected_type},"
804
+ f" provided {repr(value)}"
805
+ )
806
+
807
+ def _process_time_partitioning(
808
+ self, table: Table, time_partitioning: TimePartitioning
809
+ ):
810
+ """
811
+ Generates a SQL 'PARTITION BY' clause for partitioning a table by a date or timestamp.
812
+
813
+ Args:
814
+ - table (Table): The SQLAlchemy table object representing the BigQuery table to be partitioned.
815
+ - time_partitioning (TimePartitioning): The time partitioning details,
816
+ including the field to be used for partitioning.
817
+
818
+ Returns:
819
+ - str: A SQL 'PARTITION BY' clause that uses either TIMESTAMP_TRUNC or DATE_TRUNC to
820
+ partition data on the specified field.
821
+
822
+ Example:
823
+ - Given a table with a TIMESTAMP type column 'event_timestamp' and setting
824
+ 'time_partitioning.field' to 'event_timestamp', the function returns
825
+ "PARTITION BY TIMESTAMP_TRUNC(event_timestamp, DAY)".
826
+ """
827
+ field = "_PARTITIONDATE"
828
+ trunc_fn = "DATE_TRUNC"
829
+
830
+ if time_partitioning.field is not None:
831
+ field = time_partitioning.field
832
+ if isinstance(
833
+ table.columns[time_partitioning.field].type,
834
+ sqlalchemy.sql.sqltypes.TIMESTAMP,
835
+ ):
836
+ trunc_fn = "TIMESTAMP_TRUNC"
837
+
838
+ return f"PARTITION BY {trunc_fn}({field}, {time_partitioning.type_})"
839
+
840
+ def _process_range_partitioning(
841
+ self, table: Table, range_partitioning: RangePartitioning
842
+ ):
843
+ """
844
+ Generates a SQL 'PARTITION BY' clause for partitioning a table by a range of integers.
845
+
846
+ Args:
847
+ - table (Table): The SQLAlchemy table object representing the BigQuery table to be partitioned.
848
+ - range_partitioning (RangePartitioning): The RangePartitioning object containing the
849
+ partitioning field, range start, range end, and interval.
850
+
851
+ Returns:
852
+ - str: A SQL string for range partitioning using RANGE_BUCKET and GENERATE_ARRAY functions.
853
+
854
+ Raises:
855
+ - AttributeError: If the partitioning field is not defined.
856
+ - ValueError: If the partitioning field (i.e. column) data type is not an integer.
857
+ - TypeError: If the partitioning range start/end values are not integers.
858
+
859
+ Example:
860
+ "PARTITION BY RANGE_BUCKET(zipcode, GENERATE_ARRAY(0, 100000, 10))"
861
+ """
862
+ if range_partitioning.field is None:
863
+ raise AttributeError(
864
+ "bigquery_range_partitioning expects field to be defined"
865
+ )
866
+
867
+ if not isinstance(
868
+ table.columns[range_partitioning.field].type,
869
+ sqlalchemy.sql.sqltypes.INT,
870
+ ):
871
+ raise ValueError(
872
+ "bigquery_range_partitioning expects field (i.e. column) data type to be INTEGER"
873
+ )
874
+
875
+ range_ = range_partitioning.range_
876
+
877
+ if not isinstance(range_.start, int):
878
+ raise TypeError(
879
+ "bigquery_range_partitioning expects range_.start to be an int,"
880
+ f" provided {repr(range_.start)}"
881
+ )
882
+
883
+ if not isinstance(range_.end, int):
884
+ raise TypeError(
885
+ "bigquery_range_partitioning expects range_.end to be an int,"
886
+ f" provided {repr(range_.end)}"
887
+ )
888
+
889
+ default_interval = 1
890
+
891
+ return f"PARTITION BY RANGE_BUCKET({range_partitioning.field}, GENERATE_ARRAY({range_.start}, {range_.end}, {range_.interval or default_interval}))"
892
+
893
+ def _process_option_value(self, value):
894
+ """
895
+ Transforms the given option value into a literal representation suitable for SQL queries in BigQuery.
896
+
897
+ Args:
898
+ value: The value to be transformed.
899
+
900
+ Returns:
901
+ The processed value in a format suitable for inclusion in a SQL query.
902
+
903
+ Raises:
904
+ NotImplementedError: When there is no transformation registered for a data type.
905
+ """
906
+ option_casting = {
907
+ # Mapping from option type to its casting method
908
+ str: lambda x: process_string_literal(x),
909
+ int: lambda x: x,
910
+ float: lambda x: x,
911
+ bool: lambda x: "true" if x else "false",
912
+ datetime.datetime: lambda x: BQTimestamp.process_timestamp_literal(x),
913
+ }
914
+
915
+ if (option_cast := option_casting.get(type(value))) is not None:
916
+ return option_cast(value)
917
+
918
+ raise NotImplementedError(f"No transformation registered for {repr(value)}")
919
+
681
920
 
682
921
  def process_string_literal(value):
683
922
  return repr(value.replace("%", "%%"))
@@ -989,25 +1228,8 @@ class BigQueryDialect(DefaultDialect):
989
1228
  return {"constrained_columns": []}
990
1229
 
991
1230
  def get_indexes(self, connection, table_name, schema=None, **kw):
992
- table = self._get_table(connection, table_name, schema)
993
- indexes = []
994
- if table.time_partitioning:
995
- indexes.append(
996
- {
997
- "name": "partition",
998
- "column_names": [table.time_partitioning.field],
999
- "unique": False,
1000
- }
1001
- )
1002
- if table.clustering_fields:
1003
- indexes.append(
1004
- {
1005
- "name": "clustering",
1006
- "column_names": table.clustering_fields,
1007
- "unique": False,
1008
- }
1009
- )
1010
- return indexes
1231
+ # BigQuery has no support for indexes.
1232
+ return []
1011
1233
 
1012
1234
  def get_schema_names(self, connection, **kw):
1013
1235
  if isinstance(connection, Engine):
@@ -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.9.0"
20
+ __version__ = "1.10.0"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlalchemy-bigquery
3
- Version: 1.9.0
3
+ Version: 1.10.0
4
4
  Summary: SQLAlchemy dialect for BigQuery
5
5
  Home-page: https://github.com/googleapis/python-bigquery-sqlalchemy
6
6
  Author: The Sqlalchemy-Bigquery Authors
@@ -44,14 +44,14 @@ Requires-Dist: grpcio<2.0dev,>=1.49.1; python_version >= "3.11" and extra == "bq
44
44
  Requires-Dist: pyarrow>=3.0.0; extra == "bqstorage"
45
45
  Provides-Extra: all
46
46
  Requires-Dist: alembic; extra == "all"
47
- Requires-Dist: GeoAlchemy2; extra == "all"
48
47
  Requires-Dist: google-cloud-bigquery-storage<3.0.0dev,>=2.0.0; extra == "all"
49
- Requires-Dist: grpcio<2.0dev,>=1.47.0; extra == "all"
50
48
  Requires-Dist: shapely; extra == "all"
49
+ Requires-Dist: pyarrow>=3.0.0; extra == "all"
50
+ Requires-Dist: grpcio<2.0dev,>=1.49.1; python_version >= "3.11" and extra == "all"
51
51
  Requires-Dist: packaging; extra == "all"
52
52
  Requires-Dist: pytz; extra == "all"
53
- Requires-Dist: grpcio<2.0dev,>=1.49.1; python_version >= "3.11" and extra == "all"
54
- Requires-Dist: pyarrow>=3.0.0; extra == "all"
53
+ Requires-Dist: GeoAlchemy2; extra == "all"
54
+ Requires-Dist: grpcio<2.0dev,>=1.47.0; extra == "all"
55
55
 
56
56
  SQLAlchemy Dialect for BigQuery
57
57
  ===============================
@@ -347,7 +347,12 @@ To add metadata to a table:
347
347
 
348
348
  .. code-block:: python
349
349
 
350
- table = Table('mytable', ..., bigquery_description='my table description', bigquery_friendly_name='my table friendly name')
350
+ table = Table('mytable', ...,
351
+ bigquery_description='my table description',
352
+ bigquery_friendly_name='my table friendly name',
353
+ bigquery_default_rounding_mode="ROUND_HALF_EVEN",
354
+ bigquery_expiration_timestamp=datetime.datetime.fromisoformat("2038-01-01T00:00:00+00:00"),
355
+ )
351
356
 
352
357
  To add metadata to a column:
353
358
 
@@ -355,6 +360,52 @@ To add metadata to a column:
355
360
 
356
361
  Column('mycolumn', doc='my column description')
357
362
 
363
+ To create a clustered table:
364
+
365
+ .. code-block:: python
366
+
367
+ table = Table('mytable', ..., bigquery_clustering_fields=["a", "b", "c"])
368
+
369
+ To create a time-unit column-partitioned table:
370
+
371
+ .. code-block:: python
372
+
373
+ from google.cloud import bigquery
374
+
375
+ table = Table('mytable', ...,
376
+ bigquery_time_partitioning=bigquery.TimePartitioning(
377
+ field="mytimestamp",
378
+ type_="MONTH",
379
+ expiration_ms=1000 * 60 * 60 * 24 * 30 * 6, # 6 months
380
+ ),
381
+ bigquery_require_partition_filter=True,
382
+ )
383
+
384
+ To create an ingestion-time partitioned table:
385
+
386
+ .. code-block:: python
387
+
388
+ from google.cloud import bigquery
389
+
390
+ table = Table('mytable', ...,
391
+ bigquery_time_partitioning=bigquery.TimePartitioning(),
392
+ bigquery_require_partition_filter=True,
393
+ )
394
+
395
+ To create an integer-range partitioned table
396
+
397
+ .. code-block:: python
398
+
399
+ from google.cloud import bigquery
400
+
401
+ table = Table('mytable', ...,
402
+ bigquery_range_partitioning=bigquery.RangePartitioning(
403
+ field="zipcode",
404
+ range_=bigquery.PartitionRange(start=0, end=100000, interval=10),
405
+ ),
406
+ bigquery_require_partition_filter=True,
407
+ )
408
+
358
409
 
359
410
  Threading and Multiprocessing
360
411
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -50,5 +50,6 @@ tests/unit/test_like_reescape.py
50
50
  tests/unit/test_parse_url.py
51
51
  tests/unit/test_select.py
52
52
  tests/unit/test_sqlalchemy_bigquery.py
53
+ tests/unit/test_table_options.py
53
54
  tests/unit/test_version.py
54
55
  tests/unit/test_view.py
@@ -23,7 +23,7 @@ import pytest
23
23
  from sqlalchemy import Column, DateTime, Integer, String, Numeric
24
24
 
25
25
  import google.api_core.exceptions
26
- from google.cloud.bigquery import SchemaField
26
+ from google.cloud.bigquery import SchemaField, TimePartitioning
27
27
 
28
28
  alembic = pytest.importorskip("alembic")
29
29
 
@@ -138,15 +138,12 @@ def test_alembic_scenario(alembic_table):
138
138
  op.drop_table("accounts")
139
139
  assert alembic_table("accounts") is None
140
140
 
141
- op.execute(
142
- """
143
- create table transactions(
144
- account INT64 NOT NULL,
145
- transaction_time DATETIME NOT NULL,
146
- amount NUMERIC(11, 2) NOT NULL
147
- )
148
- partition by DATE(transaction_time)
149
- """
141
+ op.create_table(
142
+ "transactions",
143
+ Column("account", Integer, nullable=False),
144
+ Column("transaction_time", DateTime(), nullable=False),
145
+ Column("amount", Numeric(11, 2), nullable=False),
146
+ bigquery_time_partitioning=TimePartitioning(field="transaction_time"),
150
147
  )
151
148
 
152
149
  op.alter_column("transactions", "amount", nullable=True)
@@ -22,6 +22,8 @@
22
22
  import datetime
23
23
  import decimal
24
24
 
25
+ from google.cloud.bigquery import TimePartitioning
26
+
25
27
  from sqlalchemy.engine import create_engine
26
28
  from sqlalchemy.schema import Table, MetaData, Column
27
29
  from sqlalchemy.ext.declarative import declarative_base
@@ -539,6 +541,14 @@ def test_create_table(engine, bigquery_dataset):
539
541
  Column("binary_c", sqlalchemy.BINARY),
540
542
  bigquery_description="test table description",
541
543
  bigquery_friendly_name="test table name",
544
+ bigquery_expiration_timestamp=datetime.datetime(2183, 3, 26, 8, 30, 0),
545
+ bigquery_time_partitioning=TimePartitioning(
546
+ field="timestamp_c",
547
+ expiration_ms=1000 * 60 * 60 * 24 * 30, # 30 days
548
+ ),
549
+ bigquery_require_partition_filter=True,
550
+ bigquery_default_rounding_mode="ROUND_HALF_EVEN",
551
+ bigquery_clustering_fields=["integer_c", "decimal_c"],
542
552
  )
543
553
  meta.create_all(engine)
544
554
  meta.drop_all(engine)
@@ -594,17 +604,7 @@ def test_view_names(inspector, inspector_using_test_dataset, bigquery_dataset):
594
604
  def test_get_indexes(inspector, inspector_using_test_dataset, bigquery_dataset):
595
605
  for _ in [f"{bigquery_dataset}.sample", f"{bigquery_dataset}.sample_one_row"]:
596
606
  indexes = inspector.get_indexes(f"{bigquery_dataset}.sample")
597
- assert len(indexes) == 2
598
- assert indexes[0] == {
599
- "name": "partition",
600
- "column_names": ["timestamp"],
601
- "unique": False,
602
- }
603
- assert indexes[1] == {
604
- "name": "clustering",
605
- "column_names": ["integer", "string"],
606
- "unique": False,
607
- }
607
+ assert len(indexes) == 0
608
608
 
609
609
 
610
610
  def test_get_columns(inspector, inspector_using_test_dataset, bigquery_dataset):