sqlshape

package module
v1.3.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2026 License: Apache-2.0 Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

sqlshape

Go Reference release test coverage

Write SQL as SQL, and let a go vet checker prove the Go code around it fits.

日本語

var ByEmail = sqlshape.One[User, struct{ Email string }](`
SELECT id, email, name, deleted_at FROM users WHERE email = {{.Email}}`)

u, err := ByEmail.Get(ctx, db, struct{ Email string }{Email: email})
  • Checked, not generated. Every statement is analyzed against schema.sql by a pure-Go PostgreSQL analyzer: the result columns must fit the row type, the {{.X}} parameters must fit the parameter type, nullability is enforced, One has to be provably single-row, and a write must declare the constraints it can violate. Every finding is a go vet diagnostic, reported before the code ever runs.
  • Plain SQL, no injection. Templates are Go text/template: {{.X}} always becomes a $n parameter, never text, and every {{if}} / {{range}} combination is expanded and checked. The runtime refuses any rendering the checker never saw.
  • schema.sql is the only definition. The checker reads it, pgtest runs your tests against a real PostgreSQL with it applied, and sqlshape diff derives the migration from it. Views, functions, domains, composite types, row-level security and seeded lookup tables are all part of the checked surface, so the database can expose a typed API instead of raw tables.

Install

The checker and the migration commands are one binary. With Go 1.26 or newer:

$ go install github.com/kr9ly/sqlshape/cmd/sqlshape@latest
$ sqlshape version

Or take a prebuilt binary from the releases page: Linux, macOS and Windows, amd64 and arm64 each, as sqlshape_<version>_<os>_<arch>.tar.gz (.zip on Windows) with checksums.txt beside them. Unpack and put sqlshape on your PATH.

Nothing else is needed to check code. PostgreSQL's parser (libpg_query, one per supported major version) is embedded as WebAssembly and runs on wazero, so there is no C compiler to install and no library to link; the first run compiles the module (about a second) and caches the result under the user cache directory (~/.cache/sqlshape on Linux). pgtest and the migration commands, which run your schema on a real PostgreSQL, download the declared version's server binaries into the same cache on first use (see migrations.md).

The runtime is an ordinary Go module:

$ go get github.com/kr9ly/sqlshape

Versions follow semantic versioning and are tagged vX.Y.Z. Within a major version, the exported API of sqlshape and pgtest, the template syntax, the directives and the checker's flags stay compatible; what the checker reports may grow with minor versions.

Quickstart

-- schema.sql
-- sqlshape: postgres 17
CREATE TABLE users (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email      text NOT NULL UNIQUE,
    name       text NOT NULL,
    deleted_at timestamptz
);

The first line of schema.sql names the PostgreSQL version the schema is written for; every statement is judged with that version's grammar and catalog (17 and 18 are supported).

// users.go
type User struct {
	ID        int64
	Email     string
	Name      string
	DeletedAt time.Time
}

var Users = sqlshape.Query[User, struct{ Name *string }](`
SELECT id, email, name, deleted_at FROM users
 WHERE true {{if .Name}} AND name = {{.Name}} {{end}}`)

var Create = sqlshape.Query[int64, struct{ Email, Name string }](`
INSERT INTO users (email, name) VALUES ({{.Email}}, {{.Name}}) RETURNING id`)
$ sqlshape ./...
users.go:20:13: sqlshape: field DeletedAt is time.Time but column "deleted_at" may be NULL (use a pointer, or tag it `col:",notnull"` if you know better)
users.go:25:46: sqlshape: may violate users_email_key (UNIQUE (email) on users, SQLSTATE 23505); add `-- sqlshape: expect users_email_key` to the template or make it impossible

Make DeletedAt a *time.Time, put -- sqlshape: expect users_email_key on the INSERT's first line, and the package is clean. At run time:

users, err := Users.Collect(ctx, pool, struct{ Name *string }{})          // []User
id, err := Create.First(ctx, pool, struct{ Email, Name string }{e, n})     // int64
if sqlshape.Violates(err, "users_email_key") { /* the declared failure mode */ }

