Skip to content

feat(compiler): add :macro, a query annotation for reusable SQL - #4703

Draft
dayoadeyemi wants to merge 1 commit into
sqlc-dev:mainfrom
dayoadeyemi:claude/macro-annotation-01XQYsxNCrPXQyQBXSTcsUC3
Draft

dayoadeyemi wants to merge 1 commit into
sqlc-dev:mainfrom
dayoadeyemi:claude/macro-annotation-01XQYsxNCrPXQyQBXSTcsUC3

Conversation

@dayoadeyemi

Copy link
Copy Markdown

Related to #2244 and #2491.

Adds a :macro query annotation. A statement annotated :macro is not a query: it generates no code and is never parsed on its own. It names a piece of SQL that other queries include by calling sqlc.macro.<Name>().

-- name: ActiveAuthors :macro
-- @param org bigint
SELECT * FROM authors
WHERE org_id = sqlc.arg(org) AND deleted_at IS NULL;

-- name: IsRecent :macro
-- @param ts timestamptz
-- @param days
sqlc.arg(ts) > now() - sqlc.arg(days) * interval '1 day';

-- name: ListRecentAuthors :many
SELECT a.id, a.name
FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a
WHERE sqlc.macro.IsRecent(a.created_at, 7);

generates

SELECT a.id, a.name
FROM (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST($1 AS bigint) AND deleted_at IS NULL) a
WHERE (CAST(a.created_at AS timestamptz) > now() - 7 * interval '1 day')
func (q *Queries) ListRecentAuthors(ctx context.Context, orgID int64) ([]ListRecentAuthorsRow, error)

This is a draft: the mechanism is complete and tested, but the syntax involves choices that are the maintainers' to make. They are listed under Open questions.

Behavior

  • Parameters are declared with the existing @param name [type] comment flag, in call order, and referenced in the body with sqlc.arg(name) or @name.
  • A typed parameter casts its argument, as CAST(arg AS type), so passing sqlc.arg(org_id) to one gives the query a parameter of that type. This coerces; it does not type-check.
  • An untyped parameter takes its argument as written, in parentheses unless it is a single term (a name, literal, placeholder, function call or parenthesized expression).
  • The expansion is always in parentheses, so a call can stand wherever an expression or a subquery can: a select list, FROM, JOIN, IN, EXISTS, WITH a AS sqlc.macro.Active().
  • Expansion is lazy. A body is only looked at when a call reaches it, so an error in one is reported at the call and a macro nothing calls never fails. A macro can be called before it is defined and from any query file of the package. Macros can call macros; one that reaches itself is an error.
  • Anything else passes through. A sqlc.arg() in the body that is not one of the macro's parameters becomes a parameter of the calling query.
  • Engines: the ones sqlc.arg is rewritten for (PostgreSQL, MySQL, SQLite, ClickHouse). On any other engine a :macro definition is an error.

A body cannot use positional placeholders ($1, ?), which would be numbered against whichever query it lands in, or hold a string literal that spans lines (see below).

Implementation

Macros are a text pass in internal/sql/preprocess (macro.go) that runs before the existing rewrite of sqlc syntax, so the rewrite, the parsers and the analyzers only ever see the queries macros expanded into. A file that defines or calls no macro is rewritten byte for byte as before: every existing preprocess golden is unchanged.

  • A definition is blanked, not cut. Every byte but the line breaks becomes a space, so every other statement keeps its offset and its line. Result.Origin maps anything a call expanded to back to the call, and an offset inside a blanked definition past it, so errors point at the calling query. With a managed database, an error inside an expansion is reported at the call (query.sql:13:31).
  • A body is pasted on one line, without its comments. A comment pasted into a query would be read as one of its annotations, and a line break would break the package's "a rewrite never adds a line" invariant. A literal that spans lines cannot be flattened, so it is rejected. Optimizer hints (/*+ */) are kept.
  • Arguments belong to the caller. They are expanded where they are written and never rescanned inside a body, so F(F(x)) is not recursion and an argument cannot be captured by a parameter name.
  • The compiler reads every query file before rewriting the first, to collect macros across files (loadQueries in internal/compiler/compile.go).
  • Schema files. A schema file is often a query file too. Its parser takes sqlc.arg() as the function call it looks like but cannot take a macro, so the schema is now parsed with macros already expanded. Without this a combined file fails with a bare syntax error.
  • sqlc fmt keeps a statement that calls a macro as written. The parser reads sqlc.macro.ByID() as a function call and is free to fold the name, and a macro's name is matched exactly. Before this change the fingerprint check already rejected the formatter's rendering (macro.byid()); the rule is now explicit rather than incidental. A macro's own body is formatted like any other statement when the file parses.

One existing message changed: the "missing query type" error now lists ':macro', which updates three invalid_queries_foo goldens.

