-
Notifications
You must be signed in to change notification settings - Fork 540
/
__init__.py
1384 lines (1152 loc) · 40.3 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
from __future__ import annotations
import abc
import collections.abc
import functools
import importlib.metadata
import keyword
import re
import sys
import urllib.parse
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
)
import ibis
import ibis.common.exceptions as exc
import ibis.config
import ibis.expr.operations as ops
import ibis.expr.types as ir
from ibis import util
from ibis.common.caching import RefCountedCache
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator, Mapping, MutableMapping
from pathlib import Path
import pandas as pd
import pyarrow as pa
import torch
__all__ = ("BaseBackend", "Database", "connect")
_IBIS_TO_SQLGLOT_DIALECT = {
"mssql": "tsql",
"impala": "hive",
"pyspark": "spark",
"polars": "postgres",
"datafusion": "postgres",
# closest match see https://github.com/ibis-project/ibis/pull/7303#discussion_r1350223901
"exasol": "oracle",
}
_SQLALCHEMY_TO_SQLGLOT_DIALECT = {
# sqlalchemy dialects of backends not listed here match the sqlglot dialect
# name
"mssql": "tsql",
"postgresql": "postgres",
"default": "duckdb",
# druid allows double quotes for identifiers, like postgres:
# https://druid.apache.org/docs/latest/querying/sql#identifiers-and-literals
"druid": "postgres",
# closest match see https://github.com/ibis-project/ibis/pull/7303#discussion_r1350223901
"exa.websocket": "oracle",
}
class Database:
"""Generic Database class."""
def __init__(self, name: str, client: Any) -> None:
self.name = name
self.client = client
def __repr__(self) -> str:
"""Return type name and the name of the database."""
return f"{type(self).__name__}({self.name!r})"
def __dir__(self) -> list[str]:
"""Return the attributes and tables of the database.
Returns
-------
list[str]
A list of the attributes and tables available in the database.
"""
attrs = dir(type(self))
unqualified_tables = [self._unqualify(x) for x in self.tables]
return sorted(frozenset(attrs + unqualified_tables))
def __contains__(self, table: str) -> bool:
"""Check if the given table is available in the current database.
Parameters
----------
table
Table name
Returns
-------
bool
True if the given table is available in the current database.
"""
return table in self.tables
@property
def tables(self) -> list[str]:
"""Return a list with all available tables.
Returns
-------
list[str]
The list of tables in the database
"""
return self.list_tables()
def __getitem__(self, table: str) -> ir.Table:
"""Return a Table for the given table name.
Parameters
----------
table
Table name
Returns
-------
Table
Table expression
"""
return self.table(table)
def __getattr__(self, table: str) -> ir.Table:
"""Return a Table for the given table name.
Parameters
----------
table
Table name
Returns
-------
Table
Table expression
"""
return self.table(table)
def _qualify(self, value):
return value
def _unqualify(self, value):
return value
def drop(self, force: bool = False) -> None:
"""Drop the database.
Parameters
----------
force
If `True`, drop any objects that exist, and do not fail if the
database does not exist.
"""
self.client.drop_database(self.name, force=force)
def table(self, name: str) -> ir.Table:
"""Return a table expression referencing a table in this database.
Parameters
----------
name
The name of a table
Returns
-------
Table
Table expression
"""
qualified_name = self._qualify(name)
return self.client.table(qualified_name, self.name)
def list_tables(self, like=None, database=None):
"""List the tables in the database.
Parameters
----------
like
A pattern to use for listing tables.
database
The database to perform the list against
"""
return self.client.list_tables(like, database=database or self.name)
class TablesAccessor(collections.abc.Mapping):
"""A mapping-like object for accessing tables off a backend.
Tables may be accessed by name using either index or attribute access:
Examples
--------
>>> con = ibis.sqlite.connect("example.db")
>>> people = con.tables["people"] # access via index
>>> people = con.tables.people # access via attribute
"""
def __init__(self, backend: BaseBackend):
self._backend = backend
def __getitem__(self, name) -> ir.Table:
try:
return self._backend.table(name)
except Exception as exc: # noqa: BLE001
raise KeyError(name) from exc
def __getattr__(self, name) -> ir.Table:
if name.startswith("_"):
raise AttributeError(name)
try:
return self._backend.table(name)
except Exception as exc: # noqa: BLE001
raise AttributeError(name) from exc
def __iter__(self) -> Iterator[str]:
return iter(sorted(self._backend.list_tables()))
def __len__(self) -> int:
return len(self._backend.list_tables())
def __dir__(self) -> list[str]:
o = set()
o.update(dir(type(self)))
o.update(
name
for name in self._backend.list_tables()
if name.isidentifier() and not keyword.iskeyword(name)
)
return list(o)
def __repr__(self) -> str:
tables = self._backend.list_tables()
rows = ["Tables", "------"]
rows.extend(f"- {name}" for name in sorted(tables))
return "\n".join(rows)
def _ipython_key_completions_(self) -> list[str]:
return self._backend.list_tables()
class _FileIOHandler:
@staticmethod
def _import_pyarrow():
try:
import pyarrow # noqa: ICN001
except ImportError:
raise ModuleNotFoundError(
"Exporting to arrow formats requires `pyarrow` but it is not installed"
)
else:
import pyarrow_hotfix # noqa: F401
return pyarrow
def to_pandas(
self,
expr: ir.Expr,
*,
params: Mapping[ir.Scalar, Any] | None = None,
limit: int | str | None = None,
**kwargs: Any,
) -> pd.DataFrame | pd.Series | Any:
"""Execute an Ibis expression and return a pandas `DataFrame`, `Series`, or scalar.
::: {.callout-note}
This method is a wrapper around `execute`.
:::
Parameters
----------
expr
Ibis expression to execute.
params
Mapping of scalar parameter expressions to value.
limit
An integer to effect a specific row limit. A value of `None` means
"no limit". The default is in `ibis/config.py`.
kwargs
Keyword arguments
"""
return self.execute(expr, params=params, limit=limit, **kwargs)
def to_pandas_batches(
self,
expr: ir.Expr,
*,
params: Mapping[ir.Scalar, Any] | None = None,
limit: int | str | None = None,
chunk_size: int = 1_000_000,
**kwargs: Any,
) -> Iterator[pd.DataFrame | pd.Series | Any]:
"""Execute an Ibis expression and return an iterator of pandas `DataFrame`s.
Parameters
----------
expr
Ibis expression to execute.
params
Mapping of scalar parameter expressions to value.
limit
An integer to effect a specific row limit. A value of `None` means
"no limit". The default is in `ibis/config.py`.
chunk_size
Maximum number of rows in each returned `DataFrame` batch. This may have
no effect depending on the backend.
kwargs
Keyword arguments
Returns
-------
Iterator[pd.DataFrame]
An iterator of pandas `DataFrame`s.
"""
from ibis.formats.pandas import PandasData
orig_expr = expr
expr = expr.as_table()
schema = expr.schema()
yield from (
orig_expr.__pandas_result__(
PandasData.convert_table(batch.to_pandas(), schema)
)
for batch in self.to_pyarrow_batches(
expr, params=params, limit=limit, chunk_size=chunk_size, **kwargs
)
)
@util.experimental
def to_pyarrow(
self,
expr: ir.Expr,
*,
params: Mapping[ir.Scalar, Any] | None = None,
limit: int | str | None = None,
**kwargs: Any,
) -> pa.Table:
"""Execute expression and return results in as a pyarrow table.
This method is eager and will execute the associated expression
immediately.
Parameters
----------
expr
Ibis expression to export to pyarrow
params
Mapping of scalar parameter expressions to value.
limit
An integer to effect a specific row limit. A value of `None` means
"no limit". The default is in `ibis/config.py`.
kwargs
Keyword arguments
Returns
-------
Table
A pyarrow table holding the results of the executed expression.
"""
pa = self._import_pyarrow()
self._run_pre_execute_hooks(expr)
table_expr = expr.as_table()
schema = table_expr.schema()
arrow_schema = schema.to_pyarrow()
with self.to_pyarrow_batches(
table_expr, params=params, limit=limit, **kwargs
) as reader:
table = pa.Table.from_batches(reader, schema=arrow_schema)
return expr.__pyarrow_result__(
table.rename_columns(table_expr.columns).cast(arrow_schema)
)
@util.experimental
def to_pyarrow_batches(
self,
expr: ir.Expr,
*,
params: Mapping[ir.Scalar, Any] | None = None,
limit: int | str | None = None,
chunk_size: int = 1_000_000,
**kwargs: Any,
) -> pa.ipc.RecordBatchReader:
"""Execute expression and return a RecordBatchReader.
This method is eager and will execute the associated expression
immediately.
Parameters
----------
expr
Ibis expression to export to pyarrow
limit
An integer to effect a specific row limit. A value of `None` means
"no limit". The default is in `ibis/config.py`.
params
Mapping of scalar parameter expressions to value.
chunk_size
Maximum number of rows in each returned record batch.
kwargs
Keyword arguments
Returns
-------
results
RecordBatchReader
"""
raise NotImplementedError
@util.experimental
def to_torch(
self,
expr: ir.Expr,
*,
params: Mapping[ir.Scalar, Any] | None = None,
limit: int | str | None = None,
**kwargs: Any,
) -> dict[str, torch.Tensor]:
"""Execute an expression and return results as a dictionary of torch tensors.
Parameters
----------
expr
Ibis expression to execute.
params
Parameters to substitute into the expression.
limit
An integer to effect a specific row limit. A value of `None` means no limit.
kwargs
Keyword arguments passed into the backend's `to_torch` implementation.
Returns
-------
dict[str, torch.Tensor]
A dictionary of torch tensors, keyed by column name.
"""
import torch
t = self.to_pyarrow(expr, params=params, limit=limit, **kwargs)
# without .copy() the arrays are read-only and thus writing to them is
# undefined behavior; we can't ignore this warning from torch because
# we're going out of ibis and downstream code can do whatever it wants
# with the data
return {
name: torch.from_numpy(t[name].to_numpy().copy()) for name in t.schema.names
}
def read_parquet(
self, path: str | Path, table_name: str | None = None, **kwargs: Any
) -> ir.Table:
"""Register a parquet file as a table in the current backend.
Parameters
----------
path
The data source.
table_name
An optional name to use for the created table. This defaults to
a sequentially generated name.
**kwargs
Additional keyword arguments passed to the backend loading function.
Returns
-------
ir.Table
The just-registered table
"""
raise NotImplementedError(
f"{self.name} does not support direct registration of parquet data."
)
def read_csv(
self, path: str | Path, table_name: str | None = None, **kwargs: Any
) -> ir.Table:
"""Register a CSV file as a table in the current backend.
Parameters
----------
path
The data source. A string or Path to the CSV file.
table_name
An optional name to use for the created table. This defaults to
a sequentially generated name.
**kwargs
Additional keyword arguments passed to the backend loading function.
Returns
-------
ir.Table
The just-registered table
"""
raise NotImplementedError(
f"{self.name} does not support direct registration of CSV data."
)
def read_json(
self, path: str | Path, table_name: str | None = None, **kwargs: Any
) -> ir.Table:
"""Register a JSON file as a table in the current backend.
Parameters
----------
path
The data source. A string or Path to the JSON file.
table_name
An optional name to use for the created table. This defaults to
a sequentially generated name.
**kwargs
Additional keyword arguments passed to the backend loading function.
Returns
-------
ir.Table
The just-registered table
"""
raise NotImplementedError(
f"{self.name} does not support direct registration of JSON data."
)
def read_delta(
self, source: str | Path, table_name: str | None = None, **kwargs: Any
):
"""Register a Delta Lake table in the current database.
Parameters
----------
source
The data source. Must be a directory
containing a Delta Lake table.
table_name
An optional name to use for the created table. This defaults to
a sequentially generated name.
**kwargs
Additional keyword arguments passed to the underlying backend or library.
Returns
-------
ir.Table
The just-registered table.
"""
raise NotImplementedError(
f"{self.name} does not support direct registration of DeltaLake tables."
)
@util.experimental
def to_parquet(
self,
expr: ir.Table,
path: str | Path,
*,
params: Mapping[ir.Scalar, Any] | None = None,
**kwargs: Any,
) -> None:
"""Write the results of executing the given expression to a parquet file.
This method is eager and will execute the associated expression
immediately.
Parameters
----------
expr
The ibis expression to execute and persist to parquet.
path
The data source. A string or Path to the parquet file.
params
Mapping of scalar parameter expressions to value.
**kwargs
Additional keyword arguments passed to pyarrow.parquet.ParquetWriter
https://arrow.apache.org/docs/python/generated/pyarrow.parquet.ParquetWriter.html
"""
self._import_pyarrow()
import pyarrow.parquet as pq
with expr.to_pyarrow_batches(params=params) as batch_reader:
with pq.ParquetWriter(path, batch_reader.schema, **kwargs) as writer:
for batch in batch_reader:
writer.write_batch(batch)
@util.experimental
def to_csv(
self,
expr: ir.Table,
path: str | Path,
*,
params: Mapping[ir.Scalar, Any] | None = None,
**kwargs: Any,
) -> None:
"""Write the results of executing the given expression to a CSV file.
This method is eager and will execute the associated expression
immediately.
Parameters
----------
expr
The ibis expression to execute and persist to CSV.
path
The data source. A string or Path to the CSV file.
params
Mapping of scalar parameter expressions to value.
kwargs
Additional keyword arguments passed to pyarrow.csv.CSVWriter
https://arrow.apache.org/docs/python/generated/pyarrow.csv.CSVWriter.html
"""
self._import_pyarrow()
import pyarrow.csv as pcsv
with expr.to_pyarrow_batches(params=params) as batch_reader:
with pcsv.CSVWriter(path, batch_reader.schema, **kwargs) as writer:
for batch in batch_reader:
writer.write_batch(batch)
@util.experimental
def to_delta(
self,
expr: ir.Table,
path: str | Path,
*,
params: Mapping[ir.Scalar, Any] | None = None,
**kwargs: Any,
) -> None:
"""Write the results of executing the given expression to a Delta Lake table.
This method is eager and will execute the associated expression
immediately.
Parameters
----------
expr
The ibis expression to execute and persist to Delta Lake table.
path
The data source. A string or Path to the Delta Lake table.
params
Mapping of scalar parameter expressions to value.
kwargs
Additional keyword arguments passed to deltalake.writer.write_deltalake method
"""
try:
from deltalake.writer import write_deltalake
except ImportError:
raise ImportError(
"The deltalake extra is required to use the "
"to_delta method. You can install it using pip:\n\n"
"pip install 'ibis-framework[deltalake]'\n"
)
with expr.to_pyarrow_batches(params=params) as batch_reader:
write_deltalake(path, batch_reader, **kwargs)
class CanListDatabases(abc.ABC):
@abc.abstractmethod
def list_databases(self, like: str | None = None) -> list[str]:
"""List existing databases in the current connection.
Parameters
----------
like
A pattern in Python's regex format to filter returned database
names.
Returns
-------
list[str]
The database names that exist in the current connection, that match
the `like` pattern if provided.
"""
@property
@abc.abstractmethod
def current_database(self) -> str:
"""The current database in use."""
class CanCreateDatabase(CanListDatabases):
@abc.abstractmethod
def create_database(self, name: str, force: bool = False) -> None:
"""Create a new database.
Parameters
----------
name
Name of the new database.
force
If `False`, an exception is raised if the database already exists.
"""
@abc.abstractmethod
def drop_database(self, name: str, force: bool = False) -> None:
"""Drop a database with name `name`.
Parameters
----------
name
Database to drop.
force
If `False`, an exception is raised if the database does not exist.
"""
class CanCreateSchema(abc.ABC):
@abc.abstractmethod
def create_schema(
self, name: str, database: str | None = None, force: bool = False
) -> None:
"""Create a schema named `name` in `database`.
Parameters
----------
name
Name of the schema to create.
database
Name of the database in which to create the schema. If `None`, the
current database is used.
force
If `False`, an exception is raised if the schema exists.
"""
@abc.abstractmethod
def drop_schema(
self, name: str, database: str | None = None, force: bool = False
) -> None:
"""Drop the schema with `name` in `database`.
Parameters
----------
name
Name of the schema to drop.
database
Name of the database to drop the schema from. If `None`, the
current database is used.
force
If `False`, an exception is raised if the schema does not exist.
"""
@abc.abstractmethod
def list_schemas(
self, like: str | None = None, database: str | None = None
) -> list[str]:
"""List existing schemas in the current connection.
Parameters
----------
like
A pattern in Python's regex format to filter returned schema
names.
database
The database to list schemas from. If `None`, the current database
is searched.
Returns
-------
list[str]
The schema names that exist in the current connection, that match
the `like` pattern if provided.
"""
@property
@abc.abstractmethod
def current_schema(self) -> str:
"""Return the current schema."""
class BaseBackend(abc.ABC, _FileIOHandler):
"""Base backend class.
All Ibis backends must subclass this class and implement all the
required methods.
"""
name: ClassVar[str]
supports_temporary_tables = False
supports_python_udfs = False
supports_in_memory_tables = True
def __init__(self, *args, **kwargs):
self._con_args: tuple[Any] = args
self._con_kwargs: dict[str, Any] = kwargs
# expression cache
self._query_cache = RefCountedCache(
populate=self._load_into_cache,
lookup=lambda name: self.table(name).op(),
finalize=self._clean_up_cached_table,
generate_name=functools.partial(util.gen_name, "cache"),
key=lambda expr: expr.op(),
)
def __getstate__(self):
return dict(_con_args=self._con_args, _con_kwargs=self._con_kwargs)
def __rich_repr__(self):
yield "name", self.name
def __hash__(self):
return hash(self.db_identity)
def __eq__(self, other):
return self.db_identity == other.db_identity
@functools.cached_property
def db_identity(self) -> str:
"""Return the identity of the database.
Multiple connections to the same
database will return the same value for `db_identity`.
The default implementation assumes connection parameters uniquely
specify the database.
Returns
-------
Hashable
Database identity
"""
parts = [self.__class__]
parts.extend(self._con_args)
parts.extend(f"{k}={v}" for k, v in self._con_kwargs.items())
return "_".join(map(str, parts))
def connect(self, *args, **kwargs) -> BaseBackend:
"""Connect to the database.
Parameters
----------
*args
Mandatory connection parameters, see the docstring of `do_connect`
for details.
**kwargs
Extra connection parameters, see the docstring of `do_connect` for
details.
Notes
-----
This creates a new backend instance with saved `args` and `kwargs`,
then calls `reconnect` and finally returns the newly created and
connected backend instance.
Returns
-------
BaseBackend
An instance of the backend
"""
new_backend = self.__class__(*args, **kwargs)
new_backend.reconnect()
return new_backend
def _from_url(self, url: str, **kwargs) -> BaseBackend:
"""Construct an ibis backend from a SQLAlchemy-conforming URL."""
raise NotImplementedError(
f"`_from_url` not implemented for the {self.name} backend"
)
@staticmethod
def _convert_kwargs(kwargs: MutableMapping) -> None:
"""Manipulate keyword arguments to `.connect` method."""
def reconnect(self) -> None:
"""Reconnect to the database already configured with connect."""
self.do_connect(*self._con_args, **self._con_kwargs)
def do_connect(self, *args, **kwargs) -> None:
"""Connect to database specified by `args` and `kwargs`."""
@util.deprecated(instead="use equivalent methods in the backend")
def database(self, name: str | None = None) -> Database:
"""Return a `Database` object for the `name` database.
Parameters
----------
name
Name of the database to return the object for.
Returns
-------
Database
A database object for the specified database.
"""
return Database(name=name or self.current_database, client=self)
@staticmethod
def _filter_with_like(values: Iterable[str], like: str | None = None) -> list[str]:
"""Filter names with a `like` pattern (regex).
The methods `list_databases` and `list_tables` accept a `like`
argument, which filters the returned tables with tables that match the
provided pattern.
We provide this method in the base backend, so backends can use it
instead of reinventing the wheel.
Parameters
----------
values
Iterable of strings to filter
like
Pattern to use for filtering names
Returns
-------
list[str]
Names filtered by the `like` pattern.
"""
if like is None:
return sorted(values)
pattern = re.compile(like)
return sorted(filter(pattern.findall, values))
@abc.abstractmethod
def list_tables(
self, like: str | None = None, database: str | None = None
) -> list[str]:
"""Return the list of table names in the current database.
For some backends, the tables may be files in a directory,
or other equivalent entities in a SQL database.
Parameters
----------
like
A pattern in Python's regex format.
database
The database from which to list tables. If not provided, the
current database is used.
Returns
-------
list[str]
The list of the table names that match the pattern `like`.
"""
@abc.abstractmethod
def table(self, name: str, database: str | None = None) -> ir.Table:
"""Construct a table expression.
Parameters
----------
name
Table name
database
Database name
Returns
-------
Table
Table expression
"""
@functools.cached_property
def tables(self):
"""An accessor for tables in the database.
Tables may be accessed by name using either index or attribute access:
Examples
--------
>>> con = ibis.sqlite.connect("example.db")
>>> people = con.tables["people"] # access via index
>>> people = con.tables.people # access via attribute
"""
return TablesAccessor(self)
@property
@abc.abstractmethod
def version(self) -> str:
"""Return the version of the backend engine.
For database servers, return the server version.
For others such as SQLite and pandas return the version of the
underlying library or application.
Returns
-------
str
The backend version
"""
@classmethod
def register_options(cls) -> None:
"""Register custom backend options."""
options = ibis.config.options
backend_name = cls.name
try:
backend_options = cls.Options()
except AttributeError:
pass
else:
try:
setattr(options, backend_name, backend_options)
except ValueError as e:
raise exc.BackendConfigurationNotRegistered(backend_name) from e
def _register_udfs(self, expr: ir.Expr) -> None:
"""Register UDFs contained in `expr` with the backend."""
if self.supports_python_udfs:
raise NotImplementedError(self.name)