db is anything pgx gives you: a *pgxpool.Pool, *pgx.Conn or pgx.Tx.

You do not have to write the structs. Declare type Row struct{} and type Params struct{} empty, write the SQL, and every column and parameter without a field is reported with a quick fix that writes the struct from the SQL; sqlshape -fix ./... applies them all.

To check on every save, pass the binary to go vet as the -vettool. Any editor whose Go integration runs go vet on save then shows the diagnostics:

$ go vet -vettool="$(which sqlshape)" ./...

Details in docs/flags.md.

Examples

Four stages of the same order book, one per level of trust in the database:

  • examples/1-tables — The basic form: Query / One against tables, structs matched to the SQL, the constraints a write can violate declared on its expect line
  • examples/2-views — Reading through views: joins and column names decided once in the schema, so the application's SQL gets thinner
  • examples/3-database-api — Writes as functions, meaning as domains and composite types: how the checks work once logic lives in the database
  • examples/4-everything — Every feature in one place; the index to look up how a particular feature is used

What it checks

The full list is in docs/checks.md. Broadly:

  • Shapes: the columns a statement returns and the Go struct that receives them, and the {{.X}} parameters and the struct that supplies them, agree in name, type and NULL handling. Nested rows and composite types included.
  • Meaning: a Go type used for an enum or lookup-table value, a primary key or a domain is bound to that meaning from where it is used. Passing another table's ID, adding domains of different units, or constants that drift from the labels are reported even though the underlying types agree.
  • Failure modes: a write must declare the constraints it can violate on its expect line. A missing declaration and an impossible one are both reported, so the code always states which violations it has to handle. No ORM offers this: an ORM's model is a copy of the constraints, so nothing can be derived from it about what will fail, and the exception arrives at run time with a name to match by hand. Here the list is computed from schema.sql (triggers and called functions included), the names are PostgreSQL's own, and the runtime error carries the same name, so the declaration, the check and the handler are one string.
  • Cardinality: a statement declared with One is proved from the schema to return at most one row.
  • Boundaries: team rules that show up in the shape of the SQL, such as always filtering soft-deleted rows, always pinning the tenant column, or reading tables only through views, are enforced by the checker.
  • The schema itself: the functions (SQL and PL/pgSQL bodies), views and policies in schema.sql are type-checked too, and -strict adds advice such as a predicate no index serves or an enum a lookup table would serve better.

SQL outside Go

The rules schema.sql declares are not limited to Go code. sqlshape check judges any SQL against them -- an operator's UPDATE before it runs in production, a backfill mixed into a migration, a query an LLM agent is about to execute -- and prints every judgment with the path that discharged it, so the output is also the record of what a script was allowed to do:

$ sqlshape check ops.sql
ops.sql:2: ok orders: require pinned(tenant_id)
ops.sql:6: waived orders: require pinned(tenant_id): orders: `require pinned(tenant_id)` is waived by this statement
ops.sql:8: FAIL orders: visible where deleted_at IS NULL: rows of orders are visible where ...
sqlshape: 2 finding(s)

A context (-context ops) selects the rules that apply to that caller. Details in docs/checks.md.

Migrations

There are no migration files. Edit schema.sql, and sqlshape derives the DDL from the difference between it and the database:

$ sqlshape diff -db "$DSN" > up.sql         # DDL from the database's state to schema.sql
$ $EDITOR up.sql                            # reorder, split, add USING, interleave a backfill
$ sqlshape apply -db "$DSN" -packages ./... up.sql
$ sqlshape verify-schema -db "$DSN"         # drift: where a database differs from schema.sql

The generated DDL may be edited by hand. apply checks, before running anything, that applying the DDL really leads to schema.sql, and refuses otherwise. With -packages it also refuses while Go code still uses a column the DDL drops or retypes. Changes whose intent a diff cannot infer, such as a rename or the removal of an enum label, are declared in schema.sql with -- @migrate lines. See docs/migrations.md.

