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 pathloader.py
More file actions
1560 lines (1395 loc) · 60.4 KB
/
loader.py
File metadata and controls
1560 lines (1395 loc) · 60.4 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 2024 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.
from __future__ import annotations
import concurrent
import concurrent.futures
import copy
import dataclasses
import datetime
import io
import itertools
import math
import os
import threading
import typing
from typing import (
cast,
Dict,
Hashable,
IO,
Iterable,
Iterator,
List,
Literal,
Optional,
overload,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
import bigframes_vendored.constants as constants
import bigframes_vendored.pandas.io.gbq as third_party_pandas_gbq
import google.api_core.exceptions
from google.cloud import bigquery_storage_v1
import google.cloud.bigquery
import google.cloud.bigquery as bigquery
from google.cloud.bigquery.job.load import LoadJob
from google.cloud.bigquery.job.query import QueryJob
import google.cloud.bigquery.table
from google.cloud.bigquery_storage_v1 import types as bq_storage_types
import pandas
import pyarrow as pa
import bigframes._tools
import bigframes._tools.strings
from bigframes.core import (
bq_data,
guid,
identifiers,
local_data,
nodes,
ordering,
utils,
)
import bigframes.core as core
import bigframes.core.blocks as blocks
import bigframes.core.events
import bigframes.core.schema as schemata
import bigframes.dtypes
import bigframes.exceptions as bfe
import bigframes.formatting_helpers as formatting_helpers
from bigframes.session import dry_runs
import bigframes.session._io.bigquery as bf_io_bigquery
import bigframes.session._io.bigquery.read_gbq_query as bf_read_gbq_query
import bigframes.session._io.bigquery.read_gbq_table as bf_read_gbq_table
import bigframes.session.iceberg
import bigframes.session.metrics
import bigframes.session.temporary_storage
import bigframes.session.time as session_time
# Avoid circular imports.
if typing.TYPE_CHECKING:
import bigframes.dataframe as dataframe
import bigframes.session
_PLACEHOLDER_SCHEMA = (
google.cloud.bigquery.SchemaField("bf_loader_placeholder", "INTEGER"),
)
_LOAD_JOB_TYPE_OVERRIDES = {
# Json load jobs not supported yet: b/271321143
bigframes.dtypes.JSON_DTYPE: "STRING",
# Timedelta is emulated using integer in bq type system
bigframes.dtypes.TIMEDELTA_DTYPE: "INTEGER",
}
_STREAM_JOB_TYPE_OVERRIDES = {
# Timedelta is emulated using integer in bq type system
bigframes.dtypes.TIMEDELTA_DTYPE: "INTEGER",
}
TABLE_TYPE = Union[bq_data.GbqNativeTable, bq_data.BiglakeIcebergTable]
def _to_index_cols(
index_col: Iterable[str] | str | bigframes.enums.DefaultIndexKind = (),
) -> List[str]:
"""Convert index_col into a list of column names."""
if isinstance(index_col, bigframes.enums.DefaultIndexKind):
index_cols: List[str] = []
elif isinstance(index_col, str):
index_cols = [index_col]
else:
index_cols = list(index_col)
return index_cols
def _check_duplicates(name: str, columns: Optional[Iterable[str]] = None):
"""Check for duplicate column names in the provided iterable."""
if columns is None:
return
columns_list = list(columns)
set_columns = set(columns_list)
if len(columns_list) > len(set_columns):
raise ValueError(
f"The '{name}' argument contains duplicate names. "
f"All column names specified in '{name}' must be unique."
)
def _check_index_col_param(
index_cols: Iterable[str],
columns: Iterable[str],
*,
table_columns: Optional[Iterable[str]] = None,
index_col_in_columns: Optional[bool] = False,
):
"""Checks for duplicates in `index_cols` and resolves overlap with `columns`.
Args:
index_cols (Iterable[str]):
Column names designated as the index columns.
columns (Iterable[str]):
Used column names from table_columns.
table_columns (Iterable[str]):
A full list of column names in the table schema.
index_col_in_columns (bool):
A flag indicating how to handle overlap between `index_cols` and
`columns`.
- If `False`, the two lists must be disjoint (contain no common
elements). An error is raised if any overlap is found.
- If `True`, `index_cols` is expected to be a subset of
`columns`. An error is raised if an index column is not found
in the `columns` list.
"""
_check_duplicates("index_col", index_cols)
if columns is not None and len(list(columns)) > 0:
set_index = set(list(index_cols) if index_cols is not None else [])
set_columns = set(list(columns) if columns is not None else [])
if index_col_in_columns:
if not set_index.issubset(set_columns):
raise ValueError(
f"The specified index column(s) were not found: {set_index - set_columns}. "
f"Available columns are: {set_columns}"
)
else:
if not set_index.isdisjoint(set_columns):
raise ValueError(
"Found column names that exist in both 'index_col' and 'columns' arguments. "
"These arguments must specify distinct sets of columns."
)
if not index_col_in_columns and table_columns is not None:
for key in index_cols:
if key not in table_columns:
possibility = min(
table_columns,
key=lambda item: bigframes._tools.strings.levenshtein_distance(
key, item
),
)
raise ValueError(
f"Column '{key}' of `index_col` not found in this table. Did you mean '{possibility}'?"
)
def _check_columns_param(columns: Iterable[str], table_columns: Iterable[str]):
"""Validates that the specified columns are present in the table columns.
Args:
columns (Iterable[str]):
Used column names from table_columns.
table_columns (Iterable[str]):
A full list of column names in the table schema.
Raises:
ValueError: If any column in `columns` is not found in the table columns.
"""
for column_name in columns:
if column_name not in table_columns:
possibility = min(
table_columns,
key=lambda item: bigframes._tools.strings.levenshtein_distance(
column_name, item
),
)
raise ValueError(
f"Column '{column_name}' is not found. Did you mean '{possibility}'?"
)
def _check_names_param(
names: Iterable[str],
index_col: Iterable[str]
| str
| Iterable[int]
| int
| bigframes.enums.DefaultIndexKind,
columns: Iterable[str],
table_columns: Iterable[str],
):
len_names = len(list(names))
len_table_columns = len(list(table_columns))
len_columns = len(list(columns))
if len_names > len_table_columns:
raise ValueError(
f"Too many columns specified: expected {len_table_columns}"
f" and found {len_names}"
)
elif len_names < len_table_columns:
if isinstance(index_col, bigframes.enums.DefaultIndexKind) or index_col != ():
raise KeyError(
"When providing both `index_col` and `names`, ensure the "
"number of `names` matches the number of columns in your "
"data."
)
if len_columns != 0:
# The 'columns' must be identical to the 'names'. If not, raise an error.
if len_columns != len_names:
raise ValueError(
"Number of passed names did not match number of header "
"fields in the file"
)
if set(list(names)) != set(list(columns)):
raise ValueError("Usecols do not match columns")
@dataclasses.dataclass
class GbqDataLoader:
"""
Responsible for loading data into BigFrames using temporary bigquery tables.
This loader is constrained to loading local data and queries against data sources in the same region as the storage manager.
Args:
session (bigframes.session.Session):
The session the data will be loaded into. Objects will not be compatible with other sessions.
bqclient (bigquery.Client):
An object providing client library objects.
storage_manager (bigframes.session.temp_storage.TemporaryGbqStorageManager):
Manages temporary storage used by the loader.
default_index_type (bigframes.enums.DefaultIndexKind):
Determines the index type created for data loaded from gcs or gbq.
scan_index_uniqueness (bool):
Whether the loader will scan index columns to determine whether the values are unique.
This behavior is useful in total ordering mode to use index column as order key.
metrics (bigframes.session.metrics.ExecutionMetrics or None):
Used to record query execution statistics.
"""
def __init__(
self,
session: bigframes.session.Session,
bqclient: bigquery.Client,
write_client: bigquery_storage_v1.BigQueryWriteClient,
storage_manager: bigframes.session.temporary_storage.TemporaryStorageManager,
default_index_type: bigframes.enums.DefaultIndexKind,
scan_index_uniqueness: bool,
force_total_order: bool,
metrics: Optional[bigframes.session.metrics.ExecutionMetrics] = None,
*,
publisher: bigframes.core.events.Publisher,
):
self._bqclient = bqclient
self._write_client = write_client
self._storage_manager = storage_manager
self._default_index_type = default_index_type
self._scan_index_uniqueness = scan_index_uniqueness
self._force_total_order = force_total_order
self._df_snapshot: Dict[str, Tuple[datetime.datetime, TABLE_TYPE]] = {}
self._metrics = metrics
self._publisher = publisher
# Unfortunate circular reference, but need to pass reference when constructing objects
self._session = session
self._clock = session_time.BigQuerySyncedClock(bqclient)
self._clock.sync()
self._threadpool = concurrent.futures.ThreadPoolExecutor(
max_workers=1, thread_name_prefix="bigframes-loader"
)
def read_data_async(
self, local_data: local_data.ManagedArrowTable, offsets_col: str
) -> concurrent.futures.Future[bq_data.BigqueryDataSource]:
future = self._threadpool.submit(
self._load_data_or_write_data, local_data, offsets_col
)
return future
def read_pandas(
self,
pandas_dataframe: pandas.DataFrame,
method: Literal["load", "stream", "write"],
) -> dataframe.DataFrame:
# TODO: Push this into from_pandas, along with index flag
from bigframes import dataframe
val_cols, idx_cols = utils.get_standardized_ids(
pandas_dataframe.columns, pandas_dataframe.index.names, strict=True
)
prepared_df = pandas_dataframe.reset_index(drop=False).set_axis(
[*idx_cols, *val_cols], axis="columns"
)
managed_data = local_data.ManagedArrowTable.from_pandas(prepared_df)
block = blocks.Block(
self.read_managed_data(managed_data, method=method),
index_columns=idx_cols,
column_labels=pandas_dataframe.columns,
index_labels=pandas_dataframe.index.names,
)
return dataframe.DataFrame(block)
def read_managed_data(
self,
data: local_data.ManagedArrowTable,
method: Literal["load", "stream", "write"],
) -> core.ArrayValue:
offsets_col = guid.generate_guid("upload_offsets_")
if method == "load":
gbq_source = self.load_data(data, offsets_col=offsets_col)
elif method == "stream":
gbq_source = self.stream_data(data, offsets_col=offsets_col)
elif method == "write":
gbq_source = self.write_data(data, offsets_col=offsets_col)
else:
raise ValueError(f"Unsupported read method {method}")
return core.ArrayValue.from_bq_data_source(
source=gbq_source,
scan_list=nodes.ScanList(
tuple(
nodes.ScanItem(identifiers.ColumnId(item.column), item.column)
for item in data.schema.items
)
),
session=self._session,
)
def _load_data_or_write_data(
self,
data: local_data.ManagedArrowTable,
offsets_col: str,
) -> bq_data.BigqueryDataSource:
"""Write local data into BigQuery using the local API if possible,
otherwise use the write API."""
can_load = all(
_is_dtype_can_load(item.column, item.dtype) for item in data.schema.items
)
if can_load:
return self.load_data(data, offsets_col=offsets_col)
else:
return self.write_data(data, offsets_col=offsets_col)
def load_data(
self,
data: local_data.ManagedArrowTable,
offsets_col: str,
) -> bq_data.BigqueryDataSource:
"""Load managed data into bigquery"""
cannot_load_columns = {
item.column: item.dtype
for item in data.schema.items
if not _is_dtype_can_load(item.column, item.dtype)
}
if cannot_load_columns:
raise NotImplementedError(
f"Nested JSON types are currently unsupported for BigQuery Load API. "
f"Unsupported columns: {cannot_load_columns}. {constants.FEEDBACK_LINK}"
)
schema_w_offsets = data.schema.append(
schemata.SchemaItem(offsets_col, bigframes.dtypes.INT_DTYPE)
)
bq_schema = schema_w_offsets.to_bigquery(_LOAD_JOB_TYPE_OVERRIDES)
job_config = bigquery.LoadJobConfig()
job_config.source_format = bigquery.SourceFormat.PARQUET
# Ensure we can load pyarrow.list_ / BQ ARRAY type.
# See internal issue 414374215.
parquet_options = bigquery.ParquetOptions()
parquet_options.enable_list_inference = True
job_config.parquet_options = parquet_options
job_config.schema = bq_schema
load_table_destination = self._storage_manager.create_temp_table(
bq_schema, [offsets_col]
)
buffer = io.BytesIO()
data.to_parquet(
buffer,
offsets_col=offsets_col,
geo_format="wkt",
duration_type="duration",
json_type="string",
)
buffer.seek(0)
load_job = self._bqclient.load_table_from_file(
buffer, destination=load_table_destination, job_config=job_config
)
self._start_generic_job(load_job)
# must get table metadata after load job for accurate metadata
destination_table = self._bqclient.get_table(load_table_destination)
return bq_data.BigqueryDataSource(
bq_data.GbqNativeTable.from_table(destination_table),
schema=schema_w_offsets,
ordering=ordering.TotalOrdering.from_offset_col(offsets_col),
n_rows=data.metadata.row_count,
)
def stream_data(
self,
data: local_data.ManagedArrowTable,
offsets_col: str,
) -> bq_data.BigqueryDataSource:
"""Load managed data into bigquery"""
MAX_BYTES = 10000000 # streaming api has 10MB limit
SAFETY_MARGIN = (
40 # Perf seems bad for large chunks, so do 40x smaller than max
)
batch_count = math.ceil(
data.metadata.total_bytes / (MAX_BYTES // SAFETY_MARGIN)
)
rows_per_batch = math.ceil(data.metadata.row_count / batch_count)
schema_w_offsets = data.schema.append(
schemata.SchemaItem(offsets_col, bigframes.dtypes.INT_DTYPE)
)
bq_schema = schema_w_offsets.to_bigquery(_STREAM_JOB_TYPE_OVERRIDES)
load_table_destination = self._storage_manager.create_temp_table(
bq_schema, [offsets_col]
)
rows = data.itertuples(
geo_format="wkt", duration_type="int", json_type="object"
)
rows_w_offsets = ((*row, offset) for offset, row in enumerate(rows))
# TODO: don't use batched
batches = _batched(rows_w_offsets, rows_per_batch)
ids_iter = map(str, itertools.count())
for batch in batches:
batch_rows = list(batch)
row_ids = itertools.islice(ids_iter, len(batch_rows))
for errors in self._bqclient.insert_rows(
load_table_destination,
batch_rows,
selected_fields=bq_schema,
row_ids=row_ids, # used to ensure only-once insertion
):
if errors:
raise ValueError(
f"Problem loading at least one row from DataFrame: {errors}. {constants.FEEDBACK_LINK}"
)
destination_table = self._bqclient.get_table(load_table_destination)
return bq_data.BigqueryDataSource(
bq_data.GbqNativeTable.from_table(destination_table),
schema=schema_w_offsets,
ordering=ordering.TotalOrdering.from_offset_col(offsets_col),
n_rows=data.metadata.row_count,
)
def write_data(
self,
data: local_data.ManagedArrowTable,
offsets_col: str,
) -> bq_data.BigqueryDataSource:
"""Load managed data into BigQuery using multiple concurrent streams."""
schema_w_offsets = data.schema.append(
schemata.SchemaItem(offsets_col, bigframes.dtypes.INT_DTYPE)
)
bq_schema = schema_w_offsets.to_bigquery(_STREAM_JOB_TYPE_OVERRIDES)
bq_table_ref = self._storage_manager.create_temp_table(bq_schema, [offsets_col])
parent = bq_table_ref.to_bqstorage()
# Some light benchmarking went into the constants here, not definitive
TARGET_BATCH_BYTES = (
5_000_000 # Must stay under the hard 10MB limit per request
)
rows_per_batch = math.ceil(
data.metadata.row_count * TARGET_BATCH_BYTES / data.metadata.total_bytes
)
min_batches = math.ceil(data.metadata.row_count / rows_per_batch)
num_streams = min((os.cpu_count() or 4) * 4, min_batches)
schema, all_batches = data.to_arrow(
offsets_col=offsets_col,
duration_type="int",
max_chunksize=rows_per_batch,
)
serialized_schema = schema.serialize().to_pybytes()
def stream_worker(work: Iterator[pa.RecordBatch]) -> str:
requested_stream = bq_storage_types.WriteStream(
type_=bq_storage_types.WriteStream.Type.PENDING
)
stream = self._write_client.create_write_stream(
parent=parent, write_stream=requested_stream
)
stream_name = stream.name
def request_generator():
current_offset = 0
for batch in work:
request = bq_storage_types.AppendRowsRequest(
write_stream=stream.name, offset=current_offset
)
request.arrow_rows.writer_schema.serialized_schema = (
serialized_schema
)
request.arrow_rows.rows.serialized_record_batch = (
batch.serialize().to_pybytes()
)
yield request
current_offset += batch.num_rows
responses = self._write_client.append_rows(requests=request_generator())
for resp in responses:
if resp.row_errors:
raise ValueError(
f"Errors in stream {stream_name}: {resp.row_errors}"
)
self._write_client.finalize_write_stream(name=stream_name)
return stream_name
shared_batches = ThreadSafeIterator(all_batches)
stream_names = []
with concurrent.futures.ThreadPoolExecutor(max_workers=num_streams) as executor:
futures = []
for _ in range(num_streams):
try:
work = next(shared_batches)
except StopIteration:
break # existing workers have consume all work, don't create more workers
# Guarantee at least a single piece of work for each worker
future = executor.submit(
stream_worker, itertools.chain((work,), shared_batches)
)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
stream_name = future.result()
stream_names.append(stream_name)
# This makes all data from all streams visible in the table at once
commit_request = bq_storage_types.BatchCommitWriteStreamsRequest(
parent=parent, write_streams=stream_names
)
response = self._write_client.batch_commit_write_streams(commit_request)
for error in response.stream_errors:
raise ValueError(f"Errors commiting stream {error}")
result_table = bq_data.GbqNativeTable.from_ref_and_schema(
bq_table_ref,
schema=bq_schema,
cluster_cols=[offsets_col],
location=self._storage_manager.location,
table_type="TABLE",
)
return bq_data.BigqueryDataSource(
result_table,
schema=schema_w_offsets,
ordering=ordering.TotalOrdering.from_offset_col(offsets_col),
n_rows=data.metadata.row_count,
)
def _start_generic_job(self, job: formatting_helpers.GenericJob):
if bigframes.options.display.progress_bar is not None:
formatting_helpers.wait_for_job(
job, bigframes.options.display.progress_bar
) # Wait for the job to complete
else:
job.result()
if self._metrics is not None and isinstance(job, (QueryJob, LoadJob)):
self._metrics.count_job_stats(query_job=job)
@overload
def read_gbq_table( # type: ignore[overload-overlap]
self,
table_id: str,
*,
index_col: Iterable[str]
| str
| Iterable[int]
| int
| bigframes.enums.DefaultIndexKind = ...,
columns: Iterable[str] = ...,
names: Optional[Iterable[str]] = ...,
max_results: Optional[int] = ...,
use_cache: bool = ...,
filters: third_party_pandas_gbq.FiltersType = ...,
enable_snapshot: bool = ...,
dry_run: Literal[False] = ...,
force_total_order: Optional[bool] = ...,
n_rows: Optional[int] = None,
index_col_in_columns: bool = False,
publish_execution: bool = True,
) -> dataframe.DataFrame:
...
@overload
def read_gbq_table(
self,
table_id: str,
*,
index_col: Iterable[str]
| str
| Iterable[int]
| int
| bigframes.enums.DefaultIndexKind = ...,
columns: Iterable[str] = ...,
names: Optional[Iterable[str]] = ...,
max_results: Optional[int] = ...,
use_cache: bool = ...,
filters: third_party_pandas_gbq.FiltersType = ...,
enable_snapshot: bool = ...,
dry_run: Literal[True] = ...,
force_total_order: Optional[bool] = ...,
n_rows: Optional[int] = None,
index_col_in_columns: bool = False,
publish_execution: bool = True,
) -> pandas.Series:
...
def read_gbq_table(
self,
table_id: str,
*,
index_col: Iterable[str]
| str
| Iterable[int]
| int
| bigframes.enums.DefaultIndexKind = (),
columns: Iterable[str] = (),
names: Optional[Iterable[str]] = None,
max_results: Optional[int] = None,
use_cache: bool = True,
filters: third_party_pandas_gbq.FiltersType = (),
enable_snapshot: bool = True,
dry_run: bool = False,
force_total_order: Optional[bool] = None,
n_rows: Optional[int] = None,
index_col_in_columns: bool = False,
publish_execution: bool = True,
) -> dataframe.DataFrame | pandas.Series:
"""Read a BigQuery table into a BigQuery DataFrames DataFrame.
This method allows you to create a DataFrame from a BigQuery table.
You can specify the columns to load, an index column, and apply
filters.
Args:
table_id (str):
The identifier of the BigQuery table to read.
index_col (Iterable[str] | str | Iterable[int] | int | bigframes.enums.DefaultIndexKind, optional):
The column(s) to use as the index for the DataFrame. This can be
a single column name or a list of column names. If not provided,
a default index will be used based on the session's
``default_index_type``.
columns (Iterable[str], optional):
The columns to read from the table. If not specified, all
columns will be read.
names (Optional[Iterable[str]], optional):
A list of column names to use for the resulting DataFrame. This
is useful if you want to rename the columns as you read the
data.
max_results (Optional[int], optional):
The maximum number of rows to retrieve from the table. If not
specified, all rows will be loaded.
use_cache (bool, optional):
Whether to use cached results for the query. Defaults to True.
Setting this to False will force a re-execution of the query.
filters (third_party_pandas_gbq.FiltersType, optional):
A list of filters to apply to the data. Filters are specified
as a list of tuples, where each tuple contains a column name,
an operator (e.g., '==', '!='), and a value.
enable_snapshot (bool, optional):
If True, a snapshot of the table is used to ensure that the
DataFrame is deterministic, even if the underlying table
changes. Defaults to True.
dry_run (bool, optional):
If True, the function will not actually execute the query but
will instead return statistics about the table. Defaults to False.
force_total_order (Optional[bool], optional):
If True, a total ordering is enforced on the DataFrame, which
can be useful for operations that require a stable row order.
If None, the session's default behavior is used.
n_rows (Optional[int], optional):
The number of rows to consider for type inference and other
metadata operations. This does not limit the number of rows
in the final DataFrame.
index_col_in_columns (bool, optional):
Specifies if the ``index_col`` is also present in the ``columns``
list. Defaults to ``False``.
* If ``False``, ``index_col`` and ``columns`` must specify
distinct sets of columns. An error will be raised if any
column is found in both.
* If ``True``, the column(s) in ``index_col`` are expected to
also be present in the ``columns`` list. This is useful
when the index is selected from the data columns (e.g., in a
``read_csv`` scenario). The column will be used as the
DataFrame's index and removed from the list of value columns.
publish_execution (bool, optional):
If True, sends an execution started and stopped event if this
causes a query. Set to False if using read_gbq_table from
another function that is reporting execution.
"""
import bigframes.core.events
import bigframes.dataframe as dataframe
# ---------------------------------
# Validate and transform parameters
# ---------------------------------
if max_results and max_results <= 0:
raise ValueError(
f"`max_results` should be a positive number, got {max_results}."
)
_check_duplicates("columns", columns)
columns = list(columns)
include_all_columns = columns is None or len(columns) == 0
filters = typing.cast(list, list(filters))
# ---------------------------------
# Fetch table metadata and validate
# ---------------------------------
time_travel_timestamp, table = self._get_table_metadata(
table_id=table_id,
default_project=self._bqclient.project,
bq_time=self._clock.get_time(),
use_cache=use_cache,
)
if not bq_data.is_compatible(
table.metadata.location, self._storage_manager.location
):
raise ValueError(
f"Current session is in {self._storage_manager.location} but table '{table.get_full_id()}' is located in {table.metadata.location}"
)
table_column_names = [field.name for field in table.physical_schema]
rename_to_schema: Optional[Dict[str, str]] = None
if names is not None:
_check_names_param(names, index_col, columns, table_column_names)
# Additional unnamed columns is going to set as index columns
len_names = len(list(names))
len_schema = len(table.physical_schema)
if len(columns) == 0 and len_names < len_schema:
index_col = range(len_schema - len_names)
names = [
field.name
for field in table.physical_schema[: len_schema - len_names]
] + list(names)
assert len_schema >= len_names
assert len_names >= len(columns)
table_column_names = table_column_names[: len(list(names))]
rename_to_schema = dict(zip(list(names), table_column_names))
if len(columns) != 0:
if names is None:
_check_columns_param(columns, table_column_names)
else:
_check_columns_param(columns, names)
names = columns
assert rename_to_schema is not None
columns = [rename_to_schema[renamed_name] for renamed_name in columns]
# Converting index_col into a list of column names requires
# the table metadata because we might use the primary keys
# when constructing the index.
index_cols = bf_read_gbq_table.get_index_cols(
table=table,
index_col=index_col,
rename_to_schema=rename_to_schema,
default_index_type=self._default_index_type,
)
_check_index_col_param(
index_cols,
columns,
table_columns=table_column_names,
index_col_in_columns=index_col_in_columns,
)
if index_col_in_columns and not include_all_columns:
set_index = set(list(index_cols) if index_cols is not None else [])
columns = [col for col in columns if col not in set_index]
# -----------------------------
# Optionally, execute the query
# -----------------------------
if (
# max_results introduces non-determinism and limits the cost on
# clustered tables, so fallback to a query. We do this here so that
# the index is consistent with tables that have primary keys, even
# when max_results is set.
max_results is not None
# Views such as INFORMATION_SCHEMA can introduce non-determinism.
# They can update frequently and don't support time travel.
or bf_read_gbq_table.is_information_schema(table_id)
):
# TODO(b/338111344): If we are running a query anyway, we might as
# well generate ROW_NUMBER() at the same time.
all_columns: Iterable[str] = (
itertools.chain(index_cols, columns) if columns else ()
)
query = bf_io_bigquery.to_query(
table.get_full_id(quoted=False),
columns=all_columns,
sql_predicate=bf_io_bigquery.compile_filters(filters)
if filters
else None,
max_results=max_results,
# We're executing the query, so we don't need time travel for
# determinism.
time_travel_timestamp=None,
)
df = self.read_gbq_query( # type: ignore # for dry_run overload
query,
index_col=index_cols,
columns=columns,
use_cache=use_cache,
dry_run=dry_run,
# If max_results has been set, we almost certainly have < 10 GB
# of results.
allow_large_results=False,
)
return df
if dry_run:
return dry_runs.get_table_stats(table)
# -----------------------------------------
# Validate table access and features
# -----------------------------------------
# Use a time travel to make sure the DataFrame is deterministic, even
# if the underlying table changes.
# If a dry run query fails with time travel but
# succeeds without it, omit the time travel clause and raise a warning
# about potential non-determinism if the underlying tables are modified.
filter_str = bf_io_bigquery.compile_filters(filters) if filters else None
all_columns = (
()
if len(columns) == 0
else (*columns, *[col for col in index_cols if col not in columns])
)
enable_snapshot = enable_snapshot and bf_read_gbq_table.is_time_travel_eligible(
self._bqclient,
table,
all_columns,
time_travel_timestamp,
filter_str,
should_warn=True,
should_dry_run=True,
publisher=self._publisher,
)
# ----------------------------
# Create ordering and validate
# ----------------------------
# TODO(b/337925142): Generate a new subquery with just the index_cols
# in the Ibis table expression so we don't have a "SELECT *" subquery
# in the query that checks for index uniqueness.
# TODO(b/338065601): Provide a way to assume uniqueness and avoid this
# check.
primary_key = bf_read_gbq_table.infer_unique_columns(
table=table,
index_cols=index_cols,
)
# If non in strict ordering mode, don't go through overhead of scanning index column(s) to determine if unique
if not primary_key and self._scan_index_uniqueness and index_cols:
if publish_execution:
self._publisher.publish(
bigframes.core.events.ExecutionStarted(),
)
primary_key = bf_read_gbq_table.check_if_index_columns_are_unique(
self._bqclient,
table=table,
index_cols=index_cols,
publisher=self._publisher,
)
if publish_execution:
self._publisher.publish(
bigframes.core.events.ExecutionFinished(),
)
selected_cols = None if include_all_columns else (*index_cols, *columns)
array_value = core.ArrayValue.from_table(
table,
columns=selected_cols,
predicate=filter_str,
at_time=time_travel_timestamp if enable_snapshot else None,
primary_key=primary_key,
session=self._session,
n_rows=n_rows,
)
# if we don't have a unique index, we order by row hash if we are in strict mode
if (
# If the user has explicitly selected or disabled total ordering for
# this API call, respect that choice.
(force_total_order is not None and force_total_order)
# If the user has not explicitly selected or disabled total ordering
# for this API call, respect the default choice for the session.
or (force_total_order is None and self._force_total_order)
):
if not primary_key:
array_value = array_value.order_by(
[
bigframes.core.ordering.OrderingExpression(
bigframes.operations.RowKey().as_expr(
*(id for id in array_value.column_ids)
),
# More concise SQL this way.
na_last=False,
)
],
is_total_order=True,
)
# ----------------------------------------------------
# Create Default Sequential Index if still have no index
# ----------------------------------------------------
# If no index columns provided or found, fall back to session default
if (index_col != bigframes.enums.DefaultIndexKind.NULL) and len(
index_cols
) == 0:
index_col = self._default_index_type
index_names: Sequence[Hashable] = index_cols
if index_col == bigframes.enums.DefaultIndexKind.SEQUENTIAL_INT64:
array_value, sequential_index_col = array_value.promote_offsets()
index_cols = [sequential_index_col]
index_names = [None]
value_columns = [col for col in array_value.column_ids if col not in index_cols]
if names is not None:
assert rename_to_schema is not None
schema_to_rename = {value: key for key, value in rename_to_schema.items()}
if index_col != bigframes.enums.DefaultIndexKind.SEQUENTIAL_INT64:
index_names = [
schema_to_rename.get(index_col, index_col)
for index_col in index_cols
]
value_columns = [schema_to_rename.get(col, col) for col in value_columns]
block = blocks.Block(
array_value,
index_columns=index_cols,
column_labels=value_columns,
index_labels=index_names,
)