pre-alpha

Reference

Database API

Updated November 20, 2026 5 min read

For setup, application settings, URL examples and migration workflow, see configure a database.

The ORM supports PostgreSQL, SQLite, MySQL and MariaDB. SQLite is the local-development default; configure an explicit URL to select a server backend. Raw SQL uses the selected driver's placeholders: PostgreSQL uses $1, while SQLite, MySQL and MariaDB use ?. ORM-generated queries select the dialect automatically.

Configure a backend

Database URLs are secrets, so configure them through the environment rather than TOML. For local development, leave the URL unset to use the default SQLite file. The migration commands read the application's database setting too; HINOKI_DATABASE_URL overrides it for them (which database). TOML may configure non-secret pool options, for example:

[database]
max_size = 8

For PostgreSQL, use a driver URL such as postgresql://user:password@host/db. For MySQL, use mysql://user:password@host/db. MySQL connections require TLS by default; the driver verifies the server certificate and hostname. Configure the system trust store to trust your server certificate. require_ssl=false is only suitable for isolated local testing and disables transport encryption. Do not put production credentials in source-controlled settings files. For MariaDB, use mariadb://user:password@host/db; it is selected and tested as a distinct backend even though it uses the MySQL wire driver and SQL dialect.

Backend behavior and limits

Backend Status Notes
SQLite Supported Default for local development. SQLite permits one writer at a time. Schema changes that SQLite cannot express directly use a table rebuild.
PostgreSQL Supported Uses PostgreSQL-native UUID, timestamp, JSON and byte types.
MySQL Supported Uses InnoDB tables, binary UUIDs and MySQL-native JSON. MySQL DDL implicitly commits, so a failed migration can leave earlier DDL applied; inspect migration status and database schema before retrying. RETURNING is not supported by the compiler; ORM create/update operations use follow-up reads. TLS is required by default.
MariaDB Supported Tested independently on MariaDB 11.4. Its JSON alias is text, so typed ORM dict/list fields are decoded from the model declaration. Low-level Database.fetch() returns JSON values as bytes because arbitrary text columns cannot be safely inferred as JSON. DDL can implicitly commit; TLS is required by default.

SQL Server and Oracle are not currently supported. Do not assume that MySQL compatibility implies MariaDB compatibility. Hinoki does not silently roll back MySQL-family DDL: review generated migrations and keep a recoverable backup before applying schema changes.

Datetime values stored in MySQL DATETIME columns use Hinoki's UTC-naive storage convention; values returned by the ORM are interpreted as UTC. MySQL pool capacity and acquisition wait are bounded by the database pool settings.

Raw SQL must use the placeholders for the configured backend. Prefer ORM query methods when the same code should work across backends; raw SQL and migration operations may need backend-specific SQL.

hinoki.db.Database

Database(engine: Database)

A connection pool for one configured database backend.

engine instance-attribute

engine = engine

dialect property

dialect: str

The selected dialect: postgres, sqlite, mysql or mariadb.

connect async classmethod

connect(
    url: str, *, max_size: int = 8, wait: float = 5.0
) -> Database

Open the pool and check the server; PostgreSQL URLs may configure TLS.

active

active() -> ActiveTransaction | None

fetch async

fetch(sql: str, *params: Param) -> list[Row]

Rows as dicts, with placeholders selected by the active backend.

fetch_models async

fetch_models(
    sql: str, params: list[Any], plan: _ModelRows
) -> list[Any]

Rows built into finished model instances (private; QuerySet.fetch).

fetch_one async

fetch_one(sql: str, *params: Param) -> Row | None

execute async

execute(sql: str, *params: Param) -> int

Number of affected rows; raw SQL placeholders follow the backend.

atomic

atomic() -> AtomicScope

async with database.atomic(): — commit on success, roll back on any exception; inside an open scope of the same task, a savepoint.

after_commit

after_commit(callback: Callable[[], object]) -> None

Run callback (sync or async) after the outermost transaction commits, in registration order. A rollback, of the transaction or of the savepoint scope it was registered in, drops it; an exception in a callback is logged and does not undo the commit.

migration

migration() -> AtomicScope

An exclusive migration transaction with backend locking semantics.

close

close() -> None

status

status() -> tuple[int, int]

(connections, idle) in the pool.

hinoki.db.atomic

atomic(
    func: Callable[P, Coroutine[Any, Any, R]],
) -> Callable[P, Coroutine[Any, Any, R]]
atomic(func: Callable[P, R]) -> Callable[P, R]
atomic() -> Atomic
atomic(func: Callable[..., Any] | None = None) -> Any

async with db.atomic():, with db.atomic():, @db.atomic or @db.atomic(): run a block or a function, async def or plain def, atomically on the current database. The sync forms are for sync handlers.

hinoki.db.Atomic

db.atomic(): an atomic scope on the current database, as a block or as a decorator.

async with db.atomic(): opens current_database().atomic() when the block is entered; with db.atomic(): does the same in a sync handler. Decorating an async def or a plain def opens a fresh scope for every call: returning commits, an exception rolls back, and a call made inside an already atomic scope becomes a savepoint.

leave

leave() -> AtomicScope

Pop this task's innermost open scope.

hinoki.db.DatabaseModule

DatabaseModule(
    url: str, *, max_size: int = 8, wait: float = 5.0
)

Bases: Module

Opens a Database for the worker and provides it to other modules.

app.install(DatabaseModule(url)); actions with atomic=True and other modules obtain it with ctx.get(Database). The pool is created in the worker's lifespan and closed when it ends.

name class-attribute instance-attribute

name = 'database'

url instance-attribute

url = url

max_size instance-attribute

max_size = max_size

wait instance-attribute

wait = wait

from_settings classmethod

from_settings(settings: object) -> DatabaseModule

The module for settings.database (a DatabaseSettings: url and max_size), so Hinoki(settings=..., modules=[DatabaseModule]) works.

lifespan async

lifespan(ctx: ModuleContext) -> AsyncIterator[None]

hinoki.db.DatabaseError

Bases: builtins.Exception

hinoki.db.UniqueViolation

Bases: hinoki.core.DatabaseError

hinoki.db.ForeignKeyViolation

Bases: hinoki.core.DatabaseError

hinoki.db.NotNullViolation

Bases: hinoki.core.DatabaseError

hinoki.db.CheckViolation

Bases: hinoki.core.DatabaseError