Documentation

  • docs/checks.md — everything the checker verifies: shapes, meaning, failure modes (with PostgreSQL's constraint naming rules), cardinality, the rules a schema declares (require, aggregates, sqlshape check)
  • docs/templates.md — the template subset, directives, shared fragments, hazards, sparse checking
  • docs/runtime.md — Run / Collect / First / Exec, One, Batch, Copy, MatView, the Go type table, type registration, errors, tests on a real PostgreSQL
  • docs/migrations.md — diff / apply / verify-schema, -- @migrate declarations, seeded tables, requirements
  • docs/flags.md — every flag, the -strict advisories, editor setup
  • docs/design.md — design decisions: what was decided, why, and what was rejected (Japanese)

Compatibility

PostgreSQL 17 and 18; schema.sql declares which. The syntax is PostgreSQL's own: the parser is libpg_query of that version, so everything the server parses, the checker parses the same way — SELECT and DML, MERGE, CTEs, window functions, GROUPING SETS, SQL/JSON, ranges, RETURNING old / new and temporal keys on 18, extensions such as citext and hstore, and DDL including views, functions (SQL and PL/pgSQL bodies), triggers and policies. The analyzer is a pure-Go implementation built from that version's catalog; checking never connects to a PostgreSQL.

The judgment is backed by PostgreSQL's own regression suite: the statements of src/test/regress are run through the analyzer and a real PostgreSQL of the same version side by side, and parameter types, result columns and errors must agree. On 17 they disagree on 19 of 22,103 statements, on 18 on 31 of 23,384; every one is listed (internal/analyze/testdata/regress_baseline_<version>.txt), and each is either something static analysis cannot decide (row-level security recursion, permissions, server internals) or a case where the checker is right and the server's Describe cannot say (the NULLs of RETURNING old after an INSERT). The comparison is part of go test ./..., so a new disagreement fails the build.

License

The sqlshape runtime, pgtest and everything a checked program links (the root module) are Apache License 2.0, see LICENSE. The embedded pg_catalog data and the validation rules ported from PostgreSQL are used under the PostgreSQL License, see NOTICE. The sqlshape binary (cmd/sqlshape) and the MySQL dialect (mysql) are separate modules under the GNU General Public License v2, see cmd/sqlshape/LICENSE; the binary is a development tool, and nothing under it is linked into your program.

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

Constants

This section is empty.

Variables

View Source
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.

View Source
var ErrNoRows = pgx.ErrNoRows

ErrNoRows is returned by First and Get when the query produced no row.

View Source
var ErrNotSent = errors.New("sqlshape: batch not sent")

ErrNotSent is returned by a queued statement's accessors before the batch was sent.

Functions

func IsNoRows

func IsNoRows(err error) bool

IsNoRows reports whether err is ErrNoRows.

func LoadUserTypes

func LoadUserTypes(ctx context.Context, conn *pgx.Conn) error

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.

func Violates

func Violates(err error, key string) bool

Violates reports whether err is a violation of the named constraint (or table.column NOT NULL).

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.

func NewBatch

func NewBatch() *Batch

NewBatch starts an empty batch.

func (*Batch) Len

func (b *Batch) Len() int

Len is the number of queued statements.

func (*Batch) Send

func (b *Batch) Send(ctx context.Context, db BatchDB) error

Send runs the batch in one round trip. The first failing statement's error is returned (constraint violations mapped to ConstraintError like Run does); the statements after it are not executed, and their accessors return ErrNotSent.

type BatchDB

type BatchDB interface {
	SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
}

BatchDB is what Batch.Send needs; pgx.Conn, pgxpool.Pool and pgx.Tx all provide it.

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

type Copier[R any] struct {
	Table   string
	Columns []string
}

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

func Copy[R any](table string, columns ...string) Copier[R]

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)

func (Copier[R]) From

func (c Copier[R]) From(ctx context.Context, db CopyDB, rows []R) (int64, error)

