alata.
Database

Getting Started

Configure database connections and run queries with Alata's SQLAlchemy 2.0 core.

Alata provides a shared query builder, model, and migration API for PostgreSQL, MySQL, and SQLite, with sync and async database access. You can also use SQLAlchemy 2.0 directly for queries the builder does not cover.

The database guides cover:

This page covers the foundation the others stand on: connections, the DB facade, transactions, and pool management.

Configuration

Define your connections in the CONNECTIONS dictionary in config/database.py, keyed by connection name:

config/database.py
from config.settings import settings

DB_CONFIG = {
    "strict_mode": settings.EFFECTIVE_DB_STRICT_MODE,
    "default": "postgres",
}

# DB_CONNECTION selects the driver; "pgsql" is accepted as an alias so the
# settings default works out of the box.
_DRIVER = {"pgsql": "postgres"}.get(settings.DB_CONNECTION, settings.DB_CONNECTION)

CONNECTIONS = {
    "default": {
        "driver": _DRIVER,
        "host": settings.DB_HOST,
        "port": settings.DB_PORT,
        "database": settings.DB_DATABASE,
        "username": settings.DB_USERNAME,
        "password": settings.DB_PASSWORD,

        # Per-connection pool tuning
        "pool_size": 5,
        "max_overflow": 10,
        "pool_pre_ping": True,
        "pool_recycle": 1800,
        "echo": False,
    },
}

Select the database with DB_CONNECTION in .env. The generated project defaults to pgsql, an alias for postgres.

For PostgreSQL:

.env
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=alata
DB_USERNAME=postgres
DB_PASSWORD=secret

For MySQL, add the mysql extra to your framework dependency (alata[mysql]), run ./alata setup, and configure the connection:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=alata
DB_USERNAME=alata
DB_PASSWORD=secret

For SQLite, install the sqlite extra (alata[sqlite]) and use a file path. The parent directory must exist; the generated project's database/ directory is suitable:

.env
DB_CONNECTION=sqlite
DB_DATABASE=database/database.sqlite

During boot, CONNECTIONS and DB_CONFIG are loaded into the config repository as database.connections and database.config, so any code can read them through the service container:

from alata.container import container

connections = container.make("config").get("database.connections")

URL building

You never write a connection string by hand. The provider passes each connection's config dict to alata.db.url.build_urls(), which assembles two SQLAlchemy URLs per connection — one sync, one async — based on the driver key:

driverSync URL schemeAsync URL scheme
postgres / postgresqlpostgresql+psycopg2postgresql+asyncpg
mysqlmysql+pymysqlmysql+aiomysql
sqlitesqlitesqlite+aiosqlite

Usernames and passwords are URL-encoded automatically, so credentials containing @, :, or other special characters just work. For SQLite, the database key is treated as a file path (defaulting to :memory:).

Dialect support

The common API supports all three databases. Database-specific operations retain their own semantics:

DatabaseDriver installationMigration behavior
PostgreSQLIncluded with alataAdvisory locking and transactional migrations.
MySQL 8.0+alata[mysql]Migration locking; DDL implicitly commits.
SQLite 3.35+alata[sqlite]Transactional migrations, including automatic table rebuilding for schema changes.

See migration behavior by database for rollback guarantees and schema limitations. ilike and upserts work on all three; upsert conflict handling and row counts vary by database. distinct_on() is PostgreSQL-specific.

CI runs the full framework suite on PostgreSQL 14/16, MySQL 8.0/8.4, and SQLite with Python 3.12 and 3.14.

Read and write connections

Configure existing database replicas under read, and the primary under write. Each entry inherits the connection's credentials and other settings:

config/database.py
CONNECTIONS["default"].update({
    "write": {"host": "database-primary"},
    "read": {"host": ["database-replica-1", "database-replica-2"]},
    "sticky": True,
})

Reads select a replica; writes, transactions, and locking queries use the primary. With sticky enabled (the default), reads after a committed write also use the primary for the rest of that HTTP request or queue job. Separate replica credentials can be supplied as a list of connection dictionaries under read.

Force a primary read when you need the latest committed data:

with DB.use_writer():
    order = Order.find(order_id)

HTTP requests and queue jobs receive independent routing scopes automatically. A long-running custom script can use with DB.routing_scope(): around each unit of work. Raw SQL that cannot be identified as a simple read, including CTEs, uses the primary.

Sync and async engines

