This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathtest_session.py
More file actions
2250 lines (1924 loc) · 73 KB
/
test_session.py
File metadata and controls
2250 lines (1924 loc) · 73 KB
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 2023 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 io
import json
import random
import re
import tempfile
import textwrap
import time
import typing
from typing import List, Optional, Sequence
import warnings
import bigframes_vendored.pandas.io.gbq as vendored_pandas_gbq
import db_dtypes # type:ignore
import google
import google.cloud.bigquery as bigquery
import numpy as np
import pandas as pd
import pandas.arrays as arrays
import pyarrow as pa
import pytest
import bigframes
import bigframes.dataframe
import bigframes.dtypes
import bigframes.ml.linear_model
import bigframes.session.execution_spec
import bigframes.testing
from bigframes.testing import utils
all_write_engines = pytest.mark.parametrize(
"write_engine",
[
"default",
"bigquery_inline",
"bigquery_load",
"bigquery_streaming",
"bigquery_write",
],
)
@pytest.fixture(scope="module")
def df_and_local_csv(scalars_df_index):
# The auto detects of BigQuery load job have restrictions to detect the bytes,
# datetime, numeric and geometry types, so they're skipped here.
drop_columns = [
"bytes_col",
"datetime_col",
"numeric_col",
"geography_col",
"duration_col",
]
scalars_df_index = scalars_df_index.drop(columns=drop_columns)
with tempfile.TemporaryDirectory() as dir:
# Prepares local CSV file for reading
path = dir + "/test_read_csv_w_local_csv.csv"
scalars_df_index.to_csv(path, index=True)
yield scalars_df_index, path
@pytest.fixture(scope="module")
def df_and_gcs_csv(scalars_df_index, gcs_folder):
# The auto detects of BigQuery load job have restrictions to detect the bytes,
# datetime, numeric and geometry types, so they're skipped here.
drop_columns = [
"bytes_col",
"datetime_col",
"numeric_col",
"geography_col",
"duration_col",
]
scalars_df_index = scalars_df_index.drop(columns=drop_columns)
path = gcs_folder + "test_read_csv_w_gcs_csv*.csv"
read_path = utils.get_first_file_from_wildcard(path)
scalars_df_index.to_csv(path, index=True)
return scalars_df_index, read_path
@pytest.fixture(scope="module")
def df_and_gcs_csv_for_two_columns(scalars_df_index, gcs_folder):
# Some tests require only two columns to be present in the CSV file.
selected_cols = ["bool_col", "int64_col"]
scalars_df_index = scalars_df_index[selected_cols]
path = gcs_folder + "df_and_gcs_csv_for_two_columns*.csv"
read_path = utils.get_first_file_from_wildcard(path)
scalars_df_index.to_csv(path, index=True)
return scalars_df_index, read_path
def test_read_gbq_tokyo(
session_tokyo: bigframes.Session,
scalars_table_tokyo: str,
scalars_pandas_df_index: pd.DataFrame,
tokyo_location: str,
):
df = session_tokyo.read_gbq(scalars_table_tokyo, index_col=["rowindex"])
df.sort_index(inplace=True)
expected = scalars_pandas_df_index
# use_explicit_destination=True, otherwise might use path with no query_job
exec_result = session_tokyo._executor.execute(
df._block.expr,
bigframes.session.execution_spec.ExecutionSpec(
bigframes.session.execution_spec.CacheSpec(()), promise_under_10gb=False
),
)
assert exec_result.query_job is not None
assert exec_result.query_job.location == tokyo_location
assert len(expected) == exec_result.batches().approx_total_rows
@pytest.mark.parametrize(
("query_or_table", "columns"),
[
pytest.param(
"{scalars_table_id}", ["bool_col", "int64_col"], id="two_cols_in_table"
),
pytest.param(
"""SELECT
t.int64_col + 1 as my_ints,
t.float64_col * 2 AS my_floats,
CONCAT(t.string_col, "_2") AS my_strings,
t.int64_col > 0 AS my_bools,
FROM `{scalars_table_id}` AS t
""",
["my_strings"],
id="one_cols_in_query",
),
],
)
def test_read_gbq_w_columns(
session: bigframes.Session,
scalars_table_id: str,
query_or_table: str,
columns: List[str],
):
df = session.read_gbq(
query_or_table.format(scalars_table_id=scalars_table_id), columns=columns
)
assert df.columns.tolist() == columns
def test_read_gbq_w_unknown_column(
session: bigframes.Session,
scalars_table_id: str,
):
with pytest.raises(
ValueError,
match=re.escape("Column 'int63_col' is not found. Did you mean 'int64_col'?"),
):
session.read_gbq(
scalars_table_id,
columns=["string_col", "int63_col", "bool_col"],
)
def test_read_gbq_w_unknown_index_col(
session: bigframes.Session,
scalars_table_id: str,
):
with pytest.raises(
ValueError,
match=re.escape(
"Column 'int64_two' of `index_col` not found in this table. Did you mean 'int64_too'?"
),
):
session.read_gbq(
scalars_table_id,
index_col=["int64_col", "int64_two"],
)
@pytest.mark.parametrize(
("query_or_table", "index_col"),
[
pytest.param(
"{scalars_table_id}",
["bool_col", "int64_col"],
id="unique_multiindex_table",
),
pytest.param(
"""SELECT
t.float64_col * 2 AS my_floats,
CONCAT(t.string_col, "_2") AS my_strings,
t.int64_col > 0 AS my_bools,
FROM `{scalars_table_id}` AS t
ORDER BY my_strings
""",
["my_strings"],
id="string_index_w_order_by",
),
pytest.param(
"SELECT GENERATE_UUID() AS uuid, 0 AS my_value FROM UNNEST(GENERATE_ARRAY(1, 20))",
["uuid"],
id="unique_uuid_index_query",
),
pytest.param(
"""
SELECT my_index, my_value
FROM UNNEST(
[
STRUCT<my_index INT64, my_value INT64>(0, 12),
STRUCT<my_index INT64, my_value INT64>(1, 12),
STRUCT<my_index INT64, my_value INT64>(2, 24)
]
)
-- Can't normally cluster tables with ORDER BY clause.
ORDER BY my_index DESC
""",
["my_index"],
id="unique_index_query_has_order_by",
),
pytest.param(
"""
WITH my_table AS (
SELECT *
FROM UNNEST(
[
STRUCT<my_index INT64, my_value INT64>(0, 12),
STRUCT<my_index INT64, my_value INT64>(1, 12),
STRUCT<my_index INT64, my_value INT64>(2, 24)
]
)
)
SELECT my_index, my_value FROM my_table
""",
["my_index"],
id="unique_index_query_with_named_table_expression",
),
pytest.param(
"""
CREATE TEMP TABLE test_read_gbq_w_index_col_unique_index_query_with_script
AS SELECT * FROM UNNEST(
[
STRUCT<my_index INT64, my_value INT64>(0, 12),
STRUCT<my_index INT64, my_value INT64>(1, 12),
STRUCT<my_index INT64, my_value INT64>(2, 24)
]
);
SELECT my_index, my_value FROM test_read_gbq_w_index_col_unique_index_query_with_script
""",
["my_index"],
id="unique_index_query_with_script",
),
pytest.param(
"{scalars_table_id}",
["bool_col"],
id="non_unique_index",
),
pytest.param(
"{scalars_table_id}",
["float64_col"],
id="non_unique_float_index",
),
pytest.param(
"{scalars_table_id}",
[
"timestamp_col",
"float64_col",
"datetime_col",
"int64_too",
],
id="multi_part_index_direct",
),
pytest.param(
"SELECT * FROM {scalars_table_id}",
[
"timestamp_col",
"float64_col",
"string_col",
"bool_col",
"int64_col",
"int64_too",
],
id="multi_part_index_w_query",
),
],
)
def test_read_gbq_w_index_col(
session: bigframes.Session,
scalars_table_id: str,
query_or_table: str,
index_col: List[str],
):
df = session.read_gbq(
query_or_table.format(scalars_table_id=scalars_table_id),
index_col=index_col,
)
assert list(df.index.names) == index_col
# Verify that we get the expected number of results.
bf_shape = df.shape
result = df.to_pandas()
assert bf_shape == result.shape
def test_read_gbq_w_anonymous_query_results_table(session: bigframes.Session):
"""Ensure BigQuery DataFrames can be used to inspect the results of a query job."""
query = textwrap.dedent(
"""
SELECT SUM(`number`) AS total_people, name
FROM `bigquery-public-data.usa_names.usa_1910_2013`
GROUP BY name
HAVING name < "B"
"""
)
job = session.bqclient.query(query)
expected = job.to_dataframe().set_index("name").sort_index()
destination = f"{job.destination.project}.{job.destination.dataset_id}.{job.destination.table_id}"
df = session.read_gbq(destination, index_col="name")
result = df.to_pandas()
expected.index = expected.index.astype(result.index.dtype)
bigframes.testing.assert_frame_equal(result, expected, check_dtype=False)
def test_read_gbq_w_primary_keys_table(
session: bigframes.Session, usa_names_grouped_table: bigquery.Table
):
# Validate that the table we're querying has a primary key.
table = usa_names_grouped_table
table_constraints = table.table_constraints
assert table_constraints is not None
primary_key = table_constraints.primary_key
assert primary_key is not None
primary_keys = primary_key.columns
assert len(primary_keys) != 0
df = session.read_gbq(f"{table.project}.{table.dataset_id}.{table.table_id}")
result = df.head(100).to_pandas()
# Verify that primary keys are used as the index.
assert list(result.index.names) == list(primary_keys)
# Verify that the DataFrame is already sorted by primary keys.
sorted_result = result.sort_values(primary_keys)
bigframes.testing.assert_frame_equal(result, sorted_result)
# Verify that we're working from a snapshot rather than a copy of the table.
assert "FOR SYSTEM_TIME AS OF" in df.sql
def test_read_gbq_w_primary_keys_table_and_filters(
session: bigframes.Session, usa_names_grouped_table: bigquery.Table
):
"""
Verify fix for internal issue 338039517, where using filters didn't use the
primary keys for indexing / ordering.
"""
# Validate that the table we're querying has a primary key.
table = usa_names_grouped_table
table_constraints = table.table_constraints
assert table_constraints is not None
primary_key = table_constraints.primary_key
assert primary_key is not None
primary_keys = primary_key.columns
assert len(primary_keys) != 0
df = session.read_gbq(
f"{table.project}.{table.dataset_id}.{table.table_id}",
filters=typing.cast(
vendored_pandas_gbq.FiltersType,
[
("name", "LIKE", "W%"),
("total_people", ">", 100),
],
),
)
result = df.to_pandas()
# Verify that primary keys are used as the index.
assert list(result.index.names) == list(primary_keys)
# Verify that the DataFrame is already sorted by primary keys.
sorted_result = result.sort_values(primary_keys)
bigframes.testing.assert_frame_equal(result, sorted_result)
@pytest.mark.parametrize(
("query_or_table", "max_results"),
[
pytest.param("{scalars_table_id}", 2, id="two_rows_in_table"),
pytest.param(
"""SELECT
t.float64_col * 2 AS my_floats,
CONCAT(t.string_col, "_2") AS my_strings,
t.int64_col > 0 AS my_bools,
FROM `{scalars_table_id}` AS t
""",
2,
id="three_rows_in_query",
),
pytest.param(
"{scalars_table_id}",
-1,
marks=pytest.mark.xfail(
raises=ValueError,
reason="`max_results` should be a positive number.",
),
id="neg_rows",
),
],
)
def test_read_gbq_w_max_results(
session: bigframes.Session,
scalars_table_id: str,
query_or_table: str,
max_results: int,
):
df = session.read_gbq(
query_or_table.format(scalars_table_id=scalars_table_id),
max_results=max_results,
)
bf_result = df.to_pandas()
assert bf_result.shape[0] == max_results
@pytest.mark.parametrize(
("sql_template", "expected_statement_type"),
(
pytest.param(
"""
CREATE OR REPLACE TABLE `{dataset_id}.test_read_gbq_w_ddl` (
`col_a` INT64,
`col_b` STRING
);
""",
"CREATE_TABLE",
id="ddl-create-table",
),
pytest.param(
# From https://cloud.google.com/bigquery/docs/boosted-tree-classifier-tutorial
"""
CREATE OR REPLACE VIEW `{dataset_id}.test_read_gbq_w_create_view`
AS
SELECT
age,
workclass,
marital_status,
education_num,
occupation,
hours_per_week,
income_bracket,
CASE
WHEN MOD(functional_weight, 10) < 8 THEN 'training'
WHEN MOD(functional_weight, 10) = 8 THEN 'evaluation'
WHEN MOD(functional_weight, 10) = 9 THEN 'prediction'
END AS dataframe
FROM
`bigquery-public-data.ml_datasets.census_adult_income`;
""",
"CREATE_VIEW",
id="ddl-create-view",
),
pytest.param(
"""
CREATE OR REPLACE TABLE `{dataset_id}.test_read_gbq_w_dml` (
`col_a` INT64,
`col_b` STRING
);
INSERT INTO `{dataset_id}.test_read_gbq_w_dml`
VALUES (123, 'hello world');
""",
"SCRIPT",
id="dml",
),
),
)
def test_read_gbq_w_script_no_select(
session, dataset_id: str, sql_template: str, expected_statement_type: str
):
df = session.read_gbq(sql_template.format(dataset_id=dataset_id)).to_pandas()
assert df["statement_type"][0] == expected_statement_type
def test_read_gbq_twice_with_same_timestamp(session, penguins_table_id):
df1 = session.read_gbq(penguins_table_id)
time.sleep(1)
df2 = session.read_gbq(penguins_table_id)
df1.columns = [
"species1",
"island1",
"culmen_length_mm1",
"culmen_depth_mm1",
"flipper_length_mm1",
"body_mass_g1",
"sex1",
]
df3 = df1.join(df2)
assert df3 is not None
@pytest.mark.parametrize(
"source_table",
[
# Wildcard tables
"bigquery-public-data.noaa_gsod.gsod194*",
# Materialized views
"bigframes-dev.bigframes_tests_sys.base_table_mat_view",
],
)
def test_read_gbq_warns_time_travel_disabled(session, source_table):
with warnings.catch_warnings(record=True) as warned:
session.read_gbq(source_table, use_cache=False)
assert len(warned) == 1
assert warned[0].category == bigframes.exceptions.TimeTravelDisabledWarning
def test_read_gbq_w_ambigous_name(
session: bigframes.Session,
):
# Ensure read_gbq works when table and column share a name
df = (
session.read_gbq("bigframes-dev.bigframes_tests_sys.ambiguous_name")
.sort_values("x", ascending=False)
.reset_index(drop=True)
.to_pandas()
)
pd_df = pd.DataFrame({"x": [2, 1], "ambiguous_name": [20, 10]})
bigframes.testing.assert_frame_equal(
df, pd_df, check_dtype=False, check_index_type=False
)
def test_read_gbq_table_clustered_with_filter(session: bigframes.Session):
df = session.read_gbq_table(
"bigquery-public-data.cloud_storage_geo_index.landsat_index",
filters=typing.cast(
vendored_pandas_gbq.FiltersType,
[[("sensor_id", "LIKE", "OLI%")], [("sensor_id", "LIKE", "%TIRS")]],
),
columns=["sensor_id"],
)
sensors = df.groupby(["sensor_id"]).agg("count").to_pandas(ordered=False)
assert "OLI" in sensors.index
assert "TIRS" in sensors.index
assert "OLI_TIRS" in sensors.index
_GSOD_ALL_TABLES = "bigquery-public-data.noaa_gsod.gsod*"
_GSOD_1930S = "bigquery-public-data.noaa_gsod.gsod193*"
@pytest.mark.parametrize(
"api_method",
# Test that both methods work as there's a risk that read_gbq /
# read_gbq_table makes for an infinite loop. Table reads can convert to
# queries and read_gbq reads from tables.
["read_gbq", "read_gbq_table"],
)
@pytest.mark.parametrize(
("filters", "table_id", "index_col", "columns", "max_results"),
[
pytest.param(
[("_table_suffix", ">=", "1930"), ("_table_suffix", "<=", "1939")],
_GSOD_ALL_TABLES,
["stn", "wban", "year", "mo", "da"],
["temp", "max", "min"],
100,
id="all",
),
pytest.param(
(), # filters
_GSOD_1930S,
(), # index_col
["temp", "max", "min"],
None, # max_results
id="columns",
),
pytest.param(
[("_table_suffix", ">=", "1930"), ("_table_suffix", "<=", "1939")],
_GSOD_ALL_TABLES,
(), # index_col,
(), # columns
None, # max_results
id="filters",
),
pytest.param(
(), # filters
_GSOD_1930S,
["stn", "wban", "year", "mo", "da"],
(), # columns
None, # max_results
id="index_col",
),
pytest.param(
(), # filters
_GSOD_1930S,
(), # index_col
(), # columns
100, # max_results
id="max_results",
),
],
)
def test_read_gbq_wildcard(
session: bigframes.Session,
api_method: str,
filters,
table_id: str,
index_col: Sequence[str],
columns: Sequence[str],
max_results: Optional[int],
):
table_metadata = session.bqclient.get_table(table_id)
method = getattr(session, api_method)
df = method(
table_id,
filters=filters,
index_col=index_col,
columns=columns,
max_results=max_results,
)
num_rows, num_columns = df.shape
if index_col:
assert list(df.index.names) == list(index_col)
else:
assert df.index.name is None
expected_columns = (
columns
if columns
else [
field.name
for field in table_metadata.schema
if field.name not in index_col and field.name not in columns
]
)
assert list(df.columns) == expected_columns
assert num_rows > 0
assert num_columns == len(expected_columns)
@pytest.mark.parametrize(
("config"),
[
{
"query": {
"useQueryCache": True,
"maximumBytesBilled": "1000000000",
"timeoutMs": 120_000,
}
},
pytest.param(
{"query": {"useQueryCache": True, "timeoutMs": 50}},
marks=pytest.mark.xfail(
raises=google.api_core.exceptions.BadRequest,
reason="Expected failure due to timeout being set too short.",
),
),
pytest.param(
{"query": {"useQueryCache": False, "maximumBytesBilled": "100"}},
marks=pytest.mark.xfail(
raises=google.api_core.exceptions.BadRequest,
reason="Expected failure when the query exceeds the maximum bytes billed limit.",
),
),
],
)
def test_read_gbq_with_configuration(
session: bigframes.Session, scalars_table_id: str, config: dict
):
query = f"""SELECT
t.float64_col * 2 AS my_floats,
CONCAT(t.string_col, "_2") AS my_strings,
t.int64_col > 0 AS my_bools,
FROM `{scalars_table_id}` AS t
"""
df = session.read_gbq(query, configuration=config)
assert df.shape == (9, 3)
def test_read_gbq_with_custom_global_labels(
session: bigframes.Session, scalars_table_id: str
):
# Ensure we use thread-local variables to avoid conflicts with parallel tests.
with bigframes.option_context("compute.extra_query_labels", {}):
bigframes.options.compute.assign_extra_query_labels(test1=1, test2="abc")
bigframes.options.compute.extra_query_labels["test3"] = False
query_job = session.read_gbq(scalars_table_id).query_job
# No real job created from read_gbq, so we should expect 0 labels
assert query_job is not None
assert query_job.labels == {}
# No labels outside of the option_context.
assert len(bigframes.options.compute.extra_query_labels) == 0
def test_read_gbq_external_table(session: bigframes.Session):
# Verify the table is external to ensure it hasn't been altered
external_table_id = "bigframes-dev.bigframes_tests_sys.parquet_external_table"
external_table = session.bqclient.get_table(external_table_id)
assert external_table.table_type == "EXTERNAL"
df = session.read_gbq(external_table_id)
assert list(df.columns) == ["idx", "s1", "s2", "s3", "s4", "i1", "f1", "i2", "f2"]
assert df["i1"].max() == 99
def test_read_gbq_w_json(session):
sql = """
SELECT 0 AS id, JSON_OBJECT('boolean', True) AS json_col,
UNION ALL
SELECT 1, JSON_OBJECT('int', 100),
UNION ALL
SELECT 2, JSON_OBJECT('float', 0.98),
UNION ALL
SELECT 3, JSON_OBJECT('string', 'hello world'),
UNION ALL
SELECT 4, JSON_OBJECT('array', [8, 9, 10]),
UNION ALL
SELECT 5, JSON_OBJECT('null', null),
UNION ALL
SELECT 6, JSON_OBJECT('b', 2, 'a', 1),
UNION ALL
SELECT
7,
JSON_OBJECT(
'dict',
JSON_OBJECT(
'int', 1,
'array', [JSON_OBJECT('foo', 1), JSON_OBJECT('bar', 'hello')]
)
),
"""
df = session.read_gbq(sql, index_col="id")
assert df.dtypes["json_col"] == pd.ArrowDtype(db_dtypes.JSONArrowType())
assert df["json_col"][0] == '{"boolean":true}'
assert df["json_col"][1] == '{"int":100}'
assert df["json_col"][2] == '{"float":0.98}'
assert df["json_col"][3] == '{"string":"hello world"}'
assert df["json_col"][4] == '{"array":[8,9,10]}'
assert df["json_col"][5] == '{"null":null}'
# Verifies JSON strings preserve array order, regardless of dictionary key order.
assert df["json_col"][6] == '{"a":1,"b":2}'
assert df["json_col"][7] == '{"dict":{"array":[{"foo":1},{"bar":"hello"}],"int":1}}'
def test_read_gbq_w_json_and_compare_w_pandas_json(session):
df = session.read_gbq("SELECT JSON_OBJECT('foo', 10, 'bar', TRUE) AS json_col")
assert df.dtypes["json_col"] == pd.ArrowDtype(db_dtypes.JSONArrowType())
# These JSON strings are compatible with BigQuery's JSON storage,
pd_df = pd.DataFrame(
{"json_col": ['{"bar":true,"foo":10}']},
dtype=pd.ArrowDtype(db_dtypes.JSONArrowType()),
)
pd_df.index = pd_df.index.astype("Int64")
bigframes.testing.assert_series_equal(df.dtypes, pd_df.dtypes)
bigframes.testing.assert_series_equal(df["json_col"].to_pandas(), pd_df["json_col"])
def test_read_gbq_w_json_in_struct(session):
"""Avoid regressions for internal issue 381148539."""
sql = """
SELECT 0 AS id, STRUCT(JSON_OBJECT('boolean', True) AS data, 1 AS number) AS struct_col
UNION ALL
SELECT 1, STRUCT(JSON_OBJECT('int', 100), 2),
UNION ALL
SELECT 2, STRUCT(JSON_OBJECT('float', 0.98), 3),
UNION ALL
SELECT 3, STRUCT(JSON_OBJECT('string', 'hello world'), 4),
UNION ALL
SELECT 4, STRUCT(JSON_OBJECT('array', [8, 9, 10]), 5),
UNION ALL
SELECT 5, STRUCT(JSON_OBJECT('null', null), 6),
UNION ALL
SELECT
6,
STRUCT(JSON_OBJECT(
'dict',
JSON_OBJECT(
'int', 1,
'array', [JSON_OBJECT('foo', 1), JSON_OBJECT('bar', 'hello')]
)
), 7),
"""
df = session.read_gbq(sql, index_col="id")
assert isinstance(df.dtypes["struct_col"], pd.ArrowDtype)
assert isinstance(df.dtypes["struct_col"].pyarrow_dtype, pa.StructType)
data = df["struct_col"].struct.field("data")
assert data.dtype == pd.ArrowDtype(db_dtypes.JSONArrowType())
assert data[0] == '{"boolean":true}'
assert data[1] == '{"int":100}'
assert data[2] == '{"float":0.98}'
assert data[3] == '{"string":"hello world"}'
assert data[4] == '{"array":[8,9,10]}'
assert data[5] == '{"null":null}'
assert data[6] == '{"dict":{"array":[{"foo":1},{"bar":"hello"}],"int":1}}'
def test_read_gbq_w_json_in_array(session):
sql = """
SELECT
0 AS id,
[
JSON_OBJECT('boolean', True),
JSON_OBJECT('int', 100),
JSON_OBJECT('float', 0.98),
JSON_OBJECT('string', 'hello world'),
JSON_OBJECT('array', [8, 9, 10]),
JSON_OBJECT('null', null),
JSON_OBJECT(
'dict',
JSON_OBJECT(
'int', 1,
'array', [JSON_OBJECT('bar', 'hello'), JSON_OBJECT('foo', 1)]
)
)
] AS array_col,
"""
df = session.read_gbq(sql, index_col="id")
assert isinstance(df.dtypes["array_col"], pd.ArrowDtype)
assert isinstance(df.dtypes["array_col"].pyarrow_dtype, pa.ListType)
data = df["array_col"]
assert data.list.len()[0] == 7
assert data.list[0].dtype == pd.ArrowDtype(db_dtypes.JSONArrowType())
assert data[0] == [
'{"boolean":true}',
'{"int":100}',
'{"float":0.98}',
'{"string":"hello world"}',
'{"array":[8,9,10]}',
'{"null":null}',
'{"dict":{"array":[{"bar":"hello"},{"foo":1}],"int":1}}',
]
def test_read_gbq_model(session, penguins_linear_model_name):
model = session.read_gbq_model(penguins_linear_model_name)
assert isinstance(model, bigframes.ml.linear_model.LinearRegression)
def test_read_pandas(session, scalars_dfs):
_, scalars_pandas_df = scalars_dfs
df = session.read_pandas(scalars_pandas_df)
result = df.to_pandas()
expected = scalars_pandas_df
bigframes.testing.assert_frame_equal(result, expected)
def test_read_pandas_series(session):
idx: pd.Index = pd.Index([2, 7, 1, 2, 8], dtype=pd.Int64Dtype())
pd_series = pd.Series([3, 1, 4, 1, 5], dtype=pd.Int64Dtype(), index=idx)
bf_series = session.read_pandas(pd_series)
bigframes.testing.assert_series_equal(bf_series.to_pandas(), pd_series)
def test_read_pandas_index(session):
pd_idx: pd.Index = pd.Index([2, 7, 1, 2, 8], dtype=pd.Int64Dtype())
bf_idx = session.read_pandas(pd_idx)
bigframes.testing.assert_index_equal(bf_idx.to_pandas(), pd_idx)
def test_read_pandas_w_unsupported_mixed_dtype(session):
with pytest.raises(ValueError, match="Could not convert"):
session.read_pandas(pd.DataFrame({"a": [1, "hello"]}))
def test_read_pandas_inline_respects_location():
options = bigframes.BigQueryOptions(location="europe-west1")
session = bigframes.Session(options)
df = session.read_pandas(pd.DataFrame([[1, 2, 3], [4, 5, 6]]))
df.to_gbq()
assert df.query_job is not None
table = session.bqclient.get_table(df.query_job.destination)
assert table.location == "europe-west1"
def test_read_pandas_col_label_w_space(session: bigframes.Session):
expected = pd.DataFrame(
{
"Animal": ["Falcon", "Falcon", "Parrot", "Parrot"],
"Max Speed": [380.0, 370.0, 24.0, 26.0],
}
)
result = session.read_pandas(expected).to_pandas()
bigframes.testing.assert_frame_equal(
result, expected, check_index_type=False, check_dtype=False
)
def test_read_pandas_multi_index(session, scalars_pandas_df_multi_index):
df = session.read_pandas(scalars_pandas_df_multi_index)
result = df.to_pandas()
bigframes.testing.assert_frame_equal(result, scalars_pandas_df_multi_index)
def test_read_pandas_rowid_exists_adds_suffix(session, scalars_pandas_df_default_index):
pandas_df = scalars_pandas_df_default_index.copy()
pandas_df["rowid"] = np.arange(pandas_df.shape[0])
df_roundtrip = session.read_pandas(pandas_df).to_pandas()
bigframes.testing.assert_frame_equal(df_roundtrip, pandas_df, check_dtype=False)
def test_read_pandas_tokyo(
session_tokyo: bigframes.Session,
scalars_pandas_df_index: pd.DataFrame,
tokyo_location: str,
):
df = session_tokyo.read_pandas(scalars_pandas_df_index)
df.to_gbq()
expected = scalars_pandas_df_index
result = session_tokyo._executor.execute(
df._block.expr,
bigframes.session.execution_spec.ExecutionSpec(
bigframes.session.execution_spec.CacheSpec(()), promise_under_10gb=False
),
)
assert result.query_job is not None
assert result.query_job.location == tokyo_location
assert len(expected) == result.batches().approx_total_rows
@all_write_engines
def test_read_pandas_timedelta_dataframes(session, write_engine):
pytest.importorskip(
"pandas",
minversion="2.0.0",
reason="old versions don't support local casting to arrow duration",
)
pandas_df = pd.DataFrame({"my_col": pd.to_timedelta([1, 2, 3], unit="d")})
actual_result = session.read_pandas(
pandas_df, write_engine=write_engine
).to_pandas()
expected_result = pandas_df.astype(bigframes.dtypes.TIMEDELTA_DTYPE)
expected_result.index = expected_result.index.astype(bigframes.dtypes.INT_DTYPE)
bigframes.testing.assert_frame_equal(actual_result, expected_result)
@all_write_engines
def test_read_pandas_timedelta_series(session, write_engine):
expected_series = pd.Series(pd.to_timedelta([1, 2, 3], unit="d")).astype(
"timedelta64[ns]"
)
actual_result = (
session.read_pandas(expected_series, write_engine=write_engine)
.to_pandas()
.astype("timedelta64[ns]")
)
bigframes.testing.assert_series_equal(
actual_result, expected_series, check_index_type=False
)
@all_write_engines
def test_read_pandas_timedelta_index(session, write_engine):
expected_index = pd.to_timedelta([1, 2, 3], unit="d").astype(
"timedelta64[ns]"
) # to_timedelta returns an index
actual_result = (
session.read_pandas(expected_index, write_engine=write_engine)