polars_to_ibis

pypi github

Convert Polars LazyFrames to Ibis unbound tables.

Polars and Ibis have similar APIs, but while Polars supports computation in-memory and on Polars Cloud, Ibis by itself does not handle computation: Instead it translates the dataframe expression into idiomatic SQL for a particular database.

Example

First, we'll write to the database so we have something to query. To connect to a particular database, you will need to install the appropriate extra. Taking SQLite as an example:

$ pip install 'polars-to-ibis'
$ pip install 'ibis-framework[sqlite]'

Create the table for our example:

>>> import ibis
>>> import polars as pl
>>> backend = ibis.sqlite
>>> connection = backend.connect()
>>> table_name = 'readme_example'
>>> connection.create_table(
...      table_name,
...      pl.DataFrame({"ints": [1, 2, 3, 4]}),
...      overwrite=True,
... )
DatabaseTable: readme_example
  ints int64

Now we can demonstrate the typical use of polars-to-ibis. To read a database table's schema and create a LazyFrame, use scan_database:

>>> from polars_to_ibis import scan_database, convert_polars_to_ibis
>>> polars_lazy = scan_database(connection, table_name)

Next, make a query starting with that LazyFrame:

>>> polars_query = polars_lazy.sum()
>>> ibis_unbound_table = convert_polars_to_ibis(
...     polars_query,
...     table_name=table_name,
...     backend=backend,
... )
>>> print(ibis_unbound_table.to_sql())
SELECT
  SUM("t0"."ints") AS "ints"
FROM "readme_example" AS "t0"

Finally, we can execute in SQLite the query which we constructed in Polars and translated to Ibis:

>>> connection.to_polars(ibis_unbound_table).to_dict(as_series=False)
{'ints': [10]}

Coverage

A range of Polars expressions are handled. Assuming this dataframe:

{
    "animal": ["bird", "mouse", "butterfly", "spider"],
    "legs": [2, 4, 6, 8],
    "wings": [2, 0, 4, 0]
}

These Polars SQL expressions produce the given results, when translated to Ibis and executed on the target database:

SELECT wings, SUM(legs) FROM self GROUP BY wings
-- {"wings": [0, 2, 4], "legs": [12, 2, 6]}

SELECT animal, 3 * wings / legs AS ratio FROM self
-- {"animal": ["bird", "mouse", "butterfly", "spider"], "ratio": [3, 0, 2, 0]}

SELECT animal, CASE WHEN wings > 0 THEN 'flies' ELSE 'walks' END AS movement FROM self
-- {"animal": ["bird", "mouse", "butterfly", "spider"], "movement": ["flies", "walks", "flies", "walks"]}

For more details on what is and isn't covered, see the issues and the tests.

Limitations

  • Tested against python versions: 3.11, 3.12, 3.13
  • Tested against polars versions: 1.36.1, 1.37.0
  • Tested against ibis versions: 12.0.0
  • Feature coverage, and database quirks: We only cover a fraction of the Polars API, and even within that range there are often quirks in how a query is handled by a given database.

