-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy path__init__.py
1414 lines (1229 loc) · 56.5 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 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 logging
import os
import secrets
import typing
from typing import (
Any,
Callable,
Dict,
IO,
Iterable,
Literal,
Mapping,
MutableSequence,
Optional,
Sequence,
Tuple,
Union,
)
import warnings
import weakref
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.cloud.bigquery as bigquery
import google.cloud.storage as storage # type: ignore
import ibis
import ibis.backends.bigquery as ibis_bigquery
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.guid
import bigframes.core.pruning
# 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.dataframe
import bigframes.dtypes
import bigframes.exceptions
import bigframes.formatting_helpers as formatting_helpers
import bigframes.functions._remote_function_session as bigframes_rf_session
import bigframes.functions.remote_function as bigframes_rf
import bigframes.session._io.bigquery as bf_io_bigquery
import bigframes.session.clients
import bigframes.session.executor
import bigframes.session.loader
import bigframes.session.metrics
import bigframes.session.planner
import bigframes.session.temp_storage
import bigframes.version
# Avoid circular imports.
if typing.TYPE_CHECKING:
import bigframes.core.indexes
import bigframes.dataframe as dataframe
import bigframes.series
import bigframes.streaming.dataframe as streaming_dataframe
_BIGFRAMES_DEFAULT_CONNECTION_ID = "bigframes-default-connection"
# 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
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)),
)
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()
if context.location is None:
self._location = "US"
warnings.warn(
f"No explicit location is set, so using location {self._location} for the session.",
# User's code
# -> get_global_session()
# -> connect()
# -> Session()
#
# Note: We could also have:
# User's code
# -> read_gbq()
# -> with_default_session()
# -> get_global_session()
# -> connect()
# -> Session()
# but we currently have no way to disambiguate these
# situations.
stacklevel=4,
category=bigframes.exceptions.DefaultLocationWarning,
)
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,
)
# 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
# Only used to fetch remote function metadata.
# TODO: Remove in favor of raw bq client
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
# unique session identifier, short enough to be human readable
# only needs to be unique among sessions created by the same user
# at the same time in the same region
self._session_id: str = "session" + secrets.token_hex(3)
# store table ids and delete them when the session is closed
self._objects: list[
weakref.ReferenceType[
Union[
bigframes.core.indexes.Index,
bigframes.series.Series,
dataframe.DataFrame,
]
]
] = []
# Whether this session treats objects as totally ordered.
# Will expose as feature later, only False for internal testing
self._strictly_ordered: bool = context.ordering_mode != "partial"
if not self._strictly_ordered:
warnings.warn(
"Partial ordering mode is a preview feature and is subject to change.",
bigframes.exceptions.OrderingModePartialPreviewWarning,
)
self._allow_ambiguity = not self._strictly_ordered
self._default_index_type = (
bigframes.enums.DefaultIndexKind.SEQUENTIAL_INT64
if self._strictly_ordered
else bigframes.enums.DefaultIndexKind.NULL
)
self._metrics = bigframes.session.metrics.ExecutionMetrics()
self._remote_function_session = bigframes_rf_session.RemoteFunctionSession()
self._temp_storage_manager = (
bigframes.session.temp_storage.TemporaryGbqStorageManager(
self._clients_provider.bqclient,
location=self._location,
session_id=self._session_id,
kms_key=self._bq_kms_key_name,
)
)
self._executor = bigframes.session.executor.BigQueryCachingExecutor(
bqclient=self._clients_provider.bqclient,
storage_manager=self._temp_storage_manager,
strictly_ordered=self._strictly_ordered,
metrics=self._metrics,
)
self._loader = bigframes.session.loader.GbqDataLoader(
session=self,
bqclient=self._clients_provider.bqclient,
storage_manager=self._temp_storage_manager,
default_index_type=self._default_index_type,
scan_index_uniqueness=self._strictly_ordered,
metrics=self._metrics,
)
@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 session_id(self):
return self._session_id
@property
def objects(
self,
) -> Iterable[
Union[
bigframes.core.indexes.Index, bigframes.series.Series, dataframe.DataFrame
]
]:
still_alive = [i for i in self._objects if i() is not None]
self._objects = still_alive
# Create a set with strong references, be careful not to hold onto this needlessly, as will prevent garbage collection.
return tuple(i() for i in self._objects if i() is not None) # type: ignore
@property
def _project(self):
return self.bqclient.project
@property
def bytes_processed_sum(self):
"""The sum of all bytes processed by bigquery jobs using this session."""
return self._metrics.bytes_processed
@property
def slot_millis_sum(self):
"""The sum of all slot time used by bigquery jobs in this session."""
return self._metrics.slot_millis
@property
def _allows_ambiguity(self) -> bool:
return self._allow_ambiguity
@property
def _anonymous_dataset(self):
return self._temp_storage_manager.dataset
def __hash__(self):
# Stable hash needed to use in expression tree
return hash(str(self._session_id))
def close(self):
"""Delete resources that were created with this session's session_id.
This includes BigQuery tables, remote functions and cloud functions
serving the remote functions."""
self._temp_storage_manager.clean_up_tables()
self._remote_function_session.clean_up(
self.bqclient, self.cloudfunctionsclient, self.session_id
)
def read_gbq(
self,
query_or_table: str,
*,
index_col: Iterable[str] | str | bigframes.enums.DefaultIndexKind = (),
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
if bf_io_bigquery.is_query(query_or_table):
return self._loader.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,
filters=filters,
)
else:
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._loader.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,
filters=filters,
)
def _register_object(
self,
object: Union[
bigframes.core.indexes.Index, bigframes.series.Series, dataframe.DataFrame
],
):
self._objects.append(weakref.ref(object))
def read_gbq_query(
self,
query: str,
*,
index_col: Iterable[str] | str | bigframes.enums.DefaultIndexKind = (),
columns: Iterable[str] = (),
configuration: Optional[Dict] = None,
max_results: Optional[int] = None,
use_cache: Optional[bool] = None,
col_order: Iterable[str] = (),
filters: third_party_pandas_gbq.FiltersType = (),
) -> 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._loader.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,
filters=filters,
)
def read_gbq_table(
self,
query: str,
*,
index_col: Iterable[str] | str | bigframes.enums.DefaultIndexKind = (),
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
return self._loader.read_gbq_table(
query=query,
index_col=index_col,
columns=columns,
max_results=max_results,
api_name="read_gbq_table",
use_cache=use_cache,
filters=filters,
)
def read_gbq_table_streaming(
self, table: str
) -> streaming_dataframe.StreamingDataFrame:
"""Turn a BigQuery table into a StreamingDataFrame.
.. note::
The bigframes.streaming module is a preview feature, and subject to change.
**Examples:**
>>> import bigframes.streaming as bst
>>> import bigframes.pandas as bpd
>>> bpd.options.display.progress_bar = None
>>> sdf = bst.read_gbq_table("bigquery-public-data.ml_datasets.penguins")
"""
warnings.warn(
"The bigframes.streaming module is a preview feature, and subject to change.",
stacklevel=1,
category=bigframes.exceptions.PreviewWarning,
)
import bigframes.streaming.dataframe as streaming_dataframe
df = self._loader.read_gbq_table(
table,
api_name="read_gbq_table_steaming",
enable_snapshot=False,
index_col=bigframes.enums.DefaultIndexKind.NULL,
)
return streaming_dataframe.StreamingDataFrame._from_table_df(df)
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.
.. note::
Data is inlined in the query SQL if it is small enough (roughly 5MB
or less in memory). Larger size data is loaded to a BigQuery table
instead.
**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 = series.Series(bf_df._block)
# 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._loader.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:
local_block = blocks.Block.from_local(pandas_dataframe, self)
inline_df = dataframe.DataFrame(local_block)
except pa.ArrowInvalid as e:
raise pa.ArrowInvalid(
f"Could not convert with a BigQuery type: `{e}`. "
) from e
except ValueError: # Thrown by ibis for some unhandled types
return None
except pa.ArrowTypeError: # Thrown by arrow for types without mapping (geo).
return None
inline_types = inline_df._block.expr.schema.dtypes
# Ibis has problems escaping bytes literals, which will cause syntax errors server-side.
if all(dtype in INLINABLE_DTYPES for dtype in inline_types):
return inline_df
return None
def read_csv(
self,
filepath_or_buffer: str | IO["bytes"],
*,
sep: Optional[str] = ",",
header: Optional[int] = 0,
names: Optional[
Union[MutableSequence[Any], np.ndarray[Any, Any], Tuple[Any, ...], range]
] = None,
index_col: Optional[
Union[
int,
str,
Sequence[Union[str, int]],
bigframes.enums.DefaultIndexKind,
Literal[False],
]
] = None,
usecols: Optional[
Union[
MutableSequence[str],
Tuple[str, ...],
Sequence[int],
pandas.Series,
pandas.Index,
np.ndarray[Any, Any],
Callable[[Any], bool],
]
] = None,
dtype: Optional[Dict] = None,
engine: Optional[
Literal["c", "python", "pyarrow", "python-fwf", "bigquery"]
] = None,
encoding: Optional[str] = None,
**kwargs,
) -> dataframe.DataFrame:
table = self._temp_storage_manager._random_table()
if engine is not None and engine == "bigquery":
if any(param is not None for param in (dtype, names)):
not_supported = ("dtype", "names")
raise NotImplementedError(
f"BigQuery engine does not support these arguments: {not_supported}. "
f"{constants.FEEDBACK_LINK}"
)
# TODO(b/338089659): Looks like we can relax this 1 column
# restriction if we check the contents of an iterable are strings
# not integers.
if (
# Empty tuples, None, and False are allowed and falsey.
index_col
and not isinstance(index_col, bigframes.enums.DefaultIndexKind)
and not isinstance(index_col, str)
):
raise NotImplementedError(
"BigQuery engine only supports a single column name for `index_col`, "
f"got: {repr(index_col)}. {constants.FEEDBACK_LINK}"
)
# None and False cannot be passed to read_gbq.
# TODO(b/338400133): When index_col is None, we should be using the
# first column of the CSV as the index to be compatible with the
# pandas engine. According to the pandas docs, only "False"
# indicates a default sequential index.
if not index_col:
index_col = ()
index_col = typing.cast(
Union[
Sequence[str], # Falsey values
bigframes.enums.DefaultIndexKind,
str,
],
index_col,
)
# usecols should only be an iterable of strings (column names) for use as columns in read_gbq.
columns: Tuple[Any, ...] = tuple()
if usecols is not None:
if isinstance(usecols, Iterable) and all(
isinstance(col, str) for col in usecols
):
columns = tuple(col for col in usecols)
else:
raise NotImplementedError(
"BigQuery engine only supports an iterable of strings for `usecols`. "
f"{constants.FEEDBACK_LINK}"
)
if encoding is not None and encoding not in _VALID_ENCODINGS:
raise NotImplementedError(
f"BigQuery engine only supports the following encodings: {_VALID_ENCODINGS}. "
f"{constants.FEEDBACK_LINK}"
)
job_config = bigquery.LoadJobConfig()
job_config.create_disposition = bigquery.CreateDisposition.CREATE_IF_NEEDED
job_config.source_format = bigquery.SourceFormat.CSV
job_config.write_disposition = bigquery.WriteDisposition.WRITE_EMPTY
job_config.autodetect = True
job_config.field_delimiter = sep
job_config.encoding = encoding
job_config.labels = {"bigframes-api": "read_csv"}
# We want to match pandas behavior. If header is 0, no rows should be skipped, so we
# do not need to set `skip_leading_rows`. If header is None, then there is no header.
# Setting skip_leading_rows to 0 does that. If header=N and N>0, we want to skip N rows.
if header is None:
job_config.skip_leading_rows = 0
elif header > 0:
job_config.skip_leading_rows = header
return self._loader._read_bigquery_load_job(
filepath_or_buffer,
table,
job_config=job_config,
index_col=index_col,
columns=columns,
)
else:
if isinstance(index_col, bigframes.enums.DefaultIndexKind):
raise NotImplementedError(
f"With index_col={repr(index_col)}, only engine='bigquery' is supported. "
f"{constants.FEEDBACK_LINK}"
)
if any(arg in kwargs for arg in ("chunksize", "iterator")):
raise NotImplementedError(
"'chunksize' and 'iterator' arguments are not supported. "
f"{constants.FEEDBACK_LINK}"
)
if isinstance(filepath_or_buffer, str):
self._check_file_size(filepath_or_buffer)
pandas_df = pandas.read_csv(
filepath_or_buffer,
sep=sep,
header=header,
names=names,
index_col=index_col,
usecols=usecols, # type: ignore
dtype=dtype,
engine=engine,
encoding=encoding,
**kwargs,
)
return self._read_pandas(pandas_df, "read_csv") # type: ignore
def read_pickle(
self,
filepath_or_buffer: FilePath | ReadPickleBuffer,
compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
):
pandas_obj = pandas.read_pickle(
filepath_or_buffer,
compression=compression,
storage_options=storage_options,
)
if isinstance(pandas_obj, pandas.Series):
if pandas_obj.name is None:
pandas_obj.name = "0"
bigframes_df = self._read_pandas(pandas_obj.to_frame(), "read_pickle")
return bigframes_df[bigframes_df.columns[0]]
return self._read_pandas(pandas_obj, "read_pickle")
def read_parquet(
self,
path: str | IO["bytes"],
*,
engine: str = "auto",
) -> dataframe.DataFrame:
table = self._temp_storage_manager._random_table()
if engine == "bigquery":
job_config = bigquery.LoadJobConfig()
job_config.create_disposition = bigquery.CreateDisposition.CREATE_IF_NEEDED
job_config.source_format = bigquery.SourceFormat.PARQUET
job_config.write_disposition = bigquery.WriteDisposition.WRITE_EMPTY
job_config.labels = {"bigframes-api": "read_parquet"}
return self._loader._read_bigquery_load_job(
path, table, job_config=job_config
)
else:
read_parquet_kwargs: Dict[str, Any] = {}
if pandas.__version__.startswith("1."):
read_parquet_kwargs["use_nullable_dtypes"] = True
else:
read_parquet_kwargs["dtype_backend"] = "pyarrow"
pandas_obj = pandas.read_parquet(
path,
engine=engine, # type: ignore
**read_parquet_kwargs,
)
return self._read_pandas(pandas_obj, "read_parquet")
def read_json(
self,
path_or_buf: str | IO["bytes"],
*,
orient: Literal[
"split", "records", "index", "columns", "values", "table"
] = "columns",
dtype: Optional[Dict] = None,
encoding: Optional[str] = None,
lines: bool = False,
engine: Literal["ujson", "pyarrow", "bigquery"] = "ujson",
**kwargs,
) -> dataframe.DataFrame:
table = self._temp_storage_manager._random_table()
if engine == "bigquery":
if dtype is not None:
raise NotImplementedError(
"BigQuery engine does not support the dtype arguments."
)
if not lines:
raise NotImplementedError(
"Only newline delimited JSON format is supported."
)
if encoding is not None and encoding not in _VALID_ENCODINGS:
raise NotImplementedError(
f"BigQuery engine only supports the following encodings: {_VALID_ENCODINGS}"
)
if lines and orient != "records":
raise ValueError(
"'lines' keyword is only valid when 'orient' is 'records'."
)
job_config = bigquery.LoadJobConfig()
job_config.create_disposition = bigquery.CreateDisposition.CREATE_IF_NEEDED
job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON
job_config.write_disposition = bigquery.WriteDisposition.WRITE_EMPTY
job_config.autodetect = True
job_config.encoding = encoding
job_config.labels = {"bigframes-api": "read_json"}
return self._loader._read_bigquery_load_job(
path_or_buf,
table,
job_config=job_config,
)
else:
if any(arg in kwargs for arg in ("chunksize", "iterator")):
raise NotImplementedError(
"'chunksize' and 'iterator' arguments are not supported."
)
if isinstance(path_or_buf, str):
self._check_file_size(path_or_buf)
if engine == "ujson":
pandas_df = pandas.read_json( # type: ignore
path_or_buf,
orient=orient,
dtype=dtype,
encoding=encoding,
lines=lines,
**kwargs,
)
else:
pandas_df = pandas.read_json( # type: ignore
path_or_buf,
orient=orient,
dtype=dtype,
encoding=encoding,
lines=lines,
engine=engine,
**kwargs,
)
return self._read_pandas(pandas_df, "read_json")