Query Recipes
Patterns for the queries most applications need. Each one builds on the blog from Database Access: a query in db/queries/, then bin/cobo generate, then a call from an action. The SQL uses PostgreSQL syntax; adapt it to your engine's dialect on MySQL or SQLite.
Optional filters
A list endpoint with optional filters uses nullable parameters (sqlc.narg) where NULL means "don't filter":
-- name: SearchPosts :many
SELECT id, author_id, title, status
FROM posts
WHERE (sqlc.narg(author_id)::bigint IS NULL OR author_id = sqlc.narg(author_id))
AND (sqlc.narg(status)::text IS NULL OR status = sqlc.narg(status))
AND (sqlc.narg(query)::text IS NULL OR title ILIKE '%' || sqlc.narg(query) || '%')
ORDER BY id DESC
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);The ::bigint / ::text casts tell sqlc each parameter's type; using the same name twice reuses one parameter. The generated method takes nilable arguments, so optional contract fields pass straight through:
class Posts::ListPostsContract < RequestValidation::Contract
schema do
optional :author_id, Int64
optional :status, String, allowed_values: ["draft", "published"]
optional :q, String, filled: true
optional :page, Int32
end
end
class Posts::ListPosts < Blog::BaseAction
get "/posts"
call do
input = validate(ListPostsContract)
page = Runcobo::Pagination.new(input.page, 20)
posts = store.search_posts(author_id: input.author_id, status: input.status, query: input.q,
row_limit: page.per_page, row_offset: page.offset.to_i32)
render_json(posts.map { |post| {id: post.id, title: post.title, status: post.status} })
end
end/posts, /posts?status=published and /posts?author_id=3&q=crystal all run this one query.
Related rows: a JOIN
sqlc.embed(table) returns a table's columns as a nested struct:
-- name: ListPostsWithAuthor :many
SELECT sqlc.embed(posts), sqlc.embed(authors)
FROM posts
JOIN authors ON authors.id = posts.author_id
ORDER BY posts.id;store.list_posts_with_author.each do |row|
post = row.posts.not_nil!
author = row.authors.not_nil!
# post.title, author.name
endThe embedded fields are typed nilable because the generator can't always tell inner from outer joins; after an inner JOIN they're always present. A one-to-many join returns the parent once per child.
Related rows: one query per level
To attach each author's posts without repeating the author on every row, load the posts for all authors at once and group them:
-- name: ListAuthors :many
SELECT id, name, bio FROM authors ORDER BY id;
-- name: ListPostsByAuthors :many
SELECT id, author_id, title, status
FROM posts
WHERE author_id = ANY(sqlc.arg(author_ids)::bigint[])
ORDER BY id;authors = store.list_authors
posts_by_author = store.list_posts_by_authors(author_ids: authors.map(&.id)).group_by(&.author_id)
render_json(authors.map { |author|
titles = posts_by_author[author.id]?.try(&.map(&.title)) || [] of String
{id: author.id, name: author.name, posts: titles}
})Two queries however many authors — what Active Record calls eager loading. ANY(...) also accepts an empty array.
Counts and aggregates
-- name: CountPostsPerAuthor :many
SELECT authors.id, authors.name, count(posts.id) AS post_count
FROM authors
LEFT JOIN posts ON posts.author_id = authors.id
GROUP BY authors.id, authors.name
ORDER BY authors.id;row.post_count is an Int64.
Partial updates
For PATCH, an omitted field must be left alone, while an explicit null clears it. Contracts tell the two apart with <field>_present? (details); pass that flag to the query:
-- name: UpdateAuthor :one
UPDATE authors SET
name = CASE WHEN sqlc.arg(name_present)::boolean THEN sqlc.narg(name)::text ELSE name END,
bio = CASE WHEN sqlc.arg(bio_present)::boolean THEN sqlc.narg(bio)::text ELSE bio END
WHERE id = sqlc.arg(id)
RETURNING id, name, bio;class Authors::UpdateAuthorContract < RequestValidation::Contract
schema do
required :id, Int64 # from the path
optional :name, String, filled: true # from the body
optional :bio, String, nullable: true
end
endclass Authors::UpdateAuthor < Blog::BaseAction
patch "/authors/:id"
call do
input = validate(UpdateAuthorContract)
author = store.update_author?(id: input.id,
name: input.name, name_present: input.name_present?,
bio: input.bio, bio_present: input.bio_present?)
if author
render_json({id: author.id, name: author.name, bio: author.bio})
else
render_json({error: "author_not_found"}, status_code: 404)
end
end
endOne contract covers the whole request: validate merges the path parameters with the body, so id comes from /authors/:id. {"name":"Ada"} keeps the bio; {"bio":null} clears it.
Transactions
Group writes that must succeed or fail together in store.transaction:
-- name: CreateAuthor :one
INSERT INTO authors (name) VALUES (sqlc.arg(name))
RETURNING id, name, bio;call do
post = store.transaction do |tx|
author = tx.create_author(name: input.author_name)
tx.create_post(author_id: author.id, title: input.title)
end.not_nil!
render_json({id: post.id}, status_code: 201)
endEvery call on tx uses the same connection and commits together; an exception inside the block rolls everything back. Render after the block, so a client never sees data that was rolled back.
transaction returns the block's value as a nilable type: it's nil only if you roll back deliberately with raise DB::Rollback. When you don't do that, .not_nil! is safe.
To turn a constraint violation into a response, add a rescue to the call block and check the PostgreSQL error code:
call do
author = store.create_author(name: input.name)
render_json({id: author.id}, status_code: 201)
rescue error : PQ::PQError
raise error unless error.field_message(:code) == "23505" # unique_violation
render_json({error: "already_exists"}, status_code: 409)
endFor :execrows, batch inserts and COPY bulk import, see the crsql query guide. The crsql example in the repository is a complete, tested application.
Coming from Active Record
crsql works differently from Active Record–style ORMs such as Rails' Active Record or Lucky's Avram: you start from SQL rather than from model classes. If you've used one of those, this is where the familiar pieces went:
| Active Record–style | crsql |
|---|---|
| Model class | A generated row struct per query (GetPostRow) — data only, no methods |
Post.where(...), scopes | A named query per access pattern: store.search_posts(...) |
| Query builder | Optional filters with nullable parameters |
| Associations, eager loading | A JOIN, or one query per level |
save, update, destroy | INSERT, UPDATE, DELETE queries, with RETURNING when you need the row |
| Validations | Request contracts for input; database constraints (NOT NULL, UNIQUE, foreign keys) for data |
| Callbacks | Plain code in the action or a service, called explicitly |
| Lazy loading | None — every query runs exactly where you call it |
What you gain: the SQL in db/queries/ is exactly what runs, so N+1 problems are visible as a query inside a loop. Queries are checked against your migrations when you generate, and every call is checked by the compiler — renaming a column breaks the build, not production. And you can use all of PostgreSQL: CTEs, window functions, JSONB, ON CONFLICT.
What it costs: you write SQL for each operation, including simple CRUD. A query's shape is fixed when you generate — values can vary freely, but a different ORDER BY column or set of joins per request means a separate query for each variant. And rows don't link to each other; you load related data explicitly.