From copies rows into the table and returns how many.

func (Copier[R]) FromSeq

func (c Copier[R]) FromSeq(ctx context.Context, db CopyDB, rows iter.Seq[R]) (int64, error)

FromSeq copies the rows of a sequence into the table and returns how many.

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)

func (MatView) Refresh

func (m MatView) Refresh(ctx context.Context, db DB) error

Refresh runs REFRESH MATERIALIZED VIEW: readers block until it completes.

func (MatView) RefreshConcurrently

func (m MatView) RefreshConcurrently(ctx context.Context, db DB) error

RefreshConcurrently refreshes without blocking readers; the view needs a unique index.

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 Queue

func Queue[R, P any](b *Batch, s Stmt[R, P], p P) *Queued[R]

Queue renders s for p and adds it to the batch.

func QueueOne

func QueueOne[R, P any](b *Batch, s Single[R, P], p P) *Queued[R]

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.

func (*Queued[R]) First

func (q *Queued[R]) First() (R, error)

First is the first row, or ErrNoRows.

func (*Queued[R]) Rows

func (q *Queued[R]) Rows() ([]R, error)

Rows are the statement's result rows.

func (*Queued[R]) Tag

func (q *Queued[R]) Tag() (pgconn.CommandTag, error)

Tag is the statement's command tag (rows affected for INSERT / UPDATE / DELETE).

type Rendered

type Rendered struct {
	SQL  string
	Args []any
}

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

func One[R, P any](template string) Single[R, P]

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

func (s Single[R, P]) Exec(ctx context.Context, db DB, p P) (pgconn.CommandTag, error)

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]) Find

func (s Single[R, P]) Find(ctx context.Context, db DB, p P) (R, bool, error)

Find runs the single-row statement and reports whether a row was found.

func (Single[R, P]) Get

func (s Single[R, P]) Get(ctx context.Context, db DB, p P) (R, error)

Get runs the single-row statement and returns its row, or ErrNoRows.

func (Single[R, P]) Render

func (s Single[R, P]) Render(p P) (Rendered, error)

Render renders the template for p.

func (Single[R, P]) SQLTemplate

func (s Single[R, P]) SQLTemplate() string

SQLTemplate is the template text (see Stmt.SQLTemplate).

func (Single[R, P]) Unprepared

func (s Single[R, P]) Unprepared() Single[R, P]

Unprepared returns a copy that runs without a prepared statement (see Stmt.Unprepared).

type Stmt

type Stmt[R, P any] struct {
	Template string
	// contains filtered or unexported fields
}

Stmt is a checked SQL template. R is the result row type, P the parameter type.

func Query

func Query[R, P any](template string) Stmt[R, P]

Query declares a statement. The argument must be a string literal so the analyzer can expand and check it.

func (Stmt[R, P]) Collect

func (s Stmt[R, P]) Collect(ctx context.Context, db DB, p P) ([]R, error)

Collect runs the statement and returns all rows.

func (Stmt[R, P]) Exec

func (s Stmt[R, P]) Exec(ctx context.Context, db DB, p P) (pgconn.CommandTag, error)

Exec runs a statement that returns no rows (INSERT / UPDATE / DELETE without RETURNING).

func (Stmt[R, P]) First

func (s Stmt[R, P]) First(ctx context.Context, db DB, p P) (R, error)

First runs the statement and returns the first row, or ErrNoRows.

func (Stmt[R, P]) Render

func (s Stmt[R, P]) Render(p P) (Rendered, error)

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

func (s Stmt[R, P]) Run(ctx context.Context, db DB, p P) iter.Seq2[R, error]

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

func (s Stmt[R, P]) SQLTemplate() string

SQLTemplate is the template text; pgtest.Verify expands and checks it against a real PG.

func (Stmt[R, P]) Unprepared

func (s Stmt[R, P]) Unprepared() Stmt[R, P]

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

type UnknownLabelError struct {
	Type  reflect.Type
	Value string
}

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL