-
Notifications
You must be signed in to change notification settings - Fork 306
/
table.py
3310 lines (2719 loc) · 120 KB
/
table.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2015 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define API Tables."""
from __future__ import absolute_import
import copy
import datetime
import functools
import operator
import typing
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple, Union
import warnings
try:
import pandas # type: ignore
except ImportError:
pandas = None
try:
import pyarrow # type: ignore
except ImportError:
pyarrow = None
try:
import db_dtypes # type: ignore
except ImportError:
db_dtypes = None
try:
import geopandas # type: ignore
except ImportError:
geopandas = None
else:
_COORDINATE_REFERENCE_SYSTEM = "EPSG:4326"
try:
import shapely # type: ignore
from shapely import wkt # type: ignore
except ImportError:
shapely = None
else:
_read_wkt = wkt.loads
import google.api_core.exceptions
from google.api_core.page_iterator import HTTPIterator
import google.cloud._helpers # type: ignore
from google.cloud.bigquery import _helpers
from google.cloud.bigquery import _pandas_helpers
from google.cloud.bigquery import _versions_helpers
from google.cloud.bigquery import exceptions as bq_exceptions
from google.cloud.bigquery._tqdm_helpers import get_progress_bar
from google.cloud.bigquery.encryption_configuration import EncryptionConfiguration
from google.cloud.bigquery.enums import DefaultPandasDTypes
from google.cloud.bigquery.external_config import ExternalConfig
from google.cloud.bigquery.schema import _build_schema_resource
from google.cloud.bigquery.schema import _parse_schema_resource
from google.cloud.bigquery.schema import _to_schema_fields
if typing.TYPE_CHECKING: # pragma: NO COVER
# Unconditionally import optional dependencies again to tell pytype that
# they are not None, avoiding false "no attribute" errors.
import pandas
import pyarrow
import geopandas # type: ignore
from google.cloud import bigquery_storage # type: ignore
from google.cloud.bigquery.dataset import DatasetReference
_NO_GEOPANDAS_ERROR = (
"The geopandas library is not installed, please install "
"geopandas to use the to_geodataframe() function."
)
_NO_PYARROW_ERROR = (
"The pyarrow library is not installed, please install "
"pyarrow to use the to_arrow() function."
)
_NO_SHAPELY_ERROR = (
"The shapely library is not installed, please install "
"shapely to use the geography_as_object option."
)
_TABLE_HAS_NO_SCHEMA = 'Table has no schema: call "client.get_table()"'
_NO_SUPPORTED_DTYPE = (
"The dtype cannot to be converted to a pandas ExtensionArray "
"because the necessary `__from_arrow__` attribute is missing."
)
_RANGE_PYARROW_WARNING = (
"Unable to represent RANGE schema as struct using pandas ArrowDtype. Using "
"`object` instead. To use ArrowDtype, use pandas >= 1.5 and "
"pyarrow >= 10.0.1."
)
# How many of the total rows need to be downloaded already for us to skip
# calling the BQ Storage API?
#
# In microbenchmarks on 2024-05-21, I (tswast@) measure that at about 2 MB of
# remaining results, it's faster to use the BQ Storage Read API to download
# the results than use jobs.getQueryResults. Since we don't have a good way to
# know the remaining bytes, we estimate by remaining number of rows.
#
# Except when rows themselves are larger, I observe that the a single page of
# results will be around 10 MB. Therefore, the proportion of rows already
# downloaded should be 10 (first page) / 12 (all results) or less for it to be
# worth it to make a call to jobs.getQueryResults.
ALMOST_COMPLETELY_CACHED_RATIO = 0.833333
def _reference_getter(table):
"""A :class:`~google.cloud.bigquery.table.TableReference` pointing to
this table.
Returns:
google.cloud.bigquery.table.TableReference: pointer to this table.
"""
from google.cloud.bigquery import dataset
dataset_ref = dataset.DatasetReference(table.project, table.dataset_id)
return TableReference(dataset_ref, table.table_id)
def _view_use_legacy_sql_getter(table):
"""bool: Specifies whether to execute the view with Legacy or Standard SQL.
This boolean specifies whether to execute the view with Legacy SQL
(:data:`True`) or Standard SQL (:data:`False`). The client side default is
:data:`False`. The server-side default is :data:`True`. If this table is
not a view, :data:`None` is returned.
Raises:
ValueError: For invalid value types.
"""
view = table._properties.get("view")
if view is not None:
# The server-side default for useLegacySql is True.
return view.get("useLegacySql", True)
# In some cases, such as in a table list no view object is present, but the
# resource still represents a view. Use the type as a fallback.
if table.table_type == "VIEW":
# The server-side default for useLegacySql is True.
return True
class _TableBase:
"""Base class for Table-related classes with common functionality."""
_PROPERTY_TO_API_FIELD: Dict[str, Union[str, List[str]]] = {
"dataset_id": ["tableReference", "datasetId"],
"project": ["tableReference", "projectId"],
"table_id": ["tableReference", "tableId"],
}
def __init__(self):
self._properties = {}
@property
def project(self) -> str:
"""Project bound to the table."""
return _helpers._get_sub_prop(
self._properties, self._PROPERTY_TO_API_FIELD["project"]
)
@property
def dataset_id(self) -> str:
"""ID of dataset containing the table."""
return _helpers._get_sub_prop(
self._properties, self._PROPERTY_TO_API_FIELD["dataset_id"]
)
@property
def table_id(self) -> str:
"""The table ID."""
return _helpers._get_sub_prop(
self._properties, self._PROPERTY_TO_API_FIELD["table_id"]
)
@property
def path(self) -> str:
"""URL path for the table's APIs."""
return (
f"/projects/{self.project}/datasets/{self.dataset_id}"
f"/tables/{self.table_id}"
)
def __eq__(self, other):
if isinstance(other, _TableBase):
return (
self.project == other.project
and self.dataset_id == other.dataset_id
and self.table_id == other.table_id
)
else:
return NotImplemented
def __hash__(self):
return hash((self.project, self.dataset_id, self.table_id))
class TableReference(_TableBase):
"""TableReferences are pointers to tables.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#tablereference
Args:
dataset_ref: A pointer to the dataset
table_id: The ID of the table
"""
_PROPERTY_TO_API_FIELD = {
"dataset_id": "datasetId",
"project": "projectId",
"table_id": "tableId",
}
def __init__(self, dataset_ref: "DatasetReference", table_id: str):
self._properties = {}
_helpers._set_sub_prop(
self._properties,
self._PROPERTY_TO_API_FIELD["project"],
dataset_ref.project,
)
_helpers._set_sub_prop(
self._properties,
self._PROPERTY_TO_API_FIELD["dataset_id"],
dataset_ref.dataset_id,
)
_helpers._set_sub_prop(
self._properties,
self._PROPERTY_TO_API_FIELD["table_id"],
table_id,
)
@classmethod
def from_string(
cls, table_id: str, default_project: Optional[str] = None
) -> "TableReference":
"""Construct a table reference from table ID string.
Args:
table_id (str):
A table ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
ID, and table ID, each separated by ``.``.
default_project (Optional[str]):
The project ID to use when ``table_id`` does not
include a project ID.
Returns:
TableReference: Table reference parsed from ``table_id``.
Examples:
>>> TableReference.from_string('my-project.mydataset.mytable')
TableRef...(DatasetRef...('my-project', 'mydataset'), 'mytable')
Raises:
ValueError:
If ``table_id`` is not a fully-qualified table ID in
standard SQL format.
"""
from google.cloud.bigquery.dataset import DatasetReference
(
output_project_id,
output_dataset_id,
output_table_id,
) = _helpers._parse_3_part_id(
table_id, default_project=default_project, property_name="table_id"
)
return cls(
DatasetReference(output_project_id, output_dataset_id), output_table_id
)
@classmethod
def from_api_repr(cls, resource: dict) -> "TableReference":
"""Factory: construct a table reference given its API representation
Args:
resource (Dict[str, object]):
Table reference representation returned from the API
Returns:
google.cloud.bigquery.table.TableReference:
Table reference parsed from ``resource``.
"""
from google.cloud.bigquery.dataset import DatasetReference
project = resource["projectId"]
dataset_id = resource["datasetId"]
table_id = resource["tableId"]
return cls(DatasetReference(project, dataset_id), table_id)
def to_api_repr(self) -> dict:
"""Construct the API resource representation of this table reference.
Returns:
Dict[str, object]: Table reference represented as an API resource
"""
return copy.deepcopy(self._properties)
def to_bqstorage(self) -> str:
"""Construct a BigQuery Storage API representation of this table.
Install the ``google-cloud-bigquery-storage`` package to use this
feature.
If the ``table_id`` contains a partition identifier (e.g.
``my_table$201812``) or a snapshot identifier (e.g.
``mytable@1234567890``), it is ignored. Use
:class:`google.cloud.bigquery_storage.types.ReadSession.TableReadOptions`
to filter rows by partition. Use
:class:`google.cloud.bigquery_storage.types.ReadSession.TableModifiers`
to select a specific snapshot to read from.
Returns:
str: A reference to this table in the BigQuery Storage API.
"""
table_id, _, _ = self.table_id.partition("@")
table_id, _, _ = table_id.partition("$")
table_ref = (
f"projects/{self.project}/datasets/{self.dataset_id}/tables/{table_id}"
)
return table_ref
def __str__(self):
return f"{self.project}.{self.dataset_id}.{self.table_id}"
def __repr__(self):
from google.cloud.bigquery.dataset import DatasetReference
dataset_ref = DatasetReference(self.project, self.dataset_id)
return f"TableReference({dataset_ref!r}, '{self.table_id}')"
class Table(_TableBase):
"""Tables represent a set of rows whose values correspond to a schema.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#resource-table
Args:
table_ref (Union[google.cloud.bigquery.table.TableReference, str]):
A pointer to a table. If ``table_ref`` is a string, it must
included a project ID, dataset ID, and table ID, each separated
by ``.``.
schema (Optional[Sequence[Union[ \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
Mapping[str, Any] \
]]]):
The table's schema. If any item is a mapping, its content must be
compatible with
:meth:`~google.cloud.bigquery.schema.SchemaField.from_api_repr`.
"""
_PROPERTY_TO_API_FIELD = {
**_TableBase._PROPERTY_TO_API_FIELD,
"clustering_fields": "clustering",
"created": "creationTime",
"description": "description",
"encryption_configuration": "encryptionConfiguration",
"etag": "etag",
"expires": "expirationTime",
"external_data_configuration": "externalDataConfiguration",
"friendly_name": "friendlyName",
"full_table_id": "id",
"labels": "labels",
"location": "location",
"modified": "lastModifiedTime",
"mview_enable_refresh": "materializedView",
"mview_last_refresh_time": ["materializedView", "lastRefreshTime"],
"mview_query": "materializedView",
"mview_refresh_interval": "materializedView",
"num_bytes": "numBytes",
"num_rows": "numRows",
"partition_expiration": "timePartitioning",
"partitioning_type": "timePartitioning",
"range_partitioning": "rangePartitioning",
"time_partitioning": "timePartitioning",
"schema": "schema",
"snapshot_definition": "snapshotDefinition",
"clone_definition": "cloneDefinition",
"streaming_buffer": "streamingBuffer",
"self_link": "selfLink",
"type": "type",
"view_use_legacy_sql": "view",
"view_query": "view",
"require_partition_filter": "requirePartitionFilter",
"table_constraints": "tableConstraints",
}
def __init__(self, table_ref, schema=None) -> None:
table_ref = _table_arg_to_table_ref(table_ref)
self._properties = {"tableReference": table_ref.to_api_repr(), "labels": {}}
# Let the @property do validation.
if schema is not None:
self.schema = schema
reference = property(_reference_getter)
@property
def require_partition_filter(self):
"""bool: If set to true, queries over the partitioned table require a
partition filter that can be used for partition elimination to be
specified.
"""
return self._properties.get(
self._PROPERTY_TO_API_FIELD["require_partition_filter"]
)
@require_partition_filter.setter
def require_partition_filter(self, value):
self._properties[
self._PROPERTY_TO_API_FIELD["require_partition_filter"]
] = value
@property
def schema(self):
"""Sequence[Union[ \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
Mapping[str, Any] \
]]:
Table's schema.
Raises:
Exception:
If ``schema`` is not a sequence, or if any item in the sequence
is not a :class:`~google.cloud.bigquery.schema.SchemaField`
instance or a compatible mapping representation of the field.
"""
prop = self._properties.get(self._PROPERTY_TO_API_FIELD["schema"])
if not prop:
return []
else:
return _parse_schema_resource(prop)
@schema.setter
def schema(self, value):
api_field = self._PROPERTY_TO_API_FIELD["schema"]
if value is None:
self._properties[api_field] = None
else:
value = _to_schema_fields(value)
self._properties[api_field] = {"fields": _build_schema_resource(value)}
@property
def labels(self):
"""Dict[str, str]: Labels for the table.
This method always returns a dict. To change a table's labels,
modify the dict, then call ``Client.update_table``. To delete a
label, set its value to :data:`None` before updating.
Raises:
ValueError: If ``value`` type is invalid.
"""
return self._properties.setdefault(self._PROPERTY_TO_API_FIELD["labels"], {})
@labels.setter
def labels(self, value):
if not isinstance(value, dict):
raise ValueError("Pass a dict")
self._properties[self._PROPERTY_TO_API_FIELD["labels"]] = value
@property
def encryption_configuration(self):
"""google.cloud.bigquery.encryption_configuration.EncryptionConfiguration: Custom
encryption configuration for the table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See `protecting data with Cloud KMS keys
<https://cloud.google.com/bigquery/docs/customer-managed-encryption>`_
in the BigQuery documentation.
"""
prop = self._properties.get(
self._PROPERTY_TO_API_FIELD["encryption_configuration"]
)
if prop is not None:
prop = EncryptionConfiguration.from_api_repr(prop)
return prop
@encryption_configuration.setter
def encryption_configuration(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._properties[
self._PROPERTY_TO_API_FIELD["encryption_configuration"]
] = api_repr
@property
def created(self):
"""Union[datetime.datetime, None]: Datetime at which the table was
created (:data:`None` until set from the server).
"""
creation_time = self._properties.get(self._PROPERTY_TO_API_FIELD["created"])
if creation_time is not None:
# creation_time will be in milliseconds.
return google.cloud._helpers._datetime_from_microseconds(
1000.0 * float(creation_time)
)
@property
def etag(self):
"""Union[str, None]: ETag for the table resource (:data:`None` until
set from the server).
"""
return self._properties.get(self._PROPERTY_TO_API_FIELD["etag"])
@property
def modified(self):
"""Union[datetime.datetime, None]: Datetime at which the table was last
modified (:data:`None` until set from the server).
"""
modified_time = self._properties.get(self._PROPERTY_TO_API_FIELD["modified"])
if modified_time is not None:
# modified_time will be in milliseconds.
return google.cloud._helpers._datetime_from_microseconds(
1000.0 * float(modified_time)
)
@property
def num_bytes(self):
"""Union[int, None]: The size of the table in bytes (:data:`None` until
set from the server).
"""
return _helpers._int_or_none(
self._properties.get(self._PROPERTY_TO_API_FIELD["num_bytes"])
)
@property
def num_rows(self):
"""Union[int, None]: The number of rows in the table (:data:`None`
until set from the server).
"""
return _helpers._int_or_none(
self._properties.get(self._PROPERTY_TO_API_FIELD["num_rows"])
)
@property
def self_link(self):
"""Union[str, None]: URL for the table resource (:data:`None` until set
from the server).
"""
return self._properties.get(self._PROPERTY_TO_API_FIELD["self_link"])
@property
def full_table_id(self):
"""Union[str, None]: ID for the table (:data:`None` until set from the
server).
In the format ``project-id:dataset_id.table_id``.
"""
return self._properties.get(self._PROPERTY_TO_API_FIELD["full_table_id"])
@property
def table_type(self):
"""Union[str, None]: The type of the table (:data:`None` until set from
the server).
Possible values are ``'TABLE'``, ``'VIEW'``, ``'MATERIALIZED_VIEW'`` or
``'EXTERNAL'``.
"""
return self._properties.get(self._PROPERTY_TO_API_FIELD["type"])
@property
def range_partitioning(self):
"""Optional[google.cloud.bigquery.table.RangePartitioning]:
Configures range-based partitioning for a table.
.. note::
**Beta**. The integer range partitioning feature is in a
pre-release state and might change or have limited support.
Only specify at most one of
:attr:`~google.cloud.bigquery.table.Table.time_partitioning` or
:attr:`~google.cloud.bigquery.table.Table.range_partitioning`.
Raises:
ValueError:
If the value is not
:class:`~google.cloud.bigquery.table.RangePartitioning` or
:data:`None`.
"""
resource = self._properties.get(
self._PROPERTY_TO_API_FIELD["range_partitioning"]
)
if resource is not None:
return RangePartitioning(_properties=resource)
@range_partitioning.setter
def range_partitioning(self, value):
resource = value
if isinstance(value, RangePartitioning):
resource = value._properties
elif value is not None:
raise ValueError(
"Expected value to be RangePartitioning or None, got {}.".format(value)
)
self._properties[self._PROPERTY_TO_API_FIELD["range_partitioning"]] = resource
@property
def time_partitioning(self):
"""Optional[google.cloud.bigquery.table.TimePartitioning]: Configures time-based
partitioning for a table.
Only specify at most one of
:attr:`~google.cloud.bigquery.table.Table.time_partitioning` or
:attr:`~google.cloud.bigquery.table.Table.range_partitioning`.
Raises:
ValueError:
If the value is not
:class:`~google.cloud.bigquery.table.TimePartitioning` or
:data:`None`.
"""
prop = self._properties.get(self._PROPERTY_TO_API_FIELD["time_partitioning"])
if prop is not None:
return TimePartitioning.from_api_repr(prop)
@time_partitioning.setter
def time_partitioning(self, value):
api_repr = value
if isinstance(value, TimePartitioning):
api_repr = value.to_api_repr()
elif value is not None:
raise ValueError(
"value must be google.cloud.bigquery.table.TimePartitioning " "or None"
)
self._properties[self._PROPERTY_TO_API_FIELD["time_partitioning"]] = api_repr
@property
def partitioning_type(self):
"""Union[str, None]: Time partitioning of the table if it is
partitioned (Defaults to :data:`None`).
"""
warnings.warn(
"This method will be deprecated in future versions. Please use "
"Table.time_partitioning.type_ instead.",
PendingDeprecationWarning,
stacklevel=2,
)
if self.time_partitioning is not None:
return self.time_partitioning.type_
@partitioning_type.setter
def partitioning_type(self, value):
warnings.warn(
"This method will be deprecated in future versions. Please use "
"Table.time_partitioning.type_ instead.",
PendingDeprecationWarning,
stacklevel=2,
)
api_field = self._PROPERTY_TO_API_FIELD["partitioning_type"]
if self.time_partitioning is None:
self._properties[api_field] = {}
self._properties[api_field]["type"] = value
@property
def partition_expiration(self):
"""Union[int, None]: Expiration time in milliseconds for a partition.
If :attr:`partition_expiration` is set and :attr:`type_` is
not set, :attr:`type_` will default to
:attr:`~google.cloud.bigquery.table.TimePartitioningType.DAY`.
"""
warnings.warn(
"This method will be deprecated in future versions. Please use "
"Table.time_partitioning.expiration_ms instead.",
PendingDeprecationWarning,
stacklevel=2,
)
if self.time_partitioning is not None:
return self.time_partitioning.expiration_ms
@partition_expiration.setter
def partition_expiration(self, value):
warnings.warn(
"This method will be deprecated in future versions. Please use "
"Table.time_partitioning.expiration_ms instead.",
PendingDeprecationWarning,
stacklevel=2,
)
api_field = self._PROPERTY_TO_API_FIELD["partition_expiration"]
if self.time_partitioning is None:
self._properties[api_field] = {"type": TimePartitioningType.DAY}
if value is None:
self._properties[api_field]["expirationMs"] = None
else:
self._properties[api_field]["expirationMs"] = str(value)
@property
def clustering_fields(self):
"""Union[List[str], None]: Fields defining clustering for the table
(Defaults to :data:`None`).
Clustering fields are immutable after table creation.
.. note::
BigQuery supports clustering for both partitioned and
non-partitioned tables.
"""
prop = self._properties.get(self._PROPERTY_TO_API_FIELD["clustering_fields"])
if prop is not None:
return list(prop.get("fields", ()))
@clustering_fields.setter
def clustering_fields(self, value):
"""Union[List[str], None]: Fields defining clustering for the table
(Defaults to :data:`None`).
"""
api_field = self._PROPERTY_TO_API_FIELD["clustering_fields"]
if value is not None:
prop = self._properties.setdefault(api_field, {})
prop["fields"] = value
else:
# In order to allow unsetting clustering fields completely, we explicitly
# set this property to None (as oposed to merely removing the key).
self._properties[api_field] = None
@property
def description(self):
"""Union[str, None]: Description of the table (defaults to
:data:`None`).
Raises:
ValueError: For invalid value types.
"""
return self._properties.get(self._PROPERTY_TO_API_FIELD["description"])
@description.setter
def description(self, value):
if not isinstance(value, str) and value is not None:
raise ValueError("Pass a string, or None")
self._properties[self._PROPERTY_TO_API_FIELD["description"]] = value
@property
def expires(self):
"""Union[datetime.datetime, None]: Datetime at which the table will be
deleted.
Raises:
ValueError: For invalid value types.
"""
expiration_time = self._properties.get(self._PROPERTY_TO_API_FIELD["expires"])
if expiration_time is not None:
# expiration_time will be in milliseconds.
return google.cloud._helpers._datetime_from_microseconds(
1000.0 * float(expiration_time)
)
@expires.setter
def expires(self, value):
if not isinstance(value, datetime.datetime) and value is not None:
raise ValueError("Pass a datetime, or None")
value_ms = google.cloud._helpers._millis_from_datetime(value)
self._properties[
self._PROPERTY_TO_API_FIELD["expires"]
] = _helpers._str_or_none(value_ms)
@property
def friendly_name(self):
"""Union[str, None]: Title of the table (defaults to :data:`None`).
Raises:
ValueError: For invalid value types.
"""
return self._properties.get(self._PROPERTY_TO_API_FIELD["friendly_name"])
@friendly_name.setter
def friendly_name(self, value):
if not isinstance(value, str) and value is not None:
raise ValueError("Pass a string, or None")
self._properties[self._PROPERTY_TO_API_FIELD["friendly_name"]] = value
@property
def location(self):
"""Union[str, None]: Location in which the table is hosted
Defaults to :data:`None`.
"""
return self._properties.get(self._PROPERTY_TO_API_FIELD["location"])
@property
def view_query(self):
"""Union[str, None]: SQL query defining the table as a view (defaults
to :data:`None`).
By default, the query is treated as Standard SQL. To use Legacy
SQL, set :attr:`view_use_legacy_sql` to :data:`True`.
Raises:
ValueError: For invalid value types.
"""
api_field = self._PROPERTY_TO_API_FIELD["view_query"]
return _helpers._get_sub_prop(self._properties, [api_field, "query"])
@view_query.setter
def view_query(self, value):
if not isinstance(value, str):
raise ValueError("Pass a string")
api_field = self._PROPERTY_TO_API_FIELD["view_query"]
_helpers._set_sub_prop(self._properties, [api_field, "query"], value)
view = self._properties[api_field]
# The service defaults useLegacySql to True, but this
# client uses Standard SQL by default.
if view.get("useLegacySql") is None:
view["useLegacySql"] = False
@view_query.deleter
def view_query(self):
"""Delete SQL query defining the table as a view."""
self._properties.pop(self._PROPERTY_TO_API_FIELD["view_query"], None)
view_use_legacy_sql = property(_view_use_legacy_sql_getter)
@view_use_legacy_sql.setter # type: ignore # (redefinition from above)
def view_use_legacy_sql(self, value):
if not isinstance(value, bool):
raise ValueError("Pass a boolean")
api_field = self._PROPERTY_TO_API_FIELD["view_query"]
if self._properties.get(api_field) is None:
self._properties[api_field] = {}
self._properties[api_field]["useLegacySql"] = value
@property
def mview_query(self):
"""Optional[str]: SQL query defining the table as a materialized
view (defaults to :data:`None`).
"""
api_field = self._PROPERTY_TO_API_FIELD["mview_query"]
return _helpers._get_sub_prop(self._properties, [api_field, "query"])
@mview_query.setter
def mview_query(self, value):
api_field = self._PROPERTY_TO_API_FIELD["mview_query"]
_helpers._set_sub_prop(self._properties, [api_field, "query"], str(value))
@mview_query.deleter
def mview_query(self):
"""Delete SQL query defining the table as a materialized view."""
self._properties.pop(self._PROPERTY_TO_API_FIELD["mview_query"], None)
@property
def mview_last_refresh_time(self):
"""Optional[datetime.datetime]: Datetime at which the materialized view was last
refreshed (:data:`None` until set from the server).
"""
refresh_time = _helpers._get_sub_prop(
self._properties, self._PROPERTY_TO_API_FIELD["mview_last_refresh_time"]
)
if refresh_time is not None:
# refresh_time will be in milliseconds.
return google.cloud._helpers._datetime_from_microseconds(
1000 * int(refresh_time)
)
@property
def mview_enable_refresh(self):
"""Optional[bool]: Enable automatic refresh of the materialized view
when the base table is updated. The default value is :data:`True`.
"""
api_field = self._PROPERTY_TO_API_FIELD["mview_enable_refresh"]
return _helpers._get_sub_prop(self._properties, [api_field, "enableRefresh"])
@mview_enable_refresh.setter
def mview_enable_refresh(self, value):
api_field = self._PROPERTY_TO_API_FIELD["mview_enable_refresh"]
return _helpers._set_sub_prop(
self._properties, [api_field, "enableRefresh"], value
)
@property
def mview_refresh_interval(self):
"""Optional[datetime.timedelta]: The maximum frequency at which this
materialized view will be refreshed. The default value is 1800000
milliseconds (30 minutes).
"""
api_field = self._PROPERTY_TO_API_FIELD["mview_refresh_interval"]
refresh_interval = _helpers._get_sub_prop(
self._properties, [api_field, "refreshIntervalMs"]
)
if refresh_interval is not None:
return datetime.timedelta(milliseconds=int(refresh_interval))
@mview_refresh_interval.setter
def mview_refresh_interval(self, value):
if value is None:
refresh_interval_ms = None
else:
refresh_interval_ms = str(value // datetime.timedelta(milliseconds=1))
api_field = self._PROPERTY_TO_API_FIELD["mview_refresh_interval"]
_helpers._set_sub_prop(
self._properties,
[api_field, "refreshIntervalMs"],
refresh_interval_ms,
)
@property
def streaming_buffer(self):
"""google.cloud.bigquery.StreamingBuffer: Information about a table's
streaming buffer.
"""
sb = self._properties.get(self._PROPERTY_TO_API_FIELD["streaming_buffer"])
if sb is not None:
return StreamingBuffer(sb)
@property
def external_data_configuration(self):
"""Union[google.cloud.bigquery.ExternalConfig, None]: Configuration for
an external data source (defaults to :data:`None`).
Raises:
ValueError: For invalid value types.
"""
prop = self._properties.get(
self._PROPERTY_TO_API_FIELD["external_data_configuration"]
)
if prop is not None:
prop = ExternalConfig.from_api_repr(prop)
return prop
@external_data_configuration.setter
def external_data_configuration(self, value):
if not (value is None or isinstance(value, ExternalConfig)):
raise ValueError("Pass an ExternalConfig or None")
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._properties[
self._PROPERTY_TO_API_FIELD["external_data_configuration"]
] = api_repr
@property
def snapshot_definition(self) -> Optional["SnapshotDefinition"]:
"""Information about the snapshot. This value is set via snapshot creation.
See: https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#Table.FIELDS.snapshot_definition
"""
snapshot_info = self._properties.get(
self._PROPERTY_TO_API_FIELD["snapshot_definition"]
)
if snapshot_info is not None:
snapshot_info = SnapshotDefinition(snapshot_info)
return snapshot_info
@property
def clone_definition(self) -> Optional["CloneDefinition"]:
"""Information about the clone. This value is set via clone creation.
See: https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#Table.FIELDS.clone_definition
"""
clone_info = self._properties.get(
self._PROPERTY_TO_API_FIELD["clone_definition"]
)
if clone_info is not None:
clone_info = CloneDefinition(clone_info)
return clone_info
@property
def table_constraints(self) -> Optional["TableConstraints"]:
"""Tables Primary Key and Foreign Key information."""
table_constraints = self._properties.get(
self._PROPERTY_TO_API_FIELD["table_constraints"]
)
if table_constraints is not None:
table_constraints = TableConstraints.from_api_repr(table_constraints)
return table_constraints