lazybear

Creating Frames

Back to API reference

LazyBear provides three ways to construct a LazyBearFrame: read an existing database table, start from a SQL SELECT query, or use a local polars DataFrame in a database query.

All three accept a SQLAlchemy Engine. LazyBear builds SQL expressions and delegates execution to the connected database. Results are returned as polars DataFrame objects when you call collect or another execution method.

Contents

Quick example

import lazybear as lb
import sqlalchemy as sa

engine = sa.create_engine('sqlite:///example.db')

users = lb.scan_table('users', engine)

result_df = (
    users
    .filter(lb.col('age') >= 30)
    .select('id', 'name', 'age')
    .collect()
)

scan_table creates a SQL-backed lazy frame. Filtering and projection are translated to SQL; only the results of collect() are loaded into a local polars DataFrame.


scan_table(table_name, engine, schema=None, *, lowercase=True)

Back to contents

Create a LazyBearFrame from an existing database table. LazyBear uses SQLAlchemy reflection to discover the table’s columns and build a queryable source.

Parameters

Parameter Type Description
table_name str Name of the database table.
engine sqlalchemy.Engine SQLAlchemy engine connected to the database.
schema str \| None Optional database schema/namespace. Defaults to None.
lowercase bool Expose column names in lowercase when True (default); preserve reflected casing when False. Keyword-only.

Returns: LazyBearFrame.

Examples

Scan a table and apply lazy transformations:

import lazybear as lb

users = lb.scan_table('users', engine)

result_df = (
    users
    .filter(lb.col('age') >= 30)
    .select('id', 'name')
    .collect()
)

Specify a database schema:

encounters = lb.scan_table('encounters', engine, schema='clinical')

Preserve the database’s original column capitalization:

patients = lb.scan_table('Patients', engine, lowercase=False)
print(patients.columns)

Notes


sql(query, engine, columns=None)

Back to contents

Create a LazyBearFrame from a SQL SELECT statement. Prefer lb.sql(...), consistent with the naming of pl.sql(...) in polars. It provides the same SQL-query scanning behavior as scan_sql_query, rather than implementing polars’ complete SQL context interface.

Version note: The current sql.py defines sql = scan_sql_query, but the package initializer does not expose sql as a callable lb.sql(...) attribute. Apply the accompanying sql_export.patch before using lb.sql(...). Until then, use lb.scan_sql_query(...) with the same arguments.

Parameters

Parameter Type Description
query str Raw SQL SELECT statement.
engine sqlalchemy.Engine SQLAlchemy engine on which the query will run.
columns Sequence[str] \| None Optional result-column names. If omitted, LazyBear executes the query once to inspect cursor metadata without fetching rows.

Returns: LazyBearFrame.

Examples

Start from a SQL query and continue with LazyBear transformations:

import lazybear as lb

users = lb.sql(
    '''
    SELECT id, name, age
    FROM users
    WHERE active = 1
    ''',
    engine,
)

result_df = (
    users
    .filter(lb.col('age') >= 30)
    .select('id', 'name')
    .collect()
)

Provide column names explicitly to avoid the initial metadata query:

adults = lb.sql(
    'SELECT id, age FROM users WHERE age >= 18',
    engine,
    columns=['id', 'age'],
)

Inspect the composed SQL without collecting rows:

print(adults.filter(lb.col('age') >= 65).explain())

Notes


scan_sql_query(query, engine, columns=None)

Back to contents

Create a LazyBearFrame from a raw SQL SELECT statement. This is the currently implemented name for SQL-query scanning. Prefer lb.sql(...) once the alias is exported; keep scan_sql_query(...) for compatibility with existing code.

Parameters

The parameters and return type are the same as sql: query, engine, and optional columns.

Example

import lazybear as lb

users = lb.scan_sql_query(
    'SELECT id, name, age FROM users',
    engine,
    columns=['id', 'name', 'age'],
)

result_df = users.filter(lb.col('age') >= 30).collect()

Notes


scan_df(df, engine, table_name=None)

Back to contents

Create a TempLazyBearFrame from a local polars DataFrame so that it can participate in SQL-backed LazyBear operations. The DataFrame is uploaded to a temporary database table when the query is executed, not when scan_df() is called.

Parameters

Parameter Type Description
df polars.DataFrame Local polars DataFrame to upload during execution.
engine sqlalchemy.Engine Database engine in which the temporary table will be created.
table_name str \| None Optional name component for the temporary table. If omitted, LazyBear generates a name. An automatically generated suffix is added to supplied names.

Returns: TempLazyBearFrame (a subclass of LazyBearFrame).

Examples

Use a small local cohort to filter a larger database table:

import polars as pl
import lazybear as lb

cohort = pl.DataFrame({'patient_id': [101, 205, 319]})

patients = lb.scan_table('patients', engine)
cohort_table = lb.scan_df(cohort, engine)

result_df = (
    patients
    .join(cohort_table, on='patient_id', how='inner')
    .select('patient_id', 'age')
    .collect()
)

Supply a descriptive temporary-table name:

cohort_table = lb.scan_df(cohort, engine, table_name='cohort')

Notes


Choosing a scan function

Starting point Recommended API
Existing database table lb.scan_table('users', engine)
SQL SELECT statement lb.sql('SELECT ...', engine) (after exporting the function)
Existing code that uses SQL scanning lb.scan_sql_query('SELECT ...', engine)
Local polars DataFrame for a database join lb.scan_df(df, engine)

LazyBear expressions use lb.col(...), not pl.col(...), even when the query originates from a polars DataFrame. Transformations return new lazy frames; execution occurs only when an output method is called, except for table reflection and optional SQL-result metadata discovery.

Back to API reference