A mapping language to compose SQL for Go.
README.md

Library example #

A small REST catalogue using generated queries. HTTP routing and JSON responses live here; SQL declarations and generated Go live in store.

Query Result
GetBooks(after, limit, filter) An ID-ordered page of books with author ID/name and status.
GetBook(id) One book with author ID/name and status, using SelectOne.
CreateBook(title, authorID) Insert one book and return its generated ID/title/author ID/status.
UpdateBook(id, patch) Update supplied title/author fields; Exec returns the affected-row count.
DeleteBook(id) Delete one book; Exec returns the affected-row count.
GetAuthors(after, limit, filter) An ID-ordered page of authors, each with a Titles []string collection.
GetAuthorBookCounts() Stored book counts per author from a materialized view; available through the store API.

Books have one required author through books.author_id. The fixture includes Ursula K. Le Guin, Octavia E. Butler, and an author without catalogued books, N. K. Jemisin. Author collections contain titles in book ID order; authors without books return []. Duplicate titles remain separate entries. Book IDs use a PostgreSQL identity column; seed loading advances its sequence past the explicit fixture IDs.

Books declare a PostgreSQL book_status enum with draft, published, and out_of_print labels. The generator emits store.BookStatus and constants BookStatusDraft, BookStatusPublished, and BookStatusOutOfPrint in store/books_gen.go. The shared Book columns include status, so list, detail, and INSERT RETURNING results all carry the generated Go type. Seeded books are published; POST relies on the database default and returns a draft. Status is read-only through this example's HTTP API.

book, err := store.GetBook(2).SelectOne(ctx, db)
if err != nil {
    return err
}
if book.Status == store.BookStatusPublished {
    // Work with the generated enum directly.
}

The table definitions live in schema {} blocks beside their queries in store/authors.stitchql and store/books.stitchql. Regenerate the checked-in Compose/local setup SQL from the repository root:

go run ./cmd/stitchql schema generate ./examples/library/store > examples/library/schema.sql

This needs no database connection. StitchQL orders the declarations by dependency and emits SQL; applying it remains an explicit setup or migration step.

Both tables expand the shared fields Timestamps declaration from authors.stitchql, adding created/updated timestamps and their ordering constraint. The defaults initialize these columns; updates must set updated_at explicitly when needed. The example's REST response fields remain its explicit query projections.

Run with Docker Compose #

From the repository root:

docker compose -f examples/library/compose.yaml up --build

Open http://localhost:8080/books or http://localhost:8080/authors. Compose builds the Go app, starts PostgreSQL 18, and loads schema.sql followed by seed.sql on the first start. The app waits for PostgreSQL to be ready. No local Go or PostgreSQL installation is needed; the image uses the checked-in generated Go files.

The HTTP port is bound to localhost. If 8080 is occupied, use LIBRARY_PORT=8081 docker compose -f examples/library/compose.yaml up --build. PostgreSQL stays inside the Compose network. Its library credentials are for this local demo.

Data persists in a named volume. Stop the stack without deleting the data:

docker compose -f examples/library/compose.yaml down

To reset the demo, including after editing the schema or seed files, remove its volume and start again. This deletes the demo database:

docker compose -f examples/library/compose.yaml down --volumes
docker compose -f examples/library/compose.yaml up --build

Existing demo volumes created before the status enum was added need a reset using the commands above. Rebuilding the app alone does not update a persisted database schema. Resetting deletes the demo data.

To explore the database directly:

docker compose -f examples/library/compose.yaml exec db psql -U library -d library

Run locally #

Alternatively, use Go 1.27, PostgreSQL 18, and the PostgreSQL client tools. From the repository root:

export PGHOST=localhost
export PGPORT=5432
export PGDATABASE=stitchql_library
export PGUSER=postgres
export PGSSLMODE=disable  # local development
# Supply authentication through .pgpass, PGPASSFILE, or PGPASSWORD.

createdb "$PGDATABASE"
psql -v ON_ERROR_STOP=1 -f examples/library/schema.sql
psql -v ON_ERROR_STOP=1 -f examples/library/seed.sql
go run ./examples/library -listen :8080