Every named connection supports both sync and async queries. Use the a-prefixed API in async code, such as HTTP handlers, and the sync API in synchronous code, such as console commands.

Pool settings (pool_size, max_overflow, pool_pre_ping, pool_recycle, echo) can be tuned per connection. SQLite in-memory connections ignore queue capacity settings.

Multiple connections

To talk to a second database, add another entry to CONNECTIONS:

config/database.py
CONNECTIONS = {
    "default": { ... },
    "reporting": {
        "driver": "postgres",
        "host": settings.REPORTING_DB_HOST,
        "port": 5432,
        "database": "reporting",
        "username": settings.REPORTING_DB_USERNAME,
        "password": settings.REPORTING_DB_PASSWORD,
        "pool_size": 2,
        "max_overflow": 5,
    },
}

Each connection gets its own engines, session factories, and pool metrics. Route queries to it with DB.connection():

from alata.db import DB

rows = DB.connection("reporting").select("SELECT * FROM sales WHERE year = :y", {"y": 2026})
rows = DB.connection("reporting").table("sales").where("year", 2026).get()

Models can also pin themselves to a connection with __connection__ = "reporting" — see Models.

The DB facade

For raw SQL and transactions, import the DB facade:

from alata.db import DB

Raw selects

DB.select() runs a raw SELECT with named bind parameters and returns a list of dicts:

rows = DB.select("SELECT * FROM users WHERE id = :id", {"id": 1})
# [{"id": 1, "name": "Alice", ...}]

In async code, use aselect:

rows = await DB.aselect("SELECT * FROM users WHERE email = :email", {"email": email})

Raw statements

DB.statement() runs a raw INSERT/UPDATE/DELETE and returns the affected row count. astatement is the async form:

deleted = DB.statement("DELETE FROM sessions WHERE expired_at < NOW()")
deleted = await DB.astatement("DELETE FROM sessions WHERE expired_at < NOW()")

Always pass user input through the params dict — never interpolate it into the SQL string. Bind parameters are sent to the driver separately, which is what keeps raw queries injection-safe.

Raw SQL inside a transaction

select and statement — sync and async, on DB and on any connection proxy — run on the ambient transaction's session when one is open:

with DB.transaction():
    DB.statement("UPDATE accounts SET balance = balance - :n WHERE id = :id", {"n": 50, "id": 1})
    rows = DB.select("SELECT balance FROM accounts WHERE id = :id", {"id": 1})
    # the read sees the write above; both roll back if the block raises

Outside a transaction they run on their own session and commit on their own, as before. A transaction opened on default never captures statements aimed at reporting.

A raw write inside a transaction block now rolls back with it. If you have a write meant to survive a rollback — an audit-log row recording the failed attempt, say — issue it on a separate connection (DB.connection("audit").statement(...)) or move it outside the block.

Fluent table access

DB.table() returns a lightweight query builder that works on any table without a model class — handy for pivot tables, admin tooling, and migrations. It is covered in full on the Query Builder page:

DB.table("users").where("age", ">", 18).order_by("name").get()

Scoped facade methods

Everything above also exists on the connection proxy, scoped to that connection: DB.connection("reporting").select(...), .statement(...), .aselect(...), .astatement(...), .table(...), and the transaction methods below.

Transactions

Retrying transaction conflicts

Use a callback when a complete transaction should be retried after a deadlock, serialization failure, or SQLite lock conflict:

def transfer():
    Account.where("id", sender_id).decrement("balance", amount)
    Account.where("id", recipient_id).increment("balance", amount)
    return "transferred"

result = DB.run_transaction(transfer, attempts=3)

For async database calls, pass an async callback to await DB.arun_transaction(transfer, attempts=3). Named connections expose both methods through DB.connection(name).

Each attempt starts a new transaction after the previous attempt has rolled back. attempts includes the first attempt and defaults to one; retry_delay sets the initial backoff in seconds. Validation errors, integrity violations, connection failures, and cancellation are not retried. Retries must be configured on the outermost transaction.

The callback may run more than once. Send emails, publish messages, and perform other external effects after it succeeds.

Context-managed transactions

The simplest way to run work atomically is the transaction context manager. It commits on success and rolls back on an exception:

from alata.db import DB

with DB.transaction():
    account.save()
    AuditLog.create({"action": "transfer", "amount": amount})

The async counterpart is atransaction:

