Repository navigation
feat(compiler): add :macro, a query annotation for reusable SQL - #4703
Draft
dayoadeyemi wants to merge 1 commit into
Draft
dayoadeyemi wants to merge 1 commit into
dayoadeyemi wants to merge 1 commit into
Conversation
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related to #2244 and #2491.
Adds a
:macroquery annotation. A statement annotated:macrois 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 callingsqlc.macro.<Name>().generates
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
@param name [type]comment flag, in call order, and referenced in the body withsqlc.arg(name)or@name.CAST(arg AS type), so passingsqlc.arg(org_id)to one gives the query a parameter of that type. This coerces; it does not type-check.FROM,JOIN,IN,EXISTS,WITH a AS sqlc.macro.Active().sqlc.arg()in the body that is not one of the macro's parameters becomes a parameter of the calling query.sqlc.argis rewritten for (PostgreSQL, MySQL, SQLite, ClickHouse). On any other engine a:macrodefinition 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.Result.Originmaps 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)./*+ */) are kept.F(F(x))is not recursion and an argument cannot be captured by a parameter name.loadQueriesininternal/compiler/compile.go).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 fmtkeeps a statement that calls a macro as written. The parser readssqlc.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 threeinvalid_queries_foogoldens.Open questions
-- @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.sqlc.arg()s become ordinary parameters of the calling query. Grouping them would be a codegen change on top of this.ORDER BY.CAST. The type is written the way the engine'sCASTtakes it (bigintfor PostgreSQL,signedfor MySQL).Test
Coverage is end to end, per the testing strategy in
CLAUDE.md. New cases underinternal/endtoend/testdata:macro(postgresql, mysql, sqlite)macro_files(postgresql, mysql, sqlite)macro_embed(postgresql)sqlc.embedbefore and after an expansionmacro_schema_file(postgresql, mysql)macro_invalid(postgresql, mysql)@param, empty body,sqlc.nargof a parameter, positional placeholder in a bodymacro_invalid_body(postgresql)macro_unsupported(duckdb):macroon an engine that is not preprocessedfmt_macro(postgresql)sqlc fmt --diffformats a macro's body and leaves the calling statement as writteninternal/sql/preprocess/testdatagains 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.gofile was added.Run locally, with PostgreSQL and MySQL available:
go test ./...andgo test --tags=examples -timeout 20m ./internal/...pass.TestReplaypasses for the new cases in thebaseandmanaged-dbcontexts, and incore(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, andgo build ./...ininternal/goldeneye, pass.Not run: the
examplesmodule'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_embedskipscore: the core analyzer does not modelsqlc.embedyet (sqlc_embedfails there too).macro_schema_fileskipsmanaged-dband setsinvalid_schema: a managed database runs the whole schema file and rejectssqlc.arg().macro_invalid_bodyskipscore, followingrelation_does_not_exist, which commitsbaseandmanaged-dbexpectations only.Docs:
docs/reference/macros.md(sqlc.macro) anddocs/reference/query-annotations.md(:macro).🤖 Generated with Claude Code
https://claude.ai/code/session_01XQYsxNCrPXQyQBXSTcsUC3