The server connects through pgxpool and shuts down on Ctrl-C or SIGTERM. Schema and seed loading are explicit; startup does not modify the database.

curl 'http://localhost:8080/books?limit=1'
curl 'http://localhost:8080/books?after=1&limit=1'
curl 'http://localhost:8080/books?id=1&id=2&title=Kindred'
curl http://localhost:8080/books/2
curl 'http://localhost:8080/authors?after=0&limit=20'
curl 'http://localhost:8080/authors?book_title=Kindred'

GET /books/2 returns:

{
  "id": 2,
  "title": "Kindred",
  "author_id": 2,
  "author_name": "Octavia E. Butler",
  "status": "published"
}

GET /authors returns the first page:

[
  {"id": 1, "name": "Ursula K. Le Guin", "titles": ["A Wizard of Earthsea"]},
  {"id": 2, "name": "Octavia E. Butler", "titles": ["Kindred"]},
  {"id": 3, "name": "N. K. Jemisin", "titles": []}
]

GET /books returns a JSON array with the same fields as the individual book. Both /books and /authors accept after and limit. after defaults to 0 and must be nonnegative. limit defaults to 20 and accepts 1–100. Use the last returned book or author ID as the next cursor, keeping the same filters. This catalogue uses positive IDs. Invalid or repeated pagination values return 400. Author page limits apply to authors; each returned author retains all their titles.

Repeated id parameters combine with OR. An optional title combines with AND and uses exact SQL equality. It accepts empty strings and is neither trimmed nor treated as a pattern; repeated titles return 400. All values are bound parameters. Filtering happens before pagination.

GET /authors?book_title=Kindred selects authors with at least one book whose title matches exactly, using HasBook(ByTitle(title)). Omit book_title to list all authors; book_title= searches for an empty title. Repeated values return 400. Matching is case-sensitive; % and _ are literal characters. Each matching author keeps all their book titles. Combine the filter with after and limit normally.

Missing books return 404, invalid IDs return 400, and database failures return 500 with a generic JSON error. Details are logged with slog. Empty collections are []. Unknown routes and unsupported methods use ServeMux's 404/405 responses.

Create a book #

curl -i -X POST http://localhost:8080/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"The Fifth Season","author_id":3}'

Both fields are required. An empty title is a supplied value; author_id must identify an existing author. Clients cannot supply id or author_name. Success returns 201 with a Location: /books/{id} header and JSON containing id, title, author_id, and status ("draft"). GET the Location to include the author's name. The new book also appears in list queries and its author's title collection.

POST and PATCH share JSON decoding and the same two writable fields. POST requires both; PATCH allows either. Unknown/repeated fields, nulls, wrong types, malformed/trailing JSON, and bodies over 64 KiB return 400. An invalid author returns 400 without inserting a book; unexpected database errors return 500.

query CreateBook(title string, authorID int64) {
    INSERT INTO books AS b (title, author_id)
    VALUES ({title}, {authorID})
    RETURNING {Book[b]}
}

The authored INSERT omits the ID so PostgreSQL assigns it. The generated constructor takes required scalar values:

created, err := store.CreateBook("The Fifth Season", 3).SelectOne(ctx, db)

Patch a book #

curl -i -X PATCH http://localhost:8080/books/2 \
  -H 'Content-Type: application/json' \
  -d '{"title":"Kindred (updated)","author_id":2}'
curl http://localhost:8080/books/2

PATCH /books/{id} accepts title, author_id, or both. Success returns 204 with no body; GET returns the book with its author name. Omitted fields are unchanged. An empty string explicitly clears the title, and an author ID must identify an existing author. The update is one atomic statement: an invalid author cannot leave a changed title behind.

Only these two exact JSON field names are accepted. IDs and author names are not patchable. Empty objects, nulls, wrong types, repeated fields, malformed/trailing JSON, and bodies over 64 KiB return 400. Missing books return 404; unexpected database failures return a generic 500.

The SQL owns the writable columns:

query UpdateBook(id int64, patch BookPatch) {
    UPDATE books AS b
    SET title = {patch.Title},
        author_id = {patch.AuthorID}
    WHERE b.id = {id}
}

