-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
job.py
3073 lines (2441 loc) · 102 KB
/
job.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 Jobs."""
import copy
import threading
from six.moves import http_client
import google.api_core.future.polling
from google.cloud import exceptions
from google.cloud.exceptions import NotFound
from google.cloud.bigquery.dataset import DatasetReference
from google.cloud.bigquery.external_config import ExternalConfig
from google.cloud.bigquery.query import _query_param_from_api_repr
from google.cloud.bigquery.query import ArrayQueryParameter
from google.cloud.bigquery.query import ScalarQueryParameter
from google.cloud.bigquery.query import StructQueryParameter
from google.cloud.bigquery.query import UDFResource
from google.cloud.bigquery.retry import DEFAULT_RETRY
from google.cloud.bigquery.schema import SchemaField
from google.cloud.bigquery.table import _EmptyRowIterator
from google.cloud.bigquery.table import EncryptionConfiguration
from google.cloud.bigquery.table import TableReference
from google.cloud.bigquery.table import Table
from google.cloud.bigquery.table import TimePartitioning
from google.cloud.bigquery import _helpers
_DONE_STATE = 'DONE'
_STOPPED_REASON = 'stopped'
_TIMEOUT_BUFFER_SECS = 0.1
_ERROR_REASON_TO_EXCEPTION = {
'accessDenied': http_client.FORBIDDEN,
'backendError': http_client.INTERNAL_SERVER_ERROR,
'billingNotEnabled': http_client.FORBIDDEN,
'billingTierLimitExceeded': http_client.BAD_REQUEST,
'blocked': http_client.FORBIDDEN,
'duplicate': http_client.CONFLICT,
'internalError': http_client.INTERNAL_SERVER_ERROR,
'invalid': http_client.BAD_REQUEST,
'invalidQuery': http_client.BAD_REQUEST,
'notFound': http_client.NOT_FOUND,
'notImplemented': http_client.NOT_IMPLEMENTED,
'quotaExceeded': http_client.FORBIDDEN,
'rateLimitExceeded': http_client.FORBIDDEN,
'resourceInUse': http_client.BAD_REQUEST,
'resourcesExceeded': http_client.BAD_REQUEST,
'responseTooLarge': http_client.FORBIDDEN,
'stopped': http_client.OK,
'tableUnavailable': http_client.BAD_REQUEST,
}
def _error_result_to_exception(error_result):
"""Maps BigQuery error reasons to an exception.
The reasons and their matching HTTP status codes are documented on
the `troubleshooting errors`_ page.
.. _troubleshooting errors: https://cloud.google.com/bigquery\
/troubleshooting-errors
:type error_result: Mapping[str, str]
:param error_result: The error result from BigQuery.
:rtype google.cloud.exceptions.GoogleCloudError:
:returns: The mapped exception.
"""
reason = error_result.get('reason')
status_code = _ERROR_REASON_TO_EXCEPTION.get(
reason, http_client.INTERNAL_SERVER_ERROR)
return exceptions.from_http_status(
status_code, error_result.get('message', ''), errors=[error_result])
class Compression(object):
"""The compression type to use for exported files. The default value is
:attr:`NONE`.
:attr:`DEFLATE` and :attr:`SNAPPY` are
only supported for Avro.
"""
GZIP = 'GZIP'
"""Specifies GZIP format."""
DEFLATE = 'DEFLATE'
"""Specifies DEFLATE format."""
SNAPPY = 'SNAPPY'
"""Specifies SNAPPY format."""
NONE = 'NONE'
"""Specifies no compression."""
class CreateDisposition(object):
"""Specifies whether the job is allowed to create new tables. The default
value is :attr:`CREATE_IF_NEEDED`.
Creation, truncation and append actions occur as one atomic update
upon job completion.
"""
CREATE_IF_NEEDED = 'CREATE_IF_NEEDED'
"""If the table does not exist, BigQuery creates the table."""
CREATE_NEVER = 'CREATE_NEVER'
"""The table must already exist. If it does not, a 'notFound' error is
returned in the job result."""
class DestinationFormat(object):
"""The exported file format. The default value is :attr:`CSV`.
Tables with nested or repeated fields cannot be exported as CSV.
"""
CSV = 'CSV'
"""Specifies CSV format."""
NEWLINE_DELIMITED_JSON = 'NEWLINE_DELIMITED_JSON'
"""Specifies newline delimited JSON format."""
AVRO = 'AVRO'
"""Specifies Avro format."""
class Encoding(object):
"""The character encoding of the data. The default is :attr:`UTF_8`.
BigQuery decodes the data after the raw, binary data has been
split using the values of the quote and fieldDelimiter properties.
"""
UTF_8 = 'UTF-8'
"""Specifies UTF-8 encoding."""
ISO_8859_1 = 'ISO-8859-1'
"""Specifies ISO-8859-1 encoding."""
class QueryPriority(object):
"""Specifies a priority for the query. The default value is
:attr:`INTERACTIVE`.
"""
INTERACTIVE = 'INTERACTIVE'
"""Specifies interactive priority."""
BATCH = 'BATCH'
"""Specifies batch priority."""
class SourceFormat(object):
"""The format of the data files. The default value is :attr:`CSV`.
Note that the set of allowed values for loading data is different
than the set used for external data sources (see
:class:`~google.cloud.bigquery.external_config.ExternalSourceFormat`).
"""
CSV = 'CSV'
"""Specifies CSV format."""
DATASTORE_BACKUP = 'DATASTORE_BACKUP'
"""Specifies datastore backup format"""
NEWLINE_DELIMITED_JSON = 'NEWLINE_DELIMITED_JSON'
"""Specifies newline delimited JSON format."""
AVRO = 'AVRO'
"""Specifies Avro format."""
PARQUET = 'PARQUET'
"""Specifies Parquet format."""
ORC = 'ORC'
"""Specifies Orc format."""
class WriteDisposition(object):
"""Specifies the action that occurs if destination table already exists.
The default value is :attr:`WRITE_APPEND`.
Each action is atomic and only occurs if BigQuery is able to complete
the job successfully. Creation, truncation and append actions occur as one
atomic update upon job completion.
"""
WRITE_APPEND = 'WRITE_APPEND'
"""If the table already exists, BigQuery appends the data to the table."""
WRITE_TRUNCATE = 'WRITE_TRUNCATE'
"""If the table already exists, BigQuery overwrites the table data."""
WRITE_EMPTY = 'WRITE_EMPTY'
"""If the table already exists and contains data, a 'duplicate' error is
returned in the job result."""
class SchemaUpdateOption(object):
"""Specifies an update to the destination table schema as a side effect of
a load job.
"""
ALLOW_FIELD_ADDITION = 'ALLOW_FIELD_ADDITION'
"""Allow adding a nullable field to the schema."""
ALLOW_FIELD_RELAXATION = 'ALLOW_FIELD_RELAXATION'
"""Allow relaxing a required field in the original schema to nullable."""
class _JobReference(object):
"""A reference to a job.
Arguments:
job_id (str): ID of the job to run.
project (str): ID of the project where the job runs.
location (str): Location of where the job runs.
"""
def __init__(self, job_id, project, location):
self._properties = {
'jobId': job_id,
'projectId': project,
}
# The location field must not be populated if it is None.
if location:
self._properties['location'] = location
@property
def job_id(self):
"""str: ID of the job."""
return self._properties.get('jobId')
@property
def project(self):
"""str: ID of the project where the job runs."""
return self._properties.get('projectId')
@property
def location(self):
"""str: Location where the job runs."""
return self._properties.get('location')
def _to_api_repr(self):
"""Returns the API resource representation of the job reference."""
return copy.deepcopy(self._properties)
@classmethod
def _from_api_repr(cls, resource):
"""Returns a job reference for an API resource representation."""
job_id = resource.get('jobId')
project = resource.get('projectId')
location = resource.get('location')
job_ref = cls(job_id, project, location)
return job_ref
class _AsyncJob(google.api_core.future.polling.PollingFuture):
"""Base class for asynchronous jobs.
Arguments:
job_id (Union[str, _JobReference]):
Job's ID in the project associated with the client or a
fully-qualified job reference.
client (google.cloud.bigquery.client.Client):
Client which holds credentials and project configuration.
"""
def __init__(self, job_id, client):
super(_AsyncJob, self).__init__()
# The job reference can be either a plain job ID or the full resource.
# Populate the properties dictionary consistently depending on what has
# been passed in.
job_ref = job_id
if not isinstance(job_id, _JobReference):
job_ref = _JobReference(job_id, client.project, None)
self._properties = {
'jobReference': job_ref._to_api_repr(),
}
self._client = client
self._result_set = False
self._completion_lock = threading.Lock()
@property
def job_id(self):
"""str: ID of the job."""
return _helpers._get_sub_prop(
self._properties, ['jobReference', 'jobId'])
@property
def project(self):
"""Project bound to the job.
:rtype: str
:returns: the project (derived from the client).
"""
return _helpers._get_sub_prop(
self._properties, ['jobReference', 'projectId'])
@property
def location(self):
"""str: Location where the job runs."""
return _helpers._get_sub_prop(
self._properties, ['jobReference', 'location'])
def _require_client(self, client):
"""Check client or verify over-ride.
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:rtype: :class:`google.cloud.bigquery.client.Client`
:returns: The client passed in or the currently bound client.
"""
if client is None:
client = self._client
return client
@property
def job_type(self):
"""Type of job
:rtype: str
:returns: one of 'load', 'copy', 'extract', 'query'
"""
return self._JOB_TYPE
@property
def path(self):
"""URL path for the job's APIs.
:rtype: str
:returns: the path based on project and job ID.
"""
return '/projects/%s/jobs/%s' % (self.project, self.job_id)
@property
def labels(self):
"""Dict[str, str]: Labels for the job."""
return self._properties.setdefault('labels', {})
@property
def etag(self):
"""ETag for the job resource.
:rtype: str, or ``NoneType``
:returns: the ETag (None until set from the server).
"""
return self._properties.get('etag')
@property
def self_link(self):
"""URL for the job resource.
:rtype: str, or ``NoneType``
:returns: the URL (None until set from the server).
"""
return self._properties.get('selfLink')
@property
def user_email(self):
"""E-mail address of user who submitted the job.
:rtype: str, or ``NoneType``
:returns: the URL (None until set from the server).
"""
return self._properties.get('user_email')
@property
def created(self):
"""Datetime at which the job was created.
:rtype: ``datetime.datetime``, or ``NoneType``
:returns: the creation time (None until set from the server).
"""
statistics = self._properties.get('statistics')
if statistics is not None:
millis = statistics.get('creationTime')
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
@property
def started(self):
"""Datetime at which the job was started.
:rtype: ``datetime.datetime``, or ``NoneType``
:returns: the start time (None until set from the server).
"""
statistics = self._properties.get('statistics')
if statistics is not None:
millis = statistics.get('startTime')
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
@property
def ended(self):
"""Datetime at which the job finished.
:rtype: ``datetime.datetime``, or ``NoneType``
:returns: the end time (None until set from the server).
"""
statistics = self._properties.get('statistics')
if statistics is not None:
millis = statistics.get('endTime')
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
def _job_statistics(self):
"""Helper for job-type specific statistics-based properties."""
statistics = self._properties.get('statistics', {})
return statistics.get(self._JOB_TYPE, {})
@property
def error_result(self):
"""Error information about the job as a whole.
:rtype: mapping, or ``NoneType``
:returns: the error information (None until set from the server).
"""
status = self._properties.get('status')
if status is not None:
return status.get('errorResult')
@property
def errors(self):
"""Information about individual errors generated by the job.
:rtype: list of mappings, or ``NoneType``
:returns: the error information (None until set from the server).
"""
status = self._properties.get('status')
if status is not None:
return status.get('errors')
@property
def state(self):
"""Status of the job.
:rtype: str, or ``NoneType``
:returns: the state (None until set from the server).
"""
status = self._properties.get('status')
if status is not None:
return status.get('state')
def _scrub_local_properties(self, cleaned):
"""Helper: handle subclass properties in cleaned."""
pass
def _copy_configuration_properties(self, configuration):
"""Helper: assign subclass configuration properties in cleaned."""
raise NotImplementedError("Abstract")
def _set_properties(self, api_response):
"""Update properties from resource in body of ``api_response``
:type api_response: dict
:param api_response: response returned from an API call
"""
cleaned = api_response.copy()
self._scrub_local_properties(cleaned)
statistics = cleaned.get('statistics', {})
if 'creationTime' in statistics:
statistics['creationTime'] = float(statistics['creationTime'])
if 'startTime' in statistics:
statistics['startTime'] = float(statistics['startTime'])
if 'endTime' in statistics:
statistics['endTime'] = float(statistics['endTime'])
self._properties.clear()
self._properties.update(cleaned)
self._copy_configuration_properties(cleaned.get('configuration', {}))
# For Future interface
self._set_future_result()
@classmethod
def _get_resource_config(cls, resource):
"""Helper for :meth:`from_api_repr`
:type resource: dict
:param resource: resource for the job
:rtype: dict
:returns: tuple (string, dict), where the first element is the
job ID and the second contains job-specific configuration.
:raises: :class:`KeyError` if the resource has no identifier, or
is missing the appropriate configuration.
"""
if ('jobReference' not in resource or
'jobId' not in resource['jobReference']):
raise KeyError('Resource lacks required identity information: '
'["jobReference"]["jobId"]')
job_id = resource['jobReference']['jobId']
if ('configuration' not in resource or
cls._JOB_TYPE not in resource['configuration']):
raise KeyError('Resource lacks required configuration: '
'["configuration"]["%s"]' % cls._JOB_TYPE)
return job_id, resource['configuration']
def _build_resource(self):
"""Helper: Generate a resource for :meth:`_begin`."""
raise NotImplementedError("Abstract")
def _begin(self, client=None, retry=DEFAULT_RETRY):
"""API call: begin the job via a POST request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/insert
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:raises: :exc:`ValueError` if the job has already begin.
"""
if self.state is not None:
raise ValueError("Job already begun.")
client = self._require_client(client)
path = '/projects/%s/jobs' % (self.project,)
# jobs.insert is idempotent because we ensure that every new
# job has an ID.
api_response = client._call_api(
retry,
method='POST', path=path, data=self._build_resource())
self._set_properties(api_response)
def exists(self, client=None, retry=DEFAULT_RETRY):
"""API call: test for the existence of the job via a GET request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: bool
:returns: Boolean indicating existence of the job.
"""
client = self._require_client(client)
extra_params = {'fields': 'id'}
if self.location:
extra_params['location'] = self.location
try:
client._call_api(retry,
method='GET', path=self.path,
query_params=extra_params)
except NotFound:
return False
else:
return True
def reload(self, client=None, retry=DEFAULT_RETRY):
"""API call: refresh job properties via a GET request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
"""
client = self._require_client(client)
extra_params = {}
if self.location:
extra_params['location'] = self.location
api_response = client._call_api(
retry, method='GET', path=self.path, query_params=extra_params)
self._set_properties(api_response)
def cancel(self, client=None):
"""API call: cancel job via a POST request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:rtype: bool
:returns: Boolean indicating that the cancel request was sent.
"""
client = self._require_client(client)
extra_params = {}
if self.location:
extra_params['location'] = self.location
api_response = client._connection.api_request(
method='POST', path='%s/cancel' % (self.path,),
query_params=extra_params)
self._set_properties(api_response['job'])
# The Future interface requires that we return True if the *attempt*
# to cancel was successful.
return True
# The following methods implement the PollingFuture interface. Note that
# the methods above are from the pre-Future interface and are left for
# compatibility. The only "overloaded" method is :meth:`cancel`, which
# satisfies both interfaces.
def _set_future_result(self):
"""Set the result or exception from the job if it is complete."""
# This must be done in a lock to prevent the polling thread
# and main thread from both executing the completion logic
# at the same time.
with self._completion_lock:
# If the operation isn't complete or if the result has already been
# set, do not call set_result/set_exception again.
# Note: self._result_set is set to True in set_result and
# set_exception, in case those methods are invoked directly.
if self.state != _DONE_STATE or self._result_set:
return
if self.error_result is not None:
exception = _error_result_to_exception(self.error_result)
self.set_exception(exception)
else:
self.set_result(self)
def done(self, retry=DEFAULT_RETRY):
"""Refresh the job and checks if it is complete.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: bool
:returns: True if the job is complete, False otherwise.
"""
# Do not refresh is the state is already done, as the job will not
# change once complete.
if self.state != _DONE_STATE:
self.reload(retry=retry)
return self.state == _DONE_STATE
def result(self, timeout=None):
"""Start the job and wait for it to complete and get the result.
:type timeout: float
:param timeout:
How long (in seconds) to wait for job to complete before raising
a :class:`concurrent.futures.TimeoutError`.
:rtype: _AsyncJob
:returns: This instance.
:raises:
:class:`~google.cloud.exceptions.GoogleCloudError` if the job
failed or :class:`concurrent.futures.TimeoutError` if the job did
not complete in the given timeout.
"""
if self.state is None:
self._begin()
# TODO: modify PollingFuture so it can pass a retry argument to done().
return super(_AsyncJob, self).result(timeout=timeout)
def cancelled(self):
"""Check if the job has been cancelled.
This always returns False. It's not possible to check if a job was
cancelled in the API. This method is here to satisfy the interface
for :class:`google.api_core.future.Future`.
:rtype: bool
:returns: False
"""
return (self.error_result is not None
and self.error_result.get('reason') == _STOPPED_REASON)
class _JobConfig(object):
"""Abstract base class for job configuration objects.
Arguments:
job_type (str): The key to use for the job configuration.
"""
def __init__(self, job_type):
self._job_type = job_type
self._properties = {job_type: {}}
@property
def labels(self):
"""Dict[str, str]: Labels for the job.
This method always returns a dict. To change a job's labels,
modify the dict, then call ``Client.update_job``. To delete a
label, set its value to :data:`None` before updating.
Raises:
ValueError: If ``value`` type is invalid.
"""
return self._properties.setdefault('labels', {})
@labels.setter
def labels(self, value):
if not isinstance(value, dict):
raise ValueError("Pass a dict")
self._properties['labels'] = value
def _get_sub_prop(self, key, default=None):
"""Get a value in the ``self._properties[self._job_type]`` dictionary.
Most job properties are inside the dictionary related to the job type
(e.g. 'copy', 'extract', 'load', 'query'). Use this method to access
those properties::
self._get_sub_prop('destinationTable')
This is equivalent to using the ``_helpers._get_sub_prop`` function::
_helpers._get_sub_prop(
self._properties, ['query', 'destinationTable'])
Arguments:
key (str):
Key for the value to get in the
``self._properties[self._job_type]`` dictionary.
default (object):
(Optional) Default value to return if the key is not found.
Defaults to ``None``.
Returns:
object: The value if present or the default.
"""
return _helpers._get_sub_prop(
self._properties, [self._job_type, key], default=default)
def _set_sub_prop(self, key, value):
"""Set a value in the ``self._properties[self._job_type]`` dictionary.
Most job properties are inside the dictionary related to the job type
(e.g. 'copy', 'extract', 'load', 'query'). Use this method to set
those properties::
self._set_sub_prop('useLegacySql', False)
This is equivalent to using the ``_helper._set_sub_prop`` function::
_helper._set_sub_prop(
self._properties, ['query', 'useLegacySql'], False)
Arguments:
key (str):
Key to set in the ``self._properties[self._job_type]``
dictionary.
value (object): Value to set.
"""
_helpers._set_sub_prop(self._properties, [self._job_type, key], value)
def _del_sub_prop(self, key):
"""Reove ``key`` from the ``self._properties[self._job_type]`` dict.
Most job properties are inside the dictionary related to the job type
(e.g. 'copy', 'extract', 'load', 'query'). Use this method to clear
those properties::
self._del_sub_prop('useLegacySql')
This is equivalent to using the ``_helper._del_sub_prop`` function::
_helper._del_sub_prop(
self._properties, ['query', 'useLegacySql'])
Arguments:
key (str):
Key to remove in the ``self._properties[self._job_type]``
dictionary.
"""
_helpers._del_sub_prop(self._properties, [self._job_type, key])
def to_api_repr(self):
"""Build an API representation of the job config.
:rtype: dict
:returns: A dictionary in the format used by the BigQuery API.
"""
return copy.deepcopy(self._properties)
def _fill_from_default(self, default_job_config):
"""Merge this job config with a default job config.
The keys in this object take precedence over the keys in the default
config. The merge is done at the top-level as well as for keys one
level below the job type.
Arguments:
default_job_config (google.cloud.bigquery.job._JobConfig):
The default job config that will be used to fill in self.
Returns:
google.cloud.bigquery.job._JobConfig A new (merged) job config.
"""
if self._job_type != default_job_config._job_type:
raise TypeError(
"attempted to merge two incompatible job types: "
+ repr(self._job_type) + ', '
+ repr(default_job_config._job_type))
new_job_config = self.__class__()
default_job_properties = copy.deepcopy(default_job_config._properties)
for key in self._properties:
if key != self._job_type:
default_job_properties[key] = self._properties[key]
default_job_properties[self._job_type] \
.update(self._properties[self._job_type])
new_job_config._properties = default_job_properties
return new_job_config
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct a job configuration given its API representation
:type resource: dict
:param resource:
An extract job configuration in the same representation as is
returned from the API.
:rtype: :class:`google.cloud.bigquery.job._JobConfig`
:returns: Configuration parsed from ``resource``.
"""
config = cls()
config._properties = copy.deepcopy(resource)
return config
class LoadJobConfig(_JobConfig):
"""Configuration options for load jobs.
All properties in this class are optional. Values which are ``None`` ->
server defaults.
"""
def __init__(self):
super(LoadJobConfig, self).__init__('load')
@property
def allow_jagged_rows(self):
"""bool: Allow missing trailing optional columns (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.allowJaggedRows
"""
return self._get_sub_prop('allowJaggedRows')
@allow_jagged_rows.setter
def allow_jagged_rows(self, value):
self._set_sub_prop('allowJaggedRows', value)
@property
def allow_quoted_newlines(self):
"""bool: Allow quoted data containing newline characters (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.allowQuotedNewlines
"""
return self._get_sub_prop('allowQuotedNewlines')
@allow_quoted_newlines.setter
def allow_quoted_newlines(self, value):
self._set_sub_prop('allowQuotedNewlines', value)
@property
def autodetect(self):
"""bool: Automatically infer the schema from a sample of the data.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.autodetect
"""
return self._get_sub_prop('autodetect')
@autodetect.setter
def autodetect(self, value):
self._set_sub_prop('autodetect', value)
@property
def create_disposition(self):
"""google.cloud.bigquery.job.CreateDisposition: Specifies behavior
for creating tables.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.createDisposition
"""
return self._get_sub_prop('createDisposition')
@create_disposition.setter
def create_disposition(self, value):
self._set_sub_prop('createDisposition', value)
@property
def encoding(self):
"""google.cloud.bigquery.job.Encoding: The character encoding of the
data.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.encoding
"""
return self._get_sub_prop('encoding')
@encoding.setter
def encoding(self, value):
self._set_sub_prop('encoding', value)
@property
def field_delimiter(self):
"""str: The separator for fields in a CSV file.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.fieldDelimiter
"""
return self._get_sub_prop('fieldDelimiter')
@field_delimiter.setter
def field_delimiter(self, value):
self._set_sub_prop('fieldDelimiter', value)
@property
def ignore_unknown_values(self):
"""bool: Ignore extra values not represented in the table schema.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.ignoreUnknownValues
"""
return self._get_sub_prop('ignoreUnknownValues')
@ignore_unknown_values.setter
def ignore_unknown_values(self, value):
self._set_sub_prop('ignoreUnknownValues', value)
@property
def max_bad_records(self):
"""int: Number of invalid rows to ignore.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.maxBadRecords
"""
return self._get_sub_prop('maxBadRecords')
@max_bad_records.setter
def max_bad_records(self, value):
self._set_sub_prop('maxBadRecords', value)
@property
def null_marker(self):
"""str: Represents a null value (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.nullMarker
"""
return self._get_sub_prop('nullMarker')
@null_marker.setter
def null_marker(self, value):
self._set_sub_prop('nullMarker', value)