API Documentation

  1"""
  2[![pypi](https://img.shields.io/pypi/v/polars_to_ibis)](https://pypi.org/project/polars_to_ibis/)
  3[![github](https://img.shields.io/badge/github-polars__to__ibis-blue?logo=github)](https://github.com/opendp/polars-to-ibis)
  4
  5Convert [Polars LazyFrames](https://docs.pola.rs/api/python/stable/reference/lazyframe/index.html)
  6to [Ibis unbound tables](https://ibis-project.org/how-to/extending/unbound_expression#unbound-tables).
  7
  8Polars and Ibis have similar APIs, but while Polars supports computation in-memory and on
  9[Polars Cloud](https://cloud.pola.rs/), Ibis by itself does not handle computation:
 10Instead it translates the dataframe expression into idiomatic SQL for a particular database.
 11
 12## Example
 13
 14First, we'll write to the database so we have something to query.
 15To connect to a particular database, you will need to install the appropriate extra.
 16Taking SQLite as an example:
 17
 18```shell
 19$ pip install 'polars-to-ibis'
 20$ pip install 'ibis-framework[sqlite]'
 21```
 22
 23Create the table for our example:
 24
 25```python
 26>>> import ibis
 27>>> import polars as pl
 28>>> backend = ibis.sqlite
 29>>> connection = backend.connect()
 30>>> table_name = 'readme_example'
 31>>> connection.create_table(
 32...      table_name,
 33...      pl.DataFrame({"ints": [1, 2, 3, 4]}),
 34...      overwrite=True,
 35... )
 36DatabaseTable: readme_example
 37  ints int64
 38
 39```
 40
 41Now we can demonstrate the typical use of polars-to-ibis.
 42To read a database table's schema and create a LazyFrame, use `scan_database`:
 43
 44```python
 45>>> from polars_to_ibis import scan_database, convert_polars_to_ibis
 46>>> polars_lazy = scan_database(connection, table_name)
 47
 48```
 49
 50Next, make a query starting with that LazyFrame:
 51
 52```python
 53>>> polars_query = polars_lazy.sum()
 54>>> ibis_unbound_table = convert_polars_to_ibis(
 55...     polars_query,
 56...     table_name=table_name,
 57...     backend=backend,
 58... )
 59>>> print(ibis_unbound_table.to_sql())
 60SELECT
 61  SUM("t0"."ints") AS "ints"
 62FROM "readme_example" AS "t0"
 63
 64```
 65
 66Finally, we can execute in SQLite the query which we constructed in Polars and translated to Ibis:
 67
 68```python
 69>>> connection.to_polars(ibis_unbound_table).to_dict(as_series=False)
 70{'ints': [10]}
 71
 72```
 73
 74## Coverage
 75
 76A range of Polars expressions are handled.
 77Assuming this dataframe:
 78```json
 79{
 80    "animal": ["bird", "mouse", "butterfly", "spider"],
 81    "legs": [2, 4, 6, 8],
 82    "wings": [2, 0, 4, 0]
 83}
 84```
 85
 86These [Polars SQL](https://docs.pola.rs/api/python/stable/reference/sql/) expressions produce the given results,
 87when translated to Ibis and executed on the target database:
 88```sql
 89SELECT wings, SUM(legs) FROM self GROUP BY wings
 90-- {"wings": [0, 2, 4], "legs": [12, 2, 6]}
 91
 92SELECT animal, 3 * wings / legs AS ratio FROM self
 93-- {"animal": ["bird", "mouse", "butterfly", "spider"], "ratio": [3, 0, 2, 0]}
 94
 95SELECT animal, CASE WHEN wings > 0 THEN 'flies' ELSE 'walks' END AS movement FROM self
 96-- {"animal": ["bird", "mouse", "butterfly", "spider"], "movement": ["flies", "walks", "flies", "walks"]}
 97```
 98
 99For more details on what is and isn't covered,
100see the [issues](https://github.com/opendp/polars-to-ibis/issues)
101and the [tests](https://github.com/opendp/polars-to-ibis/blob/main/tests/config_parser.py).
102
103
104## Limitations
105
106- Tested against python versions: 3.11, 3.12, 3.13
107- Tested against polars versions: 1.36.1, 1.37.0
108- Tested against ibis versions: 12.0.0
109- Feature coverage, and database quirks: We only cover a fraction of the Polars API,
110  and even within that range there are often quirks in how a query is handled by a given database.
111
112---
113
114### API Documentation
115"""  # noqa: B950
116
117# Keep the "---" and "###" above: Improves the pdoc rendering.
118# Third-level headings are not added to the sidebar.
119
120from importlib.metadata import version
121from typing import Any
122
123import ibis  # pyright: ignore [reportMissingTypeStubs]
124import polars as pl
125
126from ._parse import tags
127from ._parse.table_handlers import update_polars_to_ibis
128from ._serialize import serialize
129from ._utils import PluginReplacer
130
131__version__ = version("polars_to_ibis")
132
133__all__ = ["convert_polars_to_ibis", "scan_database", "split_polars_on_ffi"]
134
135
136class PolarsToIbisWarning(Warning):
137    pass
138
139
140def scan_database(connection: Any, table_name: str) -> pl.LazyFrame:
141    """
142    Get the schema from a database table and convert it to a Polars LazyFrame.
143    If you already know the schema, or at least your columns of interest,
144    feel free to construct the LazyFrame yourself to avoid the database dependency.
145    """
146    ibis_schema = connection.get_schema(table_name)
147    return pl.LazyFrame(schema=ibis_schema.to_polars())
148
149
150def convert_polars_to_ibis(
151    lf: pl.LazyFrame,
152    table_name: str,
153    backend: ibis.BaseBackend,
154) -> ibis.Table:
155    """
156    Convert a Polars LazyFrame to an Ibis unbound table.
157
158    The name of the table in the target database is also required:
159    Ibis translates dataframe syntax to idiomatic SQL,
160    so it needs to have a table name to include in the SQL.
161    """
162    polars_plan = serialize(lf)  # type: ignore
163    input_schema = _get_input_schema(polars_plan)
164    ibis_table = ibis.table(input_schema, name=table_name)  # type: ignore
165
166    return update_polars_to_ibis(
167        polars_plan=polars_plan,
168        table=ibis_table,
169        backend=backend,
170    )
171
172
173def _get_input_schema(polars_plan: dict[str, Any]) -> ibis.expr.schema.Schema:
174    """
175    lf.collect_schema() returns the OUTPUT schema,
176    after columns have been dropped or added.
177
178    Instead, we need to walk the tree to find the input schema.
179
180    >>> polars_plan = {
181    ...     'Select': {
182    ...         'expr': [{'Column': 'ints'}],
183    ...         'input': {
184    ...             'DataFrameScan': {
185    ...                 'df': ['byte list'],
186    ...                 'schema': {'fields': {'ints': 'Int64', 'strs': 'String'}}
187    ...             }
188    ...         },
189    ...         'options': {
190    ...             'run_parallel': True,
191    ...             'duplicate_check': True,
192    ...             'should_broadcast': True
193    ...         }
194    ...     }
195    ... }
196    >>> _get_input_schema(polars_plan)
197    ibis.Schema {
198      ints  int64
199      strs  string
200    }
201
202    """
203    if not isinstance(polars_plan, dict):  # type: ignore
204        return
205    if tags.table.DATA_FRAME_SCAN in polars_plan:
206        input_schema = {
207            k: _get_type(v)
208            for k, v in polars_plan[tags.table.DATA_FRAME_SCAN]["schema"][
209                "fields"
210            ].items()
211        }
212        return ibis.expr.schema.Schema(input_schema)
213    for value in polars_plan.values():  # pragma: no cover
214        maybe_schema = _get_input_schema(value)
215        if maybe_schema:
216            return maybe_schema
217
218
219def _get_type(polars_type_name: str) -> type:
220    if polars_type_name.startswith("Int"):
221        return int
222    if polars_type_name.startswith("Float"):
223        return float
224    if polars_type_name == "String":
225        return str
226    if polars_type_name == "Boolean":
227        return bool
228    if polars_type_name == "Binary":
229        return bytes
230    raise ValueError(
231        f"No python type defined for {polars_type_name}"
232    )  # pragma: no cover
233
234
235def split_polars_on_ffi(
236    query: pl.LazyFrame,
237    table_name: str,
238    backend: ibis.BaseBackend,
239) -> tuple[dict[str, Any], list[dict[str, Any]]]:
240    """
241    Split a Polars LazyFrame on an FFI plugin,
242    returning an Ibis unbound table ready to be executed on a backend,
243    and a list of parameter dicts for the plugin.
244
245    The backend parameter is used to determine the supported operations.
246    """
247
248    polars_plan = serialize(query)
249    input_schema = _get_input_schema(polars_plan)
250
251    param_dicts = PluginReplacer(polars_plan).replace()
252
253    ibis_table = update_polars_to_ibis(
254        polars_plan=polars_plan,
255        table=ibis.table(input_schema, name=table_name),
256        backend=backend,
257    )
258
259    return ibis_table, param_dicts
def convert_polars_to_ibis( lf: polars.lazyframe.frame.LazyFrame, table_name: str, backend: ibis.backends.BaseBackend) -> ibis.expr.types.relations.Table:
151def convert_polars_to_ibis(
152    lf: pl.LazyFrame,
153    table_name: str,
154    backend: ibis.BaseBackend,
155) -> ibis.Table:
156    """
157    Convert a Polars LazyFrame to an Ibis unbound table.
158
159    The name of the table in the target database is also required:
160    Ibis translates dataframe syntax to idiomatic SQL,
161    so it needs to have a table name to include in the SQL.
162    """
163    polars_plan = serialize(lf)  # type: ignore
164    input_schema = _get_input_schema(polars_plan)
165    ibis_table = ibis.table(input_schema, name=table_name)  # type: ignore
166
167    return update_polars_to_ibis(
168        polars_plan=polars_plan,
169        table=ibis_table,
170        backend=backend,
171    )

Convert a Polars LazyFrame to an Ibis unbound table.

The name of the table in the target database is also required: Ibis translates dataframe syntax to idiomatic SQL, so it needs to have a table name to include in the SQL.

def scan_database(connection: Any, table_name: str) -> polars.lazyframe.frame.LazyFrame:
141def scan_database(connection: Any, table_name: str) -> pl.LazyFrame:
142    """
143    Get the schema from a database table and convert it to a Polars LazyFrame.
144    If you already know the schema, or at least your columns of interest,
145    feel free to construct the LazyFrame yourself to avoid the database dependency.
146    """
147    ibis_schema = connection.get_schema(table_name)
148    return pl.LazyFrame(schema=ibis_schema.to_polars())

Get the schema from a database table and convert it to a Polars LazyFrame. If you already know the schema, or at least your columns of interest, feel free to construct the LazyFrame yourself to avoid the database dependency.

def split_polars_on_ffi( query: polars.lazyframe.frame.LazyFrame, table_name: str, backend: ibis.backends.BaseBackend) -> tuple[dict[str, typing.Any], list[dict[str, typing.Any]]]:
236def split_polars_on_ffi(
237    query: pl.LazyFrame,
238    table_name: str,
239    backend: ibis.BaseBackend,
240) -> tuple[dict[str, Any], list[dict[str, Any]]]:
241    """
242    Split a Polars LazyFrame on an FFI plugin,
243    returning an Ibis unbound table ready to be executed on a backend,
244    and a list of parameter dicts for the plugin.
245
246    The backend parameter is used to determine the supported operations.
247    """
248
249    polars_plan = serialize(query)
250    input_schema = _get_input_schema(polars_plan)
251
252    param_dicts = PluginReplacer(polars_plan).replace()
253
254    ibis_table = update_polars_to_ibis(
255        polars_plan=polars_plan,
256        table=ibis.table(input_schema, name=table_name),
257        backend=backend,
258    )
259
260    return ibis_table, param_dicts

Split a Polars LazyFrame on an FFI plugin, returning an Ibis unbound table ready to be executed on a backend, and a list of parameter dicts for the plugin.

The backend parameter is used to determine the supported operations.