The handwritten BookPatch in store/books.go declares both fields optional:

type BookPatch struct {
    Title    stitchql.Optional[string]
    AuthorID stitchql.Optional[int64]
}

The handler maps supplied JSON fields to stitchql.Set(value); omitted fields keep their zero Optional value. Plain string or int64 fields would always assign, including zero values. SQL controls which fields may be written. Use the same query directly from Go:

affected, err := store.UpdateBook(2, store.BookPatch{
    Title: stitchql.Set("Kindred (updated)"),
}).Exec(ctx, db)

The query has no RETURNING list, so it generates no row type or Select methods. The handler returns 404 when affected == 0, otherwise 204. PostgreSQL counts a matched row even when the value is unchanged. POST keeps RETURNING to read the new ID and stored fields.

Delete a book #

curl -i -X DELETE http://localhost:8080/books/2

DELETE /books/{id} returns 204 with no body when the book is deleted, or 404 when it does not exist (including a repeated deletion). Invalid IDs return 400; unexpected database errors return a generic 500. The book disappears from book queries and its author's title collection. The author and other books remain.

query DeleteBook(id int64) {
    DELETE FROM books WHERE id = {id}
}
affected, err := store.DeleteBook(id).Exec(ctx, db)

SQL owns the relationships #

The base book columns are shared by reads and INSERT RETURNING. The read queries compose them with the joined author's name:

columns Book[b books] {
    b.id, b.title, b.author_id, b.status
}

columns BookWithAuthor[b books, a authors] {
    {Book[b]},
    a.name AS author_name
}

query GetBooks(after int64, limit int64, filter predicate[books, authors]) {
    SELECT {BookWithAuthor[b, a]}
    FROM books AS b
    JOIN authors AS a ON a.id = b.author_id
    WHERE b.id > {after}
      AND {filter[b, a]}
    ORDER BY b.id
    LIMIT {limit}
}

GetBook(id) uses the same BookWithAuthor projection and join, with a mandatory embedded {ByBookID[b](id)}. Brackets name SQL sources during generation; parentheses pass runtime values. RETURNING uses only Book[b] because the mutation targets the book table. Each query has its own result type: GetBooksResult, GetBookResult, and CreateBookResult. Unnamed columns expansions flatten into those structs. GetAuthorsResult has ID, Name, and Titles fields. The handlers keep explicit response structs and JSON tags, preserving the HTTP response shapes.

Predicate parameters accept caller-supplied filters whose tables fit the declared set. Declared tables are checked during generation: [b books] accepts a books alias, while [a authors] accepts an authors alias. Every fragment is also validated independently, even if no query uses it.

q := store.GetBooks(0, 20, stitchql.And(
    stitchql.Or(store.ByBookID(1), store.ByBookID(2)),
    store.ByTitle("Kindred"),
))
books, err := q.Select(ctx, db)

book, err := store.GetBook(2).SelectOne(ctx, db)

SelectOne reports pgx.ErrNoRows or pgx.ErrTooManyRows when cardinality is wrong. Connections, transactions, and pools can execute the queries. Constructors and SQL() inspection do not access the database; SQL() returns SQL and bound Args. Queries and predicates are immutable and can be reused. Pass stitchql.True() for no additional filter; a zero Predicate is invalid.

To use an application struct instead of the generated result type:

type BookView struct {
    ID     int64
    Title  string
    Writer int64  `db:"author_id"`
    Author string `db:"author_name"`
    Status store.BookStatus
}

books, err := q.SelectAs[BookView](ctx, db)
book, err := store.GetBook(2).SelectOneAs[BookView](ctx, db)

Mapping is strict and uses SQL output labels and db tags. Every result column must have a matching exported field, and every field must match a column unless tagged db:"-". Field order is irrelevant; mapping/scan errors return no partial result. SelectOneAs has the same cardinality rules as SelectOne. These methods also work on CreateBook with RETURNING (whose result has no author_name).

Authors collect their titles in SQL without multiplying author rows:

