forked from googleapis/python-bigquery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_client.py
2667 lines (2237 loc) · 103 KB
/
test_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.
import base64
import copy
import csv
import datetime
import decimal
import io
import json
import operator
import os
import pathlib
import time
import unittest
import uuid
from typing import Optional
from google.api_core.exceptions import PreconditionFailed
from google.api_core.exceptions import BadRequest
from google.api_core.exceptions import ClientError
from google.api_core.exceptions import Conflict
from google.api_core.exceptions import GoogleAPICallError
from google.api_core.exceptions import NotFound
from google.api_core.exceptions import InternalServerError
from google.api_core.exceptions import ServiceUnavailable
from google.api_core.exceptions import TooManyRequests
from google.cloud import bigquery
from google.cloud.bigquery.dataset import Dataset
from google.cloud.bigquery.dataset import DatasetReference
from google.cloud.bigquery.table import Table
from google.cloud._helpers import UTC
from google.cloud.bigquery import dbapi, enums
from google.cloud import storage
from google.cloud.datacatalog_v1 import types as datacatalog_types
from google.cloud.datacatalog_v1 import PolicyTagManagerClient
from google.cloud.resourcemanager_v3 import types as resourcemanager_types
from google.cloud.resourcemanager_v3 import TagKeysClient, TagValuesClient
import psutil
import pytest
from test_utils.retry import RetryErrors
from test_utils.retry import RetryInstanceState
from test_utils.retry import RetryResult
from test_utils.system import unique_resource_id
from . import helpers
JOB_TIMEOUT = 120 # 2 minutes
DATA_PATH = pathlib.Path(__file__).parent.parent / "data"
# Common table data used for many tests.
ROWS = [
("Phred Phlyntstone", 32),
("Bharney Rhubble", 33),
("Wylma Phlyntstone", 29),
("Bhettye Rhubble", 27),
]
HEADER_ROW = ("Full Name", "Age")
SCHEMA = [
bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
]
CLUSTERING_SCHEMA = [
bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("body_height_cm", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("date_of_birth", "DATE", mode="REQUIRED"),
]
TIME_PARTITIONING_CLUSTERING_FIELDS_SCHEMA = [
bigquery.SchemaField("transaction_time", "TIMESTAMP", mode="REQUIRED"),
bigquery.SchemaField("transaction_id", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("user_email", "STRING", mode="REQUIRED"),
bigquery.SchemaField("store_code", "STRING", mode="REQUIRED"),
bigquery.SchemaField(
"items",
"RECORD",
mode="REPEATED",
fields=[
bigquery.SchemaField("item_code", "STRING", mode="REQUIRED"),
bigquery.SchemaField("quantity", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("comments", "STRING", mode="NULLABLE"),
bigquery.SchemaField("expiration_date", "DATE", mode="REQUIRED"),
],
),
]
SOURCE_URIS_AVRO = [
"gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/a-twitter.avro",
"gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/b-twitter.avro",
"gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/c-twitter.avro",
]
SOURCE_URIS_PARQUET = [
"gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/a-twitter.parquet",
"gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/b-twitter.parquet",
"gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/c-twitter.parquet",
]
REFERENCE_FILE_SCHEMA_URI_AVRO = "gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/a-twitter.avro"
REFERENCE_FILE_SCHEMA_URI_PARQUET = "gs://cloud-samples-data/bigquery/federated-formats-reference-file-schema/a-twitter.parquet"
# The VPC-SC team maintains a mirror of the GCS bucket used for code
# samples. The public bucket crosses the configured security boundary.
# See: https://github.com/googleapis/google-cloud-python/issues/8550
SAMPLES_BUCKET = os.environ.get("GCLOUD_TEST_SAMPLES_BUCKET", "cloud-samples-data")
retry_storage_errors = RetryErrors(
(TooManyRequests, InternalServerError, ServiceUnavailable)
)
MTLS_TESTING = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE") == "true"
def _has_rows(result):
return len(result) > 0
def _make_dataset_id(prefix):
return f"python_bigquery_tests_system_{prefix}{unique_resource_id()}"
def _load_json_schema(filename="schema.json"):
from google.cloud.bigquery.table import _parse_schema_resource
json_filename = DATA_PATH / filename
with open(json_filename, "r") as schema_file:
return _parse_schema_resource(json.load(schema_file))
class Config(object):
"""Run-time configuration to be modified at set-up.
This is a mutable stand-in to allow test set-up to modify
global state.
"""
CLIENT: Optional[bigquery.Client] = None
CURSOR = None
def setUpModule():
Config.CLIENT = bigquery.Client()
Config.CURSOR = dbapi.connect(Config.CLIENT).cursor()
class TestBigQuery(unittest.TestCase):
def setUp(self):
self.to_delete = []
def tearDown(self):
policy_tag_client = PolicyTagManagerClient()
tag_keys_client = TagKeysClient()
tag_values_client = TagValuesClient()
def _still_in_use(bad_request):
return any(
error["reason"] == "resourceInUse" for error in bad_request._errors
)
retry_in_use = RetryErrors(BadRequest, error_predicate=_still_in_use)
retry_storage_errors_conflict = RetryErrors(
(Conflict, TooManyRequests, InternalServerError, ServiceUnavailable)
)
for doomed in self.to_delete:
if isinstance(doomed, storage.Bucket):
retry_storage_errors_conflict(doomed.delete)(force=True)
elif isinstance(doomed, (Dataset, bigquery.DatasetReference)):
retry_in_use(Config.CLIENT.delete_dataset)(doomed, delete_contents=True)
elif isinstance(doomed, (Table, bigquery.TableReference)):
retry_in_use(Config.CLIENT.delete_table)(doomed)
elif isinstance(doomed, datacatalog_types.Taxonomy):
policy_tag_client.delete_taxonomy(name=doomed.name)
elif isinstance(doomed, resourcemanager_types.TagKey):
tag_keys_client.delete_tag_key(name=doomed.name).result()
elif isinstance(doomed, resourcemanager_types.TagValue):
tag_values_client.delete_tag_value(name=doomed.name).result()
else:
doomed.delete()
def test_get_service_account_email(self):
client = Config.CLIENT
got = client.get_service_account_email()
self.assertIsInstance(got, str)
self.assertIn("@", got)
def _create_bucket(self, bucket_name, location=None):
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
retry_storage_errors(storage_client.create_bucket)(
bucket_name, location=location
)
self.to_delete.append(bucket)
return bucket
def test_close_releases_open_sockets(self):
current_process = psutil.Process()
conn_count_start = len(current_process.connections())
client = Config.CLIENT
client.query(
"""
SELECT
source_year AS year, COUNT(is_male) AS birth_count
FROM `bigquery-public-data.samples.natality`
GROUP BY year
ORDER BY year DESC
LIMIT 15
"""
)
client.close()
conn_count_end = len(current_process.connections())
self.assertLessEqual(conn_count_end, conn_count_start)
def test_create_dataset(self):
DATASET_ID = _make_dataset_id("create_dataset")
dataset = self.temp_dataset(DATASET_ID)
self.assertTrue(_dataset_exists(dataset))
self.assertEqual(dataset.dataset_id, DATASET_ID)
self.assertEqual(dataset.project, Config.CLIENT.project)
self.assertIs(dataset.is_case_insensitive, False)
def test_create_dataset_case_sensitive(self):
DATASET_ID = _make_dataset_id("create_cs_dataset")
dataset = self.temp_dataset(DATASET_ID, is_case_insensitive=False)
self.assertIs(dataset.is_case_insensitive, False)
def test_create_dataset_case_insensitive(self):
DATASET_ID = _make_dataset_id("create_ci_dataset")
dataset = self.temp_dataset(DATASET_ID, is_case_insensitive=True)
self.assertIs(dataset.is_case_insensitive, True)
def test_create_dataset_max_time_travel_hours(self):
DATASET_ID = _make_dataset_id("create_ci_dataset")
dataset = self.temp_dataset(DATASET_ID, max_time_travel_hours=24 * 2)
self.assertEqual(int(dataset.max_time_travel_hours), 24 * 2)
def test_get_dataset(self):
dataset_id = _make_dataset_id("get_dataset")
client = Config.CLIENT
project = client.project
dataset_ref = bigquery.DatasetReference(project, dataset_id)
dataset_arg = Dataset(dataset_ref)
dataset_arg.friendly_name = "Friendly"
dataset_arg.description = "Description"
dataset = helpers.retry_403(client.create_dataset)(dataset_arg)
self.to_delete.append(dataset)
dataset_ref = bigquery.DatasetReference(project, dataset_id)
# Get with a reference.
got = client.get_dataset(dataset_ref)
self.assertEqual(got.friendly_name, "Friendly")
self.assertEqual(got.description, "Description")
# Get with a string.
got = client.get_dataset(dataset_id)
self.assertEqual(got.friendly_name, "Friendly")
self.assertEqual(got.description, "Description")
# Get with a fully-qualified string.
got = client.get_dataset("{}.{}".format(client.project, dataset_id))
self.assertEqual(got.friendly_name, "Friendly")
self.assertEqual(got.description, "Description")
def test_create_dataset_with_default_rounding_mode(self):
DATASET_ID = _make_dataset_id("create_dataset_rounding_mode")
dataset = self.temp_dataset(DATASET_ID, default_rounding_mode="ROUND_HALF_EVEN")
self.assertTrue(_dataset_exists(dataset))
self.assertEqual(dataset.default_rounding_mode, "ROUND_HALF_EVEN")
def test_update_dataset(self):
dataset = self.temp_dataset(_make_dataset_id("update_dataset"))
self.assertTrue(_dataset_exists(dataset))
self.assertIsNone(dataset.friendly_name)
self.assertIsNone(dataset.description)
self.assertEqual(dataset.labels, {})
self.assertEqual(dataset.resource_tags, {})
self.assertIs(dataset.is_case_insensitive, False)
dataset.friendly_name = "Friendly"
dataset.description = "Description"
dataset.labels = {"priority": "high", "color": "blue"}
dataset.resource_tags = {"123456789012/env": "prod", "123456789012/component": "batch"}
dataset.is_case_insensitive = True
ds2 = Config.CLIENT.update_dataset(
dataset, ("friendly_name", "description", "labels", "resource_tags", "is_case_insensitive")
)
self.assertEqual(ds2.friendly_name, "Friendly")
self.assertEqual(ds2.description, "Description")
self.assertEqual(ds2.labels, {"priority": "high", "color": "blue"})
self.assertEqual(ds2.resource_tags, {"123456789012/env": "prod", "123456789012/component": "batch"})
self.assertIs(ds2.is_case_insensitive, True)
ds2.labels = {
"color": "green", # change
"shape": "circle", # add
"priority": None, # delete
}
ds2.resource_tags = {
"123456789012/env": "dev", # change
"123456789012/project": "atlas", # add
"123456789012/component": None, # delete
}
ds3 = Config.CLIENT.update_dataset(ds2, ["labels", "resource_tags"])
self.assertEqual(ds3.labels, {"color": "green", "shape": "circle"})
self.assertEqual(ds3.resource_tags, {"123456789012/env": "dev", "123456789012/project": "atlas"})
# Remove all tags
ds3.resource_tags = None
ds4 = Config.CLIENT.update_table(ds3, ["resource_tags"])
self.assertEqual(ds4.resource_tags, {})
# If we try to update using d2 again, it will fail because the
# previous update changed the ETag.
ds2.description = "no good"
with self.assertRaises(PreconditionFailed):
Config.CLIENT.update_dataset(ds2, ["description"])
def test_list_datasets(self):
datasets_to_create = [
"new" + unique_resource_id(),
"newer" + unique_resource_id(),
"newest" + unique_resource_id(),
]
for dataset_id in datasets_to_create:
self.temp_dataset(dataset_id)
# Retrieve the datasets.
iterator = Config.CLIENT.list_datasets()
all_datasets = list(iterator)
self.assertIsNone(iterator.next_page_token)
created = [
dataset
for dataset in all_datasets
if dataset.dataset_id in datasets_to_create
and dataset.project == Config.CLIENT.project
]
self.assertEqual(len(created), len(datasets_to_create))
def test_list_datasets_w_project(self):
# Retrieve datasets from a different project.
iterator = Config.CLIENT.list_datasets(project="bigquery-public-data")
all_datasets = frozenset([dataset.dataset_id for dataset in iterator])
self.assertIn("usa_names", all_datasets)
def test_create_table(self):
dataset = self.temp_dataset(_make_dataset_id("create_table"))
table_id = "test_table"
table_arg = Table(dataset.table(table_id), schema=SCHEMA)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
self.assertEqual(table.table_id, table_id)
def test_create_tables_in_case_insensitive_dataset(self):
ci_dataset = self.temp_dataset(
_make_dataset_id("create_table"), is_case_insensitive=True
)
table_arg = Table(ci_dataset.table("test_table2"), schema=SCHEMA)
tablemc_arg = Table(ci_dataset.table("Test_taBLe2")) # same name, in Mixed Case
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table_arg))
self.assertTrue(_table_exists(tablemc_arg))
self.assertIs(ci_dataset.is_case_insensitive, True)
def test_create_tables_in_case_sensitive_dataset(self):
ci_dataset = self.temp_dataset(
_make_dataset_id("create_table"), is_case_insensitive=False
)
table_arg = Table(ci_dataset.table("test_table3"), schema=SCHEMA)
tablemc_arg = Table(ci_dataset.table("Test_taBLe3")) # same name, in Mixed Case
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table_arg))
self.assertFalse(_table_exists(tablemc_arg))
self.assertIs(ci_dataset.is_case_insensitive, False)
def test_create_tables_in_default_sensitivity_dataset(self):
dataset = self.temp_dataset(_make_dataset_id("create_table"))
table_arg = Table(dataset.table("test_table4"), schema=SCHEMA)
tablemc_arg = Table(
dataset.table("Test_taBLe4")
) # same name, in MC (Mixed Case)
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table_arg))
self.assertFalse(_table_exists(tablemc_arg))
self.assertIs(dataset.is_case_insensitive, False)
def test_create_table_with_real_custom_policy(self):
from google.cloud.bigquery.schema import PolicyTagList
policy_tag_client = PolicyTagManagerClient()
taxonomy_parent = f"projects/{Config.CLIENT.project}/locations/us"
new_taxonomy = datacatalog_types.Taxonomy(
display_name="Custom test taxonomy" + unique_resource_id(),
description="This taxonomy is ony used for a test.",
activated_policy_types=[
datacatalog_types.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL
],
)
taxonomy = policy_tag_client.create_taxonomy(
parent=taxonomy_parent, taxonomy=new_taxonomy
)
self.to_delete.insert(0, taxonomy)
parent_policy_tag = policy_tag_client.create_policy_tag(
parent=taxonomy.name,
policy_tag=datacatalog_types.PolicyTag(
display_name="Parent policy tag", parent_policy_tag=None
),
)
child_policy_tag = policy_tag_client.create_policy_tag(
parent=taxonomy.name,
policy_tag=datacatalog_types.PolicyTag(
display_name="Child policy tag",
parent_policy_tag=parent_policy_tag.name,
),
)
dataset = self.temp_dataset(
_make_dataset_id("create_table_with_real_custom_policy")
)
table_id = "test_table"
policy_1 = PolicyTagList(names=[parent_policy_tag.name])
policy_2 = PolicyTagList(names=[child_policy_tag.name])
schema = [
bigquery.SchemaField(
"first_name", "STRING", mode="REQUIRED", policy_tags=policy_1
),
bigquery.SchemaField(
"age", "INTEGER", mode="REQUIRED", policy_tags=policy_2
),
]
table_arg = Table(dataset.table(table_id), schema=schema)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
self.assertCountEqual(
list(table.schema[0].policy_tags.names), [parent_policy_tag.name]
)
self.assertCountEqual(
list(table.schema[1].policy_tags.names), [child_policy_tag.name]
)
def test_create_table_with_default_value_expression(self):
dataset = self.temp_dataset(
_make_dataset_id("create_table_with_default_value_expression")
)
table_id = "test_table"
timestamp_field_name = "timestamp_field_with_default_value_expression"
string_default_val_expression = "'FOO'"
timestamp_default_val_expression = "CURRENT_TIMESTAMP"
schema = [
bigquery.SchemaField(
"username",
"STRING",
default_value_expression=string_default_val_expression,
),
bigquery.SchemaField(
timestamp_field_name,
"TIMESTAMP",
default_value_expression=timestamp_default_val_expression,
),
]
table_arg = Table(dataset.table(table_id), schema=schema)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
# Fetch the created table and its metadata to verify that the default
# value expression is assigned to fields
remote_table = Config.CLIENT.get_table(table)
remote_schema = remote_table.schema
self.assertEqual(remote_schema, schema)
for field in remote_schema:
if field.name == string_default_val_expression:
self.assertEqual("'FOO'", field.default_value_expression)
if field.name == timestamp_default_val_expression:
self.assertEqual("CURRENT_TIMESTAMP", field.default_value_expression)
# Insert rows into the created table to verify default values are populated
# when value is not provided
NOW_SECONDS = 1448911495.484366
NOW = datetime.datetime.utcfromtimestamp(NOW_SECONDS).replace(tzinfo=UTC)
# Rows to insert. Row #1 will have default `TIMESTAMP` defaultValueExpression CURRENT_TIME
# Row #2 will have default `STRING` defaultValueExpression "'FOO"
ROWS = [{"username": "john_doe"}, {timestamp_field_name: NOW}]
errors = Config.CLIENT.insert_rows(table, ROWS)
self.assertEqual(len(errors), 0)
# Get list of inserted rows
row_1, row_2 = [row for row in list(Config.CLIENT.list_rows(table))]
# Assert that row values are populated with default value expression
self.assertIsInstance(row_1.get(timestamp_field_name), datetime.datetime)
self.assertEqual("FOO", row_2.get("username"))
def test_create_table_w_time_partitioning_w_clustering_fields(self):
from google.cloud.bigquery.table import TimePartitioning
from google.cloud.bigquery.table import TimePartitioningType
dataset = self.temp_dataset(_make_dataset_id("create_table_tp_cf"))
table_id = "test_table"
table_arg = Table(
dataset.table(table_id), schema=TIME_PARTITIONING_CLUSTERING_FIELDS_SCHEMA
)
self.assertFalse(_table_exists(table_arg))
table_arg.time_partitioning = TimePartitioning(field="transaction_time")
table_arg.clustering_fields = ["user_email", "store_code"]
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
self.assertEqual(table.table_id, table_id)
time_partitioning = table.time_partitioning
self.assertEqual(time_partitioning.type_, TimePartitioningType.DAY)
self.assertEqual(time_partitioning.field, "transaction_time")
self.assertEqual(table.clustering_fields, ["user_email", "store_code"])
def test_delete_dataset_with_string(self):
dataset_id = _make_dataset_id("delete_table_true_with_string")
project = Config.CLIENT.project
dataset_ref = bigquery.DatasetReference(project, dataset_id)
helpers.retry_403(Config.CLIENT.create_dataset)(Dataset(dataset_ref))
self.assertTrue(_dataset_exists(dataset_ref))
Config.CLIENT.delete_dataset(dataset_id)
self.assertFalse(_dataset_exists(dataset_ref))
def test_delete_dataset_delete_contents_true(self):
dataset_id = _make_dataset_id("delete_table_true_with_content")
project = Config.CLIENT.project
dataset_ref = bigquery.DatasetReference(project, dataset_id)
dataset = helpers.retry_403(Config.CLIENT.create_dataset)(Dataset(dataset_ref))
table_id = "test_table"
table_arg = Table(dataset.table(table_id), schema=SCHEMA)
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
Config.CLIENT.delete_dataset(dataset, delete_contents=True)
self.assertFalse(_table_exists(table))
def test_delete_dataset_delete_contents_false(self):
from google.api_core import exceptions
dataset = self.temp_dataset(_make_dataset_id("delete_table_false"))
table_id = "test_table"
table_arg = Table(dataset.table(table_id), schema=SCHEMA)
helpers.retry_403(Config.CLIENT.create_table)(table_arg)
with self.assertRaises(exceptions.BadRequest):
Config.CLIENT.delete_dataset(dataset)
def test_get_table_w_public_dataset(self):
public = "bigquery-public-data"
dataset_id = "samples"
table_id = "shakespeare"
table_ref = DatasetReference(public, dataset_id).table(table_id)
# Get table with reference.
table = Config.CLIENT.get_table(table_ref)
self.assertEqual(table.table_id, table_id)
self.assertEqual(table.dataset_id, dataset_id)
self.assertEqual(table.project, public)
schema_names = [field.name for field in table.schema]
self.assertEqual(schema_names, ["word", "word_count", "corpus", "corpus_date"])
# Get table with string.
table = Config.CLIENT.get_table("{}.{}.{}".format(public, dataset_id, table_id))
self.assertEqual(table.table_id, table_id)
self.assertEqual(table.dataset_id, dataset_id)
self.assertEqual(table.project, public)
def test_list_partitions(self):
table_ref = DatasetReference(
"bigquery-public-data", "ethereum_blockchain"
).table("blocks")
all_rows = Config.CLIENT.list_partitions(table_ref)
self.assertIn("20180801", all_rows)
self.assertGreater(len(all_rows), 1000)
def test_list_tables(self):
dataset_id = _make_dataset_id("list_tables")
dataset = self.temp_dataset(dataset_id)
# Retrieve tables before any are created for the dataset.
iterator = Config.CLIENT.list_tables(dataset)
all_tables = list(iterator)
self.assertEqual(all_tables, [])
self.assertIsNone(iterator.next_page_token)
# Insert some tables to be listed.
tables_to_create = [
"new" + unique_resource_id(),
"newer" + unique_resource_id(),
"newest" + unique_resource_id(),
]
for table_name in tables_to_create:
table = Table(dataset.table(table_name), schema=SCHEMA)
created_table = helpers.retry_403(Config.CLIENT.create_table)(table)
self.to_delete.insert(0, created_table)
# Retrieve the tables.
iterator = Config.CLIENT.list_tables(dataset)
all_tables = list(iterator)
self.assertIsNone(iterator.next_page_token)
created = [
table
for table in all_tables
if (table.table_id in tables_to_create and table.dataset_id == dataset_id)
]
self.assertEqual(len(created), len(tables_to_create))
# List tables with a string ID.
iterator = Config.CLIENT.list_tables(dataset_id)
self.assertGreater(len(list(iterator)), 0)
# List tables with a fully-qualified string ID.
iterator = Config.CLIENT.list_tables(
"{}.{}".format(Config.CLIENT.project, dataset_id)
)
self.assertGreater(len(list(iterator)), 0)
def test_update_table(self):
dataset = self.temp_dataset(_make_dataset_id("update_table"))
TABLE_NAME = "test_table"
table_arg = Table(dataset.table(TABLE_NAME), schema=SCHEMA)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
self.assertIsNone(table.friendly_name)
self.assertIsNone(table.description)
self.assertEqual(table.labels, {})
table.friendly_name = "Friendly"
table.description = "Description"
table.labels = {"priority": "high", "color": "blue"}
table2 = Config.CLIENT.update_table(
table, ["friendly_name", "description", "labels"]
)
self.assertEqual(table2.friendly_name, "Friendly")
self.assertEqual(table2.description, "Description")
self.assertEqual(table2.labels, {"priority": "high", "color": "blue"})
table2.description = None
table2.labels = {
"color": "green", # change
"shape": "circle", # add
"priority": None, # delete
}
table3 = Config.CLIENT.update_table(table2, ["description", "labels"])
self.assertIsNone(table3.description)
self.assertEqual(table3.labels, {"color": "green", "shape": "circle"})
# If we try to update using table2 again, it will fail because the
# previous update changed the ETag.
table2.description = "no good"
with self.assertRaises(PreconditionFailed):
Config.CLIENT.update_table(table2, ["description"])
def test_update_table_schema(self):
dataset = self.temp_dataset(_make_dataset_id("update_table"))
TABLE_NAME = "test_table"
table_arg = Table(dataset.table(TABLE_NAME), schema=SCHEMA)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
voter = bigquery.SchemaField("voter", "BOOLEAN", mode="NULLABLE")
schema = table.schema
schema.append(voter)
table.schema = schema
updated_table = Config.CLIENT.update_table(table, ["schema"])
self.assertEqual(len(updated_table.schema), len(schema))
for found, expected in zip(updated_table.schema, schema):
self.assertEqual(found.name, expected.name)
self.assertEqual(found.field_type, expected.field_type)
self.assertEqual(found.mode, expected.mode)
def test_unset_table_schema_attributes(self):
from google.cloud.bigquery.schema import PolicyTagList
dataset = self.temp_dataset(_make_dataset_id("unset_policy_tags"))
table_id = "test_table"
policy_tags = PolicyTagList(
names=[
"projects/{}/locations/us/taxonomies/1/policyTags/2".format(
Config.CLIENT.project
),
]
)
schema = [
bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
bigquery.SchemaField(
"secret_int",
"INTEGER",
mode="REQUIRED",
description="This field is numeric",
policy_tags=policy_tags,
),
]
table_arg = Table(dataset.table(table_id), schema=schema)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
self.assertEqual(policy_tags, table.schema[1].policy_tags)
# Amend the schema to replace the policy tags
new_schema = table.schema[:]
old_field = table.schema[1]
new_schema[1] = bigquery.SchemaField(
name=old_field.name,
field_type=old_field.field_type,
mode=old_field.mode,
description=None,
fields=old_field.fields,
policy_tags=PolicyTagList(),
)
table.schema = new_schema
updated_table = Config.CLIENT.update_table(table, ["schema"])
self.assertFalse(updated_table.schema[1].description) # Empty string or None.
# policyTags key expected to be missing from response.
self.assertIsNone(updated_table.schema[1].policy_tags)
def test_update_table_clustering_configuration(self):
dataset = self.temp_dataset(_make_dataset_id("update_table"))
TABLE_NAME = "test_table"
table_arg = Table(dataset.table(TABLE_NAME), schema=CLUSTERING_SCHEMA)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
table.clustering_fields = ["full_name", "date_of_birth"]
table2 = Config.CLIENT.update_table(table, ["clustering_fields"])
self.assertEqual(table2.clustering_fields, ["full_name", "date_of_birth"])
table2.clustering_fields = None
table3 = Config.CLIENT.update_table(table2, ["clustering_fields"])
self.assertIsNone(table3.clustering_fields, None)
@staticmethod
def _fetch_single_page(table, selected_fields=None):
iterator = Config.CLIENT.list_rows(table, selected_fields=selected_fields)
page = next(iterator.pages)
return list(page)
def test_insert_rows_then_dump_table(self):
NOW_SECONDS = 1448911495.484366
NOW = datetime.datetime.utcfromtimestamp(NOW_SECONDS).replace(tzinfo=UTC)
ROWS = [
("Phred Phlyntstone", 32, NOW),
("Bharney Rhubble", 33, NOW + datetime.timedelta(seconds=10)),
("Wylma Phlyntstone", 29, NOW + datetime.timedelta(seconds=20)),
("Bhettye Rhubble", 27, None),
]
ROW_IDS = range(len(ROWS))
dataset = self.temp_dataset(_make_dataset_id("insert_rows_then_dump"))
TABLE_ID = "test_table"
schema = [
bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("now", "TIMESTAMP"),
]
table_arg = Table(dataset.table(TABLE_ID), schema=schema)
self.assertFalse(_table_exists(table_arg))
table = helpers.retry_403(Config.CLIENT.create_table)(table_arg)
self.to_delete.insert(0, table)
self.assertTrue(_table_exists(table))
errors = Config.CLIENT.insert_rows(table, ROWS, row_ids=ROW_IDS)
self.assertEqual(len(errors), 0)
rows = ()
# Allow for "warm up" before rows visible. See
# https://cloud.google.com/bigquery/streaming-data-into-bigquery#dataavailability
# 8 tries -> 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127 seconds
retry = RetryResult(_has_rows, max_tries=8)
rows = retry(self._fetch_single_page)(table)
row_tuples = [r.values() for r in rows]
by_age = operator.itemgetter(1)
self.assertEqual(sorted(row_tuples, key=by_age), sorted(ROWS, key=by_age))
def test_load_table_from_local_avro_file_then_dump_table(self):
from google.cloud.bigquery.job import SourceFormat
from google.cloud.bigquery.job import WriteDisposition
TABLE_NAME = "test_table_avro"
ROWS = [
("violet", 400),
("indigo", 445),
("blue", 475),
("green", 510),
("yellow", 570),
("orange", 590),
("red", 650),
]
dataset = self.temp_dataset(_make_dataset_id("load_local_then_dump"))
table_ref = dataset.table(TABLE_NAME)
table = Table(table_ref)
self.to_delete.insert(0, table)
with open(DATA_PATH / "colors.avro", "rb") as avrof:
config = bigquery.LoadJobConfig()
config.source_format = SourceFormat.AVRO
config.write_disposition = WriteDisposition.WRITE_TRUNCATE
job = Config.CLIENT.load_table_from_file(
avrof, table_ref, job_config=config
)
# Retry until done.
job.result(timeout=JOB_TIMEOUT)
self.assertEqual(job.output_rows, len(ROWS))
table = Config.CLIENT.get_table(table)
rows = self._fetch_single_page(table)
row_tuples = [r.values() for r in rows]
by_wavelength = operator.itemgetter(1)
self.assertEqual(
sorted(row_tuples, key=by_wavelength), sorted(ROWS, key=by_wavelength)
)
def test_load_table_from_local_parquet_file_decimal_types(self):
from google.cloud.bigquery.enums import DecimalTargetType
from google.cloud.bigquery.job import SourceFormat
from google.cloud.bigquery.job import WriteDisposition
TABLE_NAME = "test_table_parquet"
expected_rows = [
(decimal.Decimal("123.999999999999"),),
(decimal.Decimal("99999999999999999999999999.999999999999"),),
]
dataset = self.temp_dataset(_make_dataset_id("load_local_parquet_then_dump"))
table_ref = dataset.table(TABLE_NAME)
table = Table(table_ref)
self.to_delete.insert(0, table)
job_config = bigquery.LoadJobConfig()
job_config.source_format = SourceFormat.PARQUET
job_config.write_disposition = WriteDisposition.WRITE_TRUNCATE
job_config.decimal_target_types = [
DecimalTargetType.NUMERIC,
DecimalTargetType.BIGNUMERIC,
DecimalTargetType.STRING,
]
with open(DATA_PATH / "numeric_38_12.parquet", "rb") as parquet_file:
job = Config.CLIENT.load_table_from_file(
parquet_file, table_ref, job_config=job_config
)
job.result(timeout=JOB_TIMEOUT) # Retry until done.
self.assertEqual(job.output_rows, len(expected_rows))
table = Config.CLIENT.get_table(table)
rows = self._fetch_single_page(table)
row_tuples = [r.values() for r in rows]
self.assertEqual(sorted(row_tuples), sorted(expected_rows))
# Forcing the NUMERIC type, however, should result in an error.
job_config.decimal_target_types = [DecimalTargetType.NUMERIC]
with open(DATA_PATH / "numeric_38_12.parquet", "rb") as parquet_file:
job = Config.CLIENT.load_table_from_file(
parquet_file, table_ref, job_config=job_config
)
with self.assertRaises(BadRequest) as exc_info:
job.result(timeout=JOB_TIMEOUT)
exc_msg = str(exc_info.exception)
self.assertIn("out of valid NUMERIC range", exc_msg)
def test_load_table_from_json_basic_use(self):
table_schema = (
bigquery.SchemaField("name", "STRING", mode="REQUIRED"),
bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("birthday", "DATE", mode="REQUIRED"),
bigquery.SchemaField("is_awesome", "BOOLEAN", mode="REQUIRED"),
)
json_rows = [
{"name": "John", "age": 18, "birthday": "2001-10-15", "is_awesome": False},
{"name": "Chuck", "age": 79, "birthday": "1940-03-10", "is_awesome": True},
]
dataset_id = _make_dataset_id("bq_system_test")
self.temp_dataset(dataset_id)
table_id = "{}.{}.load_table_from_json_basic_use".format(
Config.CLIENT.project, dataset_id
)
# Create the table before loading so that schema mismatch errors are
# identified.
table = helpers.retry_403(Config.CLIENT.create_table)(
Table(table_id, schema=table_schema)
)
self.to_delete.insert(0, table)
job_config = bigquery.LoadJobConfig(schema=table_schema)
load_job = Config.CLIENT.load_table_from_json(
json_rows, table_id, job_config=job_config
)
load_job.result()
table = Config.CLIENT.get_table(table)
self.assertEqual(tuple(table.schema), table_schema)
self.assertEqual(table.num_rows, 2)
def test_load_table_from_json_schema_autodetect(self):
json_rows = [
{"name": "John", "age": 18, "birthday": "2001-10-15", "is_awesome": False},
{"name": "Chuck", "age": 79, "birthday": "1940-03-10", "is_awesome": True},
]
dataset_id = _make_dataset_id("bq_system_test")
self.temp_dataset(dataset_id)
table_id = "{}.{}.load_table_from_json_basic_use".format(
Config.CLIENT.project, dataset_id
)
# Use schema with NULLABLE fields, because schema autodetection
# defaults to field mode NULLABLE.
table_schema = (
bigquery.SchemaField("name", "STRING", mode="NULLABLE"),
bigquery.SchemaField("age", "INTEGER", mode="NULLABLE"),
bigquery.SchemaField("birthday", "DATE", mode="NULLABLE"),
bigquery.SchemaField("is_awesome", "BOOLEAN", mode="NULLABLE"),
)
# create the table before loading so that the column order is predictable
table = helpers.retry_403(Config.CLIENT.create_table)(
Table(table_id, schema=table_schema)
)
self.to_delete.insert(0, table)
# do not pass an explicit job config to trigger automatic schema detection