-
Notifications
You must be signed in to change notification settings - Fork 306
/
client.py
4108 lines (3547 loc) · 154 KB
/
client.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.
"""Client for interacting with the Google BigQuery API."""
from __future__ import absolute_import
from __future__ import division
from collections import abc as collections_abc
import copy
import datetime
import functools
import gzip
import io
import itertools
import json
import math
import os
import tempfile
import typing
from typing import (
Any,
BinaryIO,
Dict,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
)
import uuid
import warnings
from google import resumable_media # type: ignore
from google.resumable_media.requests import MultipartUpload # type: ignore
from google.resumable_media.requests import ResumableUpload
import google.api_core.client_options
import google.api_core.exceptions as core_exceptions
from google.api_core.iam import Policy
from google.api_core import page_iterator
from google.api_core import retry as retries
import google.cloud._helpers # type: ignore
from google.cloud import exceptions # pytype: disable=import-error
from google.cloud.client import ClientWithProject # type: ignore # pytype: disable=import-error
try:
from google.cloud.bigquery_storage_v1.services.big_query_read.client import (
DEFAULT_CLIENT_INFO as DEFAULT_BQSTORAGE_CLIENT_INFO,
)
except ImportError:
DEFAULT_BQSTORAGE_CLIENT_INFO = None # type: ignore
from google.cloud.bigquery._helpers import _del_sub_prop
from google.cloud.bigquery._helpers import _get_sub_prop
from google.cloud.bigquery._helpers import _record_field_to_json
from google.cloud.bigquery._helpers import _str_or_none
from google.cloud.bigquery._helpers import BQ_STORAGE_VERSIONS
from google.cloud.bigquery._helpers import _verify_job_config_type
from google.cloud.bigquery._http import Connection
from google.cloud.bigquery import _pandas_helpers
from google.cloud.bigquery.dataset import Dataset
from google.cloud.bigquery.dataset import DatasetListItem
from google.cloud.bigquery.dataset import DatasetReference
from google.cloud.bigquery.enums import AutoRowIDs
from google.cloud.bigquery.exceptions import LegacyBigQueryStorageError
from google.cloud.bigquery.opentelemetry_tracing import create_span
from google.cloud.bigquery import job
from google.cloud.bigquery.job import (
CopyJob,
CopyJobConfig,
ExtractJob,
ExtractJobConfig,
LoadJob,
LoadJobConfig,
QueryJob,
QueryJobConfig,
)
from google.cloud.bigquery.model import Model
from google.cloud.bigquery.model import ModelReference
from google.cloud.bigquery.model import _model_arg_to_model_ref
from google.cloud.bigquery.query import _QueryResults
from google.cloud.bigquery.retry import (
DEFAULT_JOB_RETRY,
DEFAULT_RETRY,
DEFAULT_TIMEOUT,
)
from google.cloud.bigquery.routine import Routine
from google.cloud.bigquery.routine import RoutineReference
from google.cloud.bigquery.schema import SchemaField
from google.cloud.bigquery.table import _table_arg_to_table
from google.cloud.bigquery.table import _table_arg_to_table_ref
from google.cloud.bigquery.table import Table
from google.cloud.bigquery.table import TableListItem
from google.cloud.bigquery.table import TableReference
from google.cloud.bigquery.table import RowIterator
from google.cloud.bigquery.format_options import ParquetOptions
from google.cloud.bigquery import _helpers
pyarrow = _helpers.PYARROW_VERSIONS.try_import()
TimeoutType = Union[float, None]
if typing.TYPE_CHECKING: # pragma: NO COVER
# os.PathLike is only subscriptable in Python 3.9+, thus shielding with a condition.
PathType = Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]
_DEFAULT_CHUNKSIZE = 100 * 1024 * 1024 # 100 MB
_MAX_MULTIPART_SIZE = 5 * 1024 * 1024
_DEFAULT_NUM_RETRIES = 6
_BASE_UPLOAD_TEMPLATE = "{host}/upload/bigquery/v2/projects/{project}/jobs?uploadType="
_MULTIPART_URL_TEMPLATE = _BASE_UPLOAD_TEMPLATE + "multipart"
_RESUMABLE_URL_TEMPLATE = _BASE_UPLOAD_TEMPLATE + "resumable"
_GENERIC_CONTENT_TYPE = "*/*"
_READ_LESS_THAN_SIZE = (
"Size {:d} was specified but the file-like object only had " "{:d} bytes remaining."
)
_NEED_TABLE_ARGUMENT = (
"The table argument should be a table ID string, Table, or TableReference"
)
_LIST_ROWS_FROM_QUERY_RESULTS_FIELDS = "jobReference,totalRows,pageToken,rows"
# In microbenchmarks, it's been shown that even in ideal conditions (query
# finished, local data), requests to getQueryResults can take 10+ seconds.
# In less-than-ideal situations, the response can take even longer, as it must
# be able to download a full 100+ MB row in that time. Don't let the
# connection timeout before data can be downloaded.
# https://github.com/googleapis/python-bigquery/issues/438
_MIN_GET_QUERY_RESULTS_TIMEOUT = 120
TIMEOUT_HEADER = "X-Server-Timeout"
class Project(object):
"""Wrapper for resource describing a BigQuery project.
Args:
project_id (str): Opaque ID of the project
numeric_id (int): Numeric ID of the project
friendly_name (str): Display name of the project
"""
def __init__(self, project_id, numeric_id, friendly_name):
self.project_id = project_id
self.numeric_id = numeric_id
self.friendly_name = friendly_name
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct an instance from a resource dict."""
return cls(resource["id"], resource["numericId"], resource["friendlyName"])
class Client(ClientWithProject):
"""Client to bundle configuration needed for API requests.
Args:
project (Optional[str]):
Project ID for the project which the client acts on behalf of.
Will be passed when creating a dataset / job. If not passed,
falls back to the default inferred from the environment.
credentials (Optional[google.auth.credentials.Credentials]):
The OAuth2 Credentials to use for this client. If not passed
(and if no ``_http`` object is passed), falls back to the
default inferred from the environment.
_http (Optional[requests.Session]):
HTTP object to make requests. Can be any object that
defines ``request()`` with the same interface as
:meth:`requests.Session.request`. If not passed, an ``_http``
object is created that is bound to the ``credentials`` for the
current object.
This parameter should be considered private, and could change in
the future.
location (Optional[str]):
Default location for jobs / datasets / tables.
default_query_job_config (Optional[google.cloud.bigquery.job.QueryJobConfig]):
Default ``QueryJobConfig``.
Will be merged into job configs passed into the ``query`` method.
client_info (Optional[google.api_core.client_info.ClientInfo]):
The client info used to send a user-agent string along with API
requests. If ``None``, then default info will be used. Generally,
you only need to set this if you're developing your own library
or partner tool.
client_options (Optional[Union[google.api_core.client_options.ClientOptions, Dict]]):
Client options used to set user options on the client. API Endpoint
should be set through client_options.
Raises:
google.auth.exceptions.DefaultCredentialsError:
Raised if ``credentials`` is not specified and the library fails
to acquire default credentials.
"""
SCOPE = (
"https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/cloud-platform",
)
"""The scopes required for authenticating as a BigQuery consumer."""
def __init__(
self,
project=None,
credentials=None,
_http=None,
location=None,
default_query_job_config=None,
client_info=None,
client_options=None,
):
super(Client, self).__init__(
project=project,
credentials=credentials,
client_options=client_options,
_http=_http,
)
kw_args = {"client_info": client_info}
if client_options:
if type(client_options) == dict:
client_options = google.api_core.client_options.from_dict(
client_options
)
if client_options.api_endpoint:
api_endpoint = client_options.api_endpoint
kw_args["api_endpoint"] = api_endpoint
self._connection = Connection(self, **kw_args)
self._location = location
self._default_query_job_config = copy.deepcopy(default_query_job_config)
@property
def location(self):
"""Default location for jobs / datasets / tables."""
return self._location
def close(self):
"""Close the underlying transport objects, releasing system resources.
.. note::
The client instance can be used for making additional requests even
after closing, in which case the underlying connections are
automatically re-created.
"""
self._http._auth_request.session.close()
self._http.close()
def get_service_account_email(
self,
project: str = None,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> str:
"""Get the email address of the project's BigQuery service account
Note:
This is the service account that BigQuery uses to manage tables
encrypted by a key in KMS.
Args:
project (Optional[str]):
Project ID to use for retreiving service account email.
Defaults to the client's project.
retry (Optional[google.api_core.retry.Retry]): How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
Returns:
str: service account email address
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> client.get_service_account_email()
my_service_account@my-project.iam.gserviceaccount.com
"""
if project is None:
project = self.project
path = "/projects/%s/serviceAccount" % (project,)
span_attributes = {"path": path}
api_response = self._call_api(
retry,
span_name="BigQuery.getServiceAccountEmail",
span_attributes=span_attributes,
method="GET",
path=path,
timeout=timeout,
)
return api_response["email"]
def list_projects(
self,
max_results: int = None,
page_token: str = None,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
page_size: int = None,
) -> page_iterator.Iterator:
"""List projects for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list
Args:
max_results (Optional[int]):
Maximum number of projects to return.
Defaults to a value set by the API.
page_token (Optional[str]):
Token representing a cursor into the projects. If not passed,
the API will return the first page of projects. The token marks
the beginning of the iterator to be returned and the value of
the ``page_token`` can be accessed at ``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
retry (Optional[google.api_core.retry.Retry]): How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
page_size (Optional[int]):
Maximum number of projects to return in each page.
Defaults to a value set by the API.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of :class:`~google.cloud.bigquery.client.Project`
accessible to the current client.
"""
span_attributes = {"path": "/projects"}
def api_request(*args, **kwargs):
return self._call_api(
retry,
span_name="BigQuery.listProjects",
span_attributes=span_attributes,
*args,
timeout=timeout,
**kwargs,
)
return page_iterator.HTTPIterator(
client=self,
api_request=api_request,
path="/projects",
item_to_value=_item_to_project,
items_key="projects",
page_token=page_token,
max_results=max_results,
page_size=page_size,
)
def list_datasets(
self,
project: str = None,
include_all: bool = False,
filter: str = None,
max_results: int = None,
page_token: str = None,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
page_size: int = None,
) -> page_iterator.Iterator:
"""List datasets for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list
Args:
project (Optional[str]):
Project ID to use for retreiving datasets. Defaults to the
client's project.
include_all (Optional[bool]):
True if results include hidden datasets. Defaults to False.
filter (Optional[str]):
An expression for filtering the results by label.
For syntax, see
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list#body.QUERY_PARAMETERS.filter
max_results (Optional[int]):
Maximum number of datasets to return.
page_token (Optional[str]):
Token representing a cursor into the datasets. If not passed,
the API will return the first page of datasets. The token marks
the beginning of the iterator to be returned and the value of
the ``page_token`` can be accessed at ``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
retry (Optional[google.api_core.retry.Retry]):
How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
page_size (Optional[int]):
Maximum number of datasets to return per page.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of :class:`~google.cloud.bigquery.dataset.DatasetListItem`.
associated with the project.
"""
extra_params: Dict[str, Any] = {}
if project is None:
project = self.project
if include_all:
extra_params["all"] = True
if filter:
# TODO: consider supporting a dict of label -> value for filter,
# and converting it into a string here.
extra_params["filter"] = filter
path = "/projects/%s/datasets" % (project,)
span_attributes = {"path": path}
def api_request(*args, **kwargs):
return self._call_api(
retry,
span_name="BigQuery.listDatasets",
span_attributes=span_attributes,
*args,
timeout=timeout,
**kwargs,
)
return page_iterator.HTTPIterator(
client=self,
api_request=api_request,
path=path,
item_to_value=_item_to_dataset,
items_key="datasets",
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
page_size=page_size,
)
def dataset(self, dataset_id: str, project: str = None) -> DatasetReference:
"""Deprecated: Construct a reference to a dataset.
.. deprecated:: 1.24.0
Construct a
:class:`~google.cloud.bigquery.dataset.DatasetReference` using its
constructor or use a string where previously a reference object
was used.
As of ``google-cloud-bigquery`` version 1.7.0, all client methods
that take a
:class:`~google.cloud.bigquery.dataset.DatasetReference` or
:class:`~google.cloud.bigquery.table.TableReference` also take a
string in standard SQL format, e.g. ``project.dataset_id`` or
``project.dataset_id.table_id``.
Args:
dataset_id (str): ID of the dataset.
project (Optional[str]):
Project ID for the dataset (defaults to the project of the client).
Returns:
google.cloud.bigquery.dataset.DatasetReference:
a new ``DatasetReference`` instance.
"""
if project is None:
project = self.project
warnings.warn(
"Client.dataset is deprecated and will be removed in a future version. "
"Use a string like 'my_project.my_dataset' or a "
"cloud.google.bigquery.DatasetReference object, instead.",
PendingDeprecationWarning,
stacklevel=2,
)
return DatasetReference(project, dataset_id)
def _ensure_bqstorage_client(
self,
bqstorage_client: Optional[
"google.cloud.bigquery_storage.BigQueryReadClient"
] = None,
client_options: Optional[google.api_core.client_options.ClientOptions] = None,
client_info: Optional[
"google.api_core.gapic_v1.client_info.ClientInfo"
] = DEFAULT_BQSTORAGE_CLIENT_INFO,
) -> Optional["google.cloud.bigquery_storage.BigQueryReadClient"]:
"""Create a BigQuery Storage API client using this client's credentials.
If a client cannot be created due to a missing or outdated dependency
`google-cloud-bigquery-storage`, raise a warning and return ``None``.
If the `bqstorage_client` argument is not ``None``, still perform the version
check and return the argument back to the caller if the check passes. If it
fails, raise a warning and return ``None``.
Args:
bqstorage_client:
An existing BigQuery Storage client instance to check for version
compatibility. If ``None``, a new instance is created and returned.
client_options:
Custom options used with a new BigQuery Storage client instance if one
is created.
client_info:
The client info used with a new BigQuery Storage client instance if one
is created.
Returns:
A BigQuery Storage API client.
"""
try:
from google.cloud import bigquery_storage
except ImportError:
warnings.warn(
"Cannot create BigQuery Storage client, the dependency "
"google-cloud-bigquery-storage is not installed."
)
return None
try:
BQ_STORAGE_VERSIONS.verify_version()
except LegacyBigQueryStorageError as exc:
warnings.warn(str(exc))
return None
if bqstorage_client is None:
bqstorage_client = bigquery_storage.BigQueryReadClient(
credentials=self._credentials,
client_options=client_options,
client_info=client_info, # type: ignore # (None is also accepted)
)
return bqstorage_client
def _dataset_from_arg(self, dataset) -> Union[Dataset, DatasetReference]:
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if not isinstance(dataset, (Dataset, DatasetReference)):
if isinstance(dataset, DatasetListItem):
dataset = dataset.reference
else:
raise TypeError(
"dataset must be a Dataset, DatasetReference, DatasetListItem,"
" or string"
)
return dataset
def create_dataset(
self,
dataset: Union[str, Dataset, DatasetReference, DatasetListItem],
exists_ok: bool = False,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Dataset:
"""API call: create the dataset via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/insert
Args:
dataset (Union[ \
google.cloud.bigquery.dataset.Dataset, \
google.cloud.bigquery.dataset.DatasetReference, \
google.cloud.bigquery.dataset.DatasetListItem, \
str, \
]):
A :class:`~google.cloud.bigquery.dataset.Dataset` to create.
If ``dataset`` is a reference, an empty dataset is created
with the specified ID and client's default location.
exists_ok (Optional[bool]):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the dataset.
retry (Optional[google.api_core.retry.Retry]):
How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
Returns:
google.cloud.bigquery.dataset.Dataset:
A new ``Dataset`` returned from the API.
Raises:
google.cloud.exceptions.Conflict:
If the dataset already exists.
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> dataset = bigquery.Dataset('my_project.my_dataset')
>>> dataset = client.create_dataset(dataset)
"""
dataset = self._dataset_from_arg(dataset)
if isinstance(dataset, DatasetReference):
dataset = Dataset(dataset)
path = "/projects/%s/datasets" % (dataset.project,)
data = dataset.to_api_repr()
if data.get("location") is None and self.location is not None:
data["location"] = self.location
try:
span_attributes = {"path": path}
api_response = self._call_api(
retry,
span_name="BigQuery.createDataset",
span_attributes=span_attributes,
method="POST",
path=path,
data=data,
timeout=timeout,
)
return Dataset.from_api_repr(api_response)
except core_exceptions.Conflict:
if not exists_ok:
raise
return self.get_dataset(dataset.reference, retry=retry)
def create_routine(
self,
routine: Routine,
exists_ok: bool = False,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Routine:
"""[Beta] Create a routine via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/routines/insert
Args:
routine (google.cloud.bigquery.routine.Routine):
A :class:`~google.cloud.bigquery.routine.Routine` to create.
The dataset that the routine belongs to must already exist.
exists_ok (Optional[bool]):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the routine.
retry (Optional[google.api_core.retry.Retry]):
How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
Returns:
google.cloud.bigquery.routine.Routine:
A new ``Routine`` returned from the service.
Raises:
google.cloud.exceptions.Conflict:
If the routine already exists.
"""
reference = routine.reference
path = "/projects/{}/datasets/{}/routines".format(
reference.project, reference.dataset_id
)
resource = routine.to_api_repr()
try:
span_attributes = {"path": path}
api_response = self._call_api(
retry,
span_name="BigQuery.createRoutine",
span_attributes=span_attributes,
method="POST",
path=path,
data=resource,
timeout=timeout,
)
return Routine.from_api_repr(api_response)
except core_exceptions.Conflict:
if not exists_ok:
raise
return self.get_routine(routine.reference, retry=retry)
def create_table(
self,
table: Union[str, Table, TableReference, TableListItem],
exists_ok: bool = False,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Table:
"""API call: create a table via a PUT request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
table (Union[ \
google.cloud.bigquery.table.Table, \
google.cloud.bigquery.table.TableReference, \
google.cloud.bigquery.table.TableListItem, \
str, \
]):
A :class:`~google.cloud.bigquery.table.Table` to create.
If ``table`` is a reference, an empty table is created
with the specified ID. The dataset that the table belongs to
must already exist.
exists_ok (Optional[bool]):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the table.
retry (Optional[google.api_core.retry.Retry]):
How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
Returns:
google.cloud.bigquery.table.Table:
A new ``Table`` returned from the service.
Raises:
google.cloud.exceptions.Conflict:
If the table already exists.
"""
table = _table_arg_to_table(table, default_project=self.project)
dataset_id = table.dataset_id
path = "/projects/%s/datasets/%s/tables" % (table.project, dataset_id)
data = table.to_api_repr()
try:
span_attributes = {"path": path, "dataset_id": dataset_id}
api_response = self._call_api(
retry,
span_name="BigQuery.createTable",
span_attributes=span_attributes,
method="POST",
path=path,
data=data,
timeout=timeout,
)
return Table.from_api_repr(api_response)
except core_exceptions.Conflict:
if not exists_ok:
raise
return self.get_table(table.reference, retry=retry)
def _call_api(
self,
retry,
span_name=None,
span_attributes=None,
job_ref=None,
headers: Optional[Dict[str, str]] = None,
**kwargs,
):
kwargs = _add_server_timeout_header(headers, kwargs)
call = functools.partial(self._connection.api_request, **kwargs)
if retry:
call = retry(call)
if span_name is not None:
with create_span(
name=span_name, attributes=span_attributes, client=self, job_ref=job_ref
):
return call()
return call()
def get_dataset(
self,
dataset_ref: Union[DatasetReference, str],
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Dataset:
"""Fetch the dataset referenced by ``dataset_ref``
Args:
dataset_ref (Union[ \
google.cloud.bigquery.dataset.DatasetReference, \
str, \
]):
A reference to the dataset to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
dataset reference from a string using
:func:`~google.cloud.bigquery.dataset.DatasetReference.from_string`.
retry (Optional[google.api_core.retry.Retry]):
How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
Returns:
google.cloud.bigquery.dataset.Dataset:
A ``Dataset`` instance.
"""
if isinstance(dataset_ref, str):
dataset_ref = DatasetReference.from_string(
dataset_ref, default_project=self.project
)
path = dataset_ref.path
span_attributes = {"path": path}
api_response = self._call_api(
retry,
span_name="BigQuery.getDataset",
span_attributes=span_attributes,
method="GET",
path=path,
timeout=timeout,
)
return Dataset.from_api_repr(api_response)
def get_iam_policy(
self,
table: Union[Table, TableReference, TableListItem, str],
requested_policy_version: int = 1,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Policy:
table = _table_arg_to_table_ref(table, default_project=self.project)
if requested_policy_version != 1:
raise ValueError("only IAM policy version 1 is supported")
body = {"options": {"requestedPolicyVersion": 1}}
path = "{}:getIamPolicy".format(table.path)
span_attributes = {"path": path}
response = self._call_api(
retry,
span_name="BigQuery.getIamPolicy",
span_attributes=span_attributes,
method="POST",
path=path,
data=body,
timeout=timeout,
)
return Policy.from_api_repr(response)
def set_iam_policy(
self,
table: Union[Table, TableReference, TableListItem, str],
policy: Policy,
updateMask: str = None,
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Policy:
table = _table_arg_to_table_ref(table, default_project=self.project)
if not isinstance(policy, (Policy)):
raise TypeError("policy must be a Policy")
body = {"policy": policy.to_api_repr()}
if updateMask is not None:
body["updateMask"] = updateMask
path = "{}:setIamPolicy".format(table.path)
span_attributes = {"path": path}
response = self._call_api(
retry,
span_name="BigQuery.setIamPolicy",
span_attributes=span_attributes,
method="POST",
path=path,
data=body,
timeout=timeout,
)
return Policy.from_api_repr(response)
def test_iam_permissions(
self,
table: Union[Table, TableReference, TableListItem, str],
permissions: Sequence[str],
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Dict[str, Any]:
table = _table_arg_to_table_ref(table, default_project=self.project)
body = {"permissions": permissions}
path = "{}:testIamPermissions".format(table.path)
span_attributes = {"path": path}
response = self._call_api(
retry,
span_name="BigQuery.testIamPermissions",
span_attributes=span_attributes,
method="POST",
path=path,
data=body,
timeout=timeout,
)
return response
def get_model(
self,
model_ref: Union[ModelReference, str],
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Model:
"""[Beta] Fetch the model referenced by ``model_ref``.
Args:
model_ref (Union[ \
google.cloud.bigquery.model.ModelReference, \
str, \
]):
A reference to the model to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
model reference from a string using
:func:`google.cloud.bigquery.model.ModelReference.from_string`.
retry (Optional[google.api_core.retry.Retry]):
How to retry the RPC.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
Returns:
google.cloud.bigquery.model.Model: A ``Model`` instance.
"""
if isinstance(model_ref, str):
model_ref = ModelReference.from_string(
model_ref, default_project=self.project
)
path = model_ref.path
span_attributes = {"path": path}
api_response = self._call_api(
retry,
span_name="BigQuery.getModel",
span_attributes=span_attributes,
method="GET",
path=path,
timeout=timeout,
)
return Model.from_api_repr(api_response)
def get_routine(
self,
routine_ref: Union[Routine, RoutineReference, str],
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,
) -> Routine:
"""[Beta] Get the routine referenced by ``routine_ref``.
Args:
routine_ref (Union[ \
google.cloud.bigquery.routine.Routine, \
google.cloud.bigquery.routine.RoutineReference, \
str, \
]):
A reference to the routine to fetch from the BigQuery API. If
a string is passed in, this method attempts to create a
reference from a string using
:func:`google.cloud.bigquery.routine.RoutineReference.from_string`.
retry (Optional[google.api_core.retry.Retry]):
How to retry the API call.
timeout (Optional[float]):
The number of seconds to wait for the underlying HTTP transport
before using ``retry``.
Returns:
google.cloud.bigquery.routine.Routine:
A ``Routine`` instance.
"""
if isinstance(routine_ref, str):
routine_ref = RoutineReference.from_string(
routine_ref, default_project=self.project
)
path = routine_ref.path
span_attributes = {"path": path}
api_response = self._call_api(
retry,
span_name="BigQuery.getRoutine",
span_attributes=span_attributes,
method="GET",
path=path,
timeout=timeout,
)
return Routine.from_api_repr(api_response)
def get_table(
self,
table: Union[Table, TableReference, TableListItem, str],
retry: retries.Retry = DEFAULT_RETRY,
timeout: TimeoutType = DEFAULT_TIMEOUT,