-
Notifications
You must be signed in to change notification settings - Fork 176
/
Copy pathclient.py
1922 lines (1615 loc) · 62.1 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
import calendar
import json
from logging import getLogger
from collections import defaultdict
from datetime import datetime, timedelta
from hashlib import sha256
from io import StringIO
from time import sleep, time
import six
from bigquery.errors import (BigQueryTimeoutException, JobExecutingException,
JobInsertException, UnfinishedQueryException)
from googleapiclient.discovery import build, DISCOVERY_URI
from googleapiclient.errors import HttpError
from httplib2 import Http
BIGQUERY_SCOPE = [
'https://www.googleapis.com/auth/bigquery'
]
BIGQUERY_SCOPE_READ_ONLY = [
'https://www.googleapis.com/auth/bigquery.readonly'
]
CACHE_TIMEOUT = timedelta(seconds=30)
JOB_CREATE_IF_NEEDED = 'CREATE_IF_NEEDED'
JOB_CREATE_NEVER = 'CREATE_NEVER'
JOB_WRITE_TRUNCATE = 'WRITE_TRUNCATE'
JOB_WRITE_APPEND = 'WRITE_APPEND'
JOB_WRITE_EMPTY = 'WRITE_EMPTY'
JOB_ENCODING_UTF_8 = 'UTF-8'
JOB_ENCODING_ISO_8859_1 = 'ISO-8859-1'
JOB_PRIORITY_INTERACTIVE = 'INTERACTIVE'
JOB_PRIORITY_BATCH = 'BATCH'
JOB_COMPRESSION_NONE = 'NONE'
JOB_COMPRESSION_GZIP = 'GZIP'
JOB_FORMAT_CSV = 'CSV'
JOB_FORMAT_NEWLINE_DELIMITED_JSON = 'NEWLINE_DELIMITED_JSON'
JOB_SOURCE_FORMAT_DATASTORE_BACKUP = 'DATASTORE_BACKUP'
JOB_SOURCE_FORMAT_NEWLINE_DELIMITED_JSON = JOB_FORMAT_NEWLINE_DELIMITED_JSON
JOB_SOURCE_FORMAT_CSV = JOB_FORMAT_CSV
JOB_DESTINATION_FORMAT_AVRO = 'AVRO'
JOB_DESTINATION_FORMAT_NEWLINE_DELIMITED_JSON = \
JOB_FORMAT_NEWLINE_DELIMITED_JSON
JOB_DESTINATION_FORMAT_CSV = JOB_FORMAT_CSV
logger = getLogger(__name__)
def get_client(project_id=None, credentials=None,
service_url=None, service_account=None,
private_key=None, private_key_file=None,
json_key=None, json_key_file=None,
readonly=True, swallow_results=True):
"""Return a singleton instance of BigQueryClient. Either
AssertionCredentials or a service account and private key combination need
to be provided in order to authenticate requests to BigQuery.
Parameters
----------
project_id : str, optional
The BigQuery project id, required unless json_key or json_key_file is
provided.
credentials : oauth2client.client.SignedJwtAssertionCredentials, optional
AssertionCredentials instance to authenticate requests to BigQuery
(optional, must provide `service_account` and (`private_key` or
`private_key_file`) or (`json_key` or `json_key_file`) if not included
service_url : str, optional
A URI string template pointing to the location of Google's API
discovery service. Requires two parameters {api} and {apiVersion} that
when filled in produce an absolute URI to the discovery document for
that service. If not set then the default googleapiclient discovery URI
is used. See `credentials`
service_account : str, optional
The Google API service account name. See `credentials`
private_key : str, optional
The private key associated with the service account in PKCS12 or PEM
format. See `credentials`
private_key_file : str, optional
The name of the file containing the private key associated with the
service account in PKCS12 or PEM format. See `credentials`
json_key : dict, optional
The JSON key associated with the service account. See `credentials`
json_key_file : str, optional
The name of the JSON key file associated with the service account. See
`credentials`.
readonly : bool
Bool indicating if BigQuery access is read-only. Has no effect if
credentials are provided. Default True.
swallow_results : bool
If set to False, then return the actual response value instead of
converting to boolean. Default True.
Returns
-------
BigQueryClient
An instance of the BigQuery client.
"""
if not credentials:
assert (service_account and (private_key or private_key_file)) or (
json_key or json_key_file), \
'Must provide AssertionCredentials or service account and P12 key\
or JSON key'
if not project_id:
assert json_key or json_key_file, \
'Must provide project_id unless json_key or json_key_file is\
provided'
if service_url is None:
service_url = DISCOVERY_URI
scope = BIGQUERY_SCOPE_READ_ONLY if readonly else BIGQUERY_SCOPE
if private_key_file:
credentials = _credentials().from_p12_keyfile(service_account,
private_key_file,
scopes=scope)
if private_key:
try:
if isinstance(private_key, basestring):
private_key = private_key.decode('utf-8')
except NameError:
# python3 -- private_key is already unicode
pass
credentials = _credentials().from_p12_keyfile_buffer(
service_account,
StringIO(private_key),
scopes=scope)
if json_key_file:
with open(json_key_file, 'r') as key_file:
json_key = json.load(key_file)
if json_key:
credentials = _credentials().from_json_keyfile_dict(json_key,
scopes=scope)
if not project_id:
project_id = json_key['project_id']
bq_service = _get_bq_service(credentials=credentials,
service_url=service_url)
return BigQueryClient(bq_service, project_id, swallow_results)
def get_projects(bq_service):
"""Given the BigQuery service, return data about all projects."""
projects_request = bq_service.projects().list().execute()
projects = []
for project in projects_request.get('projects', []):
project_data = {
'id': project['id'],
'name': project['friendlyName']
}
projects.append(project_data)
return projects
def _get_bq_service(credentials=None, service_url=None):
"""Construct an authorized BigQuery service object."""
assert credentials, 'Must provide ServiceAccountCredentials'
http = credentials.authorize(Http())
service = build('bigquery', 'v2', http=http,
discoveryServiceUrl=service_url)
return service
def _credentials():
"""Import and return SignedJwtAssertionCredentials class"""
from oauth2client.service_account import ServiceAccountCredentials
return ServiceAccountCredentials
class BigQueryClient(object):
def __init__(self, bq_service, project_id, swallow_results=True):
self.bigquery = bq_service
self.project_id = project_id
self.swallow_results = swallow_results
self.cache = {}
def _submit_query_job(self, query_data):
""" Submit a query job to BigQuery.
This is similar to BigQueryClient.query, but gives the user
direct access to the query method on the offical BigQuery
python client.
For fine-grained control over a query job, see:
https://google-api-client-libraries.appspot.com/documentation/bigquery/v2/python/latest/bigquery_v2.jobs.html#query
Parameters
----------
query_data
query object as per "configuration.query" in
https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.query
Returns
-------
tuple
job id and query results if query completed. If dry_run is True,
job id will be None and results will be empty if the query is valid
or a dict containing the response if invalid.
Raises
------
BigQueryTimeoutException
On timeout
"""
logger.debug('Submitting query job: %s' % query_data)
job_collection = self.bigquery.jobs()
try:
query_reply = job_collection.query(
projectId=self.project_id, body=query_data).execute()
except HttpError as e:
if query_data.get("dryRun", False):
return None, json.loads(e.content.decode('utf8'))
raise
job_id = query_reply['jobReference'].get('jobId')
schema = query_reply.get('schema', {'fields': None})['fields']
rows = query_reply.get('rows', [])
job_complete = query_reply.get('jobComplete', False)
# raise exceptions if it's not an async query
# and job is not completed after timeout
if not job_complete and query_data.get("timeoutMs", False):
logger.error('BigQuery job %s timeout' % job_id)
raise BigQueryTimeoutException()
return job_id, [self._transform_row(row, schema) for row in rows]
def _insert_job(self, body_object):
""" Submit a job to BigQuery
Direct proxy to the insert() method of the offical BigQuery
python client.
Able to submit load, link, query, copy, or extract jobs.
For more details, see:
https://google-api-client-libraries.appspot.com/documentation/bigquery/v2/python/latest/bigquery_v2.jobs.html#insert
Parameters
----------
body_object : body object passed to bigquery.jobs().insert()
Returns
-------
response of the bigquery.jobs().insert().execute() call
Raises
------
BigQueryTimeoutException on timeout
"""
logger.debug('Submitting job: %s' % body_object)
job_collection = self.bigquery.jobs()
return job_collection.insert(
projectId=self.project_id,
body=body_object
).execute()
def query(self, query, max_results=None, timeout=0, dry_run=False, use_legacy_sql=None, external_udf_uris=None):
"""Submit a query to BigQuery.
Parameters
----------
query : str
BigQuery query string
max_results : int, optional
The maximum number of rows to return per page of results.
timeout : float, optional
How long to wait for the query to complete, in seconds before
the request times out and returns.
dry_run : bool, optional
If True, the query isn't actually run. A valid query will return an
empty response, while an invalid one will return the same error
message it would if it wasn't a dry run.
use_legacy_sql : bool, optional. Default True.
If False, the query will use BigQuery's standard SQL (https://cloud.google.com/bigquery/sql-reference/)
external_udf_uris : list, optional
Contains external UDF URIs. If given, URIs must be Google Cloud
Storage and have .js extensions.
Returns
-------
tuple
(job id, query results) if the query completed. If dry_run is True,
job id will be None and results will be empty if the query is valid
or a ``dict`` containing the response if invalid.
Raises
------
BigQueryTimeoutException
on timeout
"""
logger.debug('Executing query: %s' % query)
query_data = {
'query': query,
'timeoutMs': timeout * 1000,
'dryRun': dry_run,
'maxResults': max_results
}
if use_legacy_sql is not None:
query_data['useLegacySql'] = use_legacy_sql
if external_udf_uris:
query_data['userDefinedFunctionResources'] = \
[ {'resourceUri': u} for u in external_udf_uris ]
return self._submit_query_job(query_data)
def get_query_schema(self, job_id):
"""Retrieve the schema of a query by job id.
Parameters
----------
job_id : str
The job_id that references a BigQuery query
Returns
-------
list
A ``list`` of ``dict`` objects that represent the schema.
"""
query_reply = self.get_query_results(job_id, offset=0, limit=0)
if not query_reply['jobComplete']:
logger.warning('BigQuery job %s not complete' % job_id)
raise UnfinishedQueryException()
return query_reply['schema']['fields']
def get_table_schema(self, dataset, table):
"""Return the table schema.
Parameters
----------
dataset : str
The dataset containing the `table`.
table : str
The table to get the schema for
Returns
-------
list
A ``list`` of ``dict`` objects that represent the table schema. If
the table doesn't exist, None is returned.
"""
try:
result = self.bigquery.tables().get(
projectId=self.project_id,
tableId=table,
datasetId=dataset).execute()
except HttpError as e:
if int(e.resp['status']) == 404:
logger.warn('Table %s.%s does not exist', dataset, table)
return None
raise
return result['schema']['fields']
def check_job(self, job_id):
"""Return the state and number of results of a query by job id.
Parameters
----------
job_id : str
The job id of the query to check.
Returns
-------
tuple
(``bool``, ``int``) Whether or not the query has completed and the
total number of rows included in the query table if it has
completed (else 0)
"""
query_reply = self.get_query_results(job_id, offset=0, limit=0)
return (query_reply.get('jobComplete', False),
int(query_reply.get('totalRows', 0)))
def get_query_rows(self, job_id, offset=None, limit=None, timeout=0):
"""Retrieve a list of rows from a query table by job id.
This method will append results from multiple pages together. If you
want to manually page through results, you can use `get_query_results`
method directly.
Parameters
----------
job_id : str
The job id that references a BigQuery query.
offset : int, optional
The offset of the rows to pull from BigQuery
limit : int, optional
The number of rows to retrieve from a query table.
timeout : float, optional
Timeout in seconds.
Returns
-------
list
A ``list`` of ``dict`` objects that represent table rows.
"""
# Get query results
query_reply = self.get_query_results(job_id, offset=offset,
limit=limit, timeout=timeout)
if not query_reply['jobComplete']:
logger.warning('BigQuery job %s not complete' % job_id)
raise UnfinishedQueryException()
schema = query_reply["schema"]["fields"]
rows = query_reply.get('rows', [])
page_token = query_reply.get("pageToken")
records = [self._transform_row(row, schema) for row in rows]
# Append to records if there are multiple pages for query results
while page_token and (not limit or len(records) < limit):
query_reply = self.get_query_results(
job_id, offset=offset, limit=limit, page_token=page_token,
timeout=timeout)
page_token = query_reply.get("pageToken")
rows = query_reply.get('rows', [])
records += [self._transform_row(row, schema) for row in rows]
return records[:limit] if limit else records
def check_dataset(self, dataset_id):
"""Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
Returns
-------
bool
True if dataset at `dataset_id` exists, else Fasle
"""
dataset = self.get_dataset(dataset_id)
return bool(dataset)
def get_dataset(self, dataset_id):
"""Retrieve a dataset if it exists, otherwise return an empty dict.
Parameters
----------
dataset_id : str
Dataset unique id
Returns
-------
dict
Contains dataset object if it exists, else empty
"""
try:
dataset = self.bigquery.datasets().get(
projectId=self.project_id, datasetId=dataset_id).execute()
except HttpError:
dataset = {}
return dataset
def check_table(self, dataset, table):
"""Check to see if a table exists.
Parameters
----------
dataset : str
The dataset to check
table : str
The name of the table
Returns
-------
bool
True if table exists, else False
"""
table = self.get_table(dataset, table)
return bool(table)
def get_table(self, dataset, table):
""" Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
Returns
-------
dict
Containing the table object if it exists, else empty
"""
try:
table = self.bigquery.tables().get(
projectId=self.project_id, datasetId=dataset,
tableId=table).execute()
except HttpError:
table = {}
return table
def create_table(self, dataset, table, schema,
expiration_time=None, time_partitioning=False):
"""Create a new table in the dataset.
Parameters
----------
dataset : str
The dataset to create the table in
table : str
The name of the table to create
schema : dict
The table schema
expiration_time : float, optional
The expiry time in milliseconds since the epoch.
time_partitioning : bool, optional
Create a time partitioning.
Returns
-------
Union[bool, dict]
If the table was successfully created, or response from BigQuery
if swallow_results is set to False
"""
body = {
'schema': {'fields': schema},
'tableReference': {
'tableId': table,
'projectId': self.project_id,
'datasetId': dataset
}
}
if expiration_time is not None:
body['expirationTime'] = expiration_time
if time_partitioning:
body['timePartitioning'] = {'type': 'DAY'}
try:
table = self.bigquery.tables().insert(
projectId=self.project_id,
datasetId=dataset,
body=body
).execute()
if self.swallow_results:
return True
else:
return table
except HttpError as e:
logger.error(('Cannot create table {0}.{1}\n'
'Http Error: {2}').format(dataset, table, e.content))
if self.swallow_results:
return False
else:
return {}
def update_table(self, dataset, table, schema):
"""Update an existing table in the dataset.
Parameters
----------
dataset : str
The dataset to update the table in
table : str
The name of the table to update
schema : dict
Table schema
Returns
-------
Union[bool, dict]
bool indicating if the table was successfully updated or not,
or response from BigQuery if swallow_results is set to False.
"""
body = {
'schema': {'fields': schema},
'tableReference': {
'tableId': table,
'projectId': self.project_id,
'datasetId': dataset
}
}
try:
result = self.bigquery.tables().update(
projectId=self.project_id,
datasetId=dataset,
tableId=table,
body=body
).execute()
if self.swallow_results:
return True
else:
return result
except HttpError as e:
logger.error(('Cannot update table {0}.{1}\n'
'Http Error: {2}').format(dataset, table, e.content))
if self.swallow_results:
return False
else:
return {}
def patch_table(self, dataset, table, schema):
"""Patch an existing table in the dataset.
Parameters
----------
dataset : str
The dataset to patch the table in
table : str
The name of the table to patch
schema : dict
The table schema
Returns
-------
Union[bool, dict]
Bool indicating if the table was successfully patched or not,
or response from BigQuery if swallow_results is set to False
"""
body = {
'schema': {'fields': schema},
'tableReference': {
'tableId': table,
'projectId': self.project_id,
'datasetId': dataset
}
}
try:
result = self.bigquery.tables().patch(
projectId=self.project_id,
datasetId=dataset,
tableId=table,
body=body
).execute()
if self.swallow_results:
return True
else:
return result
except HttpError as e:
logger.error(('Cannot patch table {0}.{1}\n'
'Http Error: {2}').format(dataset, table, e.content))
if self.swallow_results:
return False
else:
return {}
def create_view(self, dataset, view, query):
"""Create a new view in the dataset.
Parameters
----------
dataset : str
The dataset to create the view in
view : str
The name of the view to create
query : dict
A query that BigQuery executes when the view is referenced.
Returns
-------
Union[bool, dict]
bool indicating if the view was successfully created or not,
or response from BigQuery if swallow_results is set to False.
"""
body = {
'tableReference': {
'tableId': view,
'projectId': self.project_id,
'datasetId': dataset
},
'view': {
'query': query
}
}
try:
view = self.bigquery.tables().insert(
projectId=self.project_id,
datasetId=dataset,
body=body
).execute()
if self.swallow_results:
return True
else:
return view
except HttpError as e:
logger.error(('Cannot create view {0}.{1}\n'
'Http Error: {2}').format(dataset, view, e.content))
if self.swallow_results:
return False
else:
return {}
def delete_table(self, dataset, table):
"""Delete a table from the dataset.
Parameters
----------
dataset : str
The dataset to delete the table from.
table : str
The name of the table to delete
Returns
-------
Union[bool, dict]
bool indicating if the table was successfully deleted or not,
or response from BigQuery if swallow_results is set for False.
"""
try:
response = self.bigquery.tables().delete(
projectId=self.project_id,
datasetId=dataset,
tableId=table
).execute()
if self.swallow_results:
return True
else:
return response
except HttpError as e:
logger.error(('Cannot delete table {0}.{1}\n'
'Http Error: {2}').format(dataset, table, e.content))
if self.swallow_results:
return False
else:
return {}
def get_tables(self, dataset_id, app_id, start_time, end_time):
"""Retrieve a list of tables that are related to the given app id
and are inside the range of start and end times.
Parameters
----------
dataset_id : str
The BigQuery dataset id to consider.
app_id : str
The appspot name
start_time : Union[datetime, int]
The datetime or unix time after which records will be fetched.
end_time : Union[datetime, int]
The datetime or unix time up to which records will be fetched.
Returns
-------
list
A ``list`` of table names.
"""
if isinstance(start_time, datetime):
start_time = calendar.timegm(start_time.utctimetuple())
if isinstance(end_time, datetime):
end_time = calendar.timegm(end_time.utctimetuple())
every_table = self._get_all_tables(dataset_id)
app_tables = every_table.get(app_id, {})
return self._filter_tables_by_time(app_tables, start_time, end_time)
def import_data_from_uris(
self,
source_uris,
dataset,
table,
schema=None,
job=None,
source_format=None,
create_disposition=None,
write_disposition=None,
encoding=None,
ignore_unknown_values=None,
max_bad_records=None,
allow_jagged_rows=None,
allow_quoted_newlines=None,
field_delimiter=None,
quote=None,
skip_leading_rows=None,
):
"""
Imports data into a BigQuery table from cloud storage. Optional
arguments that are not specified are determined by BigQuery as
described:
https://developers.google.com/bigquery/docs/reference/v2/jobs
Parameters
----------
source_urls : list
A ``list`` of ``str`` objects representing the urls on cloud
storage of the form: gs://bucket/filename
dataset : str
String id of the dataset
table : str
String id of the table
job : str, optional
Identifies the job (a unique job id is automatically generated if
not provided)
schema : list, optional
Represents the BigQuery schema
source_format : str, optional
One of the JOB_SOURCE_FORMAT_* constants
create_disposition : str, optional
One of the JOB_CREATE_* constants
write_disposition : str, optional
One of the JOB_WRITE_* constants
encoding : str, optional
One of the JOB_ENCODING_* constants
ignore_unknown_values : bool, optional
Whether or not to ignore unknown values
max_bad_records : int, optional
Maximum number of bad records
allow_jagged_rows : bool, optional
For csv only
allow_quoted_newlines : bool, optional
For csv only
field_delimiter : str, optional
For csv only
quote : str, optional
Quote character for csv only
skip_leading_rows : int, optional
For csv only
Returns
-------
dict
A BigQuery job response
Raises
------
JobInsertException
on http/auth failures or error in result
"""
source_uris = source_uris if isinstance(source_uris, list) \
else [source_uris]
configuration = {
"destinationTable": {
"projectId": self.project_id,
"tableId": table,
"datasetId": dataset
},
"sourceUris": source_uris,
}
if max_bad_records:
configuration['maxBadRecords'] = max_bad_records
if ignore_unknown_values:
configuration['ignoreUnknownValues'] = ignore_unknown_values
if create_disposition:
configuration['createDisposition'] = create_disposition
if write_disposition:
configuration['writeDisposition'] = write_disposition
if encoding:
configuration['encoding'] = encoding
if schema:
configuration['schema'] = {'fields': schema}
if source_format:
configuration['sourceFormat'] = source_format
if not job:
hex = self._generate_hex_for_uris(source_uris)
job = "{dataset}-{table}-{digest}".format(
dataset=dataset,
table=table,
digest=hex
)
if source_format == JOB_SOURCE_FORMAT_CSV:
if field_delimiter:
configuration['fieldDelimiter'] = field_delimiter
if allow_jagged_rows:
configuration['allowJaggedRows'] = allow_jagged_rows
if allow_quoted_newlines:
configuration['allowQuotedNewlines'] = allow_quoted_newlines
if quote:
configuration['quote'] = quote
if skip_leading_rows:
configuration['skipLeadingRows'] = skip_leading_rows
elif field_delimiter or allow_jagged_rows \
or allow_quoted_newlines or quote or skip_leading_rows:
all_values = dict(field_delimiter=field_delimiter,
allow_jagged_rows=allow_jagged_rows,
allow_quoted_newlines=allow_quoted_newlines,
skip_leading_rows=skip_leading_rows,
quote=quote)
non_null_values = dict((k, v) for k, v
in list(all_values.items())
if v)
raise Exception("Parameters field_delimiter, allow_jagged_rows, "
"allow_quoted_newlines, quote and "
"skip_leading_rows are only allowed when "
"source_format=JOB_SOURCE_FORMAT_CSV: %s"
% non_null_values)
body = {
"configuration": {
'load': configuration
},
"jobReference": {
"projectId": self.project_id,
"jobId": job
}
}
logger.debug("Creating load job %s" % body)
job_resource = self._insert_job(body)
self._raise_insert_exception_if_error(job_resource)
return job_resource
def export_data_to_uris(
self,
destination_uris,
dataset,
table,
job=None,
compression=None,
destination_format=None,
print_header=None,
field_delimiter=None,
):
"""
Export data from a BigQuery table to cloud storage. Optional arguments
that are not specified are determined by BigQuery as described:
https://developers.google.com/bigquery/docs/reference/v2/jobs
Parameters
----------
destination_urls : Union[str, list]
``str`` or ``list`` of ``str`` objects representing the URIs on
cloud storage of the form: gs://bucket/filename
dataset : str
String id of the dataset
table : str
String id of the table
job : str, optional
String identifying the job (a unique jobid is automatically
generated if not provided)
compression : str, optional
One of the JOB_COMPRESSION_* constants
destination_format : str, optional
One of the JOB_DESTination_FORMAT_* constants
print_header : bool, optional
Whether or not to print the header
field_delimiter : str, optional
Character separating fields in delimited file
Returns
-------
dict