polars.scan_database#
- polars.scan_database(
- source: str,
- connection: str | Callable[[], Any] | Any,
- *,
- params: Sequence[Any] | Mapping[str, Any] | None = None,
- source_type: Literal['auto', 'table', 'query'] = 'auto',
- driver: str | None = None,
- dialect: str | None = None,
- connect_options: Mapping[str, Any] | None = None,
- execute_options: Mapping[str, Any] | None = None,
- credential_provider: Callable[[], Any] | None = None,
- schema: SchemaDict | None = None,
- schema_overrides: SchemaDict | None = None,
- partition_on: str | Expr | None = 'auto',
- partition_num: int | None = None,
- partition_range: tuple[Any, Any] | None = None,
- partition_predicates: Sequence[str] | None = None,
- order_by: str | Sequence[str] | None = None,
- consistency: Literal['none', 'snapshot'] = 'none',
- max_connections: int | None = None,
- batch_size: int | None = None,
- pushdown: bool = True,
Lazily read from a database table or query.
The scan runs on the streaming engine. Projections, filters and limits are pushed into the SQL sent to the database, which is read with one query.
Warning
This functionality is considered unstable. It may be changed at any point without it being considered a breaking change.
- Parameters:
- source
A table name (
"orders","public.orders",'"My Schema"."Orders"') or a SQL query. A query is wrapped as a derived table so that filters and projections can still be pushed down. As in SQL, a bare (unquoted) name part is folded to the case the database stores it in:ordersreadsORDERSon Oracle and Snowflake, andOrdersreadsorderson Postgres (also when a table"Orders"exists). If no table has the folded name, the name as written is used; withschema=(no lookup) it is always used as written. Quote a part to use it exactly.- connection
Where to connect:
a URI, e.g.
"postgresql://user@host/db","sqlite:///path.db"; a SQLAlchemy-style"scheme+driver://…"URI pins the driver. As with SQLAlchemy,"sqlite:///rel.db"is a relative path and"sqlite:////abs.db"an absolute one. URI query parameters are passed to the driver (an unknown one raises);an ODBC connection string (
"Driver={…};Server=…");a SQLAlchemy
URL(as its URI), orEngine: the engine opens the connection, with its pool,creator,connect_argsand checkout listeners. A pooled connection carries the state of its session (temporary tables,search_path, session variables), so each collect checks out ONE connection (on the scan’s own thread, in a copy of thecontextvarsof the caller ofscan_database, so checkout listeners run for every collect) and reads on it. The scan sets the session up as for a URI (read-only, UTC) and restores that before it gives the connection back to the pool, at the end of the collect: nothing is held between collects. Each Engine scan in a query (aconcator self-join of scans) holds one pooled connection until the query ends, so the pool (pool_size+max_overflow) must allow as many as the query has scans of it. A transaction a checkout listener left open is committed by that setup. An Engine without pooling (NullPool) is read as a factory.StaticPool,SingletonThreadPoolandAssertionPoolshare one DB-API connection, per thread forSingletonThreadPool. The scan usually reads that connection directly, including its uncommitted changes, and returns any checkout without the pool’s reset. For databases other than BigQuery, pass an established SQLAlchemy Connection when a statement-routing listener must run. An ORMSessionover such an Engine also reads the shared connection. A function over aSingletonThreadPoolorAssertionPoolEngine (such as itsconnectmethod, asessionmaker, a lambda or apartial) also reads directly when the Engine can be identified. A function that refers to several such Engines, or opens aSingletonThreadPoolconnection without an identifiable Engine, is refused. A function that returns a shared connection whose session the scan must set up (MySQL, Oracle) is also refused;a zero-argument callable that returns a DB-API connection (a factory), called on the scan’s own threads, in a copy of the
contextvarsof the caller ofscan_database(thread-locals are not carried over);a live connection object. It is used from another thread: open a sqlite3 connection with
check_same_thread=False. Its results are read whole, with client-side cursors: Polars may still read, or release, a scan aftercollect()returned, while the connection is the user’s again. A transaction the scan opens on it is rolled back as soon as the query ran; one already open stays. On a MySQL connection whose cursors are unbuffered (e.g. PyMySQL’sSSCursor), results are read with buffered cursors, as two scans can’t stream from one connection at once. A PyMySQL connection with an unread unbuffered result is refused; its pending results of a multi-statement query are not detected, and a scan discards them: read them first. Other code must not use the connection while a scan reads from it (for example inside acollect_batches()loop): with autocommit off, the scan’s rollback can discard writes made concurrently. A MySQLdb connection to a MySQL server with autocommit off may keep the scan’s snapshot and locks open after the read: use a URI, a factory or autocommit. A DuckDB connection with an unfinished result is read through a separate cursor, which does not see that connection’s uncommitted writes or session settings.
- params
Parameters of a query source, bound by the driver (its own placeholder style, e.g.
%sfor psycopg,?for sqlite3). They are never interpolated into the SQL. Needs a driver that binds parameters itself: not ADBC or ConnectorX. Their lists, tuples and dicts are copied when the scan is built: changing them afterwards doesn’t change the scan. Filters with a%in a string (andstr.starts_with/ends_with/contains) then stay in Polars, as%s-style drivers would read the%; with SQLAlchemy (:nameplaceholders), so do those with a:.- source_type{‘auto’, ‘table’, ‘query’}
Whether
sourceis a table name or a query.'auto'decides from its form.- driver
Pin the driver instead of choosing one automatically, e.g.
"adbc","connectorx","sqlalchemy","psycopg"(any case), one of the dialect’s drivers listed bypolars.io.database.show_drivers();"adbc:<name>"or a path to an ADBC driver library; or"python:<module>"for another DB-API module. Not for connection objects, whose module is the driver.- dialect
The SQL dialect, if it can’t be inferred from the connection.
- connect_options
Driver-specific connection options: ADBC database options (as strings), Python driver
connect()keyword arguments (as given), SQLAlchemycreate_engine()arguments, ConnectorXprotocol. Not for connection objects.- execute_options
Driver-specific statement options (Python drivers’
execute()keyword arguments). ConnectorX takes none.- credential_provider
A callable returning
{"user": …, "password": …}(either key may be left out, not both), evaluated wherever a connection is opened. The values override those of the URI. Not for connection objects; cloud storage credential providers such aspl.CredentialProviderAWSdon’t apply.- schema
The schema of the source: the database’s column types, as Polars dtypes. When given, no metadata is read from the database while planning, and filters are pushed as if the database stores these types. A Datetime’s time zone must match the column (time-zone-aware for a time-zone-aware column, naive for a naive one), since filters are pushed assuming it. To read a column as another type, use
schema_overrides.- schema_overrides
Dtypes that override the discovered schema for some columns. The values are cast after reading; filters on these columns stay in Polars. A SQL Server
datetime2/datetimeoffsetof more than 6 fractional digits is read as nanoseconds, which fails for dates outside 1677 to 2262 (every current row of a system-versioned table ends at9999-12-31 23:59:59.9999999): typed aspl.Datetime("us")(or"ms"), it is read with the digits beyond the unit cut (toward the earlier instant, never rounded).- partition_on
Partitioning is not supported yet: this parameter is reserved.
"auto"(the default) andNoneread with a single query; a column raises an error.- partition_num
Reserved for partitioning, which is not supported yet: passing it raises an error.
- partition_range
Reserved for partitioning, which is not supported yet: passing it raises an error.
- partition_predicates
Reserved for partitioning, which is not supported yet: passing it raises an error.
- order_by
Order rows by these columns. Without it, row order is unspecified.
- consistency{‘none’, ‘snapshot’}
'snapshot'requires every partition of a read to see the same database state. Every scan is read with one query for now, so it adds no check.- max_connections
The maximum number of concurrent connections. Defaults: 1 for SQLite and DuckDB and for a live connection, 8 for Snowflake, BigQuery, Databricks, Trino and ClickHouse, 4 otherwise. For a SQLAlchemy
Engine, it is capped at the number of connections its pool hands out (pool_size + max_overflow). Each scan of a query (e.g. both sides of a join) reads with its own connections: the pool must hold at least one per scan.- batch_size
Rows per batch requested from the driver.
- pushdown
Push projections, filters and limits into the SQL. With
False, the source runs as given, with a single query, and Polars does all further work.
Notes
A
LazyFramesnapshots what the scan found when it was planned: the table’s columns and types and, for a view or query, whether it is volatile. Collecting the sameLazyFrameagain reuses that plan, also after the database changed (a column dropped, added or retyped, a table replaced by a view or another table): the second collect can then read the wrong columns or fail. Callscan_databaseagain after such a change.With Google’s BigQuery DB-API driver, NUMERIC columns are read as Polars decimals. BIGNUMERIC columns are also read as decimals when the result schema reports a precision of at most 38 digits. Wider or unparameterized BIGNUMERIC columns are read as exact fixed-point strings, including in empty results.
BigQuery scans through a
StaticPoolEngine retain the SQLAlchemy execution layer. Where a shared BigQuery pool is read through the DB-API connection, the scan rejects factories that may configure the checkout and SQLAlchemy parameters, options or listeners that it cannot preserve. Use an established SQLAlchemy Connection to supply parameters or job settings in these cases.BigQuery schema discovery executes a query. The scan rejects named BigQuery destination tables and SQLAlchemy execution listeners that can change job settings, including ORM
do_orm_executelisteners. Pass an established SQLAlchemy Connection to avoid a pool pre-ping during checkout.Examples
>>> lf = pl.scan_database("orders", "sqlite:///shop.db") >>> lf.filter(pl.col("status") == "paid").select( ... "id", "amount" ... ).collect()