Install & Compatibility
Where this runs
tested against v0.6.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.910 runs
installs and imports cleanly · install 0.0s · import 5.556s · 255MB
glibcpy 3.10–3.910 runs
installs and imports cleanly · install 21.0s · import 5.407s · 255MB
249MB installed
● package 249MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
SqlAlchemyConnector
✓ from prefect_sqlalchemy import SqlAlchemyConnector
AsyncSqlAlchemyConnector
✓ from prefect_sqlalchemy import AsyncSqlAlchemyConnector
ConnectionComponents
✓ from prefect_sqlalchemy import ConnectionComponents
SyncDriver
✓ from prefect_sqlalchemy import SyncDriver
AsyncDriver
✓ from prefect_sqlalchemy import AsyncDriver
DatabaseCredentials
✓ from prefect_sqlalchemy import SqlAlchemyConnector
✗ from prefect_sqlalchemy import DatabaseCredentials
The `DatabaseCredentials` block has been replaced by `SqlAlchemyConnector` in recent versions.
This quickstart demonstrates how to set up an `SqlAlchemyConnector` block, save it to Prefect, and then use it within Prefect tasks and a flow to interact with a SQLite database. It includes creating a table, inserting data, and fetching results. Remember to run the block saving part first, or configure your block via the Prefect UI, before executing the flow.
import os
from prefect import flow, task
from prefect_sqlalchemy import SqlAlchemyConnector, ConnectionComponents, SyncDriver
@task
def setup_table(block_name: str) -> None:
"""Sets up a table and inserts data using the SQLAlchemy connector."""
with SqlAlchemyConnector.load(block_name) as connector:
connector.execute(
"CREATE TABLE IF NOT EXISTS customers (name varchar, address varchar);"
)
connector.execute(
"INSERT INTO customers (name, address) VALUES (:name, :address);",
parameters={"name": "Marvin", "address": "Highway 42"},
)
connector.execute_many(
"INSERT INTO customers (name, address) VALUES (:name, :address);",
seq_of_parameters=[
{"name": "Ford", "address": "Highway 42"},
{"name": "Unknown", "address": "Highway 42"},
],
)
@task
def fetch_data(block_name: str) -> list:
"""Fetches all data from the customers table."""
all_rows = []
with SqlAlchemyConnector.load(block_name) as connector:
while True:
new_rows = connector.fetch_many("SELECT * FROM customers", size=2)
if len(new_rows) == 0:
break
all_rows.extend(new_rows)
return all_rows
@flow(name="SQLAlchemy Flow Example")
def sqlalchemy_flow(block_name: str) -> list:
"""Orchestrates database setup and data fetching."""
setup_table(block_name)
all_rows = fetch_data(block_name)
return all_rows
if __name__ == "__main__":
# --- Configuration and Block Saving (Run this once to create the block) ---
# In a real scenario, use environment variables for sensitive info.
# Replace 'my-sqlite-block' with your desired block name.
# For SQLite, a file-based database is sufficient.
sqlite_block_name = os.environ.get('PREFECT_SQL_BLOCK_NAME', 'my-sqlite-block')
sqlite_db_path = os.environ.get('SQLITE_DB_PATH', 'prefect.db')
# Create and save the connector block programmatically
# (Alternatively, create it via the Prefect UI)
connector = SqlAlchemyConnector(
connection_info=ConnectionComponents(
driver=SyncDriver.SQLITE_PYSQLITE,
database=sqlite_db_path
)
)
connector.save(sqlite_block_name)
print(f"Saved SqlAlchemyConnector block as '{sqlite_block_name}' pointing to '{sqlite_db_path}'")
print("You can now run the flow using this block.")
# --- Running the Flow ---
# Ensure the block 'my-sqlite-block' exists in your Prefect server/Cloud.
results = sqlalchemy_flow(sqlite_block_name)
print("Fetched Data:", results)
Debug
Known issues
breakingSQLAlchemy 2.0 introduced significant API changes compared to previous 1.x versions. If you are upgrading your `prefect-sqlalchemy` integration or `SQLAlchemy` itself, ensure your database interaction code is compatible with SQLAlchemy 2.x patterns. `prefect-sqlalchemy` version 0.4.0 and later added explicit support for SQLAlchemy 2.x.fixUpgrade `prefect-sqlalchemy` to 0.4.0 or higher. Review SQLAlchemy 2.0 migration guides and update database interaction code accordingly, especially for connection and query execution.
affects: prefect-sqlalchemy < 0.4.0 with SQLAlchemy >= 2.0
gotchaDatabase drivers are not included: `prefect-sqlalchemy` provides the integration layer but does not bundle specific database drivers (e.g., `psycopg2-binary` for PostgreSQL, `aiosqlite` for async SQLite, `pymysql` for MySQL). You must install the appropriate driver(s) for your target database(s) separately.fixInstall the necessary database driver using `pip install <driver_package>` (e.g., `pip install psycopg2-binary`) alongside `prefect-sqlalchemy`.
affects: All versions
gotchaBlock state management: It is generally recommended to load and consume an `SqlAlchemyConnector` (or `AsyncSqlAlchemyConnector`) within the scope of a single task or flow. Passing the connector instance across separate tasks or flows might lead to loss of connection/cursor state and unexpected behavior.fixLoad the `SqlAlchemyConnector` block inside the task or flow where it is being used, or ensure its lifecycle is properly managed if shared. Using it as a context manager (`with connector: ...`) is the recommended pattern to ensure proper resource closure.
affects: All versions
gotchaUsing `SqlAlchemyConnector.load()` requires a pre-existing block document. If you attempt to load a block that hasn't been saved yet (either programmatically or via the Prefect UI), it will result in an error.fixBefore calling `SqlAlchemyConnector.load('your-block-name')`, ensure you have saved a block with that name using `connector_instance.save('your-block-name')` or by configuring it through the Prefect UI. affects: All versions
Errors
Common errors & fixes
RuntimeError: Unable to load 'BLOCK_NAME' of block type 'sqlalchemy-connector' due to failed validation.
This error occurs when a SqlAlchemyConnector block cannot be loaded because its configuration, particularly the connection_info or other parameters like fetch_size, fails Pydantic validation.
fixInspect the block's configuration using `prefect block inspect sqlalchemy-connector/BLOCK_NAME` to verify the `connection_info` (ensure it's a valid SQLAlchemy URL and the driver is installed) and other fields. Correct any invalid values, especially for `fetch_size` if it was accidentally cleared, and then save the block again. For `connection_info` URLs, ensure special characters in passwords are percent-encoded.
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file
This SQLAlchemy error, often encountered with Prefect's default SQLite database, indicates that the database file cannot be accessed or is locked, frequently due to file system permissions or concurrent access issues.
fixEnsure the Prefect server (or flow runner) has appropriate read/write permissions to the directory where the SQLite database file (`~/.prefect/orion.db` by default) is located. If the database is corrupted or locked, try removing the SQLite database file and restarting the Prefect server (`rm ~/.prefect/orion.db; prefect orion start`).
AttributeError: __enter__ (when using SqlAlchemyConnector.get_engine().connect() as connection)
This error typically arises when attempting to use an asynchronous SQLAlchemy connection or engine (from `prefect-sqlalchemy`) within a synchronous context manager, as the `__enter__` method is missing for synchronous use in an async context.
fixIf using an asynchronous driver (e.g., `AsyncDriver.POSTGRESQL_ASYNCPG`), ensure you are using `AsyncSqlAlchemyConnector` and calling its methods (like `get_engine().connect()`) with `async with` instead of `with`, or utilize the `execute` and `fetch` methods provided directly by the connector block which handle the async context.
ModuleNotFoundError: No module named 'prefect_sqlalchemy'
This indicates that the `prefect-sqlalchemy` library or one of its necessary database drivers (e.g., `psycopg2` for PostgreSQL) is not installed in the Python environment where the Prefect flow or script is being executed.
fixInstall the library and any required database drivers using pip: `pip install prefect-sqlalchemy` and, for example, `pip install psycopg2-binary` for PostgreSQL or `pip install asyncpg` for async PostgreSQL. If running in a Docker container or remote environment, ensure these packages are installed within that environment.
sqlalchemy.exc.ProgrammingError: function gen_random_uuid() does not exist
This specific programming error occurs when Prefect attempts to use the `gen_random_uuid()` function in a PostgreSQL database that is an older version (pre-PostgreSQL 13), which does not natively support this function.
fixUpgrade your PostgreSQL database to version 13 or newer, or ensure that the `uuid-ossp` extension is enabled in your PostgreSQL database if using an older version. You can also try resetting the Prefect database to ensure migrations are applied correctly if your PostgreSQL version supports it: `prefect orion database reset -y`.
Upgrade
Version history
0.6.1latest on PyPI · released Feb 12, 2026
Audit
Dependencies
prefectrequiredThis is a Prefect integration and requires Prefect for flow orchestration.
SQLAlchemyrequiredCore library for database interaction.
database-driveroptionalSpecific database drivers (e.g., `psycopg2-binary` for PostgreSQL, `aiosqlite` for async SQLite) must be installed separately based on the database being used.