A mapping language to compose SQL for Go.
stitchql docs content usage querying.md
5.4 kB · 171 lines
Markdown
at main


title: Querying description: Execute generated queries, read results, compose filters, and inspect SQL from Go. #

A query declaration generates a Go query type and constructor. Construct the query, then call a method to execute it and read its results:

query := store.GetBook(id)
book, err := query.SelectOne(ctx, pool)

store.GetBook(id) captures arguments without accessing the database. SelectOne executes the statement. You can also chain the calls:

book, err := store.GetBook(id).SelectOne(ctx, pool)

Generated methods accept pgx connections, pools, and transactions. To write a query declaration, see Queries. For writes and transaction boundaries, see Mutations and transactions.

Read query results #

Use Select to collect multiple rows into the generated result type. For a ListBooks() query declared without parameters:

books, err := store.ListBooks().Select(ctx, pool)

Use SelectOne when exactly one row is expected, as in the GetBook example above.

Method Behavior
Select(ctx, db) Collect all rows; an empty result is valid
SelectOne(ctx, db) Require exactly one row; return pgx.ErrNoRows for zero rows or pgx.ErrTooManyRows for multiple rows
SelectAs[T](ctx, db) Collect all rows into a chosen struct
SelectOneAs[T](ctx, db) Require exactly one row in a chosen struct; return pgx.ErrNoRows for zero rows or pgx.ErrTooManyRows for multiple rows

These methods are available on SELECT queries and mutations with RETURNING. Neither SelectOne nor SelectOneAs appends LIMIT 1. Mutations without RETURNING use Exec.

Execution honors context cancellation. Row collectors close their resources and return no partial results on error. Driver encoding, scan compatibility, and value-dependent database constraints are checked at execution.

Scan into an application type #

Define a struct with exported fields corresponding to the SQL result labels:

type BookView struct {
    ID    int64  `db:"id"`
    Title string `db:"title"`
}

book, err := store.GetBook(id).SelectOneAs[BookView](ctx, pool)

The mapping is strict, by field name or db tag. The struct must match the selected SQL columns and account for their nullability. Mapping errors are reported at runtime. SelectAs uses the same rules for multiple rows.

These methods map the original SQL result labels. A result field's @stitchql(name: ...) annotation does not rename those labels. Use Annotations when the generated result itself should have a custom field or group destination.

Supply runtime filters #

Declare the SQL position where a runtime predicate belongs:

query FindBooks(filter predicate[books]) {
    SELECT b.id, b.title
    FROM books AS b
    WHERE {filter[b]}
    ORDER BY b.id
}

Choose and combine authored predicates in Go. These examples assume exported ByAuthor and ByTitle declarations as shown in Predicates:

filter := stitchql.And(
    store.ByAuthor(authorID),
    stitchql.Or(store.ByTitle("Kindred"), store.ByTitle("Parable of the Sower")),
)

query := store.FindBooks(filter)

The query still determines which columns it selects, its sources, and its order. The predicate supplies a condition at the authored position. Use stitchql.True() to explicitly accept every row at that position. A zero-valued predicate is invalid.

Inspect SQL and bound values #

stmt, err := store.FindBooks(filter).SQL()
if err != nil {
    return err
}

fmt.Println(stmt.SQL)
fmt.Println(stmt.Args)

With authorID set to 42, the composed filter above produces this SQL, formatted here for readability:

SELECT b.id, b.title
FROM books AS b
WHERE (("b".author_id = $1) AND (("b".title = $2) OR ("b".title = $3)))
ORDER BY b.id
Placeholder Bound value
$1 42
$2 "Kindred"
$3 "Parable of the Sower"

Runtime predicates bind their sources to the query's aliases, quoting those aliases in the expanded expression. The parentheses preserve the And/Or composition.

stmt.SQL contains placeholders and stmt.Args contains captured values. Placeholders are numbered in final SQL occurrence order, including expanded fragments; repeated values can occupy separate placeholders. Strings stay bound data even when their contents resemble SQL.

SQL rendering performs no database access. It can reject an incompatible predicate or an UPDATE with no supplied assignments before execution. pgx checks value encoding when the statement is executed.

Share a filter between a page and a count #

query BookPage(after int64, limit int64, filter predicate[books]) {
    SELECT b.id, b.title
    FROM books AS b
    WHERE b.id > {after}
      AND {filter[b]}
    ORDER BY b.id
    LIMIT {limit}
}

query CountBooks(filter predicate[books]) {
    SELECT count(*) AS total
    FROM books AS b
    WHERE {filter[b]}
}
filter := store.ByAuthor(authorID)
pageQuery := store.BookPage(after, 50, filter)
countQuery := store.CountBooks(filter)

The page applies its cursor and filter before the limit. The count reuses the filter without inheriting pagination. Applications choose page sizes, cursor policies, and whether both reads need to share a transaction.