forked from googleapis/python-bigquery-dataframes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
1950 lines (1685 loc) · 75.1 KB
/
Copy path__init__.py
File metadata and controls
1950 lines (1685 loc) · 75.1 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.
"""Session manages the connection to BigQuery."""
from __future__ import annotations
import copy
import datetime
import logging
import os
import re
import typing
from typing import (
Any,
Callable,
Dict,
IO,
Iterable,
List,
Literal,
Mapping,
MutableSequence,
Optional,
Sequence,
Tuple,
Union,
)
import warnings
# Even though the ibis.backends.bigquery import is unused, it's needed
# to register new and replacement ops with the Ibis BigQuery backend.
import bigframes_vendored.ibis.backends.bigquery # noqa
import bigframes_vendored.pandas.io.gbq as third_party_pandas_gbq
import bigframes_vendored.pandas.io.parquet as third_party_pandas_parquet
import bigframes_vendored.pandas.io.parsers.readers as third_party_pandas_readers
import bigframes_vendored.pandas.io.pickle as third_party_pandas_pickle
import google.api_core.client_info
import google.api_core.client_options
import google.api_core.exceptions
import google.api_core.gapic_v1.client_info
import google.auth.credentials
import google.cloud.bigquery as bigquery
import google.cloud.bigquery.table
import google.cloud.bigquery_connection_v1
import google.cloud.bigquery_storage_v1
import google.cloud.functions_v2
import google.cloud.resourcemanager_v3
import google.cloud.storage as storage # type: ignore
import ibis
import ibis.backends.bigquery as ibis_bigquery
import ibis.expr.types as ibis_types
import numpy as np
import pandas
from pandas._typing import (
CompressionOptions,
FilePath,
ReadPickleBuffer,
StorageOptions,
)
import pyarrow as pa
import bigframes._config.bigquery_options as bigquery_options
import bigframes.clients
import bigframes.constants as constants
import bigframes.core as core
import bigframes.core.blocks as blocks
import bigframes.core.compile
import bigframes.core.nodes as nodes
from bigframes.core.ordering import IntegerEncoding
import bigframes.core.ordering as order
import bigframes.core.tree_properties as traversals
import bigframes.core.tree_properties as tree_properties
import bigframes.core.utils as utils
import bigframes.dtypes
import bigframes.formatting_helpers as formatting_helpers
from bigframes.functions.remote_function import read_gbq_function as bigframes_rgf
from bigframes.functions.remote_function import remote_function as bigframes_rf
import bigframes.session._io.bigquery as bigframes_io
import bigframes.session._io.bigquery.read_gbq_table as bf_read_gbq_table
import bigframes.session.clients
import bigframes.version
# Avoid circular imports.
if typing.TYPE_CHECKING:
import bigframes.core.indexes
import bigframes.dataframe as dataframe
import bigframes.series
_BIGFRAMES_DEFAULT_CONNECTION_ID = "bigframes-default-connection"
_MAX_CLUSTER_COLUMNS = 4
# TODO(swast): Need to connect to regional endpoints when performing remote
# functions operations (BQ Connection IAM, Cloud Run / Cloud Functions).
# Also see if resource manager client library supports regional endpoints.
_VALID_ENCODINGS = {
"UTF-8",
"ISO-8859-1",
"UTF-16BE",
"UTF-16LE",
"UTF-32BE",
"UTF-32LE",
}
# BigQuery has 1 MB query size limit. Don't want to take up more than a few % of that inlining a table.
# Also must assume that text encoding as literals is much less efficient than in-memory representation.
MAX_INLINE_DF_BYTES = 5000
# Max complexity that should be executed as a single query
QUERY_COMPLEXITY_LIMIT = 1e7
# Number of times to factor out subqueries before giving up.
MAX_SUBTREE_FACTORINGS = 5
logger = logging.getLogger(__name__)
# Excludes geography, bytes, and nested (array, struct) datatypes
INLINABLE_DTYPES: Sequence[bigframes.dtypes.Dtype] = (
pandas.BooleanDtype(),
pandas.Float64Dtype(),
pandas.Int64Dtype(),
pandas.StringDtype(storage="pyarrow"),
pandas.ArrowDtype(pa.date32()),
pandas.ArrowDtype(pa.time64("us")),
pandas.ArrowDtype(pa.timestamp("us")),
pandas.ArrowDtype(pa.timestamp("us", tz="UTC")),
pandas.ArrowDtype(pa.decimal128(38, 9)),
pandas.ArrowDtype(pa.decimal256(76, 38)),
)
def _is_query(query_or_table: str) -> bool:
"""Determine if `query_or_table` is a table ID or a SQL string"""
return re.search(r"\s", query_or_table.strip(), re.MULTILINE) is not None
def _is_table_with_wildcard_suffix(query_or_table: str) -> bool:
"""Determine if `query_or_table` is a table and contains a wildcard suffix."""
return not _is_query(query_or_table) and query_or_table.endswith("*")
class Session(
third_party_pandas_gbq.GBQIOMixin,
third_party_pandas_parquet.ParquetIOMixin,
third_party_pandas_pickle.PickleIOMixin,
third_party_pandas_readers.ReaderIOMixin,
):
"""Establishes a BigQuery connection to capture a group of job activities related to
DataFrames.
Args:
context (bigframes._config.bigquery_options.BigQueryOptions):
Configuration adjusting how to connect to BigQuery and related
APIs. Note that some options are ignored if ``clients_provider`` is
set.
clients_provider (bigframes.session.clients.ClientsProvider):
An object providing client library objects.
"""
def __init__(
self,
context: Optional[bigquery_options.BigQueryOptions] = None,
clients_provider: Optional[bigframes.session.clients.ClientsProvider] = None,
):
if context is None:
context = bigquery_options.BigQueryOptions()
# TODO(swast): Get location from the environment.
if context.location is None:
self._location = "US"
warnings.warn(
f"No explicit location is set, so using location {self._location} for the session.",
stacklevel=2,
)
else:
self._location = context.location
self._bq_kms_key_name = context.kms_key_name
# Instantiate a clients provider to help with cloud clients that will be
# used in the future operations in the session
if clients_provider:
self._clients_provider = clients_provider
else:
self._clients_provider = bigframes.session.clients.ClientsProvider(
project=context.project,
location=self._location,
use_regional_endpoints=context.use_regional_endpoints,
credentials=context.credentials,
application_name=context.application_name,
bq_kms_key_name=self._bq_kms_key_name,
)
self._create_bq_datasets()
# TODO(shobs): Remove this logic after https://github.com/ibis-project/ibis/issues/8494
# has been fixed. The ibis client changes the default query job config
# so we are going to remember the current config and restore it after
# the ibis client has been created
original_default_query_job_config = self.bqclient.default_query_job_config
self.ibis_client = typing.cast(
ibis_bigquery.Backend,
ibis.bigquery.connect(
project_id=context.project,
client=self.bqclient,
storage_client=self.bqstoragereadclient,
),
)
self.bqclient.default_query_job_config = original_default_query_job_config
# Resolve the BQ connection for remote function and Vertex AI integration
self._bq_connection = context.bq_connection or _BIGFRAMES_DEFAULT_CONNECTION_ID
self._skip_bq_connection_check = context._skip_bq_connection_check
# Now that we're starting the session, don't allow the options to be
# changed.
context._session_started = True
self._df_snapshot: Dict[
bigquery.TableReference, Tuple[datetime.datetime, bigquery.Table]
] = {}
@property
def bqclient(self):
return self._clients_provider.bqclient
@property
def bqconnectionclient(self):
return self._clients_provider.bqconnectionclient
@property
def bqstoragereadclient(self):
return self._clients_provider.bqstoragereadclient
@property
def cloudfunctionsclient(self):
return self._clients_provider.cloudfunctionsclient
@property
def resourcemanagerclient(self):
return self._clients_provider.resourcemanagerclient
_bq_connection_manager: Optional[bigframes.clients.BqConnectionManager] = None
@property
def bqconnectionmanager(self):
if not self._skip_bq_connection_check and not self._bq_connection_manager:
self._bq_connection_manager = bigframes.clients.BqConnectionManager(
self.bqconnectionclient, self.resourcemanagerclient
)
return self._bq_connection_manager
@property
def _project(self):
return self.bqclient.project
def __hash__(self):
# Stable hash needed to use in expression tree
return hash(str(self._anonymous_dataset))
def _create_bq_datasets(self):
"""Create and identify dataset(s) for temporary BQ resources."""
query_job = self.bqclient.query("SELECT 1", location=self._location)
query_job.result() # blocks until finished
# The anonymous dataset is used by BigQuery to write query results and
# session tables. BigQuery DataFrames also writes temp tables directly
# to the dataset, no BigQuery Session required. Note: there is a
# different anonymous dataset per location. See:
# https://cloud.google.com/bigquery/docs/cached-results#how_cached_results_are_stored
query_destination = query_job.destination
self._anonymous_dataset = bigquery.DatasetReference(
query_destination.project,
query_destination.dataset_id,
)
def close(self):
"""No-op. Temporary resources are deleted after 7 days."""
def read_gbq(
self,
query_or_table: str,
*,
index_col: Iterable[str] | str = (),
columns: Iterable[str] = (),
configuration: Optional[Dict] = None,
max_results: Optional[int] = None,
filters: third_party_pandas_gbq.FiltersType = (),
use_cache: Optional[bool] = None,
col_order: Iterable[str] = (),
# Add a verify index argument that fails if the index is not unique.
) -> dataframe.DataFrame:
# TODO(b/281571214): Generate prompt to show the progress of read_gbq.
if columns and col_order:
raise ValueError(
"Must specify either columns (preferred) or col_order, not both"
)
elif col_order:
columns = col_order
filters = list(filters)
if len(filters) != 0 or _is_table_with_wildcard_suffix(query_or_table):
query_or_table = self._to_query(query_or_table, columns, filters)
if _is_query(query_or_table):
return self._read_gbq_query(
query_or_table,
index_col=index_col,
columns=columns,
configuration=configuration,
max_results=max_results,
api_name="read_gbq",
use_cache=use_cache,
)
else:
# TODO(swast): Query the snapshot table but mark it as a
# deterministic query so we can avoid serializing if we have a
# unique index.
if configuration is not None:
raise ValueError(
"The 'configuration' argument is not allowed when "
"directly reading from a table. Please remove "
"'configuration' or use a query."
)
return self._read_gbq_table(
query_or_table,
index_col=index_col,
columns=columns,
max_results=max_results,
api_name="read_gbq",
use_cache=use_cache if use_cache is not None else True,
)
def _to_query(
self,
query_or_table: str,
columns: Iterable[str],
filters: third_party_pandas_gbq.FiltersType,
) -> str:
"""Compile query_or_table with conditions(filters, wildcards) to query."""
filters = list(filters)
sub_query = (
f"({query_or_table})"
if _is_query(query_or_table)
else f"`{query_or_table}`"
)
select_clause = "SELECT " + (
", ".join(f"`{column}`" for column in columns) if columns else "*"
)
where_clause = ""
if filters:
valid_operators: Mapping[third_party_pandas_gbq.FilterOps, str] = {
"in": "IN",
"not in": "NOT IN",
"LIKE": "LIKE",
"==": "=",
">": ">",
"<": "<",
">=": ">=",
"<=": "<=",
"!=": "!=",
}
# If single layer filter, add another pseudo layer. So the single layer represents "and" logic.
if isinstance(filters[0], tuple) and (
len(filters[0]) == 0 or not isinstance(list(filters[0])[0], tuple)
):
filters = typing.cast(third_party_pandas_gbq.FiltersType, [filters])
or_expressions = []
for group in filters:
if not isinstance(group, Iterable):
group = [group]
and_expressions = []
for filter_item in group:
if not isinstance(filter_item, tuple) or (len(filter_item) != 3):
raise ValueError(
f"Filter condition should be a tuple of length 3, {filter_item} is not valid."
)
column, operator, value = filter_item
if not isinstance(column, str):
raise ValueError(
f"Column name should be a string, but received '{column}' of type {type(column).__name__}."
)
if operator not in valid_operators:
raise ValueError(f"Operator {operator} is not valid.")
operator_str = valid_operators[operator]
if operator_str in ["IN", "NOT IN"]:
value_list = ", ".join([repr(v) for v in value])
expression = f"`{column}` {operator_str} ({value_list})"
else:
expression = f"`{column}` {operator_str} {repr(value)}"
and_expressions.append(expression)
or_expressions.append(" AND ".join(and_expressions))
if or_expressions:
where_clause = " WHERE " + " OR ".join(or_expressions)
full_query = f"{select_clause} FROM {sub_query} AS sub{where_clause}"
return full_query
def _query_to_destination(
self,
query: str,
index_cols: List[str],
api_name: str,
configuration: dict = {"query": {"useQueryCache": True}},
do_clustering=True,
) -> Tuple[Optional[bigquery.TableReference], bigquery.QueryJob]:
# If a dry_run indicates this is not a query type job, then don't
# bother trying to do a CREATE TEMP TABLE ... AS SELECT ... statement.
dry_run_config = bigquery.QueryJobConfig()
dry_run_config.dry_run = True
_, dry_run_job = self._start_query(query, job_config=dry_run_config)
if dry_run_job.statement_type != "SELECT":
_, query_job = self._start_query(query)
return query_job.destination, query_job
# Create a table to workaround BigQuery 10 GB query results limit. See:
# internal issue 303057336.
# Since we have a `statement_type == 'SELECT'`, schema should be populated.
schema = typing.cast(Iterable[bigquery.SchemaField], dry_run_job.schema)
if do_clustering:
cluster_cols = [
item.name
for item in schema
if (item.name in index_cols) and _can_cluster_bq(item)
][:_MAX_CLUSTER_COLUMNS]
else:
cluster_cols = []
temp_table = self._create_empty_temp_table(schema, cluster_cols)
timeout_ms = configuration.get("jobTimeoutMs") or configuration["query"].get(
"timeoutMs"
)
# Convert timeout_ms to seconds, ensuring a minimum of 0.1 seconds to avoid
# the program getting stuck on too-short timeouts.
timeout = max(int(timeout_ms) * 1e-3, 0.1) if timeout_ms else None
job_config = typing.cast(
bigquery.QueryJobConfig,
bigquery.QueryJobConfig.from_api_repr(configuration),
)
job_config.labels["bigframes-api"] = api_name
job_config.destination = temp_table
try:
# Write to temp table to workaround BigQuery 10 GB query results
# limit. See: internal issue 303057336.
job_config.labels["error_caught"] = "true"
_, query_job = self._start_query(
query, job_config=job_config, timeout=timeout
)
return query_job.destination, query_job
except google.api_core.exceptions.BadRequest:
# Some SELECT statements still aren't compatible with cluster
# tables as the destination. For example, if the query has a
# top-level ORDER BY, this conflicts with our ability to cluster
# the table by the index column(s).
_, query_job = self._start_query(query, timeout=timeout)
return query_job.destination, query_job
def read_gbq_query(
self,
query: str,
*,
index_col: Iterable[str] | str = (),
columns: Iterable[str] = (),
configuration: Optional[Dict] = None,
max_results: Optional[int] = None,
use_cache: Optional[bool] = None,
col_order: Iterable[str] = (),
) -> dataframe.DataFrame:
"""Turn a SQL query into a DataFrame.
Note: Because the results are written to a temporary table, ordering by
``ORDER BY`` is not preserved. A unique `index_col` is recommended. Use
``row_number() over ()`` if there is no natural unique index or you
want to preserve ordering.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.display.progress_bar = None
Simple query input:
>>> df = bpd.read_gbq_query('''
... SELECT
... pitcherFirstName,
... pitcherLastName,
... pitchSpeed,
... FROM `bigquery-public-data.baseball.games_wide`
... ''')
Preserve ordering in a query input.
>>> df = bpd.read_gbq_query('''
... SELECT
... -- Instead of an ORDER BY clause on the query, use
... -- ROW_NUMBER() to create an ordered DataFrame.
... ROW_NUMBER() OVER (ORDER BY AVG(pitchSpeed) DESC)
... AS rowindex,
...
... pitcherFirstName,
... pitcherLastName,
... AVG(pitchSpeed) AS averagePitchSpeed
... FROM `bigquery-public-data.baseball.games_wide`
... WHERE year = 2016
... GROUP BY pitcherFirstName, pitcherLastName
... ''', index_col="rowindex")
>>> df.head(2)
pitcherFirstName pitcherLastName averagePitchSpeed
rowindex
1 Albertin Chapman 96.514113
2 Zachary Britton 94.591039
<BLANKLINE>
[2 rows x 3 columns]
See also: :meth:`Session.read_gbq`.
"""
# NOTE: This method doesn't (yet) exist in pandas or pandas-gbq, so
# these docstrings are inline.
if columns and col_order:
raise ValueError(
"Must specify either columns (preferred) or col_order, not both"
)
elif col_order:
columns = col_order
return self._read_gbq_query(
query=query,
index_col=index_col,
columns=columns,
configuration=configuration,
max_results=max_results,
api_name="read_gbq_query",
use_cache=use_cache,
)
def _read_gbq_query(
self,
query: str,
*,
index_col: Iterable[str] | str = (),
columns: Iterable[str] = (),
configuration: Optional[Dict] = None,
max_results: Optional[int] = None,
api_name: str = "read_gbq_query",
use_cache: Optional[bool] = None,
) -> dataframe.DataFrame:
import bigframes.dataframe as dataframe
configuration = _transform_read_gbq_configuration(configuration)
if "query" not in configuration:
configuration["query"] = {}
if "query" in configuration["query"]:
raise ValueError(
"The query statement must not be included in the ",
"'configuration' because it is already provided as",
" a separate parameter.",
)
if "useQueryCache" in configuration["query"]:
if use_cache is not None:
raise ValueError(
"'useQueryCache' in 'configuration' conflicts with"
" 'use_cache' parameter. Please specify only one."
)
else:
configuration["query"]["useQueryCache"] = (
True if use_cache is None else use_cache
)
if isinstance(index_col, str):
index_cols = [index_col]
else:
index_cols = list(index_col)
destination, query_job = self._query_to_destination(
query,
index_cols,
api_name=api_name,
configuration=configuration,
)
# If there was no destination table, that means the query must have
# been DDL or DML. Return some job metadata, instead.
if not destination:
return dataframe.DataFrame(
data=pandas.DataFrame(
{
"statement_type": [
query_job.statement_type if query_job else "unknown"
],
"job_id": [query_job.job_id if query_job else "unknown"],
"location": [query_job.location if query_job else "unknown"],
}
),
session=self,
)
return self.read_gbq_table(
f"{destination.project}.{destination.dataset_id}.{destination.table_id}",
index_col=index_cols,
columns=columns,
max_results=max_results,
use_cache=configuration["query"]["useQueryCache"],
)
def read_gbq_table(
self,
query: str,
*,
index_col: Iterable[str] | str = (),
columns: Iterable[str] = (),
max_results: Optional[int] = None,
filters: third_party_pandas_gbq.FiltersType = (),
use_cache: bool = True,
col_order: Iterable[str] = (),
) -> dataframe.DataFrame:
"""Turn a BigQuery table into a DataFrame.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.display.progress_bar = None
Read a whole table, with arbitrary ordering or ordering corresponding to the primary key(s).
>>> df = bpd.read_gbq_table("bigquery-public-data.ml_datasets.penguins")
See also: :meth:`Session.read_gbq`.
"""
# NOTE: This method doesn't (yet) exist in pandas or pandas-gbq, so
# these docstrings are inline.
if columns and col_order:
raise ValueError(
"Must specify either columns (preferred) or col_order, not both"
)
elif col_order:
columns = col_order
filters = list(filters)
if len(filters) != 0 or _is_table_with_wildcard_suffix(query):
query = self._to_query(query, columns, filters)
return self._read_gbq_query(
query,
index_col=index_col,
columns=columns,
max_results=max_results,
api_name="read_gbq_table",
use_cache=use_cache,
)
return self._read_gbq_table(
query=query,
index_col=index_col,
columns=columns,
max_results=max_results,
api_name="read_gbq_table",
use_cache=use_cache,
)
def _read_gbq_table(
self,
query: str,
*,
index_col: Iterable[str] | str = (),
columns: Iterable[str] = (),
max_results: Optional[int] = None,
api_name: str,
use_cache: bool = True,
) -> dataframe.DataFrame:
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}."
)
table_ref = bigquery.table.TableReference.from_string(
query, default_project=self.bqclient.project
)
# ---------------------------------
# Fetch table metadata and validate
# ---------------------------------
(time_travel_timestamp, table,) = bf_read_gbq_table.get_table_metadata(
self.bqclient,
table_ref=table_ref,
api_name=api_name,
cache=self._df_snapshot,
use_cache=use_cache,
)
if table.location.casefold() != self._location.casefold():
raise ValueError(
f"Current session is in {self._location} but dataset '{table.project}.{table.dataset_id}' is located in {table.location}"
)
# -----------------------------------------
# Create Ibis table expression and validate
# -----------------------------------------
# Use a time travel to make sure the DataFrame is deterministic, even
# if the underlying table changes.
table_expression = bf_read_gbq_table.get_ibis_time_travel_table(
self.ibis_client,
table_ref,
time_travel_timestamp,
)
for key in columns:
if key not in table_expression.columns:
raise ValueError(
f"Column '{key}' of `columns` not found in this table."
)
# ---------------------------------------
# Create a non-default index and validate
# ---------------------------------------
# TODO(b/337925142): Move index_cols creation to before we create the
# Ibis table expression so we don't have a "SELECT *" subquery in the
# query that checks for index uniqueness.
index_cols, is_index_unique = bf_read_gbq_table.get_index_cols_and_uniqueness(
bqclient=self.bqclient,
ibis_client=self.ibis_client,
table=table,
table_expression=table_expression,
index_col=index_col,
api_name=api_name,
)
for key in index_cols:
if key not in table_expression.columns:
raise ValueError(
f"Column `{key}` of `index_col` not found in this table."
)
# TODO(b/337925142): We should push down column filters when we get the time
# travel table to avoid "SELECT *" subqueries.
if columns:
table_expression = table_expression.select([*index_cols, *columns])
# ----------------------------
# Create ordering and validate
# ----------------------------
if is_index_unique:
array_value = bf_read_gbq_table.to_array_value_with_total_ordering(
session=self,
table_expression=table_expression,
total_ordering_cols=index_cols,
)
else:
# Note: Even though we're adding a default ordering here, that's
# just so we have a deterministic total ordering. If the user
# specified a non-unique index, we still sort by that later.
array_value = bf_read_gbq_table.to_array_value_with_default_ordering(
session=self, table=table_expression, table_rows=table.num_rows
)
# ----------------------------------------------------
# Create Block & default index if len(index_cols) == 0
# ----------------------------------------------------
value_columns = [col for col in array_value.column_ids if col not in index_cols]
block = blocks.Block(
array_value,
index_columns=index_cols,
column_labels=value_columns,
index_labels=index_cols,
)
if max_results:
block = block.slice(stop=max_results)
df = dataframe.DataFrame(block)
# If user provided index columns, should sort over it
if len(index_cols) > 0:
df.sort_index()
return df
def _read_bigquery_load_job(
self,
filepath_or_buffer: str | IO["bytes"],
table: Union[bigquery.Table, bigquery.TableReference],
*,
job_config: bigquery.LoadJobConfig,
index_col: Iterable[str] | str = (),
columns: Iterable[str] = (),
) -> dataframe.DataFrame:
if isinstance(index_col, str):
index_cols = [index_col]
else:
index_cols = list(index_col)
if not job_config.clustering_fields and index_cols:
job_config.clustering_fields = index_cols[:_MAX_CLUSTER_COLUMNS]
if isinstance(filepath_or_buffer, str):
if filepath_or_buffer.startswith("gs://"):
load_job = self.bqclient.load_table_from_uri(
filepath_or_buffer, table, job_config=job_config
)
else:
with open(filepath_or_buffer, "rb") as source_file:
load_job = self.bqclient.load_table_from_file(
source_file, table, job_config=job_config
)
else:
load_job = self.bqclient.load_table_from_file(
filepath_or_buffer, table, job_config=job_config
)
self._start_generic_job(load_job)
table_id = f"{table.project}.{table.dataset_id}.{table.table_id}"
# Update the table expiration so we aren't limited to the default 24
# hours of the anonymous dataset.
table_expiration = bigquery.Table(table_id)
table_expiration.expires = (
datetime.datetime.now(datetime.timezone.utc) + constants.DEFAULT_EXPIRATION
)
self.bqclient.update_table(table_expiration, ["expires"])
# The BigQuery REST API for tables.get doesn't take a session ID, so we
# can't get the schema for a temp table that way.
return self.read_gbq_table(
table_id,
index_col=index_col,
columns=columns,
)
def read_gbq_model(self, model_name: str):
"""Loads a BigQuery ML model from BigQuery.
**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.display.progress_bar = None
Read an existing BigQuery ML model.
>>> model_name = "bigframes-dev.bqml_tutorial.penguins_model"
>>> model = bpd.read_gbq_model(model_name)
Args:
model_name (str):
the model's name in BigQuery in the format
`project_id.dataset_id.model_id`, or just `dataset_id.model_id`
to load from the default project.
Returns:
A bigframes.ml Model, Transformer or Pipeline wrapping the model.
"""
import bigframes.ml.loader
model_ref = bigquery.ModelReference.from_string(
model_name, default_project=self.bqclient.project
)
model = self.bqclient.get_model(model_ref)
return bigframes.ml.loader.from_bq(self, model)
@typing.overload
def read_pandas(
self, pandas_dataframe: pandas.Index
) -> bigframes.core.indexes.Index:
...
@typing.overload
def read_pandas(self, pandas_dataframe: pandas.Series) -> bigframes.series.Series:
...
@typing.overload
def read_pandas(self, pandas_dataframe: pandas.DataFrame) -> dataframe.DataFrame:
...
def read_pandas(
self, pandas_dataframe: Union[pandas.DataFrame, pandas.Series, pandas.Index]
):
"""Loads DataFrame from a pandas DataFrame.
The pandas DataFrame will be persisted as a temporary BigQuery table, which can be
automatically recycled after the Session is closed.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import pandas as pd
>>> bpd.options.display.progress_bar = None
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> pandas_df = pd.DataFrame(data=d)
>>> df = bpd.read_pandas(pandas_df)
>>> df
col1 col2
0 1 3
1 2 4
<BLANKLINE>
[2 rows x 2 columns]
Args:
pandas_dataframe (pandas.DataFrame, pandas.Series, or pandas.Index):
a pandas DataFrame/Series/Index object to be loaded.
Returns:
An equivalent bigframes.pandas.(DataFrame/Series/Index) object
"""
import bigframes.series as series
# Try to handle non-dataframe pandas objects as well
if isinstance(pandas_dataframe, pandas.Series):
bf_df = self._read_pandas(pandas.DataFrame(pandas_dataframe), "read_pandas")
bf_series = typing.cast(series.Series, bf_df[bf_df.columns[0]])
# wrapping into df can set name to 0 so reset to original object name
bf_series.name = pandas_dataframe.name
return bf_series
if isinstance(pandas_dataframe, pandas.Index):
return self._read_pandas(
pandas.DataFrame(index=pandas_dataframe), "read_pandas"
).index
if isinstance(pandas_dataframe, pandas.DataFrame):
return self._read_pandas(pandas_dataframe, "read_pandas")
else:
raise ValueError(
f"read_pandas() expects a pandas.DataFrame, but got a {type(pandas_dataframe)}"
)
def _read_pandas(
self, pandas_dataframe: pandas.DataFrame, api_name: str
) -> dataframe.DataFrame:
import bigframes.dataframe as dataframe
if isinstance(pandas_dataframe, dataframe.DataFrame):
raise ValueError(
"read_pandas() expects a pandas.DataFrame, but got a "
"bigframes.pandas.DataFrame."
)
inline_df = self._read_pandas_inline(pandas_dataframe)
if inline_df is not None:
return inline_df
try:
return self._read_pandas_load_job(pandas_dataframe, api_name)
except pa.ArrowInvalid as e:
raise pa.ArrowInvalid(
f"Could not convert with a BigQuery type: `{e}`. "
) from e
def _read_pandas_inline(
self, pandas_dataframe: pandas.DataFrame
) -> Optional[dataframe.DataFrame]:
import bigframes.dataframe as dataframe
if pandas_dataframe.memory_usage(deep=True).sum() > MAX_INLINE_DF_BYTES:
return None
try:
inline_df = dataframe.DataFrame(
blocks.Block.from_local(pandas_dataframe, self)
)
except pa.ArrowInvalid as e:
raise pa.ArrowInvalid(
f"Could not convert with a BigQuery type: `{e}`. "
) from e