Database backends¶
Ferro runs the same models, queries and transactions on SQLite and PostgreSQL; this page explains where the two backends still differ: column types, raw SQL and schema changes.
The examples on this page use this User model:
The URL passed to connect() picks the backend, and nothing after it changes:
from ferro import connect, engines
await connect(url, auto_migrate=True)
async with engines.session():
await User.create(username="ada", email="ada@example.com", age=36)
adults = await User.where(lambda user: user.age >= 18).all()
assert [user.username for user in adults] == ["ada"]
That block runs as written against an empty database, with url set to any of these:
| Backend | URL |
|---|---|
SQLite, file-backed (rwc creates the file if missing) |
sqlite:app.db?mode=rwc |
| SQLite, in memory | sqlite::memory: |
| PostgreSQL | postgresql://user:password@localhost:5432/app |
| PostgreSQL, short scheme | postgres://user:password@localhost:5432/app |
Hosted PostgreSQL services take the same postgresql:// URL; Connections › Supabase shows how to require TLS on one.
Ferro reads the backend from the URL once, in connect(). From then on the engine holds a SQLite pool or a PostgreSQL pool, two separate types, and no operation looks at the URL again. Any other scheme fails in connect(), naming the ones it accepts:
from ferro import InterfaceError, connect
try:
await connect("mysql://user:password@localhost:3306/app")
except InterfaceError as error:
print(f"InterfaceError: {error}")
else:
raise AssertionError("expected InterfaceError")
It prints:
InterfaceError: DB Connection failed for mysql://***: Unsupported database URL scheme 'mysql'. Supported schemes: sqlite, postgres, postgresql
The failed call registers no connection, so you can fix the URL and call connect() again.
Type mapping¶
Ferro derives each column's type from the field's annotation, and Models and fields › Field types lists the type every annotation gets on each backend, generated from the code that decides it. The differences that matter come from how each database treats a declared type:
- PostgreSQL types are strict. A
uuid.UUIDfield is a nativeuuidcolumn, aboolisbool, adatetimeistimestamp with time zone, anddict,listand nested-model fields arejsonb(db_type="json"gives plainjson). AStrEnumbecomes a native enum type. - SQLite types are advisory. SQLite stores any value in any column, whatever its declared type, so a
boolis stored as an integer, aUUIDand adatetimeas text, and a JSON field as JSON text.
Either way, a value comes back as the field's annotated Python type: a bool from SQLite's 0 or 1, an exact Decimal with no float rounding, a UUID, a datetime, date or time, an enum member, or the dict or list you saved. The model is the contract; each backend stores the value its own way, and hydration turns it back into the annotated type.
An int field is integer on both backends. For a 64-bit column, declare db_type="bigint"; Column type overrides with db_type lists every token.
Raw SQL¶
The ORM binds every value for you, with the casts the column needs. Raw SQL goes to the driver as you wrote it, so two differences show through:
- Placeholders are the backend's own:
?on SQLite,$1,$2, ... on PostgreSQL. Ferro does not translate them, and a mismatch fails with the database's own error. See Raw SQL › Placeholders. - Bound values are not cast. Raw SQL has no model to read types from, so a
UUID,datetimeorDecimalis sent as text, and rows come back as plain dicts. PostgreSQL rejects text compared with auuidornumericcolumn until you write the cast ($1::uuid,$2::numeric); SQLite accepts it, so a raw query that works on SQLite can fail on PostgreSQL. See Raw SQL › Bind types and casts.
If you want typed values in and out, use the ORM.
Schema changes¶
connect(auto_migrate=True) creates missing tables the same way on both backends, and migrate_updates=True adds missing columns and indexes on both. Beyond that, each backend changes what it can change in place:
- PostgreSQL changes a column's type (
ALTER COLUMN ... TYPE ... USING), its nullability (SET NOT NULL,DROP NOT NULL) and Ferro's constraints in place. - SQLite cannot change a column's type, nullability or constraints on an existing table; only a rebuild of the table can. Auto-migrate never rebuilds a table, so it raises a
UserWarningnaming the column and changes nothing. The warning names two fixes: rebuild the table by hand, or adopt migrations at the schema the database holds (ferro migrate new, thenferro migrate baseline) and generate the change as the next migration, a reviewed table rebuild. The Alembic bridge refuses the change and namesferro migrate new.
Because SQLite stores any value in any column, a SQLite column whose declared type differs from the model's still accepts every write; the warning is about the declared schema, not your data. Auto-migrate › Applying column changes lists every change per backend.
PostgreSQL schema isolation¶
Add ferro_search_path to a PostgreSQL URL and every pooled connection runs SET search_path to that schema:
from ferro import connect
await connect(
"postgresql://user:password@localhost:5432/app?ferro_search_path=test_42",
auto_migrate=True,
)
Unqualified table names now resolve in test_42, so many test runs can share one database, each with its own tables. Connections › Postgres schema isolation covers the rules for the name.
See also¶
- Connections: URLs, sessions, pools and named connections
- Models and fields › Field types: the column type of every annotation
- Raw SQL: placeholders and casts on each backend
- Schema management: auto-migrate, migrations and the Alembic bridge on each backend
- Architecture: where the backend layer sits in the engine