query GetAuthors(after int64, limit int64, filter predicate[authors]) {
    SELECT a.id, a.name,
        ARRAY(
            SELECT b.title
            FROM books AS b
            WHERE b.author_id = a.id
            ORDER BY b.id
        ) AS titles
    FROM authors AS a
    WHERE a.id > {after}
      AND {filter[a]}
    ORDER BY a.id
    LIMIT {limit}
}

PostgreSQL's ARRAY constructor produces an empty array when no books match. StitchQL validates the inner title column and generates Titles []string. The app maps generated rows to its own JSON response types.

HasBook filters authors using a correlated EXISTS predicate. Its books predicate argument can be a title match, ID match, or composition:

predicate HasBook[author authors](match predicate[books]) {
    EXISTS (
        SELECT 1 FROM books AS b
        WHERE b.author_id = author.id AND {match[b]}
    )
}

The local books alias is resolved during generation. The resulting predicate fits an authors parameter:

authors, err := store.GetAuthors(0, 20, store.HasBook(store.ByTitle("Kindred"))).
    Select(ctx, db)

ByTitle uses exact, case-sensitive equality. % and _ remain literal title characters. HasBook also accepts ByBookID and boolean compositions. Use HasBook(stitchql.True()) for authors with any book and negate it for authors with none. Matching authors keep every title in their result, and multiple matching books do not duplicate authors. Combine two HasBook predicates with AND to require both titles, even when different books satisfy each condition. Or and Not work as they do for book filters; pagination applies after filtering. The same HasBook predicate also fits GetBooks, which provides both books and authors.

Materialized book counts #

The store also demonstrates a materialized view:

schema {
    CREATE MATERIALIZED VIEW author_book_counts AS
    SELECT author_id, count(*) AS book_count
    FROM books
    GROUP BY author_id
    WITH NO DATA;

    CREATE UNIQUE INDEX author_book_counts_author_idx
    ON author_book_counts(author_id);
}

query GetAuthorBookCounts() {
    SELECT c.author_id, c.book_count
    FROM author_book_counts AS c
    ORDER BY c.author_id
}

Seed loading explicitly refreshes the view. Its initial rows contain one book for author 1 and one for author 2; authors without books have no summary row.

counts, err := store.GetAuthorBookCounts().Select(ctx, db)

Both fields use sql.Null[int64], following PostgreSQL's materialized-view column metadata. Read their values with .V after checking .Valid. A stored count does not inherit the nonnullable inference of a count(*) expression in a direct query.

Creating, patching, or deleting books through HTTP does not refresh stored counts. Refresh explicitly when needed:

docker compose exec db psql -U library -d library \
    -c 'REFRESH MATERIALIZED VIEW author_book_counts'
docker compose exec db psql -U library -d library \
    -c 'SELECT * FROM author_book_counts ORDER BY author_id'

Run those commands from examples/library. This summary is a store example; the REST endpoints continue reading live books and author title collections.

Generate and verify #

The checked-in generated code builds without a database. Regeneration describes SQL against the existing schema using the same PG* settings; it never executes the queries or changes the schema.

go run ./cmd/stitchql generate ./examples/library/store
go run ./cmd/stitchql generate --check ./examples/library/store
go build ./examples/library ./examples/library/store

All .stitchql files in the store package are resolved together; each source gets a sibling _gen.go file. --check reports stale or missing outputs across the whole package without writing. To try a projection change, rename b.title to b.title AS book_title in Book, regenerate, then update the handlers to use BookTitle. The inferred result types change for both reads and creation.

Integration tests apply the checked-in schema and seed fixtures in separate schemas and remove them afterward. Real tables allow materialized views to reference them:

STITCHQL_TEST_DATABASE_URL='postgres://user:password@localhost:5432/stitchql_library?sslmode=disable' \
    CGO_ENABLED=0 go test ./examples/library ./examples/library/store -count=1

They cover HTTP validation and JSON, POST-generated IDs and required fields, PATCH omission/zero values and atomic failures, joins, pagination, predicate composition, ordered title collections, authors without books, transactions, cancellation, cardinality, scan errors, and stored counts before/after an explicit refresh. Tests skip PostgreSQL cases when the variable is unset.