async with DB.atransaction():
    await account.asave()
    await AuditLog.acreate({"action": "transfer", "amount": amount})

Queries on the same connection participate in the transaction. Use sync queries inside DB.transaction() and async queries inside DB.atransaction().

Keep related operations in the same task and thread. Await them directly inside DB.atransaction(); work dispatched through asyncio.create_task(), asyncio.gather(), or asyncio.to_thread() runs outside that transaction.

Nesting

Both DB.transaction() and DB.atransaction() support nesting through savepoints: if an inner block raises, only its work rolls back; if the outer block raises, everything does.

with DB.transaction():
    order.save()
    try:
        with DB.transaction():          # savepoint
            apply_optional_discount(order)
    except DiscountError:
        pass                            # inner work undone, order.save() intact

Transactions on named connections

A transaction applies only to its selected connection. To run a transaction on a named connection, scope it:

with DB.connection("reporting").transaction():
    Report.create({...})

Manual transactions

When a context manager doesn't fit the control flow, drive the transaction yourself:

DB.begin_transaction()
try:
    ...
    DB.commit()
except BaseException:
    DB.rollback()
    raise

The async trio is abegin_transaction / acommit / arollback:

await DB.abegin_transaction()
try:
    ...
    await DB.acommit()
except BaseException:
    await DB.arollback()
    raise

commit() and rollback() end the transaction level opened by begin_transaction(). The same methods are available on named connections through DB.connection("name").

Beyond the builder: SQLAlchemy access

Because the whole layer is SQLAlchemy 2.0 underneath, you can always drop one level down and use the framework's engines and pools. This is the sanctioned path for queries the fluent API cannot express.

get_session() and get_async_session() create a new plain SQLAlchemy session bound to a named connection. They do not join an ambient DB transaction; use the session yielded by its context manager when work must share that transaction:

import sqlalchemy as sa
from alata.db import get_session, get_async_session

with get_session() as session:                    # sync, default connection
    rows = session.execute(sa.text("SELECT ...")).all()

async with get_async_session("reporting") as session:
    rows = (await session.execute(sa.text("SELECT ..."))).all()

DB.transaction() yields the transaction's session, so framework writes and hand-written SQLAlchemy calls compose in one atomic unit — everything commits or rolls back together:

from alata.db import DB

with DB.transaction() as session:
    account.save()                                                   # framework write
    session.execute(sa.text("REFRESH MATERIALIZED VIEW balances"))   # raw SQL, same transaction

Every model exposes its SQLAlchemy Table as Model.__table__ — the raw material for Core statements:

users = User.__table__
stmt  = sa.select(users.c.id, users.c.email).where(users.c.age > 18)

To run a hand-built statement and get model instances back, bridge through the query builder's from_statement() — entity-shaped rows hydrate into models via Model.hydrate(), anything else comes back as dict rows.

Below the builder, the model layer's conveniences stop: global scopes (including soft-delete filtering) are not applied, no model events fire, and attribute casts only run if you rehydrate through Model.hydrate() / from_statement(). Drop down deliberately.

Connection pool observability

Every engine's pool can report live metrics. From code:

from alata.db import DB

DB.pool_status()             # default connection
DB.pool_status("reporting")  # named connection
DB.pool_status_all()         # every registered connection

pool_status() returns a dict with pool_size, max_overflow, checked_out, checked_in, overflow, total_connections, max_capacity, and utilization_pct.

checked_in counts idle connections and checked_out counts connections in use; total_connections is their sum. overflow counts connections beyond pool_size. For bounded pools, max_capacity is pool_size + max_overflow, and utilization_pct is the percentage of that capacity currently in use.

Pool utilization produces a WARNING log at 80% and an ERROR at full capacity. If acquiring a connection times out, inspect the live metrics and review pool_size / max_overflow in config/database.py, along with how long your application holds connections.

The db:status command

For a quick look from the terminal, run:

./alata db:status

It reports the pools in the CLI process, with a status label, capacity bar, and metric breakdown. For the running HTTP process, use /health/metrics:

  Database Connection Pool Status

  default  HEALTHY
  ██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░  6.7%

    ├─ Pool Size     5 base + 10 overflow (max 15)
    ├─ Checked Out   1
    ├─ Checked In    4
    ├─ Overflow      0
    └─ Total Active  5

Next steps

With connections configured, head to the Query Builder for the full fluent query API, or Models to define your first table-backed class.

On this page