Open questions

  1. Declaring parameters. I reused -- @param name [type] because it is already a parsed comment flag and leaves the -- name: line alone. The alternative is a signature on the name line, -- name: ActiveAuthors(org bigint) :macro, which reads better but changes the annotation parser every tool shares.
  2. Parameters inlined, not embedded. Feature proposal: Query Fragments #2244 asks for a fragment's parameters to be grouped into an embedded params struct. Here a macro's arguments are expressions supplied by the caller, and pass-through sqlc.arg()s become ordinary parameters of the calling query. Grouping them would be a codegen change on top of this.
  3. Always-parenthesized expansion. It makes a call behave like a function call or subquery, at the cost of macros that stand for a bare column list or a clause such as ORDER BY.
  4. Typed parameters as CAST. The type is written the way the engine's CAST takes it (bigint for PostgreSQL, signed for MySQL).
  5. Exact-case macro names, like query names, even on engines that fold identifiers.

Test

Coverage is end to end, per the testing strategy in CLAUDE.md. New cases under internal/endtoend/testdata:

Case What it pins down
macro (postgresql, mysql, sqlite) query and expression macros, nested macros, typed and untyped parameters, pass-through parameters, the same macro twice in one query, placeholder numbering around an expansion
macro_files (postgresql, mysql, sqlite) a macro defined in another query file, read after its callers; a file of nothing but macros
macro_embed (postgresql) sqlc.embed before and after an expansion
macro_schema_file (postgresql, mysql) one file that is both the schema and the queries
macro_invalid (postgresql, mysql) unknown macro, wrong argument count, missing argument list, recursion, duplicate definition, bad @param, empty body, sqlc.narg of a parameter, positional placeholder in a body
macro_invalid_body (postgresql) a body that does not analyze is reported against the calling query
macro_unsupported (duckdb) :macro on an engine that is not preprocessed
fmt_macro (postgresql) sqlc fmt --diff formats a macro's body and leaves the calling statement as written

internal/sql/preprocess/testdata gains 25 cases for the rewritten text and the offset map, including argument shapes, flattening, case and whitespace, and error locations. The harness there now also reports errors in macro definitions; no new _test.go file was added.

Run locally, with PostgreSQL and MySQL available:

  • go test ./... and go test --tags=examples -timeout 20m ./internal/... pass.
  • TestReplay passes for the new cases in the base and managed-db contexts, and in core (SQLC_TEST_CORE=1) for the cases not restricted from it.
  • go test ./internal/docs (the docs lint) passes.
  • CGO_ENABLED=0 go build ./... for linux, darwin and windows, and go build ./... in internal/goldeneye, pass.

Not run: the examples module's tests, which this change does not touch, and anything against a live ClickHouse.

Cases restricted to some contexts, each for a limit that exists without macros:

  • macro_embed skips core: the core analyzer does not model sqlc.embed yet (sqlc_embed fails there too).
  • macro_schema_file skips managed-db and sets invalid_schema: a managed database runs the whole schema file and rejects sqlc.arg().
  • macro_invalid_body skips core, following relation_does_not_exist, which commits base and managed-db expectations only.

Docs: docs/reference/macros.md (sqlc.macro) and docs/reference/query-annotations.md (:macro).

🤖 Generated with Claude Code

https://claude.ai/code/session_01XQYsxNCrPXQyQBXSTcsUC3

A statement annotated ":macro" is not a query. It generates no code and
is never parsed on its own: it names a piece of SQL that other queries
include by calling sqlc.macro.<Name>().

    -- name: ActiveAuthors :macro
    -- @PARAM org bigint
    SELECT * FROM authors
    WHERE org_id = sqlc.arg(org) AND deleted_at IS NULL;

    -- name: ListActiveAuthors :many
    SELECT a.id, a.name
    FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a
    ORDER BY a.name;

Parameters are declared with "-- @PARAM name [type]", in call order,
and referenced in the body with sqlc.arg(name) or @name. A typed
parameter casts its argument, so passing sqlc.arg() to one types the
query's parameter; an untyped one takes its argument as written, in
parentheses unless it is a single term. The expansion is always in
parentheses, so a call can stand wherever an expression or a subquery
can. A sqlc.arg() in the body that is not one of the macro's parameters
passes through and becomes a parameter of the calling query.

Macros are expanded lazily, as a text pass in internal/sql/preprocess
that runs before the existing rewrite of sqlc syntax:

- A body is only looked at when a call reaches it. An error in one is
  reported at the call, and a macro nothing calls never fails.
- A macro can be called before it is defined and from any query file of
  the package, so the compiler reads every query file and collects its
  macros before it rewrites the first.
- Macros can call macros; one that reaches itself is an error.
  Arguments are expanded where they are written and never rescanned
  inside a body.

A definition is blanked rather than cut, so every other statement keeps
its offset and its line, and Origin maps anything a call expanded to
back to the call. A body is pasted on one line and without its
comments, which keeps the "a rewrite never adds a line" invariant; a
literal that spans lines is rejected for the same reason. Positional
placeholders are rejected in a body, where they would be numbered
against whichever query the macro lands in.

A schema file is often a query file too, and its parser takes
sqlc.arg() as a function call but cannot take a macro, so the schema is
parsed with macros already expanded. sqlc fmt keeps a statement that
calls a macro as written, since a parser that reads the call as a
function is free to fold a name that is matched exactly.

Engines that are not preprocessed have no sqlc syntax to call a macro
with; a :macro definition there is an error.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XQYsxNCrPXQyQBXSTcsUC3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant