Documentation
¶
Overview ¶
Package sqlshape makes SQL a first-class, statically checked citizen of a Go program. A query is a text/template over a parameter struct P whose finite set of expansions is checked at lint time against schema.sql; R describes the result row.
var listOrders = sqlshape.Query[OrderRow, ListOrdersParams](`
SELECT o.id, o.status, o.total
FROM orders o
WHERE true
{{if .Status}} AND o.status = {{.Status}} {{end}}
LIMIT {{.Limit}}
`)
Stmt runs against pgx (Run / Collect / First / Exec); the analyzer in cmd/sqlshape checks every expansion of every Query in a program.
One declares a statement that returns at most one row, and the checker proves it from the schema: the WHERE clause fixes a unique key of every FROM item by equality (through joins, views and subqueries), or the statement is an aggregate without GROUP BY, a constant LIMIT 1, or a single-row INSERT ... RETURNING.
var userByEmail = sqlshape.One[User, struct{ Email string }](`
SELECT id, name FROM users WHERE email = {{.Email}}`)
u, err := userByEmail.Get(ctx, db, p) // ErrNoRows when absent
u, ok, err := userByEmail.Find(ctx, db, p)
Index ¶
- Variables
- func IsNoRows(err error) bool
- func LoadUserTypes(ctx context.Context, conn *pgx.Conn) error
- func Violates(err error, key string) bool
- type Batch
- type BatchDB
- type ConstraintError
- type Copier
- type CopyDB
- type DB
- type Labelled
- type MatView
- type Queued
- type Rendered
- type Single
- func (s Single[R, P]) Exec(ctx context.Context, db DB, p P) (pgconn.CommandTag, error)
- func (s Single[R, P]) Find(ctx context.Context, db DB, p P) (R, bool, error)
- func (s Single[R, P]) Get(ctx context.Context, db DB, p P) (R, error)
- func (s Single[R, P]) Render(p P) (Rendered, error)
- func (s Single[R, P]) SQLTemplate() string
- func (s Single[R, P]) Unprepared() Single[R, P]
- type Stmt
- func (s Stmt[R, P]) Collect(ctx context.Context, db DB, p P) ([]R, error)
- func (s Stmt[R, P]) Exec(ctx context.Context, db DB, p P) (pgconn.CommandTag, error)
- func (s Stmt[R, P]) First(ctx context.Context, db DB, p P) (R, error)
- func (s Stmt[R, P]) Render(p P) (Rendered, error)
- func (s Stmt[R, P]) Run(ctx context.Context, db DB, p P) iter.Seq2[R, error]
- func (s Stmt[R, P]) SQLTemplate() string
- func (s Stmt[R, P]) Unprepared() Stmt[R, P]
- type UnknownLabelError
Constants ¶
This section is empty.
Variables ¶
var ErrManyRows = errors.New("sqlshape: statement declared with One returned more than one row")
ErrManyRows is returned by Get / Find when a statement declared with One produced more than one row: the schema no longer backs the proof the checker made.
var ErrNoRows = pgx.ErrNoRows
ErrNoRows is returned by First and Get when the query produced no row.
var ErrNotSent = errors.New("sqlshape: batch not sent")
ErrNotSent is returned by a queued statement's accessors before the batch was sent.
Functions ¶
func LoadUserTypes ¶
LoadUserTypes registers every user-defined enum, composite, domain, range and multirange type of the database (and their array types) with conn, so records containing them decode. Use it from pgxpool's AfterConnect; Run also loads result types lazily, but cannot see types nested inside an anonymous record before scanning it.
Types ¶
type Batch ¶
type Batch struct {
// contains filtered or unexported fields
}
Batch sends several statements to the server in one round trip (pgx.Batch). Queue statements with Queue / QueueOne, Send the batch, then read each statement's rows from the handle Queue returned:
b := sqlshape.NewBatch()
orders := sqlshape.Queue(b, listOrders, ListParams{Status: &paid})
paid := sqlshape.QueueOne(b, markPaid, struct{ ID int64 }{id})
if err := b.Send(ctx, db); err != nil { ... }
rows, _ := orders.Rows()
tag, _ := paid.Tag()
Result types the connection has not loaded yet cannot be loaded mid-batch: with user enums / composites in results or parameters, call LoadUserTypes on the connection first (pgxpool: in AfterConnect). A statement whose rows carry a sql.Scanner type (a declared binding) cannot ride in a pgx batch, which never requests text format; Send runs it as a plain query right after the batch.
type ConstraintError ¶
type ConstraintError struct {
Code string // SQLSTATE
Constraint string // "" for NOT NULL
Table string
Column string
Detail string
Err *pgconn.PgError
}
ConstraintError is a constraint violation (SQLSTATE class 23) mapped back to the schema: Constraint is the PG constraint name (the same one the checker lists and the template's `-- sqlshape: expect` line names), Column the NOT NULL column.
func (*ConstraintError) Error ¶
func (e *ConstraintError) Error() string
func (*ConstraintError) Key ¶
func (e *ConstraintError) Key() string
Key is the violation as the expect line spells it: the constraint name, or table.column for NOT NULL.
func (*ConstraintError) Unwrap ¶
func (e *ConstraintError) Unwrap() error
type Copier ¶
Copier bulk-loads rows of R into a table with COPY FROM (pgx.CopyFrom). Declare it with Copy; the checker verifies the table and columns against the schema and each column's type against the field that feeds it.
func Copy ¶
Copy declares a bulk load into table (optionally schema-qualified). columns are the table columns to fill, each fed by the field of R that binds to it (`col:"name"` / `db` tag or snake_case, embedded structs flattened); with no columns given, every field of R feeds the column of its name. A scalar R feeds the single column.
var loadItems = sqlshape.Copy[Item]("order_items", "order_id", "line_no", "sku", "qty")
n, err := loadItems.From(ctx, db, items)
type CopyDB ¶
type CopyDB interface {
CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}
CopyDB is what Copier.From needs; pgx.Conn, pgxpool.Pool and pgx.Tx all provide it.
type DB ¶
type DB interface {
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}
DB is what a Stmt runs against: *pgx.Conn, *pgxpool.Pool and pgx.Tx all satisfy it.
type Labelled ¶
type Labelled interface{ Known() bool }
Labelled is implemented by a Go enum type (a named string type bound to a PG enum) to say which labels the application knows. When a scanned value answers false the row is rejected with an *UnknownLabelError: the database has a label this build predates.
func (s OrderStatus) Known() bool { switch s { case Pending, Paid: return true }; return false }
type MatView ¶
type MatView string
MatView is a handle on a materialized view; the checker verifies the name against schema.sql (and, with -strict, that a unique index allows RefreshConcurrently).
var OrderStats = sqlshape.MatView("order_stats")
err := OrderStats.Refresh(ctx, db)
type Queued ¶
type Queued[R any] struct { // contains filtered or unexported fields }
Queued is one statement's place in a batch: its rows (or command tag) after Send.
func QueueOne ¶
QueueOne renders the single-row statement s for p and adds it to the batch. After Send, Rows holds at most one row (the checker's proof) and First returns it or ErrNoRows.
type Rendered ¶
Rendered is one concrete execution of a template: the SQL with $n placeholders and the argument values in placeholder order.
type Single ¶
type Single[R, P any] struct { // contains filtered or unexported fields }
Single is a checked SQL template proven to return at most one row.
func One ¶
One declares a single-row statement. The checker reports it when it cannot prove that every expansion returns at most one row.
func (Single[R, P]) Exec ¶
Exec runs a single-row statement that returns no rows (e.g. UPDATE ... WHERE id = $1). An INSERT / UPDATE / DELETE / MERGE that touched no row returns ErrNoRows (the key did not exist), one that touched more than one returns ErrManyRows (the checker's proof that the statement affects at most one row did not hold).
func (Single[R, P]) SQLTemplate ¶
SQLTemplate is the template text (see Stmt.SQLTemplate).
func (Single[R, P]) Unprepared ¶
Unprepared returns a copy that runs without a prepared statement (see Stmt.Unprepared).
type Stmt ¶
Stmt is a checked SQL template. R is the result row type, P the parameter type.
func Query ¶
Query declares a statement. The argument must be a string literal so the analyzer can expand and check it.
func (Stmt[R, P]) Exec ¶
Exec runs a statement that returns no rows (INSERT / UPDATE / DELETE without RETURNING).
func (Stmt[R, P]) Render ¶
Render evaluates the template against p. It mirrors the static expander exactly: the same value action yields the same $n within one rendering, and each range iteration gets fresh placeholders.
func (Stmt[R, P]) Run ¶
Run executes the statement and yields each row mapped into R. Iteration stops at the first error, which is yielded with a zero R. Breaking out early closes the rows.
func (Stmt[R, P]) SQLTemplate ¶
SQLTemplate is the template text; pgtest.Verify expands and checks it against a real PG.
func (Stmt[R, P]) Unprepared ¶
Unprepared returns a copy that runs without a server-side prepared statement, so the planner makes a custom plan for the actual parameter values every time. Use it for statements whose parameters have skewed value distributions, where pgx's automatic statement cache would switch to a generic plan after a few executions.
type UnknownLabelError ¶
UnknownLabelError reports a scanned enum value the application does not know.
func (*UnknownLabelError) Error ¶
func (e *UnknownLabelError) Error() string
Directories
¶
| Path | Synopsis |
|---|---|
|
check
|
|
|
mysql
module
|
|
|
postgres
module
|
|
|
cmd
|
|
|
sqlshape
module
|
|
|
examples
|
|
|
1-tables
Package tables is the first sqlshape example: an order book on plain tables, the ground an ORM also covers, written as checked SQL instead.
|
Package tables is the first sqlshape example: an order book on plain tables, the ground an ORM also covers, written as checked SQL instead. |
|
2-views
Package views is the second sqlshape example: the same order book as examples/1-tables, read through views.
|
Package views is the second sqlshape example: the same order book as examples/1-tables, read through views. |
|
3-database-api
Package dbapi is the third sqlshape example: the database as an API.
|
Package dbapi is the third sqlshape example: the database as an API. |
|
4-everything
Package everything is the fourth sqlshape example: a multi-tenant room booking service that uses the whole surface.
|
Package everything is the fourth sqlshape example: a multi-tenant room booking service that uses the whole surface. |
|
internal
|
|
|
analyze
Package analyze is the pure-Go PostgreSQL semantic analyzer: given a Schema and one SQL statement it derives parameter types, result columns (type, nullability, provenance) and PG-compatible errors, following the rules of PostgreSQL manual chapter 10 (type conversion) without running PostgreSQL.
|
Package analyze is the pure-Go PostgreSQL semantic analyzer: given a Schema and one SQL statement it derives parameter types, result columns (type, nullability, provenance) and PG-compatible errors, following the rules of PostgreSQL manual chapter 10 (type conversion) without running PostgreSQL. |
|
catalog
Package catalog is the static PostgreSQL system catalog (pg_catalog objects) the analyzer resolves types, functions, operators and casts against.
|
Package catalog is the static PostgreSQL system catalog (pg_catalog objects) the analyzer resolves types, functions, operators and casts against. |
|
catalog/gen
command
Command gen dumps the bootstrap catalog (pg_catalog objects) of the oracle's PostgreSQL into internal/catalog/data/<major>/*.tsv, and extension catalogs into internal/catalog/data/<major>/ext/<name>/.
|
Command gen dumps the bootstrap catalog (pg_catalog objects) of the oracle's PostgreSQL into internal/catalog/data/<major>/*.tsv, and extension catalogs into internal/catalog/data/<major>/ext/<name>/. |
|
cli
Package cli is the sqlshape command: `vet` (the go/analysis checker, also what a bare invocation runs so `go vet -vettool` keeps working), `check` (SQL outside Go, judged against the schema's obligations), `diff` (the DDL from a database or schema text to schema.sql), `apply` (a DDL file, checked by its end state and by the consumers of what it drops, then run), and `verify-schema` (drift between a database and schema.sql).
|
Package cli is the sqlshape command: `vet` (the go/analysis checker, also what a bare invocation runs so `go vet -vettool` keeps working), `check` (SQL outside Go, judged against the schema's obligations), `diff` (the DDL from a database or schema text to schema.sql), `apply` (a DDL file, checked by its end state and by the consumers of what it drops, then run), and `verify-schema` (drift between a database and schema.sql). |
|
consumers
Package consumers indexes which Go statements depend on which relation columns: the side of a schema change a diff tool cannot see.
|
Package consumers indexes which Go statements depend on which relation columns: the side of a schema change a diff tool cannot see. |
|
dialect
Package dialect is the seam between the checker (internal/vet) and a database's analyzer.
|
Package dialect is the seam between the checker (internal/vet) and a database's analyzer. |
|
diff
Package diff compares two schemas object by object and lists what it takes to turn one into the other.
|
Package diff compares two schemas object by object and lists what it takes to turn one into the other. |
|
dump
Package dump reads a live PostgreSQL database back into a schema.Schema by way of `pg_dump --schema-only`, and gives schema text a canonical form: the dump of a fresh PostgreSQL the text was applied to.
|
Package dump reads a live PostgreSQL database back into a schema.Schema by way of `pg_dump --schema-only`, and gives schema text a canonical form: the dump of a fresh PostgreSQL the text was applied to. |
|
expand
Package expand enumerates the finite set of SQL strings a query template can produce.
|
Package expand enumerates the finite set of SQL strings a query template can produce. |
|
facts
Package facts is the data contract between a dialect's analyzer and the obligation checker: what one analyzed statement (one expansion) provably does, written down without any parser node, so that internal/obligation can judge declarations against it without knowing which database the statement was written for.
|
Package facts is the data contract between a dialect's analyzer and the obligation checker: what one analyzed statement (one expansion) provably does, written down without any parser node, so that internal/obligation can judge declarations against it without knowing which database the statement was written for. |
|
migrate
Package migrate turns the difference between two schemas into DDL, and checks DDL by its end state: applied to a PostgreSQL holding the current schema, does the database read back as the target?
|
Package migrate turns the difference between two schemas into DDL, and checks DDL by its end state: applied to a PostgreSQL holding the current schema, does the database read back as the target? |
|
obligation
Package obligation checks the boundary rules a schema declares against the facts an analyzer derived from a statement: a table (view, schema) requires something of every statement that touches it, the statement's facts either discharge that requirement or they do not, and the ways they can discharge it are few and named.
|
Package obligation checks the boundary rules a schema declares against the facts an analyzer derived from a statement: a table (view, schema) requires something of every statement that touches it, the statement's facts either discharge that requirement or they do not, and the ways they can discharge it are few and named. |
|
oracle
Package oracle runs a real PostgreSQL (embedded-postgres) and answers "what does PG say about this statement?" via PREPARE / Describe.
|
Package oracle runs a real PostgreSQL (embedded-postgres) and answers "what does PG say about this statement?" via PREPARE / Describe. |
|
pgparse
Package pgparse is the SQL parser: libpg_query compiled to WebAssembly and run by wazero.
|
Package pgparse is the SQL parser: libpg_query compiled to WebAssembly and run by wazero. |
|
schema
Package schema layers a user's schema.sql (tables, views, enums, domains, composites, functions, indexes) over the bootstrap catalog.
|
Package schema layers a user's schema.sql (tables, views, enums, domains, composites, functions, indexes) over the bootstrap catalog. |
|
verify
Package verify compares the analyzer's conclusion about a statement with a running PostgreSQL's: parameter types, result column names and types, and whether the statement is rejected (by SQLSTATE class).
|
Package verify compares the analyzer's conclusion about a statement with a running PostgreSQL's: parameter types, result column names and types, and whether the statement is rejected (by SQLSTATE class). |
|
vet
Package vet is the go/analysis analyzer: it finds sqlshape.Query[R, P](literal) calls, expands each template, checks every expansion against schema.sql and matches result columns / parameters against R / P.
|
Package vet is the go/analysis analyzer: it finds sqlshape.Query[R, P](literal) calls, expands each template, checks every expansion against schema.sql and matches result columns / parameters against R / P. |
|
mysql
module
|
|
|
mysqltest
module
|
|
|
Package pgtest starts a real PostgreSQL with a schema.sql applied, for testing the database side of an application (views, functions, triggers, constraints) from Go the same way the checker's oracle does.
|
Package pgtest starts a real PostgreSQL with a schema.sql applied, for testing the database side of an application (views, functions, triggers, constraints) from Go the same way the checker's oracle does. |
|
postgres
module
|