diff --git a/docs/reference/macros.md b/docs/reference/macros.md index 54d44ed5c9..7095bb5ba3 100644 --- a/docs/reference/macros.md +++ b/docs/reference/macros.md @@ -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. diff --git a/docs/reference/query-annotations.md b/docs/reference/query-annotations.md index 4fabe05aae..1e992bb1b9 100644 --- a/docs/reference/query-annotations.md +++ b/docs/reference/query-annotations.md @@ -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.()`. 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. diff --git a/internal/cmd/fmt.go b/internal/cmd/fmt.go index 54763d9420..be7009fe07 100644 --- a/internal/cmd/fmt.go +++ b/internal/cmd/fmt.go @@ -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" ) @@ -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 @@ -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)) @@ -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 @@ -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 @@ -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. diff --git a/internal/compiler/compile.go b/internal/compiler/compile.go index b6f703d1cb..9050059be8 100644 --- a/internal/compiler/compile.go +++ b/internal/compiler/compile.go @@ -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 { @@ -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) } @@ -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 @@ -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 @@ -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 { diff --git a/internal/compiler/engine.go b/internal/compiler/engine.go index 959207b12f..9e6650cb7a 100644 --- a/internal/compiler/engine.go +++ b/internal/compiler/engine.go @@ -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 diff --git a/internal/compiler/parse.go b/internal/compiler/parse.go index 0fcc7cee54..527ba12f43 100644 --- a/internal/compiler/parse.go +++ b/internal/compiler/parse.go @@ -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 @@ -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) { diff --git a/internal/compiler/parse_core.go b/internal/compiler/parse_core.go index 2e1dfc7042..5f1521c202 100644 --- a/internal/compiler/parse_core.go +++ b/internal/compiler/parse_core.go @@ -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 } diff --git a/internal/endtoend/fmt_test.go b/internal/endtoend/fmt_test.go index 3420a8d0b1..cae3df2193 100644 --- a/internal/endtoend/fmt_test.go +++ b/internal/endtoend/fmt_test.go @@ -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 @@ -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) diff --git a/internal/endtoend/testdata/fmt_macro/postgresql/exec.json b/internal/endtoend/testdata/fmt_macro/postgresql/exec.json new file mode 100644 index 0000000000..191cf0ccb0 --- /dev/null +++ b/internal/endtoend/testdata/fmt_macro/postgresql/exec.json @@ -0,0 +1,5 @@ +{ + "command": "fmt", + "args": ["--diff"], + "contexts": ["base"] +} diff --git a/internal/endtoend/testdata/fmt_macro/postgresql/query.sql b/internal/endtoend/testdata/fmt_macro/postgresql/query.sql new file mode 100644 index 0000000000..fadf21615c --- /dev/null +++ b/internal/endtoend/testdata/fmt_macro/postgresql/query.sql @@ -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; diff --git a/internal/endtoend/testdata/fmt_macro/postgresql/schema.sql b/internal/endtoend/testdata/fmt_macro/postgresql/schema.sql new file mode 100644 index 0000000000..3ff09f8387 --- /dev/null +++ b/internal/endtoend/testdata/fmt_macro/postgresql/schema.sql @@ -0,0 +1,6 @@ +CREATE TABLE authors ( + id bigserial PRIMARY KEY, + org_id bigint NOT NULL, + name text NOT NULL, + deleted_at timestamptz +); diff --git a/internal/endtoend/testdata/fmt_macro/postgresql/sqlc.yaml b/internal/endtoend/testdata/fmt_macro/postgresql/sqlc.yaml new file mode 100644 index 0000000000..cbd1c13993 --- /dev/null +++ b/internal/endtoend/testdata/fmt_macro/postgresql/sqlc.yaml @@ -0,0 +1,9 @@ +version: "2" +sql: + - engine: "postgresql" + schema: "schema.sql" + queries: "query.sql" + gen: + go: + package: "querytest" + out: "go" diff --git a/internal/endtoend/testdata/fmt_macro/postgresql/stdout.txt b/internal/endtoend/testdata/fmt_macro/postgresql/stdout.txt new file mode 100644 index 0000000000..8b35e2b00f --- /dev/null +++ b/internal/endtoend/testdata/fmt_macro/postgresql/stdout.txt @@ -0,0 +1,24 @@ +--- a/query.sql ++++ b/query.sql +@@ -1,8 +1,9 @@ + -- 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; +-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. +@@ -12,6 +13,6 @@ + order by a.name; + + -- name: GetAuthor :one ++SELECT id, name ++FROM authors ++WHERE id = $1; +-select id,name +-from authors +-where id = $1; diff --git a/internal/endtoend/testdata/invalid_queries_foo/pgx/v4/stderr.txt b/internal/endtoend/testdata/invalid_queries_foo/pgx/v4/stderr.txt index 8c745b7e3b..fc62bd468c 100644 --- a/internal/endtoend/testdata/invalid_queries_foo/pgx/v4/stderr.txt +++ b/internal/endtoend/testdata/invalid_queries_foo/pgx/v4/stderr.txt @@ -1,5 +1,5 @@ # package querytest -query.sql:1:1: missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone']: -- name: ListFoos +query.sql:1:1: missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone', ':macro']: -- name: ListFoos query.sql:5:1: invalid query comment: -- name: ListFoos :one :many query.sql:8:1: invalid query type: :two query.sql:11:1: query "DeleteFoo" specifies parameter ":one" without containing a RETURNING clause diff --git a/internal/endtoend/testdata/invalid_queries_foo/pgx/v5/stderr.txt b/internal/endtoend/testdata/invalid_queries_foo/pgx/v5/stderr.txt index 8c745b7e3b..fc62bd468c 100644 --- a/internal/endtoend/testdata/invalid_queries_foo/pgx/v5/stderr.txt +++ b/internal/endtoend/testdata/invalid_queries_foo/pgx/v5/stderr.txt @@ -1,5 +1,5 @@ # package querytest -query.sql:1:1: missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone']: -- name: ListFoos +query.sql:1:1: missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone', ':macro']: -- name: ListFoos query.sql:5:1: invalid query comment: -- name: ListFoos :one :many query.sql:8:1: invalid query type: :two query.sql:11:1: query "DeleteFoo" specifies parameter ":one" without containing a RETURNING clause diff --git a/internal/endtoend/testdata/invalid_queries_foo/stdlib/stderr.txt b/internal/endtoend/testdata/invalid_queries_foo/stdlib/stderr.txt index 06ec54327f..28b984ed83 100644 --- a/internal/endtoend/testdata/invalid_queries_foo/stdlib/stderr.txt +++ b/internal/endtoend/testdata/invalid_queries_foo/stdlib/stderr.txt @@ -1,5 +1,5 @@ # package querytest -query.sql:1:1: missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone']: -- name: ListFoos +query.sql:1:1: missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone', ':macro']: -- name: ListFoos query.sql:5:1: invalid query comment: -- name: ListFoos :one :many query.sql:8:1: invalid query type: :two query.sql:11:1: query "DeleteFoo" specifies parameter ":one" without containing a RETURNING clause diff --git a/internal/endtoend/testdata/macro/mysql/go/db.go b/internal/endtoend/testdata/macro/mysql/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro/mysql/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro/mysql/go/models.go b/internal/endtoend/testdata/macro/mysql/go/models.go new file mode 100644 index 0000000000..8a58c045da --- /dev/null +++ b/internal/endtoend/testdata/macro/mysql/go/models.go @@ -0,0 +1,19 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" + "time" +) + +type Author struct { + ID int64 + OrgID int64 + Name string + Bio sql.NullString + CreatedAt time.Time + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro/mysql/go/query.sql.go b/internal/endtoend/testdata/macro/mysql/go/query.sql.go new file mode 100644 index 0000000000..c5f934a449 --- /dev/null +++ b/internal/endtoend/testdata/macro/mysql/go/query.sql.go @@ -0,0 +1,180 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package querytest + +import ( + "context" +) + +const getSettledAuthor = `-- name: GetSettledAuthor :one +SELECT id, org_id, name, bio, created_at, deleted_at FROM authors +WHERE id = ? AND NOT (TIMESTAMPDIFF(DAY, created_at, now()) < CAST(7 + 7 AS signed)) +` + +func (q *Queries) GetSettledAuthor(ctx context.Context, id int64) (Author, error) { + row := q.db.QueryRowContext(ctx, getSettledAuthor, id) + var i Author + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Bio, + &i.CreatedAt, + &i.DeletedAt, + ) + return i, err +} + +const listActiveAuthors = `-- name: ListActiveAuthors :many +SELECT a.id, a.name +FROM (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST(? AS signed) AND deleted_at IS NULL) a +ORDER BY a.name +` + +type ListActiveAuthorsRow struct { + ID int64 + Name string +} + +func (q *Queries) ListActiveAuthors(ctx context.Context, orgID int64) ([]ListActiveAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listActiveAuthors, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListActiveAuthorsRow + for rows.Next() { + var i ListActiveAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listLaterAuthors = `-- name: ListLaterAuthors :many +SELECT x.id, x.name +FROM authors x +JOIN (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST(? AS signed) AND deleted_at IS NULL) a ON a.id = x.id +WHERE x.name <> ? AND x.id > ? +` + +type ListLaterAuthorsParams struct { + OrgID int64 + Name string + ID int64 +} + +type ListLaterAuthorsRow struct { + ID int64 + Name string +} + +// Every ? is an argument of its own, numbered in the order the expanded +// query sends them. +func (q *Queries) ListLaterAuthors(ctx context.Context, arg ListLaterAuthorsParams) ([]ListLaterAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listLaterAuthors, arg.OrgID, arg.Name, arg.ID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListLaterAuthorsRow + for rows.Next() { + var i ListLaterAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listRecentAuthors = `-- name: ListRecentAuthors :many +SELECT r.id, r.name +FROM (SELECT id, org_id, name, bio, created_at, deleted_at FROM (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST(? AS signed) AND deleted_at IS NULL) a WHERE (TIMESTAMPDIFF(DAY, a.created_at, now()) < CAST(? AS signed))) r +ORDER BY r.name +` + +type ListRecentAuthorsParams struct { + OrgID int64 + WindowDays int64 +} + +type ListRecentAuthorsRow struct { + ID int64 + Name string +} + +func (q *Queries) ListRecentAuthors(ctx context.Context, arg ListRecentAuthorsParams) ([]ListRecentAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listRecentAuthors, arg.OrgID, arg.WindowDays) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListRecentAuthorsRow + for rows.Next() { + var i ListRecentAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listSharedNames = `-- name: ListSharedNames :many +SELECT a.name +FROM (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST(? AS signed) AND deleted_at IS NULL) a +JOIN (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST(? AS signed) AND deleted_at IS NULL) b ON a.name = b.name +` + +type ListSharedNamesParams struct { + FirstOrg int64 + SecondOrg int64 +} + +// The same macro twice in one query. +func (q *Queries) ListSharedNames(ctx context.Context, arg ListSharedNamesParams) ([]string, error) { + rows, err := q.db.QueryContext(ctx, listSharedNames, arg.FirstOrg, arg.SecondOrg) + if err != nil { + return nil, err + } + defer rows.Close() + var items []string + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, err + } + items = append(items, name) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro/mysql/query.sql b/internal/endtoend/testdata/macro/mysql/query.sql new file mode 100644 index 0000000000..fb39c3b1b4 --- /dev/null +++ b/internal/endtoend/testdata/macro/mysql/query.sql @@ -0,0 +1,48 @@ +# A macro whose body is an expression. +-- name: IsRecent :macro +-- @param ts +-- @param days signed +TIMESTAMPDIFF(DAY, sqlc.arg(ts), now()) < sqlc.arg(days); + +/* A macro whose body is a query. */ +-- name: ActiveAuthors :macro +-- @param org signed +SELECT * +FROM authors +WHERE org_id = sqlc.arg(org) # the tenant + 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; + +-- name: ListRecentAuthors :many +SELECT r.id, r.name +FROM sqlc.macro.RecentActiveAuthors(sqlc.arg(org_id)) r +ORDER BY r.name; + +-- Every ? is an argument of its own, numbered in the order the expanded +-- query sends them. +-- name: ListLaterAuthors :many +SELECT x.id, x.name +FROM authors x +JOIN sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a ON a.id = x.id +WHERE x.name <> ? AND x.id > ?; + +-- name: GetSettledAuthor :one +SELECT * FROM authors +WHERE id = ? AND NOT sqlc.macro.IsRecent(created_at, 7 + 7); + +-- The same macro twice in one query. +-- name: ListSharedNames :many +SELECT a.name +FROM sqlc.macro.ActiveAuthors(sqlc.arg(first_org)) a +JOIN sqlc.macro.ActiveAuthors(sqlc.arg(second_org)) b ON a.name = b.name; + +-- A macro that calls other macros. window_days is not one of its parameters, +-- so it becomes a parameter of whichever query the macro lands in. +-- name: RecentActiveAuthors :macro +-- @param org +SELECT * FROM sqlc.macro.ActiveAuthors(sqlc.arg(org)) a +WHERE sqlc.macro.IsRecent(a.created_at, sqlc.arg(window_days)); diff --git a/internal/endtoend/testdata/macro/mysql/schema.sql b/internal/endtoend/testdata/macro/mysql/schema.sql new file mode 100644 index 0000000000..b1610b23bb --- /dev/null +++ b/internal/endtoend/testdata/macro/mysql/schema.sql @@ -0,0 +1,8 @@ +CREATE TABLE authors ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + org_id BIGINT NOT NULL, + name VARCHAR(255) NOT NULL, + bio TEXT, + created_at DATETIME NOT NULL, + deleted_at DATETIME +); diff --git a/internal/endtoend/testdata/macro/mysql/sqlc.json b/internal/endtoend/testdata/macro/mysql/sqlc.json new file mode 100644 index 0000000000..e41c39e8b3 --- /dev/null +++ b/internal/endtoend/testdata/macro/mysql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "mysql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro/postgresql/go/db.go b/internal/endtoend/testdata/macro/postgresql/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro/postgresql/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro/postgresql/go/models.go b/internal/endtoend/testdata/macro/postgresql/go/models.go new file mode 100644 index 0000000000..8a58c045da --- /dev/null +++ b/internal/endtoend/testdata/macro/postgresql/go/models.go @@ -0,0 +1,19 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" + "time" +) + +type Author struct { + ID int64 + OrgID int64 + Name string + Bio sql.NullString + CreatedAt time.Time + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro/postgresql/go/query.sql.go b/internal/endtoend/testdata/macro/postgresql/go/query.sql.go new file mode 100644 index 0000000000..4b96d7b3ce --- /dev/null +++ b/internal/endtoend/testdata/macro/postgresql/go/query.sql.go @@ -0,0 +1,188 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package querytest + +import ( + "context" + "database/sql" +) + +const countRecentAuthors = `-- name: CountRecentAuthors :one +SELECT count(*) FROM (SELECT id, org_id, name, bio, created_at, deleted_at 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() - CAST($2 AS int) * interval '1 day')) r +` + +type CountRecentAuthorsParams struct { + OrgID int64 + WindowDays int32 +} + +// org_id reaches ActiveAuthors through RecentActiveAuthors, and takes its +// type from the cast ActiveAuthors declares. +func (q *Queries) CountRecentAuthors(ctx context.Context, arg CountRecentAuthorsParams) (int64, error) { + row := q.db.QueryRowContext(ctx, countRecentAuthors, arg.OrgID, arg.WindowDays) + var count int64 + err := row.Scan(&count) + return count, err +} + +const getSettledAuthor = `-- name: GetSettledAuthor :one +SELECT id, org_id, name, bio, created_at, deleted_at FROM authors +WHERE id = $1 AND NOT (CAST(created_at AS timestamptz) > now() - CAST(7 + 7 AS int) * interval '1 day') +` + +// An argument is an expression, and is evaluated as one. +func (q *Queries) GetSettledAuthor(ctx context.Context, id int64) (Author, error) { + row := q.db.QueryRowContext(ctx, getSettledAuthor, id) + var i Author + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Bio, + &i.CreatedAt, + &i.DeletedAt, + ) + return i, err +} + +const listActiveAuthors = `-- name: ListActiveAuthors :many +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 +ORDER BY a.name +` + +type ListActiveAuthorsRow struct { + ID int64 + Name string +} + +func (q *Queries) ListActiveAuthors(ctx context.Context, orgID int64) ([]ListActiveAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listActiveAuthors, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListActiveAuthorsRow + for rows.Next() { + var i ListActiveAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listAuthorsWithBio = `-- name: ListAuthorsWithBio :many +SELECT a.id, a.name, a.bio +FROM authors a +JOIN (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST($2 AS bigint) AND deleted_at IS NULL) active ON active.id = a.id +WHERE a.bio IS NOT NULL AND a.id > $1 +` + +type ListAuthorsWithBioParams struct { + ID int64 + OrgID int64 +} + +type ListAuthorsWithBioRow struct { + ID int64 + Name string + Bio sql.NullString +} + +// A placeholder the query numbers itself keeps its number, and the macro's +// parameter is numbered around it. +func (q *Queries) ListAuthorsWithBio(ctx context.Context, arg ListAuthorsWithBioParams) ([]ListAuthorsWithBioRow, error) { + rows, err := q.db.QueryContext(ctx, listAuthorsWithBio, arg.ID, arg.OrgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAuthorsWithBioRow + for rows.Next() { + var i ListAuthorsWithBioRow + if err := rows.Scan(&i.ID, &i.Name, &i.Bio); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listNames = `-- name: ListNames :many +SELECT coalesce(nullif(name, ''), ('unnamed'))::text AS name FROM authors +` + +func (q *Queries) ListNames(ctx context.Context) ([]string, error) { + rows, err := q.db.QueryContext(ctx, listNames) + if err != nil { + return nil, err + } + defer rows.Close() + var items []string + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, err + } + items = append(items, name) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listSharedNames = `-- name: ListSharedNames :many +SELECT 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 +JOIN (SELECT id, org_id, name, bio, created_at, deleted_at FROM authors WHERE org_id = CAST($2 AS bigint) AND deleted_at IS NULL) b ON a.name = b.name +` + +type ListSharedNamesParams struct { + FirstOrg int64 + SecondOrg int64 +} + +// The same macro twice in one query. +func (q *Queries) ListSharedNames(ctx context.Context, arg ListSharedNamesParams) ([]string, error) { + rows, err := q.db.QueryContext(ctx, listSharedNames, arg.FirstOrg, arg.SecondOrg) + if err != nil { + return nil, err + } + defer rows.Close() + var items []string + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, err + } + items = append(items, name) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro/postgresql/query.sql b/internal/endtoend/testdata/macro/postgresql/query.sql new file mode 100644 index 0000000000..7f454ce248 --- /dev/null +++ b/internal/endtoend/testdata/macro/postgresql/query.sql @@ -0,0 +1,57 @@ +-- A macro whose body is an expression. It is called before it is defined in +-- the queries below, and after: a macro is expanded where it is called. +-- name: IsRecent :macro +-- @param ts timestamptz +-- @param days int +sqlc.arg(ts) > now() - @days * interval '1 day'; + +-- A macro whose body is a query. +-- name: ActiveAuthors :macro +-- @param org bigint +SELECT * +FROM authors +WHERE org_id = sqlc.arg(org) -- the tenant + 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; + +-- org_id reaches ActiveAuthors through RecentActiveAuthors, and takes its +-- type from the cast ActiveAuthors declares. +-- name: CountRecentAuthors :one +SELECT count(*) FROM sqlc.macro.RecentActiveAuthors(sqlc.arg(org_id)) r; + +-- An argument is an expression, and is evaluated as one. +-- name: GetSettledAuthor :one +SELECT * FROM authors +WHERE id = $1 AND NOT sqlc.macro.IsRecent(created_at, 7 + 7); + +-- The same macro twice in one query. +-- name: ListSharedNames :many +SELECT a.name +FROM sqlc.macro.ActiveAuthors(sqlc.arg(first_org)) a +JOIN sqlc.macro.ActiveAuthors(sqlc.arg(second_org)) b ON a.name = b.name; + +-- A placeholder the query numbers itself keeps its number, and the macro's +-- parameter is numbered around it. +-- name: ListAuthorsWithBio :many +SELECT a.id, a.name, a.bio +FROM authors a +JOIN sqlc.macro.ActiveAuthors(@org_id) active ON active.id = a.id +WHERE a.bio IS NOT NULL AND a.id > $1; + +-- A macro that calls other macros. window_days is not one of its parameters, +-- so it becomes a parameter of whichever query the macro lands in. +-- name: RecentActiveAuthors :macro +-- @param org +SELECT * FROM sqlc.macro.ActiveAuthors(sqlc.arg(org)) a +WHERE sqlc.macro.IsRecent(a.created_at, sqlc.arg(window_days)); + +-- A macro without parameters. +-- name: Unnamed :macro +'unnamed'; + +-- name: ListNames :many +SELECT coalesce(nullif(name, ''), sqlc.macro.Unnamed())::text AS name FROM authors; diff --git a/internal/endtoend/testdata/macro/postgresql/schema.sql b/internal/endtoend/testdata/macro/postgresql/schema.sql new file mode 100644 index 0000000000..61ec6af66b --- /dev/null +++ b/internal/endtoend/testdata/macro/postgresql/schema.sql @@ -0,0 +1,8 @@ +CREATE TABLE authors ( + id bigserial PRIMARY KEY, + org_id bigint NOT NULL, + name text NOT NULL, + bio text, + created_at timestamptz NOT NULL, + deleted_at timestamptz +); diff --git a/internal/endtoend/testdata/macro/postgresql/sqlc.json b/internal/endtoend/testdata/macro/postgresql/sqlc.json new file mode 100644 index 0000000000..f717ca2e66 --- /dev/null +++ b/internal/endtoend/testdata/macro/postgresql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "postgresql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro/sqlite/go/db.go b/internal/endtoend/testdata/macro/sqlite/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro/sqlite/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro/sqlite/go/models.go b/internal/endtoend/testdata/macro/sqlite/go/models.go new file mode 100644 index 0000000000..159a5124ea --- /dev/null +++ b/internal/endtoend/testdata/macro/sqlite/go/models.go @@ -0,0 +1,17 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" +) + +type Author struct { + ID int64 + OrgID int64 + Name string + Bio sql.NullString + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro/sqlite/go/query.sql.go b/internal/endtoend/testdata/macro/sqlite/go/query.sql.go new file mode 100644 index 0000000000..9d4a441ead --- /dev/null +++ b/internal/endtoend/testdata/macro/sqlite/go/query.sql.go @@ -0,0 +1,155 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package querytest + +import ( + "context" +) + +const listActiveAuthors = `-- name: ListActiveAuthors :many +SELECT a.id, a.name +FROM (SELECT id, org_id, name, bio, deleted_at FROM authors WHERE org_id = CAST(?1 AS integer) AND deleted_at IS NULL) a +ORDER BY a.name +` + +type ListActiveAuthorsRow struct { + ID int64 + Name string +} + +func (q *Queries) ListActiveAuthors(ctx context.Context, orgID int64) ([]ListActiveAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listActiveAuthors, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListActiveAuthorsRow + for rows.Next() { + var i ListActiveAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listAuthorsWithBio = `-- name: ListAuthorsWithBio :many +SELECT w.id, w.name +FROM (SELECT id, org_id, name, bio, deleted_at FROM (SELECT id, org_id, name, bio, deleted_at FROM authors WHERE org_id = CAST(?1 AS integer) AND deleted_at IS NULL) a WHERE (a.bio IS NOT NULL AND a.bio <> '')) w +ORDER BY w.name +` + +type ListAuthorsWithBioRow struct { + ID int64 + Name string +} + +func (q *Queries) ListAuthorsWithBio(ctx context.Context, orgID int64) ([]ListAuthorsWithBioRow, error) { + rows, err := q.db.QueryContext(ctx, listAuthorsWithBio, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAuthorsWithBioRow + for rows.Next() { + var i ListAuthorsWithBioRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listLaterAuthors = `-- name: ListLaterAuthors :many +SELECT x.id, x.name +FROM authors x +JOIN (SELECT id, org_id, name, bio, deleted_at FROM authors WHERE org_id = CAST(?2 AS integer) AND deleted_at IS NULL) a ON a.id = x.id +WHERE x.id > ?1 +` + +type ListLaterAuthorsParams struct { + ID int64 + OrgID int64 +} + +type ListLaterAuthorsRow struct { + ID int64 + Name string +} + +// A numbered placeholder keeps its number, and the macro's parameters are +// numbered around it. +func (q *Queries) ListLaterAuthors(ctx context.Context, arg ListLaterAuthorsParams) ([]ListLaterAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listLaterAuthors, arg.ID, arg.OrgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListLaterAuthorsRow + for rows.Next() { + var i ListLaterAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listSharedNames = `-- name: ListSharedNames :many +SELECT a.name +FROM (SELECT id, org_id, name, bio, deleted_at FROM authors WHERE org_id = CAST(?1 AS integer) AND deleted_at IS NULL) a +JOIN (SELECT id, org_id, name, bio, deleted_at FROM authors WHERE org_id = CAST(?2 AS integer) AND deleted_at IS NULL) b ON a.name = b.name +` + +type ListSharedNamesParams struct { + FirstOrg int64 + SecondOrg int64 +} + +// The same macro twice in one query. +func (q *Queries) ListSharedNames(ctx context.Context, arg ListSharedNamesParams) ([]string, error) { + rows, err := q.db.QueryContext(ctx, listSharedNames, arg.FirstOrg, arg.SecondOrg) + if err != nil { + return nil, err + } + defer rows.Close() + var items []string + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, err + } + items = append(items, name) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro/sqlite/query.sql b/internal/endtoend/testdata/macro/sqlite/query.sql new file mode 100644 index 0000000000..1da9282678 --- /dev/null +++ b/internal/endtoend/testdata/macro/sqlite/query.sql @@ -0,0 +1,42 @@ +-- A macro whose body is an expression. +-- name: HasBio :macro +-- @param bio +sqlc.arg(bio) IS NOT NULL AND @bio <> ''; + +-- A macro whose body is a query. +-- name: ActiveAuthors :macro +-- @param org integer +SELECT * +FROM authors +WHERE org_id = sqlc.arg(org) -- the tenant + 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; + +-- name: ListAuthorsWithBio :many +SELECT w.id, w.name +FROM sqlc.macro.AuthorsWithBio(sqlc.arg(org_id)) w +ORDER BY w.name; + +-- A numbered placeholder keeps its number, and the macro's parameters are +-- numbered around it. +-- name: ListLaterAuthors :many +SELECT x.id, x.name +FROM authors x +JOIN sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a ON a.id = x.id +WHERE x.id > ?1; + +-- The same macro twice in one query. +-- name: ListSharedNames :many +SELECT a.name +FROM sqlc.macro.ActiveAuthors(@first_org) a +JOIN sqlc.macro.ActiveAuthors(@second_org) b ON a.name = b.name; + +-- A macro that calls other macros. +-- name: AuthorsWithBio :macro +-- @param org +SELECT * FROM sqlc.macro.ActiveAuthors(sqlc.arg(org)) a +WHERE sqlc.macro.HasBio(a.bio); diff --git a/internal/endtoend/testdata/macro/sqlite/schema.sql b/internal/endtoend/testdata/macro/sqlite/schema.sql new file mode 100644 index 0000000000..b6e875f876 --- /dev/null +++ b/internal/endtoend/testdata/macro/sqlite/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE authors ( + id integer PRIMARY KEY, + org_id integer NOT NULL, + name text NOT NULL, + bio text, + deleted_at datetime +); diff --git a/internal/endtoend/testdata/macro/sqlite/sqlc.json b/internal/endtoend/testdata/macro/sqlite/sqlc.json new file mode 100644 index 0000000000..cd66df063b --- /dev/null +++ b/internal/endtoend/testdata/macro/sqlite/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "sqlite", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro_embed/postgresql/exec.json b/internal/endtoend/testdata/macro_embed/postgresql/exec.json new file mode 100644 index 0000000000..5958e7f5bf --- /dev/null +++ b/internal/endtoend/testdata/macro_embed/postgresql/exec.json @@ -0,0 +1,3 @@ +{ + "contexts": ["base", "managed-db"] +} diff --git a/internal/endtoend/testdata/macro_embed/postgresql/go/db.go b/internal/endtoend/testdata/macro_embed/postgresql/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro_embed/postgresql/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro_embed/postgresql/go/models.go b/internal/endtoend/testdata/macro_embed/postgresql/go/models.go new file mode 100644 index 0000000000..9b8f3bdc62 --- /dev/null +++ b/internal/endtoend/testdata/macro_embed/postgresql/go/models.go @@ -0,0 +1,22 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" +) + +type Author struct { + ID int64 + OrgID int64 + Name string + DeletedAt sql.NullTime +} + +type Book struct { + ID int64 + AuthorID int64 + Title string +} diff --git a/internal/endtoend/testdata/macro_embed/postgresql/go/query.sql.go b/internal/endtoend/testdata/macro_embed/postgresql/go/query.sql.go new file mode 100644 index 0000000000..3a05421329 --- /dev/null +++ b/internal/endtoend/testdata/macro_embed/postgresql/go/query.sql.go @@ -0,0 +1,95 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package querytest + +import ( + "context" +) + +const listActiveAuthorsAndBooks = `-- name: ListActiveAuthorsAndBooks :many +SELECT a.id, a.org_id, a.name, a.deleted_at, b.id, b.author_id, b.title +FROM authors a +JOIN books b ON b.author_id = a.id +WHERE a.id IN (SELECT active.id FROM (SELECT id, org_id, name, deleted_at FROM authors WHERE org_id = CAST($1 AS bigint) AND deleted_at IS NULL) active) +` + +type ListActiveAuthorsAndBooksRow struct { + Author Author + Book Book +} + +func (q *Queries) ListActiveAuthorsAndBooks(ctx context.Context, orgID int64) ([]ListActiveAuthorsAndBooksRow, error) { + rows, err := q.db.QueryContext(ctx, listActiveAuthorsAndBooks, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListActiveAuthorsAndBooksRow + for rows.Next() { + var i ListActiveAuthorsAndBooksRow + if err := rows.Scan( + &i.Author.ID, + &i.Author.OrgID, + &i.Author.Name, + &i.Author.DeletedAt, + &i.Book.ID, + &i.Book.AuthorID, + &i.Book.Title, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listBooksOfActiveAuthors = `-- name: ListBooksOfActiveAuthors :many +WITH active AS (SELECT id, org_id, name, deleted_at FROM authors WHERE org_id = CAST($1 AS bigint) AND deleted_at IS NULL) +SELECT active.name AS author_name, b.id, b.author_id, b.title +FROM active +JOIN books b ON b.author_id = active.id +` + +type ListBooksOfActiveAuthorsRow struct { + AuthorName string + Book Book +} + +// An embed is found by where it sits in the query, and a macro that expands +// before it moves it. +func (q *Queries) ListBooksOfActiveAuthors(ctx context.Context, orgID int64) ([]ListBooksOfActiveAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listBooksOfActiveAuthors, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListBooksOfActiveAuthorsRow + for rows.Next() { + var i ListBooksOfActiveAuthorsRow + if err := rows.Scan( + &i.AuthorName, + &i.Book.ID, + &i.Book.AuthorID, + &i.Book.Title, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_embed/postgresql/query.sql b/internal/endtoend/testdata/macro_embed/postgresql/query.sql new file mode 100644 index 0000000000..8042110e2b --- /dev/null +++ b/internal/endtoend/testdata/macro_embed/postgresql/query.sql @@ -0,0 +1,17 @@ +-- name: ActiveAuthors :macro +-- @param org bigint +SELECT * FROM authors WHERE org_id = sqlc.arg(org) AND deleted_at IS NULL; + +-- An embed is found by where it sits in the query, and a macro that expands +-- before it moves it. +-- name: ListBooksOfActiveAuthors :many +WITH active AS sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) +SELECT active.name AS author_name, sqlc.embed(b) +FROM active +JOIN books b ON b.author_id = active.id; + +-- name: ListActiveAuthorsAndBooks :many +SELECT sqlc.embed(a), sqlc.embed(b) +FROM authors a +JOIN books b ON b.author_id = a.id +WHERE a.id IN (SELECT active.id FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) active); diff --git a/internal/endtoend/testdata/macro_embed/postgresql/schema.sql b/internal/endtoend/testdata/macro_embed/postgresql/schema.sql new file mode 100644 index 0000000000..5d7cdfa886 --- /dev/null +++ b/internal/endtoend/testdata/macro_embed/postgresql/schema.sql @@ -0,0 +1,12 @@ +CREATE TABLE authors ( + id bigserial PRIMARY KEY, + org_id bigint NOT NULL, + name text NOT NULL, + deleted_at timestamptz +); + +CREATE TABLE books ( + id bigserial PRIMARY KEY, + author_id bigint NOT NULL REFERENCES authors (id), + title text NOT NULL +); diff --git a/internal/endtoend/testdata/macro_embed/postgresql/sqlc.json b/internal/endtoend/testdata/macro_embed/postgresql/sqlc.json new file mode 100644 index 0000000000..f717ca2e66 --- /dev/null +++ b/internal/endtoend/testdata/macro_embed/postgresql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "postgresql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro_files/mysql/go/authors.sql.go b/internal/endtoend/testdata/macro_files/mysql/go/authors.sql.go new file mode 100644 index 0000000000..93e39534e8 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/go/authors.sql.go @@ -0,0 +1,39 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: authors.sql + +package querytest + +import ( + "context" +) + +const listAuthors = `-- name: ListAuthors :many +SELECT id, name, deleted_at FROM authors a WHERE (a.deleted_at IS NULL) ORDER BY a.name +` + +// The macro these queries call is defined in macros.sql, which is read after +// this file. +func (q *Queries) ListAuthors(ctx context.Context) ([]Author, error) { + rows, err := q.db.QueryContext(ctx, listAuthors) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Author + for rows.Next() { + var i Author + if err := rows.Scan(&i.ID, &i.Name, &i.DeletedAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_files/mysql/go/books.sql.go b/internal/endtoend/testdata/macro_files/mysql/go/books.sql.go new file mode 100644 index 0000000000..e9160e0f2d --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/go/books.sql.go @@ -0,0 +1,46 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: books.sql + +package querytest + +import ( + "context" +) + +const listBooksByAuthor = `-- name: ListBooksByAuthor :many +SELECT b.id, b.author_id, b.title, b.deleted_at +FROM books b +WHERE b.author_id = ? + AND (b.deleted_at IS NULL) +ORDER BY b.title +` + +func (q *Queries) ListBooksByAuthor(ctx context.Context, authorID int64) ([]Book, error) { + rows, err := q.db.QueryContext(ctx, listBooksByAuthor, authorID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i Book + if err := rows.Scan( + &i.ID, + &i.AuthorID, + &i.Title, + &i.DeletedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_files/mysql/go/db.go b/internal/endtoend/testdata/macro_files/mysql/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro_files/mysql/go/models.go b/internal/endtoend/testdata/macro_files/mysql/go/models.go new file mode 100644 index 0000000000..b1bd7e865d --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/go/models.go @@ -0,0 +1,22 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" +) + +type Author struct { + ID int64 + Name string + DeletedAt sql.NullTime +} + +type Book struct { + ID int64 + AuthorID int64 + Title string + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro_files/mysql/query/authors.sql b/internal/endtoend/testdata/macro_files/mysql/query/authors.sql new file mode 100644 index 0000000000..787a18323a --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/query/authors.sql @@ -0,0 +1,4 @@ +-- The macro these queries call is defined in macros.sql, which is read after +-- this file. +-- name: ListAuthors :many +SELECT * FROM authors a WHERE sqlc.macro.NotDeleted(a.deleted_at) ORDER BY a.name; diff --git a/internal/endtoend/testdata/macro_files/mysql/query/books.sql b/internal/endtoend/testdata/macro_files/mysql/query/books.sql new file mode 100644 index 0000000000..59a02f58ed --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/query/books.sql @@ -0,0 +1,6 @@ +-- name: ListBooksByAuthor :many +SELECT b.* +FROM books b +WHERE b.author_id = sqlc.arg(author_id) + AND sqlc.macro.NotDeleted(b.deleted_at) +ORDER BY b.title; diff --git a/internal/endtoend/testdata/macro_files/mysql/query/macros.sql b/internal/endtoend/testdata/macro_files/mysql/query/macros.sql new file mode 100644 index 0000000000..88c96acf28 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/query/macros.sql @@ -0,0 +1,4 @@ +-- A file of nothing but macros holds no queries, and generates no code. +-- name: NotDeleted :macro +-- @param deleted_at +sqlc.arg(deleted_at) IS NULL; diff --git a/internal/endtoend/testdata/macro_files/mysql/schema.sql b/internal/endtoend/testdata/macro_files/mysql/schema.sql new file mode 100644 index 0000000000..d0f264d80b --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/schema.sql @@ -0,0 +1,12 @@ +CREATE TABLE authors ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + name VARCHAR(255) NOT NULL, + deleted_at DATETIME +); + +CREATE TABLE books ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + author_id BIGINT NOT NULL, + title VARCHAR(255) NOT NULL, + deleted_at DATETIME +); diff --git a/internal/endtoend/testdata/macro_files/mysql/sqlc.json b/internal/endtoend/testdata/macro_files/mysql/sqlc.json new file mode 100644 index 0000000000..af3a14e774 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/mysql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "mysql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query" + } + ] +} diff --git a/internal/endtoend/testdata/macro_files/postgresql/go/authors.sql.go b/internal/endtoend/testdata/macro_files/postgresql/go/authors.sql.go new file mode 100644 index 0000000000..02421f6953 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/go/authors.sql.go @@ -0,0 +1,39 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: authors.sql + +package querytest + +import ( + "context" +) + +const listAuthors = `-- name: ListAuthors :many +SELECT id, name, deleted_at FROM authors a WHERE (CAST(a.deleted_at AS timestamptz) IS NULL) ORDER BY a.name +` + +// The macro these queries call is defined in macros.sql, which is read after +// this file. +func (q *Queries) ListAuthors(ctx context.Context) ([]Author, error) { + rows, err := q.db.QueryContext(ctx, listAuthors) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Author + for rows.Next() { + var i Author + if err := rows.Scan(&i.ID, &i.Name, &i.DeletedAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_files/postgresql/go/books.sql.go b/internal/endtoend/testdata/macro_files/postgresql/go/books.sql.go new file mode 100644 index 0000000000..e9071ea031 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/go/books.sql.go @@ -0,0 +1,46 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: books.sql + +package querytest + +import ( + "context" +) + +const listBooksByAuthor = `-- name: ListBooksByAuthor :many +SELECT b.id, b.author_id, b.title, b.deleted_at +FROM books b +WHERE b.author_id = $1 + AND (CAST(b.deleted_at AS timestamptz) IS NULL) +ORDER BY b.title +` + +func (q *Queries) ListBooksByAuthor(ctx context.Context, authorID int64) ([]Book, error) { + rows, err := q.db.QueryContext(ctx, listBooksByAuthor, authorID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i Book + if err := rows.Scan( + &i.ID, + &i.AuthorID, + &i.Title, + &i.DeletedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_files/postgresql/go/db.go b/internal/endtoend/testdata/macro_files/postgresql/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro_files/postgresql/go/models.go b/internal/endtoend/testdata/macro_files/postgresql/go/models.go new file mode 100644 index 0000000000..b1bd7e865d --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/go/models.go @@ -0,0 +1,22 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" +) + +type Author struct { + ID int64 + Name string + DeletedAt sql.NullTime +} + +type Book struct { + ID int64 + AuthorID int64 + Title string + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro_files/postgresql/query/authors.sql b/internal/endtoend/testdata/macro_files/postgresql/query/authors.sql new file mode 100644 index 0000000000..787a18323a --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/query/authors.sql @@ -0,0 +1,4 @@ +-- The macro these queries call is defined in macros.sql, which is read after +-- this file. +-- name: ListAuthors :many +SELECT * FROM authors a WHERE sqlc.macro.NotDeleted(a.deleted_at) ORDER BY a.name; diff --git a/internal/endtoend/testdata/macro_files/postgresql/query/books.sql b/internal/endtoend/testdata/macro_files/postgresql/query/books.sql new file mode 100644 index 0000000000..59a02f58ed --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/query/books.sql @@ -0,0 +1,6 @@ +-- name: ListBooksByAuthor :many +SELECT b.* +FROM books b +WHERE b.author_id = sqlc.arg(author_id) + AND sqlc.macro.NotDeleted(b.deleted_at) +ORDER BY b.title; diff --git a/internal/endtoend/testdata/macro_files/postgresql/query/macros.sql b/internal/endtoend/testdata/macro_files/postgresql/query/macros.sql new file mode 100644 index 0000000000..c5d781ed06 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/query/macros.sql @@ -0,0 +1,3 @@ +-- name: NotDeleted :macro +-- @param deleted_at timestamptz +sqlc.arg(deleted_at) IS NULL; diff --git a/internal/endtoend/testdata/macro_files/postgresql/schema.sql b/internal/endtoend/testdata/macro_files/postgresql/schema.sql new file mode 100644 index 0000000000..f6610f3752 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/schema.sql @@ -0,0 +1,12 @@ +CREATE TABLE authors ( + id bigserial PRIMARY KEY, + name text NOT NULL, + deleted_at timestamptz +); + +CREATE TABLE books ( + id bigserial PRIMARY KEY, + author_id bigint NOT NULL REFERENCES authors (id), + title text NOT NULL, + deleted_at timestamptz +); diff --git a/internal/endtoend/testdata/macro_files/postgresql/sqlc.json b/internal/endtoend/testdata/macro_files/postgresql/sqlc.json new file mode 100644 index 0000000000..9be642f133 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/postgresql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "postgresql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query" + } + ] +} diff --git a/internal/endtoend/testdata/macro_files/sqlite/go/authors.sql.go b/internal/endtoend/testdata/macro_files/sqlite/go/authors.sql.go new file mode 100644 index 0000000000..93e39534e8 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/go/authors.sql.go @@ -0,0 +1,39 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: authors.sql + +package querytest + +import ( + "context" +) + +const listAuthors = `-- name: ListAuthors :many +SELECT id, name, deleted_at FROM authors a WHERE (a.deleted_at IS NULL) ORDER BY a.name +` + +// The macro these queries call is defined in macros.sql, which is read after +// this file. +func (q *Queries) ListAuthors(ctx context.Context) ([]Author, error) { + rows, err := q.db.QueryContext(ctx, listAuthors) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Author + for rows.Next() { + var i Author + if err := rows.Scan(&i.ID, &i.Name, &i.DeletedAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_files/sqlite/go/books.sql.go b/internal/endtoend/testdata/macro_files/sqlite/go/books.sql.go new file mode 100644 index 0000000000..8864ca4423 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/go/books.sql.go @@ -0,0 +1,46 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: books.sql + +package querytest + +import ( + "context" +) + +const listBooksByAuthor = `-- name: ListBooksByAuthor :many +SELECT b.id, b.author_id, b.title, b.deleted_at +FROM books b +WHERE b.author_id = ?1 + AND (b.deleted_at IS NULL) +ORDER BY b.title +` + +func (q *Queries) ListBooksByAuthor(ctx context.Context, authorID int64) ([]Book, error) { + rows, err := q.db.QueryContext(ctx, listBooksByAuthor, authorID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i Book + if err := rows.Scan( + &i.ID, + &i.AuthorID, + &i.Title, + &i.DeletedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_files/sqlite/go/db.go b/internal/endtoend/testdata/macro_files/sqlite/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro_files/sqlite/go/models.go b/internal/endtoend/testdata/macro_files/sqlite/go/models.go new file mode 100644 index 0000000000..b1bd7e865d --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/go/models.go @@ -0,0 +1,22 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" +) + +type Author struct { + ID int64 + Name string + DeletedAt sql.NullTime +} + +type Book struct { + ID int64 + AuthorID int64 + Title string + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro_files/sqlite/query/authors.sql b/internal/endtoend/testdata/macro_files/sqlite/query/authors.sql new file mode 100644 index 0000000000..787a18323a --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/query/authors.sql @@ -0,0 +1,4 @@ +-- The macro these queries call is defined in macros.sql, which is read after +-- this file. +-- name: ListAuthors :many +SELECT * FROM authors a WHERE sqlc.macro.NotDeleted(a.deleted_at) ORDER BY a.name; diff --git a/internal/endtoend/testdata/macro_files/sqlite/query/books.sql b/internal/endtoend/testdata/macro_files/sqlite/query/books.sql new file mode 100644 index 0000000000..59a02f58ed --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/query/books.sql @@ -0,0 +1,6 @@ +-- name: ListBooksByAuthor :many +SELECT b.* +FROM books b +WHERE b.author_id = sqlc.arg(author_id) + AND sqlc.macro.NotDeleted(b.deleted_at) +ORDER BY b.title; diff --git a/internal/endtoend/testdata/macro_files/sqlite/query/macros.sql b/internal/endtoend/testdata/macro_files/sqlite/query/macros.sql new file mode 100644 index 0000000000..88c96acf28 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/query/macros.sql @@ -0,0 +1,4 @@ +-- A file of nothing but macros holds no queries, and generates no code. +-- name: NotDeleted :macro +-- @param deleted_at +sqlc.arg(deleted_at) IS NULL; diff --git a/internal/endtoend/testdata/macro_files/sqlite/schema.sql b/internal/endtoend/testdata/macro_files/sqlite/schema.sql new file mode 100644 index 0000000000..ef63660a52 --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/schema.sql @@ -0,0 +1,12 @@ +CREATE TABLE authors ( + id integer PRIMARY KEY, + name text NOT NULL, + deleted_at datetime +); + +CREATE TABLE books ( + id integer PRIMARY KEY, + author_id integer NOT NULL, + title text NOT NULL, + deleted_at datetime +); diff --git a/internal/endtoend/testdata/macro_files/sqlite/sqlc.json b/internal/endtoend/testdata/macro_files/sqlite/sqlc.json new file mode 100644 index 0000000000..389fe9a7da --- /dev/null +++ b/internal/endtoend/testdata/macro_files/sqlite/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "sqlite", + "name": "querytest", + "schema": "schema.sql", + "queries": "query" + } + ] +} diff --git a/internal/endtoend/testdata/macro_invalid/mysql/query.sql b/internal/endtoend/testdata/macro_invalid/mysql/query.sql new file mode 100644 index 0000000000..bd53ad4ca0 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/mysql/query.sql @@ -0,0 +1,18 @@ +-- name: ByID :macro +-- @param id signed +SELECT * FROM foo WHERE id = sqlc.arg(id); + +-- name: UnknownMacro :many +SELECT * FROM sqlc.macro.Missing(1) m; + +-- name: TooManyArguments :many +SELECT * FROM sqlc.macro.ByID(1, 2) m; + +-- name: Positional :macro +SELECT * FROM foo WHERE id = ?; + +-- name: PositionalInMacro :many +SELECT * FROM sqlc.macro.Positional() p; + +-- name: Valid :many +SELECT * FROM sqlc.macro.ByID(?) m; diff --git a/internal/endtoend/testdata/macro_invalid/mysql/schema.sql b/internal/endtoend/testdata/macro_invalid/mysql/schema.sql new file mode 100644 index 0000000000..79e260952e --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/mysql/schema.sql @@ -0,0 +1 @@ +CREATE TABLE foo (id BIGINT NOT NULL, name TEXT); diff --git a/internal/endtoend/testdata/macro_invalid/mysql/sqlc.json b/internal/endtoend/testdata/macro_invalid/mysql/sqlc.json new file mode 100644 index 0000000000..e41c39e8b3 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/mysql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "mysql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro_invalid/mysql/stderr.txt b/internal/endtoend/testdata/macro_invalid/mysql/stderr.txt new file mode 100644 index 0000000000..8d9533c3c7 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/mysql/stderr.txt @@ -0,0 +1,4 @@ +# package querytest +query.sql:6:15: macro "Missing" is not defined +query.sql:9:15: macro "ByID" takes 1 argument; got 2 +query.sql:15:15: in macro "Positional": positional placeholder "?" is not allowed in a macro; use sqlc.arg() diff --git a/internal/endtoend/testdata/macro_invalid/postgresql/query.sql b/internal/endtoend/testdata/macro_invalid/postgresql/query.sql new file mode 100644 index 0000000000..f454e34dad --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/postgresql/query.sql @@ -0,0 +1,56 @@ +-- name: ByID :macro +-- @param id bigint +SELECT * FROM foo WHERE id = sqlc.arg(id); + +-- name: UnknownMacro :many +SELECT * FROM sqlc.macro.Missing(1) m; + +-- name: TooFewArguments :many +SELECT * FROM sqlc.macro.ByID() m; + +-- name: TooManyArguments :many +SELECT * FROM sqlc.macro.ByID(1, 2) m; + +-- name: NoArgumentList :many +SELECT * FROM sqlc.macro.ByID m; + +-- name: Ping :macro +SELECT * FROM sqlc.macro.Pong() p; + +-- name: Pong :macro +SELECT * FROM sqlc.macro.Ping() p; + +-- name: Recursive :many +SELECT * FROM sqlc.macro.Ping() p; + +-- name: ByID :macro +SELECT 1; + +-- name: Nullable :macro +-- @param id +SELECT * FROM foo WHERE id = sqlc.narg(id); + +-- name: NargOfParameter :many +SELECT * FROM sqlc.macro.Nullable(1) n; + +-- name: Positional :macro +SELECT * FROM foo WHERE id = $1; + +-- name: PositionalInMacro :many +SELECT * FROM sqlc.macro.Positional() p; + +-- name: Twice :macro +-- @param id +-- @param ID +-- @param +SELECT sqlc.arg(id); + +-- name: Empty :macro +; + +-- A macro is only expanded where it is called, so this one never fails. +-- name: Unused :macro +SELECT * FROM sqlc.macro.Missing($1); + +-- name: Valid :many +SELECT * FROM sqlc.macro.ByID($1) m; diff --git a/internal/endtoend/testdata/macro_invalid/postgresql/schema.sql b/internal/endtoend/testdata/macro_invalid/postgresql/schema.sql new file mode 100644 index 0000000000..961c807888 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/postgresql/schema.sql @@ -0,0 +1 @@ +CREATE TABLE foo (id bigint NOT NULL, name text); diff --git a/internal/endtoend/testdata/macro_invalid/postgresql/sqlc.json b/internal/endtoend/testdata/macro_invalid/postgresql/sqlc.json new file mode 100644 index 0000000000..f717ca2e66 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/postgresql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "postgresql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro_invalid/postgresql/stderr.txt b/internal/endtoend/testdata/macro_invalid/postgresql/stderr.txt new file mode 100644 index 0000000000..6561b90cd3 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid/postgresql/stderr.txt @@ -0,0 +1,12 @@ +# package querytest +query.sql:27:1: macro "ByID" is already defined +query.sql:46:1: macro "Twice" declares the parameter "ID" twice +query.sql:46:1: macro "Twice" has a @param without a name +query.sql:49:1: macro "Empty" has no body +query.sql:6:15: macro "Missing" is not defined +query.sql:9:15: macro "ByID" takes 1 argument; got 0 +query.sql:12:15: macro "ByID" takes 1 argument; got 2 +query.sql:15:15: sqlc.macro.ByID must be called with an argument list +query.sql:24:15: in macro "Ping": in macro "Pong": macro "Ping" expands itself: Ping -> Pong -> Ping +query.sql:34:15: in macro "Nullable": the macro parameter "id" can only be referenced with sqlc.arg() +query.sql:40:15: in macro "Positional": positional placeholder "$1" is not allowed in a macro; use sqlc.arg() diff --git a/internal/endtoend/testdata/macro_invalid_body/postgresql/exec.json b/internal/endtoend/testdata/macro_invalid_body/postgresql/exec.json new file mode 100644 index 0000000000..5958e7f5bf --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid_body/postgresql/exec.json @@ -0,0 +1,3 @@ +{ + "contexts": ["base", "managed-db"] +} diff --git a/internal/endtoend/testdata/macro_invalid_body/postgresql/query.sql b/internal/endtoend/testdata/macro_invalid_body/postgresql/query.sql new file mode 100644 index 0000000000..0ad70d85e0 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid_body/postgresql/query.sql @@ -0,0 +1,13 @@ +-- A macro is never checked on its own. This one expands, and the query it +-- leaves does not analyze: the error is reported against the query that +-- called it. +-- name: Archived :macro +-- @param id +SELECT * FROM foo_archive WHERE id = sqlc.arg(id); + +-- name: ListFoo :many +SELECT * FROM foo; + +-- name: ListArchived :many +SELECT * FROM foo +WHERE id IN (SELECT a.id FROM sqlc.macro.Archived(sqlc.arg(id)) a); diff --git a/internal/endtoend/testdata/macro_invalid_body/postgresql/schema.sql b/internal/endtoend/testdata/macro_invalid_body/postgresql/schema.sql new file mode 100644 index 0000000000..961c807888 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid_body/postgresql/schema.sql @@ -0,0 +1 @@ +CREATE TABLE foo (id bigint NOT NULL, name text); diff --git a/internal/endtoend/testdata/macro_invalid_body/postgresql/sqlc.json b/internal/endtoend/testdata/macro_invalid_body/postgresql/sqlc.json new file mode 100644 index 0000000000..f717ca2e66 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid_body/postgresql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "postgresql", + "name": "querytest", + "schema": "schema.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro_invalid_body/postgresql/stderr/base.txt b/internal/endtoend/testdata/macro_invalid_body/postgresql/stderr/base.txt new file mode 100644 index 0000000000..bb832a06c7 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid_body/postgresql/stderr/base.txt @@ -0,0 +1,2 @@ +# package querytest +query.sql:12:1: relation "foo_archive" does not exist diff --git a/internal/endtoend/testdata/macro_invalid_body/postgresql/stderr/managed-db.txt b/internal/endtoend/testdata/macro_invalid_body/postgresql/stderr/managed-db.txt new file mode 100644 index 0000000000..68e7ef8b47 --- /dev/null +++ b/internal/endtoend/testdata/macro_invalid_body/postgresql/stderr/managed-db.txt @@ -0,0 +1,2 @@ +# package querytest +query.sql:13:31: relation "foo_archive" does not exist diff --git a/internal/endtoend/testdata/macro_schema_file/mysql/exec.json b/internal/endtoend/testdata/macro_schema_file/mysql/exec.json new file mode 100644 index 0000000000..37457508a5 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/mysql/exec.json @@ -0,0 +1,6 @@ +{ + "contexts": ["base", "core"], + "meta": { + "invalid_schema": true + } +} diff --git a/internal/endtoend/testdata/macro_schema_file/mysql/go/db.go b/internal/endtoend/testdata/macro_schema_file/mysql/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/mysql/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro_schema_file/mysql/go/models.go b/internal/endtoend/testdata/macro_schema_file/mysql/go/models.go new file mode 100644 index 0000000000..35e9f16d14 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/mysql/go/models.go @@ -0,0 +1,16 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" +) + +type Author struct { + ID int64 + OrgID int64 + Name string + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro_schema_file/mysql/go/query.sql.go b/internal/endtoend/testdata/macro_schema_file/mysql/go/query.sql.go new file mode 100644 index 0000000000..6ca77e5aec --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/mysql/go/query.sql.go @@ -0,0 +1,42 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package querytest + +import ( + "context" +) + +const listActiveAuthors = `-- name: ListActiveAuthors :many +SELECT a.id, a.name FROM (SELECT id, org_id, name, deleted_at FROM authors a WHERE a.org_id = CAST(? AS signed) AND (a.deleted_at IS NULL)) a ORDER BY a.name +` + +type ListActiveAuthorsRow struct { + ID int64 + Name string +} + +func (q *Queries) ListActiveAuthors(ctx context.Context, orgID int64) ([]ListActiveAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listActiveAuthors, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListActiveAuthorsRow + for rows.Next() { + var i ListActiveAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_schema_file/mysql/query.sql b/internal/endtoend/testdata/macro_schema_file/mysql/query.sql new file mode 100644 index 0000000000..ea0a1ce2b3 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/mysql/query.sql @@ -0,0 +1,19 @@ +-- This file is the schema and the queries both. A macro is not SQL, so it is +-- expanded before the schema is read, just as it is before the queries are. +CREATE TABLE authors ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + org_id BIGINT NOT NULL, + name VARCHAR(255) NOT NULL, + deleted_at DATETIME +); + +-- name: NotDeleted :macro +-- @param deleted_at +sqlc.arg(deleted_at) IS NULL; + +-- name: ActiveAuthors :macro +-- @param org signed +SELECT * FROM authors a WHERE a.org_id = sqlc.arg(org) AND sqlc.macro.NotDeleted(a.deleted_at); + +-- name: ListActiveAuthors :many +SELECT a.id, a.name FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a ORDER BY a.name; diff --git a/internal/endtoend/testdata/macro_schema_file/mysql/sqlc.json b/internal/endtoend/testdata/macro_schema_file/mysql/sqlc.json new file mode 100644 index 0000000000..445bbd1589 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/mysql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "mysql", + "name": "querytest", + "schema": "query.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro_schema_file/postgresql/exec.json b/internal/endtoend/testdata/macro_schema_file/postgresql/exec.json new file mode 100644 index 0000000000..37457508a5 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/postgresql/exec.json @@ -0,0 +1,6 @@ +{ + "contexts": ["base", "core"], + "meta": { + "invalid_schema": true + } +} diff --git a/internal/endtoend/testdata/macro_schema_file/postgresql/go/db.go b/internal/endtoend/testdata/macro_schema_file/postgresql/go/db.go new file mode 100644 index 0000000000..32faa9f2b8 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/postgresql/go/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/endtoend/testdata/macro_schema_file/postgresql/go/models.go b/internal/endtoend/testdata/macro_schema_file/postgresql/go/models.go new file mode 100644 index 0000000000..35e9f16d14 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/postgresql/go/models.go @@ -0,0 +1,16 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package querytest + +import ( + "database/sql" +) + +type Author struct { + ID int64 + OrgID int64 + Name string + DeletedAt sql.NullTime +} diff --git a/internal/endtoend/testdata/macro_schema_file/postgresql/go/query.sql.go b/internal/endtoend/testdata/macro_schema_file/postgresql/go/query.sql.go new file mode 100644 index 0000000000..94eb4e403b --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/postgresql/go/query.sql.go @@ -0,0 +1,42 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package querytest + +import ( + "context" +) + +const listActiveAuthors = `-- name: ListActiveAuthors :many +SELECT a.id, a.name FROM (SELECT id, org_id, name, deleted_at FROM authors a WHERE a.org_id = CAST($1 AS bigint) AND (a.deleted_at IS NULL)) a ORDER BY a.name +` + +type ListActiveAuthorsRow struct { + ID int64 + Name string +} + +func (q *Queries) ListActiveAuthors(ctx context.Context, orgID int64) ([]ListActiveAuthorsRow, error) { + rows, err := q.db.QueryContext(ctx, listActiveAuthors, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListActiveAuthorsRow + for rows.Next() { + var i ListActiveAuthorsRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/endtoend/testdata/macro_schema_file/postgresql/query.sql b/internal/endtoend/testdata/macro_schema_file/postgresql/query.sql new file mode 100644 index 0000000000..a2c79982fc --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/postgresql/query.sql @@ -0,0 +1,19 @@ +-- This file is the schema and the queries both. A macro is not SQL, so it is +-- expanded before the schema is read, just as it is before the queries are. +CREATE TABLE authors ( + id bigserial PRIMARY KEY, + org_id bigint NOT NULL, + name text NOT NULL, + deleted_at timestamptz +); + +-- name: NotDeleted :macro +-- @param deleted_at +sqlc.arg(deleted_at) IS NULL; + +-- name: ActiveAuthors :macro +-- @param org bigint +SELECT * FROM authors a WHERE a.org_id = sqlc.arg(org) AND sqlc.macro.NotDeleted(a.deleted_at); + +-- name: ListActiveAuthors :many +SELECT a.id, a.name FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a ORDER BY a.name; diff --git a/internal/endtoend/testdata/macro_schema_file/postgresql/sqlc.json b/internal/endtoend/testdata/macro_schema_file/postgresql/sqlc.json new file mode 100644 index 0000000000..c72b6132d5 --- /dev/null +++ b/internal/endtoend/testdata/macro_schema_file/postgresql/sqlc.json @@ -0,0 +1,12 @@ +{ + "version": "1", + "packages": [ + { + "path": "go", + "engine": "postgresql", + "name": "querytest", + "schema": "query.sql", + "queries": "query.sql" + } + ] +} diff --git a/internal/endtoend/testdata/macro_unsupported/duckdb/exec.json b/internal/endtoend/testdata/macro_unsupported/duckdb/exec.json new file mode 100644 index 0000000000..2e996ca79d --- /dev/null +++ b/internal/endtoend/testdata/macro_unsupported/duckdb/exec.json @@ -0,0 +1,3 @@ +{ + "contexts": ["base"] +} diff --git a/internal/endtoend/testdata/macro_unsupported/duckdb/query.sql b/internal/endtoend/testdata/macro_unsupported/duckdb/query.sql new file mode 100644 index 0000000000..e9ce01704c --- /dev/null +++ b/internal/endtoend/testdata/macro_unsupported/duckdb/query.sql @@ -0,0 +1,7 @@ +-- DuckDB queries are not preprocessed, so there is no sqlc.macro to call a +-- macro with. +-- name: AllFoo :macro +SELECT * FROM foo; + +-- name: ListFoo :many +SELECT * FROM foo; diff --git a/internal/endtoend/testdata/macro_unsupported/duckdb/schema.sql b/internal/endtoend/testdata/macro_unsupported/duckdb/schema.sql new file mode 100644 index 0000000000..79e260952e --- /dev/null +++ b/internal/endtoend/testdata/macro_unsupported/duckdb/schema.sql @@ -0,0 +1 @@ +CREATE TABLE foo (id BIGINT NOT NULL, name TEXT); diff --git a/internal/endtoend/testdata/macro_unsupported/duckdb/sqlc.yaml b/internal/endtoend/testdata/macro_unsupported/duckdb/sqlc.yaml new file mode 100644 index 0000000000..07d6d9d3b8 --- /dev/null +++ b/internal/endtoend/testdata/macro_unsupported/duckdb/sqlc.yaml @@ -0,0 +1,10 @@ +version: "2" +sql: + - engine: "duckdb" + schema: "schema.sql" + queries: "query.sql" + gen: + go: + package: "querytest" + out: "go" + sql_package: "database/sql" diff --git a/internal/endtoend/testdata/macro_unsupported/duckdb/stderr.txt b/internal/endtoend/testdata/macro_unsupported/duckdb/stderr.txt new file mode 100644 index 0000000000..d459cc1d38 --- /dev/null +++ b/internal/endtoend/testdata/macro_unsupported/duckdb/stderr.txt @@ -0,0 +1,2 @@ +# package querytest +query.sql:1:1: macro "AllFoo": the :macro annotation is not supported by the duckdb engine diff --git a/internal/metadata/meta.go b/internal/metadata/meta.go index 76ee992a7a..9ac14ce73f 100644 --- a/internal/metadata/meta.go +++ b/internal/metadata/meta.go @@ -37,6 +37,11 @@ const ( CmdBatchExec = ":batchexec" CmdBatchMany = ":batchmany" CmdBatchOne = ":batchone" + + // CmdMacro marks a statement as a macro definition rather than a query. + // It generates no code of its own: internal/sql/preprocess expands it + // wherever another query calls sqlc.macro.(). + CmdMacro = ":macro" ) // A query name must be a valid Go identifier @@ -98,7 +103,7 @@ func ParseQueryNameAndType(t string, commentStyle CommentSyntax) (string, string part = part[:len(part)-1] // removes the trailing "*/" element } if len(part) == 3 { - return "", "", fmt.Errorf("missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone']: %s", line) + return "", "", fmt.Errorf("missing query type [':one', ':many', ':exec', ':execrows', ':execlastid', ':execresult', ':copyfrom', 'batchexec', 'batchmany', 'batchone', ':macro']: %s", line) } if len(part) != 4 { return "", "", fmt.Errorf("invalid query comment: %s", line) @@ -106,7 +111,7 @@ func ParseQueryNameAndType(t string, commentStyle CommentSyntax) (string, string queryName := part[2] queryType := strings.TrimSpace(part[3]) switch queryType { - case CmdOne, CmdMany, CmdExec, CmdExecResult, CmdExecRows, CmdExecLastId, CmdCopyFrom, CmdBatchExec, CmdBatchMany, CmdBatchOne: + case CmdOne, CmdMany, CmdExec, CmdExecResult, CmdExecRows, CmdExecLastId, CmdCopyFrom, CmdBatchExec, CmdBatchMany, CmdBatchOne, CmdMacro: default: return "", "", fmt.Errorf("invalid query type: %s", queryType) } diff --git a/internal/sql/preprocess/CLAUDE.md b/internal/sql/preprocess/CLAUDE.md index a7f4d9aafe..a7d59fd60d 100644 --- a/internal/sql/preprocess/CLAUDE.md +++ b/internal/sql/preprocess/CLAUDE.md @@ -12,6 +12,8 @@ parsers, converters and `astutils` traversals only ever deal with SQL. | `sqlc.slice(name)` | the placeholder wrapped in `/*SLICE:name*/` | | `sqlc.embed(table)` | `table.*` | | `@name` | the native placeholder, on dialects where `@` is sqlc syntax | +| `sqlc.macro.Name(args)` | the body of the `:macro` named `Name`, in parentheses | +| a statement annotated `:macro` | whitespace | Native placeholders by dialect: @@ -46,6 +48,62 @@ top-level semicolons and, for each statement: 3. The statement is rewritten into the output buffer and a `Statement` records what changed. +## Macros + +A statement annotated `-- name: Name :macro` is a macro, not a query. macro.go +expands macros in a pass of its own, **before** the rewrite above, so the +rewrite only ever sees the queries macros expanded into: + +```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 FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a; +-- after the macro pass: +-- SELECT a.id FROM (SELECT * FROM authors WHERE org_id = CAST(sqlc.arg(org_id) AS bigint) AND deleted_at IS NULL) a; +-- after the rewrite: +-- SELECT a.id FROM (SELECT * FROM authors WHERE org_id = CAST($1 AS bigint) AND deleted_at IS NULL) a; +``` + +`Macros` is the set of definitions a group of query files shares. `Collect` +records the macros a file defines and returns the errors in the definitions +themselves; `File` rewrites a file against the set. The package-level `File` +is the same thing for a single file on its own. `Expand` runs the macro pass +alone, for the schema parser: a schema file is often a query file too, and +takes `sqlc.arg()` as the function call it looks like but cannot take a macro. + +- **Parameters** are declared with `-- @param name [type]`, in call order. In + the body `sqlc.arg(name)` and `@name` refer to them. A typed parameter becomes + `CAST(arg AS type)`; an untyped one is the argument as written, in + parentheses unless it is a single term (`atomic`). +- **Anything else passes through.** A `sqlc.arg()` that is not a parameter of + the macro is left for the rewrite, so it becomes a parameter of the calling + query. +- **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. Definition order and file order do not matter. Recursion is an error. +- **Arguments belong to the caller.** They are expanded where they are + written and never rescanned inside the body, so `F(F(x))` is not recursion + and an argument can never be captured by a parameter name. +- **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. `Origin` + maps an offset inside the gap to the end of it: a parser places the start of + a statement right after the one before, which in the source is the macro. +- **A body is flattened.** Comments are dropped (a comment pasted into a query + would be read as one of its annotations) and line breaks become spaces, which + is what keeps the "never adds a line" invariant below. A literal that spans + lines cannot be flattened and is an error. Optimizer hints (`/*+ */`) stay. +- **No positional placeholders in a body.** `$1` or `?` would be numbered + against whichever query the macro lands in. + +A statement whose macros cannot be expanded is handled like any other invalid +statement: copied through untouched, with the reason in `Statement.Err`. + +An engine without a dialect has no macros. A `:macro` definition reaches its +compiler as a statement, and the compiler rejects it. + ## The side table `Result.Statement(offset)` returns the `Statement` covering an offset in the @@ -63,7 +121,8 @@ top-level semicolons and, for each statement: argument that is not an identifier or string) `Result.Origin(offset)` maps an offset in the rewritten text back to the -original source, so errors point at what the user wrote. +original source, so errors point at what the user wrote. Everything a macro +call expanded to maps to the call. ## Invariants @@ -87,7 +146,9 @@ original source, so errors point at what the user wrote. | `side_table.json` | everything the preprocessor recorded | | `stderr.txt` | reported errors, only when the input is invalid | -`TestRewrite` runs one subtest per directory. `side_table.json` is rendered by +`TestRewrite` runs one subtest per directory; the macros a case can call are +the ones its `input.sql` defines, and errors in those definitions are listed +first in `stderr.txt`. `side_table.json` is rendered by reading the result back through the same API the compiler uses, so it covers parameter names and nullability, embed and slice spans, placeholder numbering and the offset map — a parameter's `location` is its offset in the rewritten diff --git a/internal/sql/preprocess/macro.go b/internal/sql/preprocess/macro.go new file mode 100644 index 0000000000..aec4d68f00 --- /dev/null +++ b/internal/sql/preprocess/macro.go @@ -0,0 +1,620 @@ +package preprocess + +import ( + "fmt" + "slices" + "strings" + + "github.com/sqlc-dev/sqlc/internal/config" + "github.com/sqlc-dev/sqlc/internal/constants" + "github.com/sqlc-dev/sqlc/internal/metadata" + "github.com/sqlc-dev/sqlc/internal/source" + "github.com/sqlc-dev/sqlc/internal/sql/sqlerr" +) + +// A macro is a statement annotated ":macro". It is not a query: it generates +// no code and is never parsed on its own. Its body is a piece of SQL that is +// pasted, in parentheses, wherever another query calls sqlc.macro.(). +// +// -- 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; +type macro struct { + name string + filename string + params []macroParam + // body is the statement without its comments, its terminator or its line + // breaks, so pasting it never adds a line to the query it lands in. + body string + // spansLines is set when the body could not be put on one line. + spansLines bool +} + +// macroParam is a parameter declared with "-- @param name [type]". A typed +// parameter casts whatever it is given to that type. +type macroParam struct { + name string + typ string +} + +// Macros is the set of macros visible to a group of query files. Macros are +// expanded lazily — only where a query calls one — so a definition may sit in +// any file of the group, before or after its callers. +type Macros struct { + d Dialect + ok bool + defs map[string]*macro +} + +// NewMacros returns an empty set of macros for an engine. An engine that is not +// preprocessed has no sqlc syntax, and so no macros: its set stays empty and +// File returns the source unchanged. +func NewMacros(engine config.Engine) *Macros { + d, ok := DialectFor(engine) + return newMacros(d, ok) +} + +func newMacros(d Dialect, ok bool) *Macros { + return &Macros{d: d, ok: ok, defs: map[string]*macro{}} +} + +// commentSyntax is how the dialect writes the comments annotations live in. +func (d Dialect) commentSyntax() source.CommentSyntax { + return source.CommentSyntax{Dash: true, SlashStar: true, Hash: d.HashComment} +} + +// fold returns the form of a parameter name that references are matched by. +func (d Dialect) fold(name string) string { + if d.FoldIdentifier { + return strings.ToLower(name) + } + return name +} + +// macroName returns the name of the macro a statement defines, and whether it +// defines one at all. +func (d Dialect) macroName(stmt string) (string, bool) { + name, cmd, err := metadata.ParseQueryNameAndType(stmt, metadata.CommentSyntax(d.commentSyntax())) + if err != nil || cmd != metadata.CmdMacro { + return "", false + } + return name, true +} + +// Collect records every macro defined in src. The errors it returns are +// problems with the definitions themselves, located in src; a definition that +// has one is still recorded, so its callers are not reported a second time for +// calling a macro that does not exist. +func (m *Macros) Collect(filename, src string) []*sqlerr.Error { + if !m.ok { + return nil + } + var errs []*sqlerr.Error + l := &lexer{d: m.d, src: src} + for _, span := range l.statements() { + start, end := span[0], span[1] + stmt := src[start:end] + name, ok := m.d.macroName(stmt) + if !ok { + continue + } + fail := func(format string, args ...any) { + errs = append(errs, &sqlerr.Error{ + Message: fmt.Sprintf("macro %q ", name) + fmt.Sprintf(format, args...), + Location: start, + }) + } + if prev, exists := m.defs[name]; exists { + if prev.filename != filename { + fail("is already defined in %s", prev.filename) + } else { + fail("is already defined") + } + continue + } + + def := ¯o{name: name, filename: filename} + m.defs[name] = def + + comments, err := source.CleanedComments(stmt, m.d.commentSyntax()) + if err != nil { + fail("has unreadable comments: %s", err) + continue + } + seen := map[string]bool{} + for _, line := range comments { + fields := strings.Fields(line) + if len(fields) == 0 || fields[0] != constants.QueryFlagParam { + continue + } + if len(fields) == 1 { + fail("has a @param without a name") + continue + } + param := macroParam{name: m.d.fold(fields[1]), typ: strings.Join(fields[2:], " ")} + if seen[param.name] { + fail("declares the parameter %q twice", fields[1]) + continue + } + seen[param.name] = true + def.params = append(def.params, param) + } + + body, ok := flatten(m.d, stmt) + def.body = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(body), ";")) + def.spansLines = !ok + if def.body == "" { + fail("has no body") + } + } + return errs +} + +// File rewrites src like the package-level File does, after expanding every +// call to a macro in the set and blanking out the definitions src holds. +func (m *Macros) File(src string) *Result { + if !m.ok { + return &Result{Text: src} + } + text, edits, blanks, errs := m.expandFile(src) + res := rewrite(m.d, text, errs) + res.macroEdits = edits + res.blanks = blanks + return res +} + +// Expand returns src with its macro definitions blanked and its macro calls +// expanded, and the rest of its sqlc syntax as it was written. It is for a +// reader that takes sqlc syntax as it comes but has no way to take a macro: a +// schema parser, when a schema file holds queries as well. A statement whose +// macros cannot be expanded is returned as it was written; File reports why. +func (m *Macros) Expand(src string) string { + if !m.ok || len(m.defs) == 0 { + return src + } + text, _, _, _ := m.expandFile(src) + return text +} + +// CallsMacro reports whether text holds a call to a macro, whether or not the +// macro exists. A tool that rewrites queries without expanding them has to +// leave such a statement alone: the name of a macro is matched exactly, and a +// parser that reads the call as a function is free to fold it. +func CallsMacro(engine config.Engine, text string) bool { + d, ok := DialectFor(engine) + if !ok { + return false + } + l := &lexer{d: d, src: text} + for i := 0; i < len(text); { + if stop := l.skip(i); stop >= 0 { + if stop <= i { + stop = i + 1 + } + i = stop + continue + } + if !isIdentStart(text[i]) { + i++ + continue + } + j := l.identEnd(i) + if strings.EqualFold(text[i:j], "sqlc") { + // A call that is not well formed is still a call. + if _, ok, err := l.macroCall(i, j); ok || err != nil { + return true + } + } + i = j + } + return false +} + +// expandFile returns src with its macro definitions blanked and its macro +// calls expanded, the spans it replaced, the spans it blanked, and one error — +// located in the returned text — for every statement it had to leave alone. +func (m *Macros) expandFile(src string) (string, []edit, [][2]int, []*sqlerr.Error) { + var ( + b strings.Builder + edits []edit + blanks [][2]int + errs []*sqlerr.Error + ) + b.Grow(len(src)) + + l := &lexer{d: m.d, src: src} + for _, span := range l.statements() { + start, end := span[0], span[1] + stmt := src[start:end] + + // A definition is not SQL the engine should see. It is blanked rather + // than cut so every other statement keeps its offset and its line. + if _, ok := m.d.macroName(stmt); ok { + b.WriteString(blank(stmt)) + blanks = append(blanks, [2]int{start, end}) + continue + } + + var local []edit + out, err := m.expand(stmt, nil, nil, &local) + if err != nil { + // Like any other invalid statement, this one is copied through as + // written and the error is reported against it. + err.Location += b.Len() + errs = append(errs, err) + b.WriteString(stmt) + continue + } + for _, e := range local { + edits = append(edits, edit{ + oldStart: start + e.oldStart, oldEnd: start + e.oldEnd, + newStart: b.Len() + e.newStart, newEnd: b.Len() + e.newEnd, + }) + } + b.WriteString(out) + } + return b.String(), edits, blanks, errs +} + +// expand copies text, replacing each macro call with its expansion. Inside a +// macro's body bind is non-nil, and maps each of the macro's parameters to +// the argument it stands for; everywhere else sqlc.arg() is left for the +// placeholder rewrite that follows. +// +// stack names the macros being expanded, outermost first. record, when set, +// collects the span of each call replaced, relative to text and to the result. +// An error is located in text. +func (m *Macros) expand(text string, bind map[string]string, stack []string, record *[]edit) (string, *sqlerr.Error) { + l := &lexer{d: m.d, src: text} + inBody := bind != nil + + var b strings.Builder + b.Grow(len(text)) + for i := 0; i < len(text); { + if stop := l.skip(i); stop >= 0 { + if stop <= i { + stop = i + 1 + } + b.WriteString(text[i:stop]) + i = stop + continue + } + c := text[i] + switch { + case isIdentStart(c): + j := l.identEnd(i) + if !strings.EqualFold(text[i:j], "sqlc") { + b.WriteString(text[i:j]) + i = j + continue + } + if call, ok, err := l.macroCall(i, j); err != nil { + return "", err + } else if ok { + expansion, err := m.call(l, call, bind, stack) + if err != nil { + return "", err + } + newStart := b.Len() + b.WriteString(expansion) + if record != nil { + *record = append(*record, edit{ + oldStart: call.start, oldEnd: call.end, + newStart: newStart, newEnd: b.Len(), + }) + } + i = call.end + continue + } + if inBody { + // A reference to one of the macro's own parameters. Any other + // sqlc call is copied whole, so its argument is never taken + // for a reference itself. + if occ, next, ok := l.sqlcCall(i, j); ok { + arg, bound := bind[m.d.fold(occ.name)] + if occ.err == nil && bound && occ.kind != kindEmbed { + if occ.kind != kindArg { + return "", &sqlerr.Error{ + Message: fmt.Sprintf("the macro parameter %q can only be referenced with sqlc.arg()", occ.name), + Location: i, + } + } + b.WriteString(arg) + } else { + b.WriteString(text[i:next]) + } + i = next + continue + } + } + b.WriteString(text[i:j]) + i = j + + case inBody && c == '@' && m.d.AtSign && isIdentStart(l.at(i+1)): + j := l.identEnd(i + 1) + if arg, bound := bind[m.d.fold(text[i+1:j])]; bound { + b.WriteString(arg) + } else { + b.WriteString(text[i:j]) + } + i = j + + case inBody && ((c == '$' && m.d.DollarNumber && isDigit(l.at(i+1))) || (c == '?' && m.d.Question)): + // A positional placeholder would be numbered against whichever + // query the macro lands in, which is never what was meant. + j := i + 1 + for j < len(text) && isDigit(text[j]) { + j++ + } + return "", &sqlerr.Error{ + Message: fmt.Sprintf("positional placeholder %q is not allowed in a macro; use sqlc.arg()", text[i:j]), + Location: i, + } + + default: + b.WriteByte(c) + i++ + } + } + return b.String(), nil +} + +// macroCall is a "sqlc.macro.()" call found in a lexer's source. +type macroCall struct { + name string + start, end int + // open and closing are the offsets of the call's parentheses. + open, closing int +} + +// macroCall parses the macro call that starts at start, where afterSqlc is the +// offset just past the "sqlc" identifier. It reports false when the text is +// not a macro call at all. +func (l *lexer) macroCall(start, afterSqlc int) (macroCall, bool, *sqlerr.Error) { + i := l.skipSpace(afterSqlc) + if l.at(i) != '.' { + return macroCall{}, false, nil + } + i = l.skipSpace(i + 1) + if !isIdentStart(l.at(i)) { + return macroCall{}, false, nil + } + j := l.identEnd(i) + if !strings.EqualFold(l.src[i:j], "macro") { + return macroCall{}, false, nil + } + i = l.skipSpace(j) + if l.at(i) != '.' { + return macroCall{}, false, nil + } + i = l.skipSpace(i + 1) + if !isIdentStart(l.at(i)) { + return macroCall{}, false, nil + } + j = l.identEnd(i) + call := macroCall{name: l.src[i:j], start: start} + + call.open = l.skipSpace(j) + if l.at(call.open) != '(' { + return call, false, &sqlerr.Error{ + Message: fmt.Sprintf("sqlc.macro.%s must be called with an argument list", call.name), + Location: start, + } + } + call.closing = l.matchParen(call.open) + if call.closing < 0 { + return call, false, &sqlerr.Error{ + Message: fmt.Sprintf("sqlc.macro.%s is missing its closing parenthesis", call.name), + Location: start, + } + } + call.end = call.closing + 1 + return call, true, nil +} + +// call returns the expansion of one macro call: the macro's body, with each +// parameter replaced by its argument, in parentheses. +func (m *Macros) call(l *lexer, call macroCall, bind map[string]string, stack []string) (string, *sqlerr.Error) { + fail := func(format string, args ...any) (string, *sqlerr.Error) { + return "", &sqlerr.Error{Message: fmt.Sprintf(format, args...), Location: call.start} + } + + def, ok := m.defs[call.name] + if !ok { + return fail("macro %q is not defined", call.name) + } + if slices.Contains(stack, call.name) { + return fail("macro %q expands itself: %s", call.name, strings.Join(append(stack, call.name), " -> ")) + } + + if def.spansLines { + return fail("in macro %q: %s", call.name, errSpansLines) + } + + args := l.splitArgs(call.open+1, call.closing) + if len(args) != len(def.params) { + return fail("macro %q takes %s; got %d", call.name, plural(len(def.params), "argument"), len(args)) + } + + // Arguments belong to the caller: they are expanded where they were + // written, and are not looked at again once they are inside the body. + callee := make(map[string]string, len(args)) + offset := call.open + 1 + for i, arg := range args { + if strings.TrimSpace(arg) == "" { + return fail("macro %q is missing argument %d", call.name, i+1) + } + expanded, err := m.expand(arg, bind, stack, nil) + if err != nil { + err.Location += offset + return "", err + } + flat, ok := flatten(m.d, expanded) + if !ok { + return "", &sqlerr.Error{Message: errSpansLines, Location: offset} + } + offset += len(arg) + 1 + param := def.params[i] + callee[param.name] = m.d.macroArg(param, strings.TrimSpace(flat)) + } + + body, err := m.expand(def.body, callee, append(stack, call.name), nil) + if err != nil { + // The body is not in the file the error is reported against, so the + // error points at the call that reached it. + return fail("in macro %q: %s", call.name, err.Message) + } + return "(" + body + ")", nil +} + +func plural(n int, noun string) string { + if n == 1 { + return fmt.Sprintf("1 %s", noun) + } + return fmt.Sprintf("%d %ss", n, noun) +} + +// macroArg returns the text that stands in for a parameter. A typed parameter +// casts its argument. An untyped one takes it as written, in parentheses +// unless it is already a single term, so that the operators around the +// reference cannot regroup an expression. +func (d Dialect) macroArg(p macroParam, arg string) string { + if p.typ != "" { + return "CAST(" + arg + " AS " + p.typ + ")" + } + if d.atomic(arg) { + return arg + } + return "(" + arg + ")" +} + +// atomic reports whether s is a single term: a literal, a placeholder, a +// possibly qualified name, a function call or something already in +// parentheses. +func (d Dialect) atomic(s string) bool { + l := &lexer{d: d, src: s} + n := len(s) + if n == 0 { + return false + } + if l.skip(0) == n { + return true // a string literal or a quoted identifier + } + switch c := s[0]; { + case c == '(': + return l.matchParen(0) == n-1 + case isDigit(c): + for i := 1; i < n; i++ { + if !isDigit(s[i]) && s[i] != '.' { + return false + } + } + return true + case c == '$' || c == '?': + for i := 1; i < n; i++ { + if !isDigit(s[i]) { + return false + } + } + return true + case c == '@': + return isIdentStart(l.at(1)) && l.identEnd(1) == n + } + for i := 0; ; { + switch c := s[i]; { + case isIdentStart(c): + i = l.identEnd(i) + case c == '"' || (c == '`' && d.Backtick): + i = l.skip(i) + default: + return false + } + if i >= n { + return true + } + switch s[i] { + case '.': + if i++; i >= n { + return false + } + case '(': + return l.matchParen(i) == n-1 + default: + return false + } + } +} + +// errSpansLines is the error for text flatten could not put on one line. +const errSpansLines = "a string or quoted name that spans lines cannot be expanded by a macro" + +// flatten returns s on a single line and without its comments, which is the +// form text is pasted into another query in. A comment that reached the query +// would be read as one of its own annotations, and a line break would move +// every line after it. Optimizer hints are comments in name only, and stay. +// +// It reports false when a line break is part of a literal, where it cannot be +// taken out without changing what the literal says. +func flatten(d Dialect, s string) (string, bool) { + l := &lexer{d: d, src: s} + var b strings.Builder + b.Grow(len(s)) + space := func() { + if b.Len() > 0 && !strings.HasSuffix(b.String(), " ") { + b.WriteByte(' ') + } + } + ok := true + for i := 0; i < len(s); { + if stop := l.skip(i); stop >= 0 { + if stop <= i { + stop = i + 1 + } + if l.isComment(i) && !strings.HasPrefix(s[i:], "/*+") && !strings.HasPrefix(s[i:], "/*!") { + space() + } else { + if strings.Contains(s[i:stop], "\n") { + ok = false + } + b.WriteString(s[i:stop]) + } + i = stop + continue + } + if isSpace(s[i]) { + space() + } else { + b.WriteByte(s[i]) + } + i++ + } + return b.String(), ok +} + +// isComment reports whether the token skip found at i is a comment rather than +// a literal. +func (l *lexer) isComment(i int) bool { + switch l.at(i) { + case '-': + return l.at(i+1) == '-' + case '/': + return l.at(i+1) == '*' + case '#': + return l.d.HashComment + } + return false +} + +// blank returns s with everything but its line breaks replaced by spaces. +func blank(s string) string { + out := []byte(s) + for i, c := range out { + if c != '\n' { + out[i] = ' ' + } + } + return string(out) +} diff --git a/internal/sql/preprocess/preprocess.go b/internal/sql/preprocess/preprocess.go index ad25bc9b2f..aceeb5500e 100644 --- a/internal/sql/preprocess/preprocess.go +++ b/internal/sql/preprocess/preprocess.go @@ -92,12 +92,22 @@ type Statement struct { // Result is the outcome of preprocessing a SQL file. type Result struct { - // Text is the rewritten SQL. It has the same number of statements and the - // same line structure as the input. + // Text is the rewritten SQL. It has the same line structure as the input, + // and the same statements less the macro definitions, which are blanked. Text string stmts []*Statement - edits []edit + + // The rewrite happens in two steps, each with its own record of what it + // replaced: macro calls are expanded first, and sqlc syntax is rewritten + // in the text that leaves. edits maps Text back to the expanded text and + // macroEdits maps that back to the source. + edits []edit + macroEdits []edit + + // blanks are the spans of the source that held a macro definition, in + // source order. Text has only whitespace there. + blanks [][2]int } // edit records one rewritten span, in both coordinate systems. @@ -124,9 +134,24 @@ func (r *Result) Statement(location int) *Statement { // Origin maps an offset in the rewritten text back to the offset in the // original source, so errors can be reported against what the user wrote. +// +// Everything a macro call expanded to maps to the call. An offset in the gap a +// macro definition left maps past the definition, to the statement after it: +// a parser places the start of a statement right after the one before, and +// what sits there in the source is the macro, not the query. func (r *Result) Origin(location int) int { + location = origin(r.macroEdits, origin(r.edits, location)) + for _, b := range r.blanks { + if location >= b[0] && location < b[1] { + location = b[1] + } + } + return location +} + +func origin(edits []edit, location int) int { delta := 0 - for _, e := range r.edits { + for _, e := range edits { if location < e.newStart { break } @@ -170,16 +195,26 @@ type occurrence struct { // parameter syntax — gets the source back unchanged, with an empty side // table. sqlc.arg() and friends are not rewritten for it, so they reach the // parser as the function calls they look like. +// +// The only macros a query in src can call are the ones src defines. Queries +// spread over several files share theirs through a Macros set. func File(engine config.Engine, src string) *Result { - d, ok := DialectFor(engine) - if !ok { - return &Result{Text: src} - } - return Dialected(d, src) + m := NewMacros(engine) + m.Collect("", src) + return m.File(src) } // Dialected rewrites src using an explicit dialect. func Dialected(d Dialect, src string) *Result { + m := newMacros(d, true) + m.Collect("", src) + return m.File(src) +} + +// rewrite replaces the sqlc syntax in src, which has already had its macros +// expanded. failed holds an error, located in src, for each statement the +// expansion could not complete. +func rewrite(d Dialect, src string, failed []*sqlerr.Error) *Result { l := &lexer{d: d, src: src} res := &Result{} @@ -204,7 +239,14 @@ func Dialected(d Dialect, src string) *Result { // A statement that fails validation is copied through unchanged so the // engine parses what the user actually wrote and the error keeps its // original shape. - if err := firstError(occs); err != nil { + err := firstError(occs) + for _, f := range failed { + if f.Location >= start && f.Location < end { + err = f + break + } + } + if err != nil { b.WriteString(src[start:end]) stmt.End = b.Len() err.Location = stmt.Start + (err.Location - start) diff --git a/internal/sql/preprocess/preprocess_test.go b/internal/sql/preprocess/preprocess_test.go index 5b0eb3e0aa..76c4e1ba99 100644 --- a/internal/sql/preprocess/preprocess_test.go +++ b/internal/sql/preprocess/preprocess_test.go @@ -29,6 +29,8 @@ var update = flag.Bool("update", false, "update the testdata golden files") // testdata///side_table.json what the preprocessor recorded // testdata///stderr.txt reported errors (only when invalid) // +// The macros a case can call are the ones its input.sql defines. +// // Regenerate the golden files with `go test ./internal/sql/preprocess -update`. func TestRewrite(t *testing.T) { for _, dir := range cases(t) { @@ -37,11 +39,13 @@ func TestRewrite(t *testing.T) { engine := config.Engine(filepath.Dir(dir)) input := readFile(t, filepath.Join(path, "input.sql")) - res := preprocess.File(engine, input) + macros := preprocess.NewMacros(engine) + defErrs := macros.Collect("input.sql", input) + res := macros.File(input) compare(t, filepath.Join(path, "output.sql"), res.Text) compare(t, filepath.Join(path, "side_table.json"), sideTable(res)) - compare(t, filepath.Join(path, "stderr.txt"), errors(input, res)) + compare(t, filepath.Join(path, "stderr.txt"), errors(input, defErrs, res)) // A rewrite only ever replaces text with something shorter or // equal in lines, so a line number taken from the rewritten text is @@ -146,9 +150,14 @@ func sideTable(res *preprocess.Result) string { } // errors renders every validation error the preprocessor recorded, one per -// line, as "line:column: message" against the original source. -func errors(input string, res *preprocess.Result) string { +// line, as "line:column: message" against the original source: the errors in +// the macro definitions first, then the ones in each statement. +func errors(input string, defErrs []*sqlerr.Error, res *preprocess.Result) string { var out []string + for _, err := range defErrs { + line, column := source.LineNumber(input, err.Location) + out = append(out, fmt.Sprintf("%d:%d: %s", line, column, err)) + } for _, stmt := range res.Statements() { for _, err := range []error{stmt.Err, stmt.ParamErr} { if err == nil { diff --git a/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/input.sql b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/input.sql new file mode 100644 index 0000000000..af3bad5183 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/input.sql @@ -0,0 +1,5 @@ +-- name: ByID :macro +SELECT * FROM foo WHERE id = ?; + +-- name: Use :many +SELECT * FROM sqlc.macro.ByID() f; diff --git a/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/output.sql b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/output.sql new file mode 100644 index 0000000000..1702747f70 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/output.sql @@ -0,0 +1,5 @@ + + + +-- name: Use :many +SELECT * FROM sqlc.macro.ByID() f; diff --git a/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/side_table.json b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/side_table.json new file mode 100644 index 0000000000..897d968538 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/side_table.json @@ -0,0 +1,9 @@ +[ + { + "start": 0, + "end": 107, + "dollar": true, + "error": "in macro \"ByID\": positional placeholder \"?\" is not allowed in a macro; use sqlc.arg()", + "error_at": 87 + } +] diff --git a/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/stderr.txt b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/stderr.txt new file mode 100644 index 0000000000..da82a41f25 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/error_macro_positional_placeholder/stderr.txt @@ -0,0 +1 @@ +5:15: in macro "ByID": positional placeholder "?" is not allowed in a macro; use sqlc.arg() diff --git a/internal/sql/preprocess/testdata/mysql/macro/input.sql b/internal/sql/preprocess/testdata/mysql/macro/input.sql new file mode 100644 index 0000000000..fcbecc300e --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/macro/input.sql @@ -0,0 +1,16 @@ +# A macro is blanked, and expands where it is called. +-- name: ActiveAuthors :macro +-- @param org signed +SELECT /*+ MAX_EXECUTION_TIME(1000) */ * +FROM `authors` +WHERE org_id = sqlc.arg(org) # the tenant + AND deleted_at IS NULL; + +-- Every ? is an argument of its own, numbered in the order the expanded query +-- sends them. +-- name: ListActiveAuthors :many +SELECT a.id +FROM authors x +JOIN sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a ON a.id = x.id +JOIN sqlc.macro.ActiveAuthors(?) b ON b.id = x.id +WHERE x.name = ? AND x.bio <> sqlc.arg(bio) AND @uservar IS NULL; diff --git a/internal/sql/preprocess/testdata/mysql/macro/output.sql b/internal/sql/preprocess/testdata/mysql/macro/output.sql new file mode 100644 index 0000000000..0ab3312f29 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/macro/output.sql @@ -0,0 +1,16 @@ + + + + + + + + +-- Every ? is an argument of its own, numbered in the order the expanded query +-- sends them. +-- name: ListActiveAuthors :many +SELECT a.id +FROM authors x +JOIN (SELECT /*+ MAX_EXECUTION_TIME(1000) */ * FROM `authors` WHERE org_id = CAST(? AS signed) AND deleted_at IS NULL) a ON a.id = x.id +JOIN (SELECT /*+ MAX_EXECUTION_TIME(1000) */ * FROM `authors` WHERE org_id = CAST(? AS signed) AND deleted_at IS NULL) b ON b.id = x.id +WHERE x.name = ? AND x.bio <> ? AND @uservar IS NULL; diff --git a/internal/sql/preprocess/testdata/mysql/macro/side_table.json b/internal/sql/preprocess/testdata/mysql/macro/side_table.json new file mode 100644 index 0000000000..0a40bf6c17 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/macro/side_table.json @@ -0,0 +1,35 @@ +[ + { + "start": 0, + "end": 709, + "dollar": false, + "params": [ + { + "number": 1, + "location": 466, + "origin": 389, + "name": "org_id", + "named": true + }, + { + "number": 2, + "location": 602, + "origin": 454, + "named": false + }, + { + "number": 3, + "location": 671, + "origin": 514, + "named": false + }, + { + "number": 4, + "location": 686, + "origin": 529, + "name": "bio", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/input.sql b/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/input.sql new file mode 100644 index 0000000000..61c5b6fd33 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/input.sql @@ -0,0 +1,10 @@ +-- A parameter the body uses twice is an argument written twice, and a ? is +-- sent each time it is written. +-- name: Between :macro +-- @param v +-- @param lo +-- @param hi +sqlc.arg(lo) <= sqlc.arg(v) AND sqlc.arg(v) <= sqlc.arg(hi); + +-- name: InRange :many +SELECT * FROM prices WHERE sqlc.macro.Between(sqlc.arg(amount), 1, `max`); diff --git a/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/output.sql b/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/output.sql new file mode 100644 index 0000000000..bbde2e958e --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/output.sql @@ -0,0 +1,10 @@ + + + + + + + + +-- name: InRange :many +SELECT * FROM prices WHERE (1 <= ? AND ? <= `max`); diff --git a/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/side_table.json b/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/side_table.json new file mode 100644 index 0000000000..f1c183fa89 --- /dev/null +++ b/internal/sql/preprocess/testdata/mysql/macro_parameter_used_twice/side_table.json @@ -0,0 +1,23 @@ +[ + { + "start": 0, + "end": 307, + "dollar": true, + "params": [ + { + "number": 1, + "location": 289, + "origin": 283, + "name": "amount", + "named": true + }, + { + "number": 2, + "location": 295, + "origin": 283, + "name": "amount", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/input.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/input.sql new file mode 100644 index 0000000000..ce19edc164 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/input.sql @@ -0,0 +1,19 @@ +-- name: Pair :macro +-- @param a +-- @param b +SELECT sqlc.arg(a), sqlc.arg(b); + +-- name: TooFew :one +SELECT * FROM sqlc.macro.Pair(1) p; + +-- name: TooMany :one +SELECT * FROM sqlc.macro.Pair(1, 2, 3) p; + +-- name: Missing :one +SELECT * FROM sqlc.macro.Pair(1, ) p; + +-- name: NoList :one +SELECT * FROM sqlc.macro.Pair p; + +-- name: Unclosed :one +SELECT * FROM sqlc.macro.Pair(1, 2 p; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/output.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/output.sql new file mode 100644 index 0000000000..eafba2c42c --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/output.sql @@ -0,0 +1,19 @@ + + + + + +-- name: TooFew :one +SELECT * FROM sqlc.macro.Pair(1) p; + +-- name: TooMany :one +SELECT * FROM sqlc.macro.Pair(1, 2, 3) p; + +-- name: Missing :one +SELECT * FROM sqlc.macro.Pair(1, ) p; + +-- name: NoList :one +SELECT * FROM sqlc.macro.Pair p; + +-- name: Unclosed :one +SELECT * FROM sqlc.macro.Pair(1, 2 p; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/side_table.json b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/side_table.json new file mode 100644 index 0000000000..09e5c745c7 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/side_table.json @@ -0,0 +1,37 @@ +[ + { + "start": 0, + "end": 135, + "dollar": true, + "error": "macro \"Pair\" takes 2 arguments; got 1", + "error_at": 114 + }, + { + "start": 135, + "end": 200, + "dollar": true, + "error": "macro \"Pair\" takes 2 arguments; got 3", + "error_at": 173 + }, + { + "start": 200, + "end": 261, + "dollar": true, + "error": "macro \"Pair\" is missing argument 2", + "error_at": 238 + }, + { + "start": 261, + "end": 316, + "dollar": true, + "error": "sqlc.macro.Pair must be called with an argument list", + "error_at": 298 + }, + { + "start": 316, + "end": 378, + "dollar": true, + "error": "sqlc.macro.Pair is missing its closing parenthesis", + "error_at": 355 + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/stderr.txt b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/stderr.txt new file mode 100644 index 0000000000..5124a51932 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_arguments/stderr.txt @@ -0,0 +1,5 @@ +7:15: macro "Pair" takes 2 arguments; got 1 +10:15: macro "Pair" takes 2 arguments; got 3 +13:15: macro "Pair" is missing argument 2 +16:15: sqlc.macro.Pair must be called with an argument list +19:15: sqlc.macro.Pair is missing its closing parenthesis diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_body/input.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_body/input.sql new file mode 100644 index 0000000000..ee0efbd5c4 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_body/input.sql @@ -0,0 +1,28 @@ +-- An error in a body is reported where the macro is called, and only there: +-- a macro nothing calls is never looked at. +-- name: Positional :macro +SELECT * FROM foo WHERE id = $1; + +-- name: Nullable :macro +-- @param id +SELECT * FROM foo WHERE id = sqlc.narg(id); + +-- name: Sliced :macro +-- @param ids +SELECT * FROM foo WHERE id = ANY(sqlc.slice(ids)); + +-- name: Unused :macro +SELECT * FROM sqlc.macro.Nowhere($1); + +-- name: UsePositional :many +SELECT * FROM sqlc.macro.Positional() p; + +-- name: UseNullable :many +SELECT * FROM sqlc.macro.Nullable(1) n; + +-- name: UseSliced :many +SELECT * FROM sqlc.macro.Sliced(sqlc.arg(ids)) s; + +-- An error in an argument is reported at the argument. +-- name: BadArgument :many +SELECT * FROM sqlc.macro.Nullable(1 + sqlc.macro.Nowhere()) n; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_body/output.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_body/output.sql new file mode 100644 index 0000000000..74f074e84d --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_body/output.sql @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + +-- name: UsePositional :many +SELECT * FROM sqlc.macro.Positional() p; + +-- name: UseNullable :many +SELECT * FROM sqlc.macro.Nullable(1) n; + +-- name: UseSliced :many +SELECT * FROM sqlc.macro.Sliced(sqlc.arg(ids)) s; + +-- An error in an argument is reported at the argument. +-- name: BadArgument :many +SELECT * FROM sqlc.macro.Nullable(1 + sqlc.macro.Nowhere()) n; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_body/side_table.json b/internal/sql/preprocess/testdata/postgresql/error_macro_body/side_table.json new file mode 100644 index 0000000000..8e20da6840 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_body/side_table.json @@ -0,0 +1,30 @@ +[ + { + "start": 0, + "end": 486, + "dollar": true, + "error": "in macro \"Positional\": positional placeholder \"$1\" is not allowed in a macro; use sqlc.arg()", + "error_at": 460 + }, + { + "start": 486, + "end": 554, + "dollar": true, + "error": "in macro \"Nullable\": the macro parameter \"id\" can only be referenced with sqlc.arg()", + "error_at": 529 + }, + { + "start": 554, + "end": 630, + "dollar": true, + "error": "in macro \"Sliced\": the macro parameter \"ids\" can only be referenced with sqlc.arg()", + "error_at": 595 + }, + { + "start": 630, + "end": 777, + "dollar": true, + "error": "macro \"Nowhere\" is not defined", + "error_at": 753 + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_body/stderr.txt b/internal/sql/preprocess/testdata/postgresql/error_macro_body/stderr.txt new file mode 100644 index 0000000000..02b62ad6f1 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_body/stderr.txt @@ -0,0 +1,4 @@ +18:15: in macro "Positional": positional placeholder "$1" is not allowed in a macro; use sqlc.arg() +21:15: in macro "Nullable": the macro parameter "id" can only be referenced with sqlc.arg() +24:15: in macro "Sliced": the macro parameter "ids" can only be referenced with sqlc.arg() +28:39: macro "Nowhere" is not defined diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_definition/input.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/input.sql new file mode 100644 index 0000000000..c1b7a2de22 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/input.sql @@ -0,0 +1,19 @@ +-- name: Dup :macro +SELECT 1; + +-- name: Dup :macro +SELECT 2; + +-- name: Params :macro +-- @param id +-- @param ID bigint +-- @param +SELECT sqlc.arg(id); + +-- name: Empty :macro +-- nothing but a comment +; + +-- The first definition is the one that is called. +-- name: Use :one +SELECT * FROM sqlc.macro.Dup() d; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_definition/output.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/output.sql new file mode 100644 index 0000000000..1ea0fdb33a --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/output.sql @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + +-- The first definition is the one that is called. +-- name: Use :one +SELECT * FROM (SELECT 1) d; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_definition/side_table.json b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/side_table.json new file mode 100644 index 0000000000..ef735ff6ec --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/side_table.json @@ -0,0 +1,7 @@ +[ + { + "start": 0, + "end": 296, + "dollar": true + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_definition/stderr.txt b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/stderr.txt new file mode 100644 index 0000000000..7340a4c272 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_definition/stderr.txt @@ -0,0 +1,4 @@ +5:1: macro "Dup" is already defined +11:1: macro "Params" declares the parameter "ID" twice +11:1: macro "Params" has a @param without a name +15:1: macro "Empty" has no body diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/input.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/input.sql new file mode 100644 index 0000000000..b1bc92c2f3 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/input.sql @@ -0,0 +1,14 @@ +-- name: Self :macro +SELECT * FROM sqlc.macro.Self() s; + +-- name: Ping :macro +SELECT * FROM sqlc.macro.Pong() p; + +-- name: Pong :macro +SELECT * FROM sqlc.macro.Ping() p; + +-- name: Direct :many +SELECT * FROM sqlc.macro.Self() s; + +-- name: Mutual :many +SELECT * FROM sqlc.macro.Ping() p; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/output.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/output.sql new file mode 100644 index 0000000000..9ae141730f --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/output.sql @@ -0,0 +1,14 @@ + + + + + + + + + +-- name: Direct :many +SELECT * FROM sqlc.macro.Self() s; + +-- name: Mutual :many +SELECT * FROM sqlc.macro.Ping() p; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/side_table.json b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/side_table.json new file mode 100644 index 0000000000..e450528848 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/side_table.json @@ -0,0 +1,16 @@ +[ + { + "start": 0, + "end": 227, + "dollar": true, + "error": "in macro \"Self\": macro \"Self\" expands itself: Self -\u003e Self", + "error_at": 207 + }, + { + "start": 227, + "end": 285, + "dollar": true, + "error": "in macro \"Ping\": in macro \"Pong\": macro \"Ping\" expands itself: Ping -\u003e Pong -\u003e Ping", + "error_at": 265 + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/stderr.txt b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/stderr.txt new file mode 100644 index 0000000000..745b4d6cd9 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_recursive/stderr.txt @@ -0,0 +1,2 @@ +11:15: in macro "Self": macro "Self" expands itself: Self -> Self +14:15: in macro "Ping": in macro "Pong": macro "Ping" expands itself: Ping -> Pong -> Ping diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/input.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/input.sql new file mode 100644 index 0000000000..250026698a --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/input.sql @@ -0,0 +1,16 @@ +-- A line break inside a literal cannot be taken out, so the literal cannot be +-- pasted without moving every line after it. +-- name: Note :macro +'two +lines'; + +-- name: Echo :macro +-- @param x +sqlc.arg(x); + +-- name: Body :one +SELECT sqlc.macro.Note(); + +-- name: Argument :one +SELECT sqlc.macro.Echo(1), sqlc.macro.Echo($$ two +lines $$); diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/output.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/output.sql new file mode 100644 index 0000000000..26df7ab21f --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/output.sql @@ -0,0 +1,16 @@ + + + + + + + + + + +-- name: Body :one +SELECT sqlc.macro.Note(); + +-- name: Argument :one +SELECT sqlc.macro.Echo(1), sqlc.macro.Echo($$ two +lines $$); diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/side_table.json b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/side_table.json new file mode 100644 index 0000000000..ded5a0bc46 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/side_table.json @@ -0,0 +1,16 @@ +[ + { + "start": 0, + "end": 251, + "dollar": true, + "error": "in macro \"Note\": a string or quoted name that spans lines cannot be expanded by a macro", + "error_at": 233 + }, + { + "start": 251, + "end": 336, + "dollar": true, + "error": "a string or quoted name that spans lines cannot be expanded by a macro", + "error_at": 319 + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/stderr.txt b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/stderr.txt new file mode 100644 index 0000000000..a623fc546d --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_spans_lines/stderr.txt @@ -0,0 +1,2 @@ +12:8: in macro "Note": a string or quoted name that spans lines cannot be expanded by a macro +15:44: a string or quoted name that spans lines cannot be expanded by a macro diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/input.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/input.sql new file mode 100644 index 0000000000..ec9b47d14f --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/input.sql @@ -0,0 +1,12 @@ +-- name: Known :macro +SELECT 1; + +-- name: Bad :one +SELECT * FROM sqlc.macro.Unknown(sqlc.arg(id)) u; + +-- name: Good :one +SELECT * FROM sqlc.macro.Known() k WHERE id = sqlc.arg(id); + +-- The name of a macro is matched exactly. +-- name: WrongCase :one +SELECT * FROM sqlc.macro.known() k; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/output.sql b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/output.sql new file mode 100644 index 0000000000..43414b509d --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/output.sql @@ -0,0 +1,12 @@ + + + +-- name: Bad :one +SELECT * FROM sqlc.macro.Unknown(sqlc.arg(id)) u; + +-- name: Good :one +SELECT * FROM (SELECT 1) k WHERE id = $1; + +-- The name of a macro is matched exactly. +-- name: WrongCase :one +SELECT * FROM sqlc.macro.known() k; diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/side_table.json b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/side_table.json new file mode 100644 index 0000000000..0a72689b36 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/side_table.json @@ -0,0 +1,30 @@ +[ + { + "start": 0, + "end": 100, + "dollar": true, + "error": "macro \"Unknown\" is not defined", + "error_at": 65 + }, + { + "start": 100, + "end": 162, + "dollar": true, + "params": [ + { + "number": 1, + "location": 159, + "origin": 167, + "name": "id", + "named": true + } + ] + }, + { + "start": 162, + "end": 266, + "dollar": true, + "error": "macro \"known\" is not defined", + "error_at": 245 + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/stderr.txt b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/stderr.txt new file mode 100644 index 0000000000..55eaffda23 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/error_macro_unknown/stderr.txt @@ -0,0 +1,2 @@ +5:15: macro "Unknown" is not defined +12:15: macro "known" is not defined diff --git a/internal/sql/preprocess/testdata/postgresql/macro/input.sql b/internal/sql/preprocess/testdata/postgresql/macro/input.sql new file mode 100644 index 0000000000..e67653c8d1 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro/input.sql @@ -0,0 +1,13 @@ +-- A macro is blanked, and expands where it is called. +-- name: ActiveAuthors :macro +-- @param org bigint +SELECT * +FROM authors +WHERE org_id = sqlc.arg(org) -- the tenant + AND deleted_at IS NULL; + +-- name: ListActiveAuthors :many +SELECT a.id FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a WHERE a.name = sqlc.arg(name); + +-- name: CountAuthors :one +SELECT count(*) FROM authors WHERE org_id = sqlc.arg(org_id); diff --git a/internal/sql/preprocess/testdata/postgresql/macro/output.sql b/internal/sql/preprocess/testdata/postgresql/macro/output.sql new file mode 100644 index 0000000000..50c7d7e61b --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro/output.sql @@ -0,0 +1,13 @@ + + + + + + + + +-- name: ListActiveAuthors :many +SELECT a.id FROM (SELECT * FROM authors WHERE org_id = CAST($1 AS bigint) AND deleted_at IS NULL) a WHERE a.name = $2; + +-- name: CountAuthors :one +SELECT count(*) FROM authors WHERE org_id = $1; diff --git a/internal/sql/preprocess/testdata/postgresql/macro/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro/side_table.json new file mode 100644 index 0000000000..2c855dfd1b --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro/side_table.json @@ -0,0 +1,37 @@ +[ + { + "start": 0, + "end": 349, + "dollar": true, + "params": [ + { + "number": 1, + "location": 291, + "origin": 248, + "name": "org_id", + "named": true + }, + { + "number": 2, + "location": 346, + "origin": 308, + "name": "name", + "named": true + } + ] + }, + { + "start": 349, + "end": 425, + "dollar": true, + "params": [ + { + "number": 1, + "location": 422, + "origin": 396, + "name": "org_id", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/input.sql new file mode 100644 index 0000000000..a9f03e46c3 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/input.sql @@ -0,0 +1,24 @@ +-- An untyped parameter takes a single term as it is written and anything +-- else in parentheses. +-- name: Twice :macro +-- @param x +sqlc.arg(x) * 2; + +-- name: Shapes :many +SELECT + sqlc.macro.Twice(a), + sqlc.macro.Twice(t.a), + sqlc.macro.Twice("t"."a"), + sqlc.macro.Twice(42), + sqlc.macro.Twice(1.5), + sqlc.macro.Twice('7'), + sqlc.macro.Twice($1), + sqlc.macro.Twice(@b), + sqlc.macro.Twice(sqlc.arg(c)), + sqlc.macro.Twice(abs(a)), + sqlc.macro.Twice((a + 1)), + sqlc.macro.Twice(a + 1), + sqlc.macro.Twice(a::int), + sqlc.macro.Twice(greatest(a, 1) + least(a, 2)), + sqlc.macro.Twice(- a) +FROM t; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/output.sql new file mode 100644 index 0000000000..e63f743316 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/output.sql @@ -0,0 +1,24 @@ + + + + + + +-- name: Shapes :many +SELECT + (a * 2), + (t.a * 2), + ("t"."a" * 2), + (42 * 2), + (1.5 * 2), + ('7' * 2), + ($1 * 2), + ($2 * 2), + ($3 * 2), + (abs(a) * 2), + ((a + 1) * 2), + ((a + 1) * 2), + ((a::int) * 2), + ((greatest(a, 1) + least(a, 2)) * 2), + ((- a) * 2) +FROM t; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/side_table.json new file mode 100644 index 0000000000..f1b997b509 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_argument_shapes/side_table.json @@ -0,0 +1,29 @@ +[ + { + "start": 0, + "end": 423, + "dollar": true, + "params": [ + { + "number": 1, + "location": 261, + "origin": 332, + "named": false + }, + { + "number": 2, + "location": 273, + "origin": 356, + "name": "b", + "named": true + }, + { + "number": 3, + "location": 285, + "origin": 380, + "name": "c", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/input.sql new file mode 100644 index 0000000000..136095bb46 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/input.sql @@ -0,0 +1,15 @@ +-- The body lands on one line, without its comments, so the query it is pasted +-- into keeps its lines and gains no annotations. +-- name: Recent :macro +-- @param n int +SELECT id, -- the key + 'not -- a comment' AS note, /* left +out */ $tag$ /* nor this */ $tag$ AS tagged +FROM events +ORDER BY id DESC +LIMIT sqlc.arg(n); + +-- name: ListRecent :many +SELECT * +FROM sqlc.macro.Recent(10) r +WHERE r.id > sqlc.arg(after); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/output.sql new file mode 100644 index 0000000000..4bb4d320d5 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/output.sql @@ -0,0 +1,15 @@ + + + + + + + + + + + +-- name: ListRecent :many +SELECT * +FROM (SELECT id, 'not -- a comment' AS note, $tag$ /* nor this */ $tag$ AS tagged FROM events ORDER BY id DESC LIMIT CAST(10 AS int)) r +WHERE r.id > $1; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/side_table.json new file mode 100644 index 0000000000..09c24541f2 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_body_is_flattened/side_table.json @@ -0,0 +1,16 @@ +[ + { + "start": 0, + "end": 517, + "dollar": true, + "params": [ + { + "number": 1, + "location": 514, + "origin": 407, + "name": "after", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/input.sql new file mode 100644 index 0000000000..7726638798 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/input.sql @@ -0,0 +1,7 @@ +-- name: One :macro +-- @param X +sqlc.arg(x) + SQLC.ARG(X) + @X; + +-- The sqlc.macro prefix is matched like every other sqlc function. +-- name: Spaced :one +SELECT SQLC.Macro.One(1), sqlc . macro . One ( 2 ); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/output.sql new file mode 100644 index 0000000000..edbbe9a77f --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/output.sql @@ -0,0 +1,7 @@ + + + + +-- The sqlc.macro prefix is matched like every other sqlc function. +-- name: Spaced :one +SELECT (1 + 1 + 1), (2 + 2 + 2); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/side_table.json new file mode 100644 index 0000000000..319547ce31 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_case_and_whitespace/side_table.json @@ -0,0 +1,7 @@ +[ + { + "start": 0, + "end": 186, + "dollar": true + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/input.sql new file mode 100644 index 0000000000..230b2d260b --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/input.sql @@ -0,0 +1,8 @@ +-- name: ListA :many +SELECT * FROM sqlc.macro.Rows() r; + +-- name: Rows :macro +SELECT 1 AS n; + +-- name: ListB :many +SELECT * FROM sqlc.macro.Rows() r; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/output.sql new file mode 100644 index 0000000000..69e31452b0 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/output.sql @@ -0,0 +1,8 @@ +-- name: ListA :many +SELECT * FROM (SELECT 1 AS n) r; + + + + +-- name: ListB :many +SELECT * FROM (SELECT 1 AS n) r; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/side_table.json new file mode 100644 index 0000000000..2711279d26 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_defined_after_use/side_table.json @@ -0,0 +1,12 @@ +[ + { + "start": 0, + "end": 53, + "dollar": true + }, + { + "start": 53, + "end": 145, + "dollar": true + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_expression/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_expression/input.sql new file mode 100644 index 0000000000..e0708de16c --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_expression/input.sql @@ -0,0 +1,7 @@ +-- name: IsRecent :macro +-- @param ts timestamptz +-- @param days +@ts > now() - sqlc.arg(days) * interval '1 day'; + +-- name: ListRecent :many +SELECT * FROM authors WHERE NOT sqlc.macro.IsRecent(created_at, 7) OR id = $1; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_expression/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_expression/output.sql new file mode 100644 index 0000000000..878cab62a2 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_expression/output.sql @@ -0,0 +1,7 @@ + + + + + +-- name: ListRecent :many +SELECT * FROM authors WHERE NOT (CAST(created_at AS timestamptz) > now() - 7 * interval '1 day') OR id = $1; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_expression/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_expression/side_table.json new file mode 100644 index 0000000000..299991c813 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_expression/side_table.json @@ -0,0 +1,15 @@ +[ + { + "start": 0, + "end": 249, + "dollar": true, + "params": [ + { + "number": 1, + "location": 246, + "origin": 216, + "named": false + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/input.sql new file mode 100644 index 0000000000..c27a6d4039 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/input.sql @@ -0,0 +1,5 @@ +-- name: Use :one +SELECT sqlc.macro.Last(); + +-- name: Last :macro +1 + 1 \ No newline at end of file diff --git a/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/output.sql new file mode 100644 index 0000000000..b951931c16 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/output.sql @@ -0,0 +1,5 @@ +-- name: Use :one +SELECT (1 + 1); + + + \ No newline at end of file diff --git a/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/side_table.json new file mode 100644 index 0000000000..392345eee0 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_last_statement_without_terminator/side_table.json @@ -0,0 +1,7 @@ +[ + { + "start": 0, + "end": 33, + "dollar": true + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/input.sql new file mode 100644 index 0000000000..5d626da84e --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/input.sql @@ -0,0 +1,12 @@ +-- name: Clamp :macro +-- @param v +-- @param lo +-- @param hi +least(greatest(sqlc.arg(v), sqlc.arg(lo)), sqlc.arg(hi)); + +-- name: Clamped :many +SELECT sqlc.macro.Clamp( + amount, -- the value + /* the bounds */ sqlc.arg(lo), + sqlc.arg(hi) +) FROM prices WHERE id = sqlc.arg(id); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/output.sql new file mode 100644 index 0000000000..9692da72e4 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/output.sql @@ -0,0 +1,8 @@ + + + + + + +-- name: Clamped :many +SELECT (least(greatest(amount, $1), $2)) FROM prices WHERE id = $3; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/side_table.json new file mode 100644 index 0000000000..179c0fb555 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_multiline_call/side_table.json @@ -0,0 +1,30 @@ +[ + { + "start": 0, + "end": 209, + "dollar": true, + "params": [ + { + "number": 1, + "location": 173, + "origin": 149, + "name": "lo", + "named": true + }, + { + "number": 2, + "location": 178, + "origin": 149, + "name": "hi", + "named": true + }, + { + "number": 3, + "location": 206, + "origin": 263, + "name": "id", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_nested/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_nested/input.sql new file mode 100644 index 0000000000..fceff9326b --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_nested/input.sql @@ -0,0 +1,11 @@ +-- name: Inner :macro +-- @param x +sqlc.arg(x) + 1; + +-- name: Outer :macro +-- @param y +sqlc.macro.Inner(sqlc.arg(y)) * sqlc.macro.Inner(2); + +-- A macro may be an argument to itself: an argument belongs to the caller. +-- name: Nested :one +SELECT sqlc.macro.Outer(sqlc.macro.Inner(sqlc.macro.Inner(sqlc.arg(n)))); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_nested/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_nested/output.sql new file mode 100644 index 0000000000..21d4259988 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_nested/output.sql @@ -0,0 +1,11 @@ + + + + + + + + +-- A macro may be an argument to itself: an argument belongs to the caller. +-- name: Nested :one +SELECT (((($1 + 1) + 1) + 1) * (2 + 1)); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_nested/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_nested/side_table.json new file mode 100644 index 0000000000..81e3a8e218 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_nested/side_table.json @@ -0,0 +1,16 @@ +[ + { + "start": 0, + "end": 277, + "dollar": true, + "params": [ + { + "number": 1, + "location": 248, + "origin": 244, + "name": "n", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/input.sql new file mode 100644 index 0000000000..363f5aef38 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/input.sql @@ -0,0 +1,10 @@ +-- tenant is not a parameter of the macro, so it is one of the query's. +-- name: Visible :macro +-- @param owner +sqlc.arg(owner) = sqlc.arg(tenant) OR sqlc.narg(admin)::bool IS TRUE; + +-- name: ListDocs :many +SELECT * FROM docs d +WHERE sqlc.macro.Visible(d.owner_id) + AND d.kind = ANY(sqlc.slice(kinds)) + AND d.tenant_id = @tenant; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/output.sql new file mode 100644 index 0000000000..843f1f0c1c --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/output.sql @@ -0,0 +1,10 @@ + + + + + +-- name: ListDocs :many +SELECT * FROM docs d +WHERE (d.owner_id = $1 OR $2::bool IS TRUE) + AND d.kind = ANY($3) + AND d.tenant_id = $1; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/side_table.json new file mode 100644 index 0000000000..003e318817 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_passes_through_parameters/side_table.json @@ -0,0 +1,39 @@ +[ + { + "start": 0, + "end": 318, + "dollar": true, + "params": [ + { + "number": 1, + "location": 248, + "origin": 234, + "name": "tenant", + "named": true + }, + { + "number": 2, + "location": 254, + "origin": 234, + "name": "admin", + "named": true, + "nullable": true + }, + { + "number": 3, + "location": 291, + "origin": 284, + "name": "kinds", + "named": true, + "slice": true + }, + { + "number": 1, + "location": 315, + "origin": 323, + "name": "tenant", + "named": true + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/input.sql new file mode 100644 index 0000000000..7f4ce92f1e --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/input.sql @@ -0,0 +1,6 @@ +-- name: One :macro +SELECT 1; + +-- sqlc.macro.One() in a comment is left alone. +-- name: Skipped :one +SELECT 'sqlc.macro.One()', "sqlc.macro.One()", $$ sqlc.macro.One() $$ /* sqlc.macro.One() */; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/output.sql new file mode 100644 index 0000000000..8c3d6e0bf1 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/output.sql @@ -0,0 +1,6 @@ + + + +-- sqlc.macro.One() in a comment is left alone. +-- name: Skipped :one +SELECT 'sqlc.macro.One()', "sqlc.macro.One()", $$ sqlc.macro.One() $$ /* sqlc.macro.One() */; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/side_table.json new file mode 100644 index 0000000000..c869400447 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_skip_comments_and_literals/side_table.json @@ -0,0 +1,7 @@ +[ + { + "start": 0, + "end": 194, + "dollar": true + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/input.sql new file mode 100644 index 0000000000..bd76eee279 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/input.sql @@ -0,0 +1,9 @@ +-- A typed parameter casts whatever it is given. +-- name: Between :macro +-- @param v numeric(10, 2) +-- @param lo double precision +-- @param hi +sqlc.arg(v) >= sqlc.arg(lo) AND sqlc.arg(v) <= sqlc.arg(hi); + +-- name: InRange :many +SELECT * FROM prices WHERE sqlc.macro.Between(amount, $1, $2 + 1); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/output.sql new file mode 100644 index 0000000000..35ab1e371a --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/output.sql @@ -0,0 +1,9 @@ + + + + + + + +-- name: InRange :many +SELECT * FROM prices WHERE (CAST(amount AS numeric(10, 2)) >= CAST($1 AS double precision) AND CAST(amount AS numeric(10, 2)) <= ($2 + 1)); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/side_table.json new file mode 100644 index 0000000000..2c61856822 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_typed_parameter/side_table.json @@ -0,0 +1,21 @@ +[ + { + "start": 0, + "end": 367, + "dollar": true, + "params": [ + { + "number": 1, + "location": 295, + "origin": 255, + "named": false + }, + { + "number": 2, + "location": 358, + "origin": 255, + "named": false + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_with_embed/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_with_embed/input.sql new file mode 100644 index 0000000000..301ced2400 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_with_embed/input.sql @@ -0,0 +1,6 @@ +-- name: Active :macro +SELECT * FROM authors WHERE deleted_at IS NULL; + +-- name: ListBooks :many +WITH a AS sqlc.macro.Active() +SELECT sqlc.embed(b), a.name FROM a JOIN books b ON b.author_id = a.id WHERE b.id > sqlc.arg(after); diff --git a/internal/sql/preprocess/testdata/postgresql/macro_with_embed/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_with_embed/output.sql new file mode 100644 index 0000000000..f0931bee8d --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_with_embed/output.sql @@ -0,0 +1,6 @@ + + + +-- name: ListBooks :many +WITH a AS (SELECT * FROM authors WHERE deleted_at IS NULL) +SELECT b.*, a.name FROM a JOIN books b ON b.author_id = a.id WHERE b.id > $1; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_with_embed/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_with_embed/side_table.json new file mode 100644 index 0000000000..070c0d7ba3 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_with_embed/side_table.json @@ -0,0 +1,24 @@ +[ + { + "start": 0, + "end": 233, + "dollar": true, + "params": [ + { + "number": 1, + "location": 230, + "origin": 211, + "name": "after", + "named": true + } + ], + "embeds": [ + { + "table": "b", + "location": 163, + "origin": 134, + "orig": "sqlc.embed(b)" + } + ] + } +] diff --git a/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/input.sql b/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/input.sql new file mode 100644 index 0000000000..98fc838f70 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/input.sql @@ -0,0 +1,5 @@ +-- name: Unnamed :macro +'unnamed'; + +-- name: Names :many +SELECT coalesce(name, sqlc.macro.Unnamed()) FROM authors; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/output.sql b/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/output.sql new file mode 100644 index 0000000000..4381d46a45 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/output.sql @@ -0,0 +1,5 @@ + + + +-- name: Names :many +SELECT coalesce(name, ('unnamed')) FROM authors; diff --git a/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/side_table.json b/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/side_table.json new file mode 100644 index 0000000000..36cb3a4669 --- /dev/null +++ b/internal/sql/preprocess/testdata/postgresql/macro_without_parameters/side_table.json @@ -0,0 +1,7 @@ +[ + { + "start": 0, + "end": 105, + "dollar": true + } +] diff --git a/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/input.sql b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/input.sql new file mode 100644 index 0000000000..cb0b762575 --- /dev/null +++ b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/input.sql @@ -0,0 +1,2 @@ +-- name: Bad :one +SELECT * FROM sqlc.macro.Unknown(?1) u; diff --git a/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/output.sql b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/output.sql new file mode 100644 index 0000000000..cb0b762575 --- /dev/null +++ b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/output.sql @@ -0,0 +1,2 @@ +-- name: Bad :one +SELECT * FROM sqlc.macro.Unknown(?1) u; diff --git a/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/side_table.json b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/side_table.json new file mode 100644 index 0000000000..83516f558e --- /dev/null +++ b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/side_table.json @@ -0,0 +1,9 @@ +[ + { + "start": 0, + "end": 57, + "dollar": true, + "error": "macro \"Unknown\" is not defined", + "error_at": 32 + } +] diff --git a/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/stderr.txt b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/stderr.txt new file mode 100644 index 0000000000..5bfc7b4c32 --- /dev/null +++ b/internal/sql/preprocess/testdata/sqlite/error_macro_unknown/stderr.txt @@ -0,0 +1 @@ +2:15: macro "Unknown" is not defined diff --git a/internal/sql/preprocess/testdata/sqlite/macro/input.sql b/internal/sql/preprocess/testdata/sqlite/macro/input.sql new file mode 100644 index 0000000000..7154f30111 --- /dev/null +++ b/internal/sql/preprocess/testdata/sqlite/macro/input.sql @@ -0,0 +1,11 @@ +-- name: ActiveAuthors :macro +-- @param org integer +SELECT * FROM authors WHERE org_id = @org AND deleted_at IS NULL; + +-- A numbered placeholder keeps its number, and the macro's arguments are +-- numbered around it. +-- name: ListActiveAuthors :many +SELECT a.id +FROM sqlc.macro.ActiveAuthors(sqlc.arg(org_id)) a +JOIN sqlc.macro.ActiveAuthors(?1) b ON b.id = a.id +WHERE a.name = @name AND a.id IN (sqlc.slice(ids)); diff --git a/internal/sql/preprocess/testdata/sqlite/macro/output.sql b/internal/sql/preprocess/testdata/sqlite/macro/output.sql new file mode 100644 index 0000000000..5404562fcd --- /dev/null +++ b/internal/sql/preprocess/testdata/sqlite/macro/output.sql @@ -0,0 +1,11 @@ + + + + +-- A numbered placeholder keeps its number, and the macro's arguments are +-- numbered around it. +-- name: ListActiveAuthors :many +SELECT a.id +FROM (SELECT * FROM authors WHERE org_id = CAST(?2 AS integer) AND deleted_at IS NULL) a +JOIN (SELECT * FROM authors WHERE org_id = CAST(?1 AS integer) AND deleted_at IS NULL) b ON b.id = a.id +WHERE a.name = ?3 AND a.id IN (/*SLICE:ids*/?); diff --git a/internal/sql/preprocess/testdata/sqlite/macro/side_table.json b/internal/sql/preprocess/testdata/sqlite/macro/side_table.json new file mode 100644 index 0000000000..385bd000a7 --- /dev/null +++ b/internal/sql/preprocess/testdata/sqlite/macro/side_table.json @@ -0,0 +1,37 @@ +[ + { + "start": 0, + "end": 501, + "dollar": true, + "params": [ + { + "number": 2, + "location": 309, + "origin": 266, + "name": "org_id", + "named": true + }, + { + "number": 1, + "location": 398, + "origin": 316, + "named": false + }, + { + "number": 3, + "location": 469, + "origin": 377, + "name": "name", + "named": true + }, + { + "number": 4, + "location": 498, + "origin": 396, + "name": "ids", + "named": true, + "slice": true + } + ] + } +]