Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions docs/reference/macros.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,79 @@ func (q *Queries) GetStudentAndScore(ctx context.Context, id int64) (GetStudentA

See a full example in [Embedding structs](../howto/embedding.md).

## `sqlc.macro`

Expand a macro you defined yourself. A query annotated
[`:macro`](query-annotations.md#macro) is not a query: it generates no code,
and stands for a piece of SQL that is pasted into the queries that call it.

```sql
-- 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);

-- >>> EXPANDS TO >>>

-- name: ListRecentAuthors :many
SELECT a.id, a.name
FROM (SELECT * 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');
```

```go
func (q *Queries) ListRecentAuthors(ctx context.Context, orgID int64) ([]ListRecentAuthorsRow, error) {
// ...
}
```

A macro's parameters are declared with `-- @param name [type]` comments, in
the order they are passed, and referenced in its body with `sqlc.arg(name)`
(or `@name`). A call passes one SQL expression for each:

- A parameter **with a type** casts its argument, as `CAST(argument AS type)`.
The type is written the way the database's `CAST` takes it, so
`bigint` for PostgreSQL and `signed` for MySQL. Passing `sqlc.arg(org_id)`
to a typed parameter gives the query a parameter of that type.
- A parameter **without a type** takes its argument as written. An argument
that is more than a single term is wrapped in parentheses, so the operators
around the reference cannot regroup it.

The expansion is always wrapped in parentheses, so a call can stand wherever
an expression or a subquery can: in a select list, after `FROM`, `JOIN`, `IN`
or `EXISTS`, as a common table expression (`WITH a AS sqlc.macro.Active()`)
and so on.

Macros are expanded lazily, where they are called:

- A macro is never checked on its own. Its body does not have to be a
statement, and an error in it is reported against the query that calls it.
A macro nothing calls is never looked at.
- A macro can be called before it is defined, and from any query file of the
same package.
- A macro can call other macros. A macro that ends up calling itself is an
error.
- A `sqlc.arg()` in the body that does not name one of the macro's parameters
is left alone, and becomes a parameter of every query the macro is expanded
in.

A macro's body cannot use positional placeholders (`$1`, `?`), which would be
numbered against whichever query it lands in, and cannot hold a string that
spans lines.

Macros are available for the engines sqlc rewrites `sqlc.arg` for:
PostgreSQL, MySQL, SQLite and ClickHouse.

## `sqlc.narg`

The same as `sqlc.arg`, but always marks the parameter as nullable.
Expand Down
27 changes: 27 additions & 0 deletions docs/reference/query-annotations.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,30 @@ func (b *CreateBookBatchResults) Close() error {
__NOTE: This command is driver and package specific, see [how to insert](../howto/insert.md#using-copyfrom)

This command is used to insert rows a lot faster than sequential inserts.

## `:macro`

The statement is not a query, and no method is generated for it. It defines a
macro: a piece of SQL that other queries include by calling
`sqlc.macro.<name>()`. Parameters are declared with `-- @param name [type]`
comments and passed in that order.

```sql
-- 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;
```

```go
func (q *Queries) ListActiveAuthors(ctx context.Context, orgID int64) ([]ListActiveAuthorsRow, error) {
// ...
}
```

See [`sqlc.macro`](macros.md#sqlcmacro) for how a macro is expanded.
22 changes: 18 additions & 4 deletions internal/cmd/fmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/sqlc-dev/sqlc/internal/engine/sqlite"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
"github.com/sqlc-dev/sqlc/internal/sql/format"
"github.com/sqlc-dev/sqlc/internal/sql/preprocess"
"github.com/sqlc-dev/sqlc/internal/sql/sqlpath"
)

Expand Down Expand Up @@ -184,7 +185,7 @@ func Format(ctx context.Context, dir, filename string, o *Options) (map[string]s
fmt.Fprintf(stderr, "%s: skipped: %s\n", rel, err)
continue
}
formatted, err := formatQueries(f, string(contents))
formatted, err := formatQueries(f, engines[file], string(contents))
if err != nil {
// Not every query file parses without the compiler's help — for
// example, some engines only accept sqlc.slice() after
Expand All @@ -210,7 +211,11 @@ func Format(ctx context.Context, dir, filename string, o *Options) (map[string]s
// every statement (that's where the "-- name:" annotation lives) are kept
// as written; comments inside a statement are threaded through the printer
// by position.
func formatQueries(f queryFormatter, src string) (string, error) {
//
// A statement that calls a macro is kept as written. sqlc.macro.Name() reads
// as a function call to the parser, which is free to fold the name, and the
// name of a macro is matched exactly.
func formatQueries(f queryFormatter, engine config.Engine, src string) (string, error) {
// The parser hands over statements and comments from one lexer pass;
// statement bodies slice the comment list by span.
file, err := f.ParseFile(strings.NewReader(src))
Expand Down Expand Up @@ -272,7 +277,11 @@ func formatQueries(f queryFormatter, src string) (string, error) {
}
}
block := append([]string{}, header...)
block = append(block, formatStmt(f, stmt.Raw, rest, interior, src))
if preprocess.CallsMacro(engine, rest) {
block = append(block, asWritten(rest))
} else {
block = append(block, formatStmt(f, stmt.Raw, rest, interior, src))
}
blocks = append(blocks, strings.Join(block, "\n"))
}
// Everything after the last statement is its terminator, whitespace and
Expand Down Expand Up @@ -400,7 +409,7 @@ type fingerprinter interface {
// formatStmt returns the canonical form of a single statement, or the
// original text when formatting cannot be proven to preserve the query.
func formatStmt(f queryFormatter, raw *ast.RawStmt, orig string, interior []ast.Comment, src string) string {
fallback := strings.TrimSuffix(strings.TrimSpace(orig), ";") + ";"
fallback := asWritten(orig)
if out, ok := formatWithComments(f, raw, interior, src); ok {
if fp, ok := f.(fingerprinter); ok && !sameFingerprint(fp, orig, out) {
return fallback
Expand All @@ -410,6 +419,11 @@ func formatStmt(f queryFormatter, raw *ast.RawStmt, orig string, interior []ast.
return fallback
}

// asWritten returns a statement as its author wrote it, with its terminator.
func asWritten(orig string) string {
return strings.TrimSuffix(strings.TrimSpace(orig), ";") + ";"
}

// sameFingerprint reports that both texts fingerprint successfully to the
// same value. Anything less is not a proof, so the caller keeps the
// statement as written.
Expand Down
87 changes: 71 additions & 16 deletions internal/compiler/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,69 @@ type schemaFile struct {
contents string
}

// queryFile is a query file as it was read.
type queryFile struct {
name string
src string
}

// querySet is the query files and the macros they define. A macro can be
// called from any file, so every file is read, and its macros collected,
// before the first one is rewritten.
type querySet struct {
files []queryFile
macros *preprocess.Macros

// globErr is why the files could not be listed, and errs is what went
// wrong reading them or collecting their macros.
globErr error
errs *multierr.Error
}

// loadQueries reads the query files, once. The schema is parsed before the
// queries are, and it needs their macros: a schema file is often a query file
// too.
func (c *Compiler) loadQueries() *querySet {
if c.queries != nil {
return c.queries
}
set := &querySet{
macros: preprocess.NewMacros(c.conf.Engine),
errs: multierr.New(),
}
c.queries = set

files, err := sqlpath.Glob(c.conf.Queries)
if err != nil {
set.globErr = err
return set
}
for _, filename := range files {
blob, err := os.ReadFile(filename)
if err != nil {
set.errs.Add(filename, "", 0, err)
continue
}
src := string(blob)
for _, err := range set.macros.Collect(filename, src) {
set.errs.Add(filename, src, err.Location, err)
}
set.files = append(set.files, queryFile{name: filename, src: src})
}
return set
}

func (c *Compiler) parseCatalog(schemas []string) error {
paths, err := sqlpath.Glob(schemas)
if err != nil {
return err
}

// A macro is not SQL, and a schema file that is a query file too may
// define or call one. Whatever is wrong with the queries themselves is
// reported when they are parsed.
macros := c.loadQueries().macros

merr := multierr.New()
files := make([]schemaFile, 0, len(paths))
for _, path := range paths {
Expand All @@ -54,6 +111,7 @@ func (c *Compiler) parseCatalog(schemas []string) error {
}
contents := migrations.RemoveRollbackStatements(string(blob))
contents = migrations.RemovePsqlMetaCommands(contents)
contents = macros.Expand(contents)
files = append(files, schemaFile{name: path, contents: contents})
c.schema = append(c.schema, contents)
}
Expand Down Expand Up @@ -85,7 +143,7 @@ func (c *Compiler) parseCatalogLegacy(files []schemaFile, merr *multierr.Error)
// A schema file and a query file are often the same file, so a
// query's sqlc syntax can fail here. Look for an explanation
// before reporting the syntax error it caused.
if reported := addSyntaxErrors(merr, file.name, file.contents, preprocess.File(c.conf.Engine, file.contents)); !reported {
if reported := addSyntaxErrors(merr, file.name, file.contents, c.loadQueries().macros.File(file.contents)); !reported {
merr.Add(file.name, file.contents, 0, err)
}
continue
Expand Down Expand Up @@ -117,7 +175,7 @@ func (c *Compiler) parseCatalogCore(files []schemaFile, merr *multierr.Error) er
// A schema file and a query file are often the same file, so a
// query's sqlc syntax can fail here. Look for an explanation
// before reporting the syntax error it caused.
if reported := addSyntaxErrors(merr, file.name, file.contents, preprocess.File(c.conf.Engine, file.contents)); !reported {
if reported := addSyntaxErrors(merr, file.name, file.contents, c.loadQueries().macros.File(file.contents)); !reported {
merr.Add(file.name, file.contents, 0, err)
}
continue
Expand Down Expand Up @@ -162,24 +220,21 @@ type statement struct {
}

func (c *Compiler) parseQueries(o opts.Parser) (*Result, error) {
merr := multierr.New()
files, err := sqlpath.Glob(c.conf.Queries)
if err != nil {
return nil, err
loaded := c.loadQueries()
if loaded.globErr != nil {
return nil, loaded.globErr
}
merr := loaded.errs
macros := loaded.macros

var stmts []statement
for _, filename := range files {
blob, err := os.ReadFile(filename)
if err != nil {
merr.Add(filename, "", 0, err)
continue
}
src := string(blob)
for _, file := range loaded.files {
filename, src := file.name, file.src

// sqlc syntax is not SQL. Rewrite it to native placeholders before the
// engine parser ever sees the query, so parsers only handle SQL.
pp := preprocess.File(c.conf.Engine, src)
// sqlc syntax is not SQL. Expand the macros and rewrite the rest to
// native placeholders before the engine parser ever sees the query,
// so parsers only handle SQL.
pp := macros.File(src)

parsed, err := c.parser.Parse(strings.NewReader(pp.Text))
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions internal/compiler/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ type Compiler struct {

coreCatalog *core.Catalog

// queries is the query files, read once and shared by the schema and the
// query passes. See loadQueries.
queries *querySet

// coreAnalysis routes every engine through the core catalog and analyzer,
// and coreDialect seeds the catalog it does so with. The catalog itself is
// not built until the schema is loaded, because the two are cached
Expand Down
11 changes: 11 additions & 0 deletions internal/compiler/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ func (c *Compiler) parseQuery(stmt ast.Node, pp *preprocess.Result, o opts.Parse
if name == "" {
return nil, nil
}
if cmd == metadata.CmdMacro {
return nil, c.macroUnsupported(name)
}

if err := validate.Cmd(raw.Stmt, name, cmd); err != nil {
return nil, err
Expand Down Expand Up @@ -145,6 +148,14 @@ func (c *Compiler) parseQuery(stmt ast.Node, pp *preprocess.Result, o opts.Parse
}, nil
}

// macroUnsupported is the error for a macro definition that reached the
// compiler. The preprocessor removes every definition it understands, so one
// that is still here belongs to an engine that is not preprocessed, and has no
// sqlc syntax to call it with.
func (c *Compiler) macroUnsupported(name string) error {
return fmt.Errorf("macro %q: the :macro annotation is not supported by the %s engine", name, c.conf.Engine)
}

// renumberParams applies the parameter numbers the preprocessor assigned,
// matching each node by the location of its placeholder in the query text.
func renumberParams(raw *ast.RawStmt, numbers map[int]int) {
Expand Down
3 changes: 3 additions & 0 deletions internal/compiler/parse_core.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ func (c *Compiler) parseQueryCore(raw *ast.RawStmt, src string, pre *preprocess.
if name == "" {
return nil, nil
}
if cmd == metadata.CmdMacro {
return nil, c.macroUnsupported(name)
}
if err := validate.Cmd(raw.Stmt, name, cmd); err != nil {
return nil, err
}
Expand Down
8 changes: 8 additions & 0 deletions internal/endtoend/fmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/sqlc-dev/sqlc/internal/engine/sqlite"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
"github.com/sqlc-dev/sqlc/internal/sql/format"
"github.com/sqlc-dev/sqlc/internal/sql/preprocess"
)

// sqlParser is an interface for SQL parsers
Expand Down Expand Up @@ -158,6 +159,13 @@ func TestFormat(t *testing.T) {
}
query := strings.TrimSpace(string(contents[start : start+length]))

// sqlc fmt keeps a statement that calls a macro as it
// was written: the call is not SQL until it is
// expanded, and the formatter has no rendering of it.
if preprocess.CallsMacro(engine, query) {
t.Skip("statement calls a macro")
}

expected, err := fingerprint(query)
if err != nil {
t.Fatal(err)
Expand Down
5 changes: 5 additions & 0 deletions internal/endtoend/testdata/fmt_macro/postgresql/exec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"command": "fmt",
"args": ["--diff"],
"contexts": ["base"]
}
17 changes: 17 additions & 0 deletions internal/endtoend/testdata/fmt_macro/postgresql/query.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- A macro's own body is SQL, and is formatted like any other statement.
-- name: ActiveAuthors :macro
-- @param org bigint
select * from authors
where org_id = sqlc.arg(org) and deleted_at is null;

-- A statement that calls a macro is kept as it was written: the name of a
-- macro is matched exactly, and the call is not SQL until it is expanded.
-- name: ListActiveAuthors :many
select a.id,a.name
from sqlc.macro.ActiveAuthors( sqlc.arg(org_id) ) a
order by a.name;

-- name: GetAuthor :one
select id,name
from authors
where id = $1;
Loading
Loading