Query Builder
A fluent, chainable interface for reading and writing rows, with sync and async execution built in.
The query builder is how you talk to the database in Alata. You start a chain from a model class, stack constraints fluently, and finish with a terminal method that executes the query. Under the hood every chain compiles to a SQLAlchemy 2.0 statement, so you get real bind parameters, dialect-aware SQL, and the async engine for free.
from app.models.user import User
users = await User.where("active", True).order_by("created_at", "desc").limit(10).aget()Sync and async: one API, two prefixes
Every terminal method comes in two flavors: a sync form for CLI commands, migrations, and workers, and an async form — same name with an a prefix — for HTTP endpoints and anything running on the event loop:
user = User.where("email", email).first() # sync
user = await User.where("email", email).afirst() # asyncget/aget, count/acount, update/aupdate, paginate/apaginate — the pattern holds across the entire API. The chain-building methods (where, order_by, limit, …) are identical in both worlds; only the terminal call differs. Examples below use whichever form reads best — the other is always one prefix away.
Chains are immutable: every builder method returns a new builder, so you can branch from a base query safely.
base = User.where("active", True)
admins = base.where("role", "admin").get()
recent = base.order_by("created_at", "desc").limit(5).get() # base is unchangedStarting a query
A chain starts from one of the model's query-starter class methods:
Model.where(...)and thewhere_*family (where_null,where_not_null,where_in,where_not_in,where_between,where_raw)Model.with_(...)— start with eager loadingModel.with_count(...)and thewith_sum/with_max/with_min/with_avgfamily — start with relation aggregatesModel.has(...)/Model.where_has(...)— start with a relationship-existence filterModel.query()— a bare builder, for methods with no starter of their own (select,join,distinct,union,from_statement,where_relation, …)
Once the chain is started, every builder method below is available. For table access without a model, see raw table queries at the end of this page.
Retrieving rows
All matching rows: get
get() executes the query and returns a Collection of model instances (or of plain dicts when the query projects columns — see selecting specific columns):
posts = await Post.where("status", "published").aget()
for post in posts:
print(post.title)To fetch every row in the table, use the model shortcut all() / aall():
users = await User.aall()A single row: first, sole
first() limits the query to one row and returns the instance or None:
user = await User.where("email", email).afirst()
if user is None:
...first_or_fail() raises ModelNotFoundError instead of returning None — useful when a missing row is an error:
from alata.db import ModelNotFoundError
user = await User.where("email", email).afirst_or_fail()sole() asserts the query matches exactly one row — it raises ModelNotFoundError when there are zero matches or more than one:
setting = await Setting.where("key", "billing.currency").asole()By primary key: find
The model exposes primary-key lookups directly:
user = await User.afind(42) # instance or None
user = await User.afind_or_fail(42) # raises ModelNotFoundError if missing
users = await User.afind_many([1, 2, 3]) # Collectionfind resolves the model's actual primary-key column — it is not hardcoded to id. There is also first_where, a one-liner for the most common lookup:
user = await User.afirst_where("email", email) # == where("email", email).afirst()Single values: value and pluck
value() returns one column from the first matching row:
name = await User.where("id", 42).avalue("name")pluck() returns a Collection of a single column across all matching rows — or a dict when you pass a second column to key by:
emails = await User.where("active", True).apluck("email")
# Collection(["a@example.com", "b@example.com", ...])
names_by_id = await User.where("active", True).apluck("name", "id")
# {1: "Alice", 2: "Bob", ...}Both work in row mode too — after select() the rows are dicts, and the named key is read from them:
User.where("id", 42).select("id", "name").value("name") # "Alice"
User.where("active", True).select("id", "age").pluck("age") # Collection([31, 27, ...])Existence and counting
if await User.where("email", email).aexists():
...
if await User.where("email", email).adoesnt_exist():
...
total = await Post.where("status", "published").acount()exists() compiles to SELECT EXISTS(SELECT 1 ... LIMIT 1), so the database stops at the first matching row instead of counting everything — always prefer it over count() > 0 when you only need a yes/no answer.
Other aggregates
max, min, avg, and sum each take a column and respect every accumulated constraint:
q = Order.where("status", "paid")
highest = await q.amax("total")
lowest = await q.amin("total")
average = await q.aavg("total")
revenue = await q.asum("total")Selecting specific columns
By default a query selects the full row and hydrates complete model instances. select() switches the query into row mode: you name the columns, and results come back as plain dicts, still wrapped in a Collection:
rows = await User.where("age", ">", 18).select("id", "name as username").aget()
# Collection([{"id": 7, "username": "Ada"}, ...])Column strings support "col", "col as alias", and — after a join — "table.col". In row mode, first() returns a dict (or None), and eager loading does not apply.
select_raw() adds a raw SQL fragment to the projection and combines freely with select(). A trailing as alias names the result key:
rows = User.where("active", True).select("name").select_raw("upper(name) as shout").get()
# [{"name": "Ada", "shout": "ADA"}, ...]The alias is taken from the last as in the string, so expressions carrying their own AS survive intact, and a quoted alias becomes a clean dict key:
User.select_raw("CAST(age AS text) as label") # {"label": "42"} — the CAST is not split
User.select_raw("CAST(age AS text)") # no alias; the fragment is left whole
User.select('age as "user age"') # {"user age": 42}Why dicts instead of partial models? A model instance with only some of its columns loaded is a trap — every missing attribute looks like real data. Alata refuses to hydrate incomplete instances: either you get the whole model (no select()), or you get honest dict rows. Model hydration is completely unaffected when select() is not used.
Joins
join() adds an INNER JOIN so you can filter, order, or project across another table. Pass a table name or a model class, then the two sides of the ON clause:
authors = (
User.where("active", True)
.join("posts", "id", "=", "posts.user_id")
.where("posts.status", "published")
.get()
)After a join, "table.col" strings resolve across every joined table — in where(), order_by(), select(), group_by(), and having(). Plain column names keep resolving against the base model, and the ON clause accepts the same operators as where().
Without select(), a joined query still hydrates the base model — the results above are User instances; the join exists for filtering. Add select() to project columns from both sides:
rows = (
User.where("active", True)
.join("posts", "id", "=", "posts.user_id")
.select("users.name", "posts.title")
.get()
)left_join() takes the same arguments and keeps base rows with no match (LEFT OUTER JOIN):
users = User.where("active", True).left_join("posts", "id", "=", "posts.user_id").get()join_sub() joins a derived table built from another builder. The subquery's filters compile into the derived table, which is joined under an alias — reference its columns as "alias.col":
published = Post.where("status", "published")
users = (
User.where("active", True)
.join_sub(published, "pub", "id", "=", "pub.user_id")
.get()
)Distinct
distinct() de-duplicates result rows (SELECT DISTINCT) and is portable across databases:
ages = User.where("active", True).select("age").distinct().order_by("age").get()distinct_on() keeps one row per distinct combination of the given columns (SELECT DISTINCT ON). Order by the same leading columns to control which row wins per group:
latest_per_thread = (
Message.where_not_null("thread_id")
.distinct_on("thread_id")
.order_by("thread_id")
.order_by("sent_at", "desc")
.get()
)count() honors both forms — it counts the de-duplicated rows, so a paginate() total always matches the number of rows the page query can actually return:
q = User.where("active", True).select("age").distinct()
len(q.get()) # 4 distinct ages
q.count() # 4 — not the raw row countdistinct_on() is PostgreSQL-only — on any other dialect the query raises NotImplementedError when it is built. Use distinct() for portable de-duplication. For the "one row per group" pattern on other databases, reach for latest_of_many() / oldest_of_many() on a relationship, or a row_number() window query via from_statement().
Unions
union() combines two builders and removes duplicate rows; union_all() keeps them:
young = User.where("age", "<", 20)
old = User.where("age", ">", 60)
users = young.union(old).order_by("age").get()Both queries must produce the same shape — the same model, or row mode with matching columns. Ordering, limit(), and offset() on the receiving builder apply to the combined result; the other builder's ordering and limit are not carried over. In model mode the combined rows hydrate as usual; in row mode you get dicts:
rows = (
User.where("age", "<", 20).select("id", "age")
.union_all(User.where("age", ">", 60).select("id", "age"))
.order_by("age")
.get()
)count(), exists(), and paginate() totals cover every part of the union — they wrap the compound select rather than counting the receiving builder's table alone.
Keyset pagination is not available on a union. cursor_paginate(), chunk_by_id(), and lazy_by_id() (plus their async twins) raise NotImplementedError on a union query. A keyset predicate is ANDed into the receiving builder's own select, so it never reaches the other parts — their rows would be served again on every page and the iteration would never terminate. Paginate each part separately and merge, or use offset pagination (paginate() / chunk()) over the union.
Where clauses
Basic where
where() takes two or three arguments. With two, the operator is =:
User.where("name", "Alice") # name = 'Alice'
User.where("age", ">=", 18) # age >= 18Supported operators: =, !=, <>, <, <=, >, >=, like, ilike, not like.
User.where("email", "like", "%@example.com")
User.where("name", "ilike", "ali%") # case-insensitive matching
User.where("name", "not like", "test%")Chained where() calls are combined with AND:
User.where("active", True).where("age", ">=", 18).get()
# WHERE active = true AND age >= 18When strict mode is enabled (DB_STRICT_MODE), referencing a column that doesn't exist on the model raises immediately with the list of valid columns — instead of failing later at the database.
or_where
or_where() adds an OR branch:
users = User.where("role", "admin").or_where("role", "owner").get()
# WHERE role = 'admin' OR role = 'owner'OR grouping semantics. or_where always ORs against the entire accumulated AND group, not just the previous where:
User.where("name", "mw").where("age", ">=", 20).or_where("name", "other").get()
# WHERE (name = 'mw' AND age >= 20) OR name = 'other'If you need A AND (B OR C), wrap the OR pair in a closure — see nested wheres below.
Nested wheres
Both where() and or_where() accept a lambda that receives a fresh builder. The nested group is parenthesized as a unit:
results = (
User.where("age", ">", 25)
.where(lambda q: q.where("name", "Alice").or_where("email", "like", "%@corp.com"))
.get()
)
# WHERE age > 25 AND (name = 'Alice' OR email LIKE '%@corp.com')Null, in, between, and column comparisons
User.where_null("deleted_reason") # IS NULL
User.where_not_null("email_verified_at") # IS NOT NULL
User.where_in("role", ["admin", "owner"]) # IN (...)
User.where_not_in("status", ["banned", "spam"]) # NOT IN (...)
Order.where_between("total", [100, 500]) # BETWEEN 100 AND 500
Order.where("status", "paid").where_not_between("total", [100, 500]) # NOT BETWEEN
Task.where_not_null("id").where_column("updated_at", "created_at") # compare two columnswhere, where_null, where_not_null, where_in, where_not_in, where_between, and where_raw double as chain starters on the model class. The remaining builder methods (where_not_between, where_column, or_where, when, ordering, grouping, …) are available anywhere after the chain has started — including straight off Model.query().
Conditional clauses: when
when() applies a constraint only if a condition is truthy — no need to break the chain into if/else:
status = request.query_params.get("status")
posts = await (
Post.where("author_id", author.id)
.when(status, lambda q: q.where("status", status))
.aget()
)Raw where clauses
where_raw() injects a raw SQL fragment with named bind parameters:
users = await User.where_raw("score > :min", {"min": 80}).aget()
users = await User.where_raw("LOWER(email) = :email", {"email": value.lower()}).aget()Raw parameters thread through every terminal method — get, count, aggregates, update, delete, sync and async alike. All raw parameters on one query share a single namespace, so reusing a name across where_raw() calls raises ValueError rather than silently corrupting the earlier clause:
q = (
User.where_raw("age > :min_age", {"min_age": 18})
.where_raw("score > :min_score", {"min_score": 80}) # distinct names — OK
)Raw clauses inside a nested closure or a where_has() callback join the same namespace, so their parameters bind normally — and reusing a name across the boundary raises the same ValueError:
User.where(lambda q: q.where_raw("age > :min", {"min": 18})).get()
User.where_has("posts", lambda q: q.where_raw("views > :v", {"v": 100})).get()Filtering by relationships: has and where_has
has() keeps only rows that have at least one related record; an operator and count let you set a threshold:
authors = User.has("posts").get() # users with any post
prolific = User.has("posts", ">=", 3).get() # users with 3+ postswhere_has() adds constraints on the related rows via an EXISTS subquery:
publishers = User.where_has("posts", lambda q: q.where("status", "published")).get()For the common single-condition case, where_relation() is a compact shorthand — it takes the same 2- or 3-argument forms as where() and expands to where_has(relation, lambda q: q.where(col, ...)):
publishers = User.where("active", True).where_relation("posts", "status", "published").get()
popular = User.where("active", True).where_relation("posts", "views", ">=", 100).get()where_relation lives on the builder, so chain it after a query starter — Model.query().where_relation(...) works.
Correlated subqueries: where_exists
When the correlation isn't a declared relationship, where_exists() filters with a correlated EXISTS (SELECT 1 ...) subquery built from another builder (or a callable that receives a fresh builder). The subquery reaches the outer query through "table.col" references — where_column() with dotted names expresses the correlation:
published = Post.where("status", "published").where_column("posts.user_id", "users.id")
authors = User.where("active", True).where_exists(published).get()
# ... WHERE active AND EXISTS (
# SELECT 1 FROM posts
# WHERE status = 'published' AND posts.user_id = users.id)where_not_exists() accepts the same argument and negates the check.
Subqueries in where_in
where_in() and where_not_in() accept another builder in place of a value list, compiling to WHERE col IN (SELECT ...) — one round trip, no intermediate id list in Python. The inner query must project exactly one column with select(); anything else raises ValueError:
author_ids = Post.where("status", "published").select("user_id")
authors = User.where("active", True).where_in("id", author_ids).get()
lurkers = User.where("active", True).where_not_in("id", author_ids).get()JSON queries
Query JSON columns on PostgreSQL, MySQL, and SQLite. Separate nested path segments with ->:
User.where_json_contains("preferences->languages", "en").get()
User.where_json_contains("preferences->languages", ["en", "ja"]).get()
User.where_json_contains_key("preferences->notifications").get()
User.where_json_length("preferences->languages", ">", 1).get()where_json_doesnt_contain() and where_json_doesnt_contain_key() provide the negative forms. A present key with a JSON null value still counts as present. Length predicates apply to arrays. Each helper also has an or_where_... form for chaining and works with async terminal methods such as aget().
These helpers are also available on DB.table("users") and named connections.
Full-text search
Search indexed text on MySQL and PostgreSQL:
Post.where_full_text(["title", "body"], "python framework").get()Create a matching full-text index first. Plain search is the default. mode="boolean" accepts the database's native boolean-search syntax; PostgreSQL also supports mode="websearch" and a language option. or_where_full_text() adds an OR condition. SQLite full-text modules are not exposed through this API.
Ordering, grouping, limit and offset
Ordering
User.where("active", True).order_by("name").get() # ASC (default)
User.where("active", True).order_by("created_at", "desc").get()latest() and oldest() are shortcuts that default to created_at:
Post.where("status", "published").latest().first() # newest first
Post.where("status", "published").oldest("id").get()in_random_order() shuffles at the database level, and order_by_raw() accepts a raw SQL fragment:
Quote.where_not_null("text").in_random_order().limit(1).first()
Post.where("status", "published").order_by_raw("char_length(title) DESC").get()Grouping and having
rows = (
Order.where("status", "paid")
.group_by("customer_id")
.having("customer_id", ">", 100)
.get()
)having() takes the same operators as where(). For aggregate conditions, having_raw() accepts a raw SQL fragment with named parameters — the bind namespace (and its name-collision guard) is shared with where_raw():
big_customers = (
Order.where("status", "paid")
.select("customer_id")
.select_raw("sum(total) as revenue")
.group_by("customer_id")
.having_raw("sum(total) > :min", {"min": 1000})
.get()
)
# [{"customer_id": 7, "revenue": 1520}, ...]Limit and offset
User.where("active", True).order_by("id").limit(20).offset(40).get()Pagination
paginate() / apaginate() runs a count plus a page query and returns a plain dict:
page = await Post.where("status", "published").order_by("id").apaginate(per_page=15, page=2)
page["data"] # Collection of model instances for this page
page["total"] # total matching rows
page["per_page"] # 15
page["current_page"] # 2
page["last_page"] # total pages (always >= 1)Because it is a plain dict, it serializes straight into a JSON response.
Grouped counts
count() — and therefore paginate() totals — understands grouping. On a grouped query, the count is the number of groups that survive GROUP BY / HAVING, not the raw row count:
distinct_ages = User.where("active", True).group_by("age").count()
# SELECT count(*) FROM (SELECT age ... GROUP BY age) — number of groups
surviving = User.where("active", True).group_by("age").having("age", ">", 25).count()
# only groups passing HAVING are countedCursor pagination
Offset pagination degrades on big tables: page N forces the database to scan and discard everything before it. cursor_paginate() / acursor_paginate() paginates by keyset over the query's order_by() columns instead — each page filters on the previous page's boundary values, so page 500 costs the same as page 1:
page = await Post.where("status", "published").order_by("id").acursor_paginate(per_page=15)
page["data"] # Collection of model instances for this page
page["per_page"] # 15
page["next_cursor"] # opaque string, or None on the last page
page["prev_cursor"] # opaque string, or None on the first pagePass a returned cursor back in to fetch the adjacent page — next_cursor pages forward, prev_cursor pages backward:
page2 = await (
Post.where("status", "published")
.order_by("id")
.acursor_paginate(per_page=15, cursor=page["next_cursor"])
)Cursors are opaque URL-safe strings encoding the boundary row's ordering values, so they drop straight into a query parameter. Because they arrive from user-controlled query strings, the decoded payload is fully shape-checked before anything reaches the database: a cursor that is not valid base64 JSON, does not carry a v mapping of the query's exact ordering columns, holds a nested object or list in place of a scalar, or carries an unparseable date raises ValueError("Invalid pagination cursor").
A few rules:
- With no
order_by()on the query, rows are ordered by the primary key ascending automatically. - The ordering should uniquely identify rows — include the primary key as a tie-breaker (
.order_by("created_at", "desc").order_by("id", "desc")), or ties across a page boundary may be skipped. - All ordering must come from
order_by()columns;order_by_raw()andin_random_order()raiseValueError. - Boundary values are decoded back into the ordering column's own Python type, so text,
int,float,bool,Decimal,datetime,date,timeandUUIDcolumns all round-trip exactly. A column whose values a cursor cannot carry —bytes,timedelta, anEnummember — raisesValueErrornaming the column instead of serving a wrong page. - Nullable ordering columns are fine — NULLs sort last, deterministically. See below.
- Unions are not supported — see Unions.
- There is no
totalkey — computing it would require the full count that keyset pagination exists to avoid. Usepaginate()when you need page numbers.
Nullable ordering columns
Ordering on a nullable column (published_at, created_at, a nullable score) is supported, and every row is served exactly once — no duplicates, no omissions:
page = Post.order_by("published_at", "desc").order_by("id").cursor_paginate(per_page=20)
# unpublished posts (published_at IS NULL) arrive on the final pages, once eachThe contract:
- NULLs sort last in both directions, ascending and descending alike, on every database. Databases disagree about NULL placement by default — one treats NULL as the largest value, the other as the smallest — so the builder pins the placement itself with an explicit rank term rather than inheriting the dialect's default. PostgreSQL and MySQL therefore serve identical row sequences.
- The keyset predicate matches that placement, so a page boundary landing on a NULL row pages on correctly. Cursors round-trip a NULL boundary value as JSON
null. - A
NOT NULLordering column costs nothing extra — no rank term is added, and the ORDER BY stays index-friendly.
The tie-breaker rule still applies: NULLs compare equal to one another, so pair a nullable column with the primary key (.order_by("published_at").order_by("id")) if you want a total order.
Cursors are still validated. A cursor claiming null for a NOT NULL column cannot come from a real boundary row, so it is rejected as tampering with ValueError("Invalid pagination cursor") — the same guard that catches malformed payloads and unparseable dates.
Cursor pagination works in row mode too — after select(), page["data"] holds dicts.
Keyset iteration for large tables
For iteration-style workloads (backfills, exports), the *_by_id chunking methods below apply the same keyset idea internally — they walk the table with WHERE id > last_seen instead of OFFSET, keeping total work linear.
Chunking and lazy iteration
chunk and chunk_by_id
chunk() processes results in batches so you never hold the full result set in memory. The callback receives a list of instances; return False to stop early. It returns True when every chunk was processed, False if stopped early:
def index_batch(users):
search.index(users)
User.where("active", True).chunk(500, index_batch)chunk() paginates via SQL OFFSET, which makes total work O(n²) on large tables. Past roughly 100k rows, use chunk_by_id() — it walks the table with an indexed keyset cursor and stays O(n).
User.where("active", True).chunk_by_id(500, index_batch) # cursor on "id"
Event.where("kind", "click").chunk_by_id(1000, handle, column="event_id")chunk_by_id() / lazy_by_id() order by column alone when it is NOT NULL. If column is nullable they follow the same NULL contract as cursor pagination — NULLs last, primary key appended as a tie-breaker — so a chunk ending on a NULL still advances and every row is visited exactly once. They also replace any earlier order_by() on the query: the walk order has to match the keyset cursor, or rows would be skipped.
The async forms take a coroutine callback:
async def index_batch(users):
await search.aindex(users)
await User.where("active", True).achunk_by_id(500, index_batch)each
each() wraps chunk() to hand you one instance at a time; return False to stop:
User.where("active", True).each(lambda user: mailer.queue(user))
await User.where("active", True).aeach(notify_user, size=200)lazy and lazy_by_id
lazy() returns a generator that yields instances chunk by chunk — iterate a huge table with a plain for loop:
for user in User.where("active", True).lazy(chunk_size=500):
process(user)Like chunk(), lazy() uses OFFSET under the hood; prefer lazy_by_id() for large tables. The async variants are async generators:
async for user in User.where("active", True).alazy_by_id(500):
await process(user)Inserting rows
Creation goes through the model. create() inserts one row and returns the instance with its primary key populated; insert() bulk-inserts without building instances:
user = await User.acreate({"name": "Alice", "email": "alice@example.com"})
user.id # populated
await User.ainsert([
{"name": "Bob", "email": "bob@example.com"},
{"name": "Carol", "email": "carol@example.com"},
])first_or_create() and update_or_create() handle find-or-insert flows atomically — see Models for those and for mass-assignment (__fillable__) rules that apply to all creation paths.
Updating rows
update() applies a dict of changes to every row matched by the accumulated constraints and returns the affected count:
count = await User.where("email", email).aupdate({"name": "New Name"})If the model has an updated_at column, it is touched automatically on every builder update (unless you set it explicitly). Model-level casts (__casts__) are applied to the values.
Updates and deletes honor the full WHERE composition — including or_where. A mutation targets exactly the rows the equivalent get() would return:
User.where("name", "A").or_where("name", "B").update({"age": 99})
# updates rows matching name = 'A' OR name = 'B'Also note: a builder update with no where clause updates every row in the table.
Updating and deleting through a join
UPDATE and DELETE have no FROM/JOIN list of their own, so a join-narrowed mutation is scoped through a primary-key subquery instead:
(
User.join("posts", "id", "=", "posts.user_id")
.where("posts.status", "published")
.update({"is_author": True})
)
# UPDATE users SET is_author = true
# WHERE id IN (SELECT pk FROM (SELECT users.id FROM users
# JOIN posts ON ... WHERE ...) AS scope)The mutation therefore hits exactly the rows the equivalent get() returns — the same guarantee as an unjoined update. The extra derived-table wrapper keeps it portable: MySQL otherwise refuses a subquery that reads the table being modified.
This path needs a single-column primary key. On a model with a composite key, a join-narrowed update() / delete() raises NotImplementedError rather than mutating too many rows — fetch the rows with get() and mutate them individually.
Increment and decrement
await Post.where("id", post_id).aincrement("views") # +1
await User.where("id", user_id).aincrement("credits", 50) # +50
await User.where("id", user_id).adecrement("credits", 10) # -10Deleting rows
delete() hard-deletes matching rows and returns the affected count:
count = await Session.where("expired_at", "<", now).adelete()Like update(), delete() honors or_where, and a delete with no constraints removes every row.
Soft deletes
On models using soft deletes, the builder offers:
await Post.where("id", post.id).asoft_delete() # sets deleted_at — row hidden from queries
await Post.where("id", post.id).with_trashed().arestore() # sets deleted_at back to NULL
Post.where("user_id", uid).with_trashed().get() # include soft-deleted rows
Post.where("user_id", uid).only_trashed().get() # ONLY soft-deleted rowsSoft-deleted rows are excluded from every query automatically via a global scope — see Models for the full soft-delete lifecycle.
Global scopes
Any named global scope can be bypassed per query:
Invoice.where("total", ">", 0).without_global_scope("tenant").get()
Invoice.where("total", ">", 0).without_global_scopes().get() # bypass ALL scopesUpserts
upsert() inserts multiple rows and updates the ones that collide on a unique constraint — one statement, no read-modify-write race:
await Flight.aupsert(
[
{"departure": "Oakland", "destination": "San Diego", "price": 99},
{"departure": "Chicago", "destination": "New York", "price": 150},
],
unique_by=["departure", "destination"], # conflict target
update_cols=["price"], # columns to overwrite on conflict
)An explicit update_cols list is taken literally — exactly those columns are written, nothing is added. Naming the primary key or created_at there is allowed, and will overwrite them. update_cols=[] raises ValueError: it names nothing to write, so it is almost always an empty computation rather than intent.
If update_cols is omitted, the conflicting row is updated with only the columns the supplied rows actually name, minus the unique_by columns, the primary key, and created_at. Columns the rows leave out keep their stored values, and the row keeps its primary key — so foreign keys pointing at it stay valid:
await Flight.aupsert(
[{"departure": "Oakland", "destination": "San Diego", "price": 79}],
unique_by=["departure", "destination"],
) # SET price = excluded.price, updated_at = now()
# airline, seat_count, created_at, id — all untouchedOn a model with timestamps, updated_at is stamped with the current time on conflict unless the rows supply their own value.
Rows that name nothing but the conflict key have nothing to write: they insert the rows that are missing and leave existing rows untouched — ON CONFLICT DO NOTHING on PostgreSQL and SQLite, a no-op self-assignment on MySQL.
On PostgreSQL and SQLite the update compiles to ON CONFLICT (...) DO UPDATE; on MySQL to ON DUPLICATE KEY UPDATE.
The returned integer is dialect-dependent and is not a "rows changed" figure anywhere: PostgreSQL and SQLite count 1 per row written, while MySQL counts an updated row as 2 and a row whose values did not change as 0. Do not branch on it.
On MySQL, unique_by is accepted for API consistency but not used to target a specific constraint — MySQL fires the update on any unique-key violation.
The default used to be every column except unique_by, derived from the table rather than the rows. That emitted SET id = excluded.id, reassigning the conflicting row's primary key and orphaning every foreign key referencing it; it also reset omitted columns to their column defaults and moved created_at, and on MySQL it failed outright on partial rows with Unknown column 'new.id' in 'field list'. If you were passing update_cols explicitly to work around any of that, the explicit list still behaves exactly as before.
Pessimistic locking
Inside a transaction, lock the selected rows:
from alata.db import DB
with DB.transaction():
account = Account.where("id", account_id).lock_for_update().first() # SELECT ... FOR UPDATE
account.balance -= amount
account.save()lock_for_update() accepts two options: skip_locked=True skips rows another transaction has already locked (SKIP LOCKED — the standard pattern for pulling work from a job table without contention), and nowait=True raises immediately instead of waiting on a conflicting lock (NOWAIT):
job = Job.where("status", "pending").order_by("id").lock_for_update(skip_locked=True).first()shared_lock() takes a shared lock instead (SELECT ... FOR SHARE), blocking writers but not other readers; it accepts the same skip_locked / nowait options.
These row locks apply to PostgreSQL and MySQL. SQLite does not support row-level locks: these methods add no locking clause, and SQLite permits only one writer per database file. Use PostgreSQL or MySQL for workflows that depend on SKIP LOCKED or concurrent row locks.
The skip_locked and nowait options require PostgreSQL or MySQL 8.0+ — earlier MySQL versions accept FOR UPDATE but not the SKIP LOCKED / NOWAIT modifiers.
Eager loading
with_() loads relationships alongside the main query, avoiding N+1 patterns. Dotted paths load nested relations:
posts = await Post.with_("author", "comments.author").where("status", "published").aget()
for post in posts:
post.author # already loaded — no extra querywith_() also accepts {relation: callable} entries that constrain the eager sub-query, and the with_count() / with_sum() family loads relation aggregates without N+1. Relationships and eager-loading details — including those forms — live on the Models page.
Aggregates never overwrite a stored column. A relation aggregate is loaded onto each instance under a derived name — with_count("posts") fills posts_count, with_sum("orders", "total") fills orders_sum_total. If the model already has a real column by that name, building the query raises ValueError:
class User(Model):
posts_count = int_col(default=0) # a stored, denormalized counter
User.with_count("posts").get()
# ValueError: Relation aggregate 'posts_count' collides with the real column
# 'User.posts_count'. ...Silently assigning it would shadow the stored value, mark the instance dirty, and let the next save() persist the computed aggregate over your data. Rename the column, or read the aggregate with a separate query.
Debugging queries
to_sql and get_bindings
to_sql() returns the compiled SQL with literal values inlined — copy-paste-runnable in psql. get_bindings() returns the bind values as a dict:
q = User.where("age", ">", 18).order_by("name")
print(q.to_sql())
# SELECT users.id, users.name, ... FROM users WHERE users.age > 18 ORDER BY users.name ASC
print(q.get_bindings())
# {"age_1": 18}dump and dd
dump() pretty-prints the SQL and bindings to the console and returns the builder, so you can drop it mid-chain. dd() does the same, then exits the process:
User.where("active", True).dump().where("age", ">", 18).get() # prints, keeps going
User.where("active", True).dd() # prints and exitsexplain
explain() runs the query through the database's EXPLAIN and returns the plan rows as dicts — bind parameters (including where_raw() params) are passed to the driver normally:
plan = User.where("email", "like", "%@example.com").explain()
for row in plan:
print(row)
# {'QUERY PLAN': 'Seq Scan on users (cost=0.00..1.14 rows=1 width=244) ...'}If a sequential scan shows up where you expected an index, you know before production does.
Dropping to SQLAlchemy
The builder covers the common ninety-five percent. For the rest — window functions, recursive CTEs, lateral joins — you don't leave the framework: compose the statement with SQLAlchemy Core and run it through from_statement(). This is the blessed path beyond the builder, not a workaround.
import sqlalchemy as sa
from app.models.user import User
users_t = User.__table__ # every model exposes its SQLAlchemy Table
ranked = sa.select(
users_t,
sa.func.rank().over(order_by=users_t.c.age.desc()).label("age_rank"),
).where(users_t.c.active.is_(True))
users = User.query().from_statement(ranked).get()
users[0].age_rank # extra columns ride along as plain attributesThe statement executes on the framework's session for the builder's connection — same engine, same pool, same ambient transaction — and results come back in the most useful shape:
- An ORM-enabled statement (
sa.select(User)) hydrates model instances directly. - Rows containing every model column hydrate through
Model.hydrate()— real instances with read casts applied, plus any extra columns as plain attributes. - Anything else (partial projections, aggregates) returns dict rows.
Model.query() hands you a bare builder — the entry point for any builder method that has no classmethod starter of its own (select(), join(), distinct(), union(), from_statement()). All the usual terminals work — get/aget, first/afirst.
The statement runs exactly as written: global scopes (including soft-delete filtering) are not applied, and no model events fire. from_statement() also replaces the composed query entirely — any where() / order_by() already on the builder is ignored.
When even a hand-built statement isn't enough, take the session itself — get_session() / get_async_session() and the session yielded by DB.transaction() are covered under SQLAlchemy access on the Getting Started page.
Raw table queries: DB.table()
For tables without a model — pivot tables, one-off admin queries, data fixes — DB.table() gives you a compact builder that returns plain dicts instead of model instances:
from alata.db import DB
rows = DB.table("users").where("age", ">", 18).order_by("name").get()
# [{"id": 1, "name": "Alice", ...}, ...]
row = await DB.table("users").where("email", email).afirst() # dict or None
n = await DB.table("users").where_in("role", ["admin"]).acount()Its surface is a focused subset of the model builder:
- Wheres —
where(col, val)/where(col, op, val)(operators:=,!=,<>,>,<,>=,<=,like,ilike),where_in,where_null,where_not_null. Conditions combine with AND. - Select —
select("id", "name")to pick columns,select_raw("count(*) AS n")for raw expressions. - Shaping —
order_by(col, direction),limit(n),offset(n). - Reads —
get,first,count(async:aget,afirst,acount). - Writes —
insert(dict),update(dict),delete()(async:ainsert,aupdate,adelete).updateanddeletereturn affected row counts and honor the accumulated wheres.
DB.table("role_user").insert({"role_id": 1, "user_id": 42})
DB.table("users").where("id", 42).update({"name": "Renamed"})
DB.table("sessions").where("expired_at", "<", now).delete()
totals = DB.table("orders").select_raw("customer_id, sum(total) AS revenue").get()Table and column names are validated and quoted with the connection's dialect rules, and all values travel as bind parameters. Scope it to a named connection with DB.connection("reporting").table("sales").
DB.table() is deliberately lower-level: no casts, no soft deletes, no global scopes, no model events. When those matter, reach for a model.