-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathcontext.py
More file actions
1386 lines (1133 loc) · 49 KB
/
context.py
File metadata and controls
1386 lines (1133 loc) · 49 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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 Context and it's associated configuration."""
from __future__ import annotations
import uuid
import warnings
from typing import TYPE_CHECKING, Any, Protocol
try:
from warnings import deprecated # Python 3.13+
except ImportError:
from typing_extensions import deprecated # Python 3.12
import pyarrow as pa
from datafusion.catalog import (
Catalog,
CatalogList,
CatalogProviderExportable,
CatalogProviderList,
CatalogProviderListExportable,
)
from datafusion.dataframe import DataFrame
from datafusion.expr import sort_list_to_raw_sort_list
from datafusion.options import (
DEFAULT_MAX_INFER_SCHEMA,
CsvReadOptions,
_convert_table_partition_cols,
)
from datafusion.record_batch import RecordBatchStream
from ._internal import RuntimeEnvBuilder as RuntimeEnvBuilderInternal
from ._internal import SessionConfig as SessionConfigInternal
from ._internal import SessionContext as SessionContextInternal
from ._internal import SQLOptions as SQLOptionsInternal
from ._internal import expr as expr_internal
if TYPE_CHECKING:
import pathlib
from collections.abc import Sequence
import pandas as pd
import polars as pl # type: ignore[import]
from datafusion.catalog import CatalogProvider, Table
from datafusion.expr import SortKey
from datafusion.plan import ExecutionPlan, LogicalPlan
from datafusion.user_defined import (
AggregateUDF,
ScalarUDF,
TableFunction,
WindowUDF,
)
class ArrowStreamExportable(Protocol):
"""Type hint for object exporting Arrow C Stream via Arrow PyCapsule Interface.
https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html
"""
def __arrow_c_stream__( # noqa: D105
self, requested_schema: object | None = None
) -> object: ...
class ArrowArrayExportable(Protocol):
"""Type hint for object exporting Arrow C Array via Arrow PyCapsule Interface.
https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html
"""
def __arrow_c_array__( # noqa: D105
self, requested_schema: object | None = None
) -> tuple[object, object]: ...
class TableProviderExportable(Protocol):
"""Type hint for object that has __datafusion_table_provider__ PyCapsule.
https://datafusion.apache.org/python/user-guide/io/table_provider.html
"""
def __datafusion_table_provider__(self, session: Any) -> object: ... # noqa: D105
class SessionConfig:
"""Session configuration options."""
def __init__(self, config_options: dict[str, str] | None = None) -> None:
"""Create a new :py:class:`SessionConfig` with the given configuration options.
Args:
config_options: Configuration options.
"""
self.config_internal = SessionConfigInternal(config_options)
def with_create_default_catalog_and_schema(
self, enabled: bool = True
) -> SessionConfig:
"""Control if the default catalog and schema will be automatically created.
Args:
enabled: Whether the default catalog and schema will be
automatically created.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = (
self.config_internal.with_create_default_catalog_and_schema(enabled)
)
return self
def with_default_catalog_and_schema(
self, catalog: str, schema: str
) -> SessionConfig:
"""Select a name for the default catalog and schema.
Args:
catalog: Catalog name.
schema: Schema name.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_default_catalog_and_schema(
catalog, schema
)
return self
def with_information_schema(self, enabled: bool = True) -> SessionConfig:
"""Enable or disable the inclusion of ``information_schema`` virtual tables.
Args:
enabled: Whether to include ``information_schema`` virtual tables.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_information_schema(enabled)
return self
def with_batch_size(self, batch_size: int) -> SessionConfig:
"""Customize batch size.
Args:
batch_size: Batch size.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_batch_size(batch_size)
return self
def with_target_partitions(self, target_partitions: int) -> SessionConfig:
"""Customize the number of target partitions for query execution.
Increasing partitions can increase concurrency.
Args:
target_partitions: Number of target partitions.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_target_partitions(
target_partitions
)
return self
def with_repartition_aggregations(self, enabled: bool = True) -> SessionConfig:
"""Enable or disable the use of repartitioning for aggregations.
Enabling this improves parallelism.
Args:
enabled: Whether to use repartitioning for aggregations.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_repartition_aggregations(
enabled
)
return self
def with_repartition_joins(self, enabled: bool = True) -> SessionConfig:
"""Enable or disable the use of repartitioning for joins to improve parallelism.
Args:
enabled: Whether to use repartitioning for joins.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_repartition_joins(enabled)
return self
def with_repartition_windows(self, enabled: bool = True) -> SessionConfig:
"""Enable or disable the use of repartitioning for window functions.
This may improve parallelism.
Args:
enabled: Whether to use repartitioning for window functions.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_repartition_windows(enabled)
return self
def with_repartition_sorts(self, enabled: bool = True) -> SessionConfig:
"""Enable or disable the use of repartitioning for window functions.
This may improve parallelism.
Args:
enabled: Whether to use repartitioning for window functions.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_repartition_sorts(enabled)
return self
def with_repartition_file_scans(self, enabled: bool = True) -> SessionConfig:
"""Enable or disable the use of repartitioning for file scans.
Args:
enabled: Whether to use repartitioning for file scans.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_repartition_file_scans(enabled)
return self
def with_repartition_file_min_size(self, size: int) -> SessionConfig:
"""Set minimum file range size for repartitioning scans.
Args:
size: Minimum file range size.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_repartition_file_min_size(size)
return self
def with_parquet_pruning(self, enabled: bool = True) -> SessionConfig:
"""Enable or disable the use of pruning predicate for parquet readers.
Pruning predicates will enable the reader to skip row groups.
Args:
enabled: Whether to use pruning predicate for parquet readers.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.with_parquet_pruning(enabled)
return self
def set(self, key: str, value: str) -> SessionConfig:
"""Set a configuration option.
Args:
key: Option key.
value: Option value.
Returns:
A new :py:class:`SessionConfig` object with the updated setting.
"""
self.config_internal = self.config_internal.set(key, value)
return self
class RuntimeEnvBuilder:
"""Runtime configuration options."""
def __init__(self) -> None:
"""Create a new :py:class:`RuntimeEnvBuilder` with default values."""
self.config_internal = RuntimeEnvBuilderInternal()
def with_disk_manager_disabled(self) -> RuntimeEnvBuilder:
"""Disable the disk manager, attempts to create temporary files will error.
Returns:
A new :py:class:`RuntimeEnvBuilder` object with the updated setting.
"""
self.config_internal = self.config_internal.with_disk_manager_disabled()
return self
def with_disk_manager_os(self) -> RuntimeEnvBuilder:
"""Use the operating system's temporary directory for disk manager.
Returns:
A new :py:class:`RuntimeEnvBuilder` object with the updated setting.
"""
self.config_internal = self.config_internal.with_disk_manager_os()
return self
def with_disk_manager_specified(
self, *paths: str | pathlib.Path
) -> RuntimeEnvBuilder:
"""Use the specified paths for the disk manager's temporary files.
Args:
paths: Paths to use for the disk manager's temporary files.
Returns:
A new :py:class:`RuntimeEnvBuilder` object with the updated setting.
"""
paths_list = [str(p) for p in paths]
self.config_internal = self.config_internal.with_disk_manager_specified(
paths_list
)
return self
def with_unbounded_memory_pool(self) -> RuntimeEnvBuilder:
"""Use an unbounded memory pool.
Returns:
A new :py:class:`RuntimeEnvBuilder` object with the updated setting.
"""
self.config_internal = self.config_internal.with_unbounded_memory_pool()
return self
def with_fair_spill_pool(self, size: int) -> RuntimeEnvBuilder:
"""Use a fair spill pool with the specified size.
This pool works best when you know beforehand the query has multiple spillable
operators that will likely all need to spill. Sometimes it will cause spills
even when there was sufficient memory (reserved for other operators) to avoid
doing so::
┌───────────────────────z──────────────────────z───────────────┐
│ z z │
│ z z │
│ Spillable z Unspillable z Free │
│ Memory z Memory z Memory │
│ z z │
│ z z │
└───────────────────────z──────────────────────z───────────────┘
Args:
size: Size of the memory pool in bytes.
Returns:
A new :py:class:`RuntimeEnvBuilder` object with the updated setting.
Examples usage::
config = RuntimeEnvBuilder().with_fair_spill_pool(1024)
"""
self.config_internal = self.config_internal.with_fair_spill_pool(size)
return self
def with_greedy_memory_pool(self, size: int) -> RuntimeEnvBuilder:
"""Use a greedy memory pool with the specified size.
This pool works well for queries that do not need to spill or have a single
spillable operator. See :py:func:`with_fair_spill_pool` if there are
multiple spillable operators that all will spill.
Args:
size: Size of the memory pool in bytes.
Returns:
A new :py:class:`RuntimeEnvBuilder` object with the updated setting.
Example usage::
config = RuntimeEnvBuilder().with_greedy_memory_pool(1024)
"""
self.config_internal = self.config_internal.with_greedy_memory_pool(size)
return self
def with_temp_file_path(self, path: str | pathlib.Path) -> RuntimeEnvBuilder:
"""Use the specified path to create any needed temporary files.
Args:
path: Path to use for temporary files.
Returns:
A new :py:class:`RuntimeEnvBuilder` object with the updated setting.
Example usage::
config = RuntimeEnvBuilder().with_temp_file_path("/tmp")
"""
self.config_internal = self.config_internal.with_temp_file_path(str(path))
return self
@deprecated("Use `RuntimeEnvBuilder` instead.")
class RuntimeConfig(RuntimeEnvBuilder):
"""See `RuntimeEnvBuilder`."""
class SQLOptions:
"""Options to be used when performing SQL queries."""
def __init__(self) -> None:
"""Create a new :py:class:`SQLOptions` with default values.
The default values are:
- DDL commands are allowed
- DML commands are allowed
- Statements are allowed
"""
self.options_internal = SQLOptionsInternal()
def with_allow_ddl(self, allow: bool = True) -> SQLOptions:
"""Should DDL (Data Definition Language) commands be run?
Examples of DDL commands include ``CREATE TABLE`` and ``DROP TABLE``.
Args:
allow: Allow DDL commands to be run.
Returns:
A new :py:class:`SQLOptions` object with the updated setting.
Example usage::
options = SQLOptions().with_allow_ddl(True)
"""
self.options_internal = self.options_internal.with_allow_ddl(allow)
return self
def with_allow_dml(self, allow: bool = True) -> SQLOptions:
"""Should DML (Data Manipulation Language) commands be run?
Examples of DML commands include ``INSERT INTO`` and ``DELETE``.
Args:
allow: Allow DML commands to be run.
Returns:
A new :py:class:`SQLOptions` object with the updated setting.
Example usage::
options = SQLOptions().with_allow_dml(True)
"""
self.options_internal = self.options_internal.with_allow_dml(allow)
return self
def with_allow_statements(self, allow: bool = True) -> SQLOptions:
"""Should statements such as ``SET VARIABLE`` and ``BEGIN TRANSACTION`` be run?
Args:
allow: Allow statements to be run.
Returns:
A new :py:class:SQLOptions` object with the updated setting.
Example usage::
options = SQLOptions().with_allow_statements(True)
"""
self.options_internal = self.options_internal.with_allow_statements(allow)
return self
class SessionContext:
"""This is the main interface for executing queries and creating DataFrames.
See :ref:`user_guide_concepts` in the online documentation for more information.
"""
def __init__(
self,
config: SessionConfig | None = None,
runtime: RuntimeEnvBuilder | None = None,
) -> None:
"""Main interface for executing queries with DataFusion.
Maintains the state of the connection between a user and an instance
of the connection between a user and an instance of the DataFusion
engine.
Args:
config: Session configuration options.
runtime: Runtime configuration options.
Example usage:
The following example demonstrates how to use the context to execute
a query against a CSV data source using the :py:class:`DataFrame` API::
from datafusion import SessionContext
ctx = SessionContext()
df = ctx.read_csv("data.csv")
"""
config = config.config_internal if config is not None else None
runtime = runtime.config_internal if runtime is not None else None
self.ctx = SessionContextInternal(config, runtime)
def __repr__(self) -> str:
"""Print a string representation of the Session Context."""
return self.ctx.__repr__()
@classmethod
def global_ctx(cls) -> SessionContext:
"""Retrieve the global context as a `SessionContext` wrapper.
Returns:
A `SessionContext` object that wraps the global `SessionContextInternal`.
"""
internal_ctx = SessionContextInternal.global_ctx()
wrapper = cls()
wrapper.ctx = internal_ctx
return wrapper
def enable_url_table(self) -> SessionContext:
"""Control if local files can be queried as tables.
Returns:
A new :py:class:`SessionContext` object with url table enabled.
"""
klass = self.__class__
obj = klass.__new__(klass)
obj.ctx = self.ctx.enable_url_table()
return obj
def register_object_store(
self, schema: str, store: Any, host: str | None = None
) -> None:
"""Add a new object store into the session.
Args:
schema: The data source schema.
store: The :py:class:`~datafusion.object_store.ObjectStore` to register.
host: URL for the host.
"""
self.ctx.register_object_store(schema, store, host)
def register_listing_table(
self,
name: str,
path: str | pathlib.Path,
table_partition_cols: list[tuple[str, str | pa.DataType]] | None = None,
file_extension: str = ".parquet",
schema: pa.Schema | None = None,
file_sort_order: Sequence[Sequence[SortKey]] | None = None,
) -> None:
"""Register multiple files as a single table.
Registers a :py:class:`~datafusion.catalog.Table` that can assemble multiple
files from locations in an :py:class:`~datafusion.object_store.ObjectStore`
instance.
Args:
name: Name of the resultant table.
path: Path to the file to register.
table_partition_cols: Partition columns.
file_extension: File extension of the provided table.
schema: The data source schema.
file_sort_order: Sort order for the file. Each sort key can be
specified as a column name (``str``), an expression
(``Expr``), or a ``SortExpr``.
"""
if table_partition_cols is None:
table_partition_cols = []
table_partition_cols = _convert_table_partition_cols(table_partition_cols)
self.ctx.register_listing_table(
name,
str(path),
table_partition_cols,
file_extension,
schema,
self._convert_file_sort_order(file_sort_order),
)
def sql(
self,
query: str,
options: SQLOptions | None = None,
param_values: dict[str, Any] | None = None,
**named_params: Any,
) -> DataFrame:
"""Create a :py:class:`~datafusion.DataFrame` from SQL query text.
See the online documentation for a description of how to perform
parameterized substitution via either the ``param_values`` option
or passing in ``named_params``.
Note: This API implements DDL statements such as ``CREATE TABLE`` and
``CREATE VIEW`` and DML statements such as ``INSERT INTO`` with in-memory
default implementation.See
:py:func:`~datafusion.context.SessionContext.sql_with_options`.
Args:
query: SQL query text.
options: If provided, the query will be validated against these options.
param_values: Provides substitution of scalar values in the query
after parsing.
named_params: Provides string or DataFrame substitution in the query string.
Returns:
DataFrame representation of the SQL query.
"""
def value_to_scalar(value: Any) -> pa.Scalar:
if isinstance(value, pa.Scalar):
return value
return pa.scalar(value)
def value_to_string(value: Any) -> str:
if isinstance(value, DataFrame):
view_name = str(uuid.uuid4()).replace("-", "_")
view_name = f"view_{view_name}"
view = value.df.into_view(temporary=True)
self.ctx.register_table(view_name, view)
return view_name
return str(value)
param_values = (
{name: value_to_scalar(value) for (name, value) in param_values.items()}
if param_values is not None
else {}
)
param_strings = (
{name: value_to_string(value) for (name, value) in named_params.items()}
if named_params is not None
else {}
)
options_raw = options.options_internal if options is not None else None
return DataFrame(
self.ctx.sql_with_options(
query,
options=options_raw,
param_values=param_values,
param_strings=param_strings,
)
)
def sql_with_options(
self,
query: str,
options: SQLOptions,
param_values: dict[str, Any] | None = None,
**named_params: Any,
) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from SQL query text.
This function will first validate that the query is allowed by the
provided options.
Args:
query: SQL query text.
options: SQL options.
param_values: Provides substitution of scalar values in the query
after parsing.
named_params: Provides string or DataFrame substitution in the query string.
Returns:
DataFrame representation of the SQL query.
"""
return self.sql(
query, options=options, param_values=param_values, **named_params
)
def create_dataframe(
self,
partitions: list[list[pa.RecordBatch]],
name: str | None = None,
schema: pa.Schema | None = None,
) -> DataFrame:
"""Create and return a dataframe using the provided partitions.
Args:
partitions: :py:class:`pa.RecordBatch` partitions to register.
name: Resultant dataframe name.
schema: Schema for the partitions.
Returns:
DataFrame representation of the SQL query.
"""
return DataFrame(self.ctx.create_dataframe(partitions, name, schema))
def create_dataframe_from_logical_plan(self, plan: LogicalPlan) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from an existing plan.
Args:
plan: Logical plan.
Returns:
DataFrame representation of the logical plan.
"""
return DataFrame(self.ctx.create_dataframe_from_logical_plan(plan._raw_plan))
def from_pylist(
self, data: list[dict[str, Any]], name: str | None = None
) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from a list.
Args:
data: List of dictionaries.
name: Name of the DataFrame.
Returns:
DataFrame representation of the list of dictionaries.
"""
return DataFrame(self.ctx.from_pylist(data, name))
def from_pydict(
self, data: dict[str, list[Any]], name: str | None = None
) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from a dictionary.
Args:
data: Dictionary of lists.
name: Name of the DataFrame.
Returns:
DataFrame representation of the dictionary of lists.
"""
return DataFrame(self.ctx.from_pydict(data, name))
def from_arrow(
self,
data: ArrowStreamExportable | ArrowArrayExportable,
name: str | None = None,
) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from an Arrow source.
The Arrow data source can be any object that implements either
``__arrow_c_stream__`` or ``__arrow_c_array__``. For the latter, it must return
a struct array.
Arrow data can be Polars, Pandas, Pyarrow etc.
Args:
data: Arrow data source.
name: Name of the DataFrame.
Returns:
DataFrame representation of the Arrow table.
"""
return DataFrame(self.ctx.from_arrow(data, name))
@deprecated("Use ``from_arrow`` instead.")
def from_arrow_table(self, data: pa.Table, name: str | None = None) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from an Arrow table.
This is an alias for :py:func:`from_arrow`.
"""
return self.from_arrow(data, name)
def from_pandas(self, data: pd.DataFrame, name: str | None = None) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from a Pandas DataFrame.
Args:
data: Pandas DataFrame.
name: Name of the DataFrame.
Returns:
DataFrame representation of the Pandas DataFrame.
"""
return DataFrame(self.ctx.from_pandas(data, name))
def from_polars(self, data: pl.DataFrame, name: str | None = None) -> DataFrame:
"""Create a :py:class:`~datafusion.dataframe.DataFrame` from a Polars DataFrame.
Args:
data: Polars DataFrame.
name: Name of the DataFrame.
Returns:
DataFrame representation of the Polars DataFrame.
"""
return DataFrame(self.ctx.from_polars(data, name))
# https://github.com/apache/datafusion-python/pull/1016#discussion_r1983239116
# is the discussion on how we arrived at adding register_view
def register_view(self, name: str, df: DataFrame) -> None:
"""Register a :py:class:`~datafusion.dataframe.DataFrame` as a view.
Args:
name (str): The name to register the view under.
df (DataFrame): The DataFrame to be converted into a view and registered.
"""
view = df.into_view()
self.ctx.register_table(name, view)
def register_table(
self,
name: str,
table: Table | TableProviderExportable | DataFrame | pa.dataset.Dataset,
) -> None:
"""Register a :py:class:`~datafusion.Table` with this context.
The registered table can be referenced from SQL statements executed against
this context.
Args:
name: Name of the resultant table.
table: Any object that can be converted into a :class:`Table`.
"""
self.ctx.register_table(name, table)
def deregister_table(self, name: str) -> None:
"""Remove a table from the session."""
self.ctx.deregister_table(name)
def catalog_names(self) -> set[str]:
"""Returns the list of catalogs in this context."""
return self.ctx.catalog_names()
def register_catalog_provider_list(
self,
provider: CatalogProviderListExportable | CatalogProviderList | CatalogList,
) -> None:
"""Register a catalog provider list."""
if isinstance(provider, CatalogList):
self.ctx.register_catalog_provider_list(provider.catalog)
else:
self.ctx.register_catalog_provider_list(provider)
def register_catalog_provider(
self, name: str, provider: CatalogProviderExportable | CatalogProvider | Catalog
) -> None:
"""Register a catalog provider."""
if isinstance(provider, Catalog):
self.ctx.register_catalog_provider(name, provider.catalog)
else:
self.ctx.register_catalog_provider(name, provider)
@deprecated("Use register_table() instead.")
def register_table_provider(
self,
name: str,
provider: Table | TableProviderExportable | DataFrame | pa.dataset.Dataset,
) -> None:
"""Register a table provider.
Deprecated: use :meth:`register_table` instead.
"""
self.register_table(name, provider)
def register_udtf(self, func: TableFunction) -> None:
"""Register a user defined table function."""
self.ctx.register_udtf(func._udtf)
def register_record_batches(
self, name: str, partitions: list[list[pa.RecordBatch]]
) -> None:
"""Register record batches as a table.
This function will convert the provided partitions into a table and
register it into the session using the given name.
Args:
name: Name of the resultant table.
partitions: Record batches to register as a table.
"""
self.ctx.register_record_batches(name, partitions)
def register_parquet(
self,
name: str,
path: str | pathlib.Path,
table_partition_cols: list[tuple[str, str | pa.DataType]] | None = None,
parquet_pruning: bool = True,
file_extension: str = ".parquet",
skip_metadata: bool = True,
schema: pa.Schema | None = None,
file_sort_order: Sequence[Sequence[SortKey]] | None = None,
) -> None:
"""Register a Parquet file as a table.
The registered table can be referenced from SQL statement executed
against this context.
Args:
name: Name of the table to register.
path: Path to the Parquet file.
table_partition_cols: Partition columns.
parquet_pruning: Whether the parquet reader should use the
predicate to prune row groups.
file_extension: File extension; only files with this extension are
selected for data input.
skip_metadata: Whether the parquet reader should skip any metadata
that may be in the file schema. This can help avoid schema
conflicts due to metadata.
schema: The data source schema.
file_sort_order: Sort order for the file. Each sort key can be
specified as a column name (``str``), an expression
(``Expr``), or a ``SortExpr``.
"""
if table_partition_cols is None:
table_partition_cols = []
table_partition_cols = _convert_table_partition_cols(table_partition_cols)
self.ctx.register_parquet(
name,
str(path),
table_partition_cols,
parquet_pruning,
file_extension,
skip_metadata,
schema,
self._convert_file_sort_order(file_sort_order),
)
def register_csv(
self,
name: str,
path: str | pathlib.Path | list[str | pathlib.Path],
schema: pa.Schema | None = None,
has_header: bool = True,
delimiter: str = ",",
schema_infer_max_records: int = DEFAULT_MAX_INFER_SCHEMA,
file_extension: str = ".csv",
file_compression_type: str | None = None,
options: CsvReadOptions | None = None,
) -> None:
"""Register a CSV file as a table.
The registered table can be referenced from SQL statement executed against.
Args:
name: Name of the table to register.
path: Path to the CSV file. It also accepts a list of Paths.
schema: An optional schema representing the CSV file. If None, the
CSV reader will try to infer it based on data in file.
has_header: Whether the CSV file have a header. If schema inference
is run on a file with no headers, default column names are
created.
delimiter: An optional column delimiter.
schema_infer_max_records: Maximum number of rows to read from CSV
files for schema inference if needed.
file_extension: File extension; only files with this extension are
selected for data input.
file_compression_type: File compression type.
options: Set advanced options for CSV reading. This cannot be
combined with any of the other options in this method.
"""
path_arg = [str(p) for p in path] if isinstance(path, list) else str(path)
if options is not None and (
schema is not None
or not has_header
or delimiter != ","
or schema_infer_max_records != DEFAULT_MAX_INFER_SCHEMA
or file_extension != ".csv"
or file_compression_type is not None
):
message = (
"Combining CsvReadOptions parameter with additional options "
"is not supported. Use CsvReadOptions to set parameters."
)
warnings.warn(
message,
category=UserWarning,
stacklevel=2,
)
options = (
options
if options is not None
else CsvReadOptions(
schema=schema,
has_header=has_header,
delimiter=delimiter,
schema_infer_max_records=schema_infer_max_records,
file_extension=file_extension,
file_compression_type=file_compression_type,
)
)
self.ctx.register_csv(
name,
path_arg,