Documentation
¶
Overview ¶
Package schema layers a user's schema.sql (tables, views, enums, domains, composites, functions, indexes) over the bootstrap catalog. It parses DDL with libpg_query and resolves column / argument types; expression bodies (view queries, CHECK, DEFAULT) are kept as AST for the analyzer.
Index ¶
- Constants
- Variables
- func AddWaiver(m map[string][]string, table string, specs ...string) map[string][]string
- func ColumnRefs(e Expr) []string
- func DeclaredVersion(schemaSQL string) (pgparse.Version, error)
- func Deparse(e Expr) string
- func DeparseBody(body Expr) string
- func DeparseStmt(n *pgparse.Node) string
- func NumericTypmod(m int32) (precision, scale int32, ok bool)
- func ReadSource(path string) (string, error)
- func Waivers(list string) map[string][]string
- func WalkNodes(m proto.Message, f func(*pgparse.Node))
- type Column
- type Constraint
- type ConstraintKind
- type Domain
- type Expr
- type FuncArg
- type Function
- type Index
- type Policy
- type Problem
- type RaisedError
- type RelKind
- type Relation
- type RuleDef
- type Schema
- func Load(schemaSQL string) (*Schema, error)
- func LoadWith(cat *catalog.Catalog, schemaSQL string) (*Schema, error)
- func LoadWithHook(cat *catalog.Catalog, schemaSQL string, hook func(*Schema, *Relation)) (*Schema, error)
- func LoadWithHooks(cat *catalog.Catalog, schemaSQL string, ...) (*Schema, error)
- func (s *Schema) Apply(schemaSQL string) error
- func (s *Schema) DateTimeSettings() (dateOrder, intervalStyle, timeZone string)
- func (s *Schema) DependentViews(rel *Relation) []*Relation
- func (s *Schema) Function(schema, name string) *Function
- func (s *Schema) HasSchema(name string) bool
- func (s *Schema) KnownCollation(name string) bool
- func (s *Schema) OnSearchPath(schema string) bool
- func (s *Schema) Relation(schema, name string) *Relation
- func (s *Schema) ResolveType(tn *pgparse.TypeName) (TypeRef, error)
- func (s *Schema) Schemas() []string
- func (s *Schema) SearchPath() []string
- func (s *Schema) ViewsRestricted() bool
- func (s *Schema) XMLOptionDocument() bool
- type Seed
- type Trigger
- type TypeRef
- type Types
- func (ts *Types) ArrayOf(elem catalog.OID) catalog.OID
- func (ts *Types) BaseOf(r TypeRef) TypeRef
- func (ts *Types) ByOID(oid catalog.OID) *catalog.Type
- func (ts *Types) Format(r TypeRef) string
- func (ts *Types) Lookup(schema, name string) *catalog.Type
- func (ts *Types) RangeForSubtype(sub catalog.OID) *catalog.Range
- func (ts *Types) RangeOf(rng catalog.OID) *catalog.Range
- func (ts *Types) RangeOfMulti(multi catalog.OID) *catalog.Range
- func (ts *Types) User() []*catalog.Type
- type ViewColumn
Constants ¶
const FirstUserOID catalog.OID = 16384
FirstUserOID is where synthetic OIDs for user-defined objects start (mirrors PG's FirstNormalObjectId). They are stable within one Schema only.
Variables ¶
var CheckStatement func(s *Schema, stmt *pgparse.Node) error
CheckStatement type-checks a data statement of the schema text against the schema as it stands (the analyzer installs it); nil leaves the INSERTs unchecked.
var ErrNeedsReload = errors.New("schema: statement needs a full reload")
ErrNeedsReload is Apply's answer to DDL that only Load can take.
PartitionKeyProblem checks one PARTITION BY expression against the table (the analyzer installs it): the message PG would give, or "" when the expression is acceptable.
QueryColumns types a query's result columns for CREATE TABLE AS / SELECT INTO. The analyzer installs it (package analyze imports schema, not the reverse); nil leaves such tables as problems.
Functions ¶
func ColumnRefs ¶
ColumnRefs lists the distinct unqualified column names an expression references, in order.
func DeclaredVersion ¶ added in v1.2.0
DeclaredVersion reads the schema's `-- sqlshape: postgres <N>` declaration, anywhere in the text; pgparse.Default when there is none. Two declarations that disagree, or a version without an embedded parser, are errors: nothing can be judged until it is fixed. Load reads it before anything else: the catalog and the parser both follow it.
func Deparse ¶
Deparse renders an expression back to SQL text. Two expressions that deparse the same are the same for the loader's purposes; "" if the node cannot be rendered.
func DeparseBody ¶
DeparseBody renders a SQL-standard function body (Function.SQLBody): `RETURN expr` or `BEGIN ATOMIC stmt; ... END`, which Deparse cannot render on their own.
func DeparseStmt ¶
DeparseStmt renders a whole statement (a view's query, a rule) back to SQL text.
func NumericTypmod ¶
NumericTypmod decodes a numeric typmod into precision and scale (the scale may be negative since PG 15); ok is false for -1 / no typmod.
func ReadSource ¶
ReadSource reads the schema at path: a .sql file, or a directory whose *.sql files are concatenated in name order (so `schema/010_types.sql`, `schema/020_tables.sql`, ... apply like one file). Each file's text is preceded by a comment naming it, so a problem's position can be traced back. ReadSource reads a schema.sql file, or a directory of *.sql files in name order, and requires the text to declare its PostgreSQL version (`-- sqlshape: postgres 17`): the version decides the grammar, the catalog and the PostgreSQL pgtest runs, so a file without one is not judged. Schema text built in code (Load) may leave it out and gets pgparse.Default.
func Waivers ¶ added in v1.1.0
Waivers reads the list of a `waive` directive: comma-separated (outside parentheses) entries of `<table> [<obligation>]`, where the obligation is the body as declared (`pinned(tenant_id)`, `via view`, a predicate) and its absence waives every obligation on the table ("*").
Types ¶
type Column ¶
type Column struct {
Num int16 // 1-based attnum
Name string
Type TypeRef
NotNull bool
Default Expr // raw DEFAULT expression, nil if none
Identity byte // 'a' always / 'd' by default / 0
Generated Expr // GENERATED ALWAYS AS (expr)
// GeneratedVirtual: the generated column is VIRTUAL (computed on read, PostgreSQL 18)
// rather than STORED.
GeneratedVirtual bool
Collation string
// Inherited: the column comes from a parent table (attinhcount > 0); LocalDef: the
// child declares it too (attislocal). Dropping the parent's column drops an inherited
// column without a local definition; a child cannot drop an inherited column.
Inherited, LocalDef bool
// Values is the closed value set a `CHECK (col IN ('a', 'b'))` constraint gives the
// column (nil when none): a value set the checker diffs with Go constants like enum labels.
Values []string
}
Column is one attribute.
type Constraint ¶
type Constraint struct {
Name string
Kind ConstraintKind
Columns []string
// ForeignKey:
RefTable string // schema-qualified unless public
RefColumns []string // empty = referenced table's primary key
// Check:
Expr Expr
// Partial unique index:
Predicate Expr
NullsNotDistinct bool
Deferrable bool
// WithoutOverlaps (PrimaryKey / Unique): the last column is a range or multirange and
// the key is temporal, PRIMARY KEY (id, valid_at WITHOUT OVERLAPS); WithPeriod
// (ForeignKey): the last column pair is PERIOD on both sides. PostgreSQL 18.
WithoutOverlaps bool
WithPeriod bool
// NotEnforced (Check / ForeignKey): declared NOT ENFORCED (PostgreSQL 18), so the
// constraint never raises; it documents an intent the database does not check.
NotEnforced bool
// Exclude: the access method (e.g. "gist") and, one per Columns entry, the WITH
// operator (EXCLUDE USING gist (room WITH =, during WITH &&)). Predicate above doubles
// as its optional WHERE clause.
AccessMethod string
Operators []string
// ForeignKey actions (pg_constraint confdeltype / confupdtype):
// 'a' NO ACTION, 'r' RESTRICT, 'c' CASCADE, 'n' SET NULL, 'd' SET DEFAULT
OnDelete, OnUpdate byte
// Definition is the text of the ALTER TABLE ... ADD CONSTRAINT that made it, "" when
// it was declared inside CREATE TABLE.
Definition string
}
Constraint is a table constraint. Unique indexes are recorded as Unique constraints (with Predicate set when partial).
type ConstraintKind ¶
type ConstraintKind byte
ConstraintKind is the constraint flavour.
const ( PrimaryKey ConstraintKind = 'p' Unique ConstraintKind = 'u' ForeignKey ConstraintKind = 'f' Check ConstraintKind = 'c' Exclude ConstraintKind = 'x' )
type Domain ¶
type Domain struct {
NotNull bool
Checks []*Constraint // Kind Check, named <domain>_check like PG
// Collation is the COLLATE of CREATE DOMAIN, "" for the base type's default.
Collation string
}
Domain is the CHECK / NOT NULL side of a domain type; the base type lives in catalog.Type.BaseType.
type FuncArg ¶
type FuncArg struct {
Name string
Type TypeRef
Mode byte // i in, o out, b inout, v variadic, t table
HasDefault bool
}
FuncArg is one parameter.
type Function ¶
type Function struct {
OID catalog.OID
Schema string
Name string
Args []FuncArg
RetType TypeRef // Record for RETURNS TABLE / OUT params without explicit type
RetSet bool
IsProc bool
// IsWindow marks CREATE FUNCTION ... WINDOW (callable with OVER only).
IsWindow bool
// IsAgg marks a CREATE AGGREGATE (RetType is the final / state type); AggKind is
// pg_aggregate.aggkind: n normal, o ordered-set, h hypothetical-set.
IsAgg bool
AggKind byte
Language string
Volatile byte // i / s / v (default v)
Strict bool
// SecurityDefiner: the function runs with its owner's privileges, so the owner's
// tables' row-level security policies do not apply inside it unless forced.
SecurityDefiner bool
// NotNull is the `-- sqlshape: not null` annotation: the result is never NULL (PG
// cannot tell; the schema author asserts it).
NotNull bool
// Raises are the `-- sqlshape: error XX001 = Name` annotations: SQLSTATEs the function
// (typically a trigger function) raises on purpose.
Raises []RaisedError
// Body is the `AS $$ ... $$` text of a LANGUAGE sql function (analyzable); SQLBody the
// parsed BEGIN ATOMIC body (a List of statements, or a ReturnStmt). Nil for other languages.
Body string
SQLBody Expr
// Definition is the text of the CREATE FUNCTION statement.
Definition string
}
Function is a user-defined function / procedure signature (body is not analyzed).
type Index ¶
type Index struct {
Name string
Columns []string
Unique bool
Predicate Expr
// Definition is the text of the CREATE INDEX statement.
Definition string
// contains filtered or unexported fields
}
Index is an index on a table; Columns is empty when the leading element is an expression.
type Policy ¶
type Policy struct {
Name string
// Command is the command the policy applies to: all, select, insert, update, delete.
Command string
// Permissive (the default) policies are ORed; restrictive ones ANDed on top.
Permissive bool
// Roles the policy applies to; empty (PUBLIC) means every role.
Roles []string
// Using is the USING predicate (rows visible / modifiable), WithCheck the WITH CHECK
// predicate (rows a write may produce). Either may be nil.
Using, WithCheck Expr
// Definition is the text of the CREATE POLICY statement.
Definition string
}
Policy is one CREATE POLICY.
type RaisedError ¶
RaisedError is a custom SQLSTATE a function raises, with its application-side name.
type Relation ¶
type Relation struct {
OID catalog.OID // synthetic pg_class oid
Schema string
Name string
Kind RelKind
RowType catalog.OID // the composite type of a row
// OfType is the composite type of a typed table (CREATE TABLE ... OF type), 0 otherwise.
OfType catalog.OID
Columns []*Column
// Constraints: PK / UNIQUE / FK / CHECK on the table, plus unique indexes (as Unique).
Constraints []*Constraint
// Query is the defining query of a view / matview (nil for tables).
Query Expr
// Definition is the text of the CREATE statement that made the relation; Alters the
// ALTER TABLE statements that shaped it afterwards, other than ADD CONSTRAINT (a
// constraint keeps its own Definition).
Definition string
Alters []string
// ColumnAliases are explicit column names given to a view (CREATE VIEW v (a, b) AS ...).
ColumnAliases []string
// CheckOption (views): WITH [LOCAL|CASCADED] CHECK OPTION, 0 when none. 'l' local: an
// INSERT/UPDATE through the view is checked only against this view's own WHERE.
// 'c' cascaded: also against the WHERE of every updatable view underneath it.
CheckOption byte
// Frozen (views / matviews) is the output column list as it was when the view was
// created, filled by the ViewHook: PG fixes a view's columns at CREATE time (a later
// RENAME / ADD COLUMN on a base table does not reach it), so readers use this rather
// than re-resolving Query against the current schema. Nil when no hook ran or the
// body did not analyze.
Frozen []ViewColumn
// ViewDefaults (views): ALTER VIEW ... ALTER COLUMN SET DEFAULT, by column name; an
// INSERT through the view uses these in place of the base column's default.
ViewDefaults map[string]Expr
// Indexes are every index on the table (unique ones also appear in Constraints), for
// the advisory "no index leads with a predicate column".
Indexes []*Index
// Visible is the `-- sqlshape: visible where <predicate>` policy: rows of the table are
// only meant to be seen through this predicate, so every statement reading it (and
// every view over it) must carry the predicate. Nil when none.
Visible Expr
// Unfiltered (views): tables a `-- sqlshape: unfiltered t1, t2` directive before the
// CREATE VIEW exempts from their visibility policy inside this view's query.
Unfiltered map[string]bool
// Waived (views): the obligations the view's definition opts out of, by table, from
// `-- sqlshape: waive t1, t2 pinned(x)` and `unfiltered` directives before the CREATE:
// "*" waives every obligation on the table, "unfiltered" the predicate ones, anything
// else names one obligation's body (internal/obligation).
Waived map[string][]string
// Directives are the `-- sqlshape: ...` lines written before the CREATE, verbatim
// (normalized whitespace), for the packages whose grammar they belong to
// (internal/obligation reads `require ...`). The loader keeps them all, whether or
// not it interprets them itself.
Directives []string
// InsteadRules (views): the write commands ("insert" / "update" / "delete") a
// CREATE RULE ... DO INSTEAD makes the view take.
InsteadRules map[string]bool
// Parents are the tables this one INHERITS from / is a PARTITION OF.
Parents []*Relation
// Temp: CREATE TEMP; the relation is modeled in the creation schema (hiding a
// permanent one of the same name) but PG keeps it in pg_temp
Temp bool
// IsPartition: created as PARTITION OF (dropped with its parent).
IsPartition bool
// OwnedBy (sequences): "schema.table.column" of the serial / identity column, or the
// ALTER SEQUENCE ... OWNED BY target; the sequence goes with the table or column.
OwnedBy string
// OnCommitDrop: a temporary table created ON COMMIT DROP (gone at transaction end).
OnCommitDrop bool
// Seed (tables): the rows the schema text's INSERT statements give the table, nil
// for a table that holds runtime data.
Seed *Seed
// Policies are the table's row-level security policies (rls.go); RowSecurity is ALTER
// TABLE ... ENABLE ROW LEVEL SECURITY (without it the policies do not apply), and
// ForceRowSecurity makes them apply to the table's owner as well.
Policies []*Policy
RowSecurity bool
ForceRowSecurity bool
// PartKey (partitioned tables): the columns the partition key names or its expressions
// reference (they cannot be dropped; a type they depend on takes the table with it);
// PartKeyFuncs: the functions the key expressions call (DROP FUNCTION CASCADE takes
// the table).
PartKey, PartKeyFuncs []string
// QualifiedRules (views): write commands that have a conditional DO INSTEAD rule
// (WHERE ...), which does not make the view take the write but does stop it from
// being auto-updatable.
QualifiedRules map[string]bool
// RuleNoReturning: write commands taken by an unconditional DO INSTEAD rule whose
// single action has no RETURNING (RETURNING on the command is 0A000).
RuleNoReturning map[string]bool
// RuleCTEUnsupported: write commands with a rule a data-modifying WITH item cannot use
// (anything but one unconditional DO INSTEAD INSERT / UPDATE / DELETE).
RuleCTEUnsupported map[string]bool
// RuleInsertSelect: write commands with a DO INSTEAD INSERT ... SELECT action (0A000
// when the query also has data-modifying WITH items).
RuleInsertSelect map[string]bool
// RuleNames maps each enabled rule's name to its event.
RuleNames map[string]string
// RuleEvents: the write commands ("insert" / "update" / "delete") that have any rule
// on the relation (MERGE refuses an action kind that has one).
RuleEvents map[string]bool
// contains filtered or unexported fields
}
Relation is a table or view with its columns and constraints.
func (*Relation) FullName ¶
FullName is schema.name, with public elided; a temporary relation is its bare name (regclass output: pg_temp is always visible, whatever the search path).
func (*Relation) InheritsFrom ¶
InheritsFrom reports whether rel is anc or descends from it.
type Schema ¶
type Schema struct {
Catalog *catalog.Catalog
Types *Types
// Version is the PostgreSQL major version the schema declared with
// `-- sqlshape: postgres <N>` (pgparse.Default when it declared none): every statement,
// the schema's own and the application's, is parsed with that version's grammar.
Version pgparse.Version
Relations []*Relation
Functions []*Function
Triggers []*Trigger
Comments map[string]string // "table" / "table.column" / "type:name" → comment
// Operators and Casts are the user-defined ones (CREATE OPERATOR / CREATE CAST); the
// analyzer consults them after the catalog's.
Operators []*catalog.Operator
Casts []*catalog.Cast
// Problems are statements the loader could not apply. Loading continues past them.
Problems []Problem
// TypeDefs holds the statement text that created each user type (enum, domain,
// composite, range), for regenerating it elsewhere.
TypeDefs map[catalog.OID]string
// ViewHook runs after every CREATE (MATERIALIZED) VIEW with the schema as it stands
// at that point; the analyzer installs it to fill Relation.Frozen.
ViewHook func(s *Schema, rel *Relation)
// NotNullHook runs after a table's column NOT NULL changes (ALTER COLUMN SET/DROP NOT
// NULL, or ADD CONSTRAINT PRIMARY KEY, which implies it), passing the table relation.
// PG does not freeze a view's nullability the way it freezes its column list -- a view
// reads the referenced column's current attnotnull on every query -- so the analyzer
// installs this to re-derive Relation.Frozen's Nullable (and Type) for every view that
// depends on rel, transitively, in declaration order (DependentViews).
NotNullHook func(s *Schema, rel *Relation)
// contains filtered or unexported fields
}
Schema is the loaded user schema.
func LoadWithHook ¶
func LoadWithHook(cat *catalog.Catalog, schemaSQL string, hook func(*Schema, *Relation)) (*Schema, error)
LoadWithHook is LoadWith with a ViewHook installed before the first statement applies.
func LoadWithHooks ¶
func LoadWithHooks(cat *catalog.Catalog, schemaSQL string, viewHook, notNullHook func(*Schema, *Relation)) (*Schema, error)
LoadWithHooks is LoadWithHook with a NotNullHook installed too, before the first statement applies.
func (*Schema) Apply ¶
Apply extends a loaded schema with more DDL, as if it had been appended to the text Load saw. CREATE EXTENSION cannot be added after the fact (the catalog is fixed at Load): it returns ErrNeedsReload and leaves the schema untouched.
func (*Schema) DateTimeSettings ¶
DateTimeSettings is the datetime input state SET statements in the schema left behind: the DateStyle field order ("mdy" / "dmy" / "ymd"), the IntervalStyle and the TimeZone. Empty means the PG default (MDY, postgres, the session's zone).
func (*Schema) DependentViews ¶
DependentViews lists the views and materialized views whose defining query names rel, and theirs in turn (what DROP ... CASCADE would take), in declaration order.
func (*Schema) HasSchema ¶
HasSchema is whether a schema of that name exists: built in, created with CREATE SCHEMA, or holding an object.
func (*Schema) KnownCollation ¶
KnownCollation reports whether a COLLATE name can be trusted to exist: the built-in ones, one declared with CREATE COLLATION, or a locale-style name (en_US, en-US-x-icu, de_DE.utf8), whose presence depends on the server and is not checked.
func (*Schema) OnSearchPath ¶
OnSearchPath reports whether an unqualified name may resolve into schema.
func (*Schema) ResolveType ¶
ResolveType resolves a TypeName AST node against this schema (exported for the analyzer).
func (*Schema) SearchPath ¶
SearchPath is the schemas an unqualified name is looked up in, first match wins; the first entry is where unqualified CREATE puts new objects. SET search_path in schema.sql changes it for the statements that follow.
func (*Schema) ViewsRestricted ¶
ViewsRestricted reports SET restrict_nonsystem_relation_kind = view: user views may not be accessed.
func (*Schema) XMLOptionDocument ¶
XMLOptionDocument reports SET xmloption = document (XML literals are documents).
type Seed ¶
type Seed struct {
// Columns are the columns the INSERTs name (every table column when they name none),
// in the first INSERT's order. Columns left out take their DEFAULT and are not part of
// the declared content: the migration neither writes nor compares them.
Columns []string
// Key are the columns that identify a row, a subset of Columns.
Key []string
// Rows are the value expressions, one slice per row, aligned with Columns.
Rows [][]Expr
// Additive: `-- sqlshape: seed` before the INSERT. The declaration owns the rows it
// lists but not the table: rows found in the database that it does not list stay.
Additive bool
}
Seed is the fixed content of a table: the rows the schema text itself gives it with ordinary INSERT statements. A table with a Seed is a lookup table whose rows are part of the schema (a value set the checker reads like enum labels, and data the migration keeps in step with the declaration); a table without one holds runtime data.
The INSERT must be idempotent, so that applying the schema text twice means the same thing: rows are identified by a key (the primary key, or a non-partial unique constraint over NOT NULL columns) every row gives as constants, values are constant expressions (no volatile or stable functions, no subqueries, no DEFAULT), there is no ON CONFLICT clause, and no key appears twice.
type Trigger ¶
type Trigger struct {
Name string
Table string // FullName of the table
Insert bool
Update bool
Delete bool
UpdateOf []string // UPDATE OF col, col: the trigger fires only when one of these is assigned (empty: any)
Function string // schema-qualified unless public
// Definition is the text of the CREATE TRIGGER statement.
Definition string
}
Trigger is a row / statement trigger on a table.
type Types ¶
type Types struct {
// extras carried by user types
Enums map[catalog.OID][]string // enum oid → labels in sort order
Domains map[catalog.OID]*Domain // domain oid → details
Schemas map[catalog.OID]string // user type oid → schema name
// Collations declared with CREATE COLLATION (name → true).
Collations map[string]bool
// Ranges are user range types (CREATE TYPE ... AS RANGE) with their multirange.
Ranges []catalog.Range
// contains filtered or unexported fields
}
Types is the type universe: the bootstrap catalog plus user types (enums, domains, composites, relation row types) and their array types.
func (*Types) BaseOf ¶
BaseOf follows domain types down to the underlying non-domain type, keeping the typmod of the outermost declared one. PG reports result columns on the wire (RowDescription / Describe) with the base type, so the oracle never shows a domain.
func (*Types) Format ¶
Format renders a TypeRef the way PostgreSQL's format_type() does (the oracle's golden files use this spelling).
func (*Types) Lookup ¶
Lookup resolves a possibly qualified type name against the search path (public, pg_catalog).
func (*Types) RangeForSubtype ¶
RangeForSubtype is the (first) range type over sub.
func (*Types) RangeOfMulti ¶
RangeOfMulti is the pg_range row of a multirange type.
type ViewColumn ¶
type ViewColumn struct {
Name string
Type TypeRef
Nullable bool
Collation string // the column's collation name, "" for none / default
// SrcRel / Src: the base relation and column this output column is a plain reference
// to (writes through the view land there); nil for computed columns. Pointers, so a
// later RENAME of the base column is followed the way PG follows attnums. When the
// base is itself a view (no Column objects) SrcColumn holds the column's name instead,
// and SrcTable the base's full name when it is not a user relation (a catalog table).
SrcRel *Relation
Src *Column
SrcTable string
SrcColumn string
}
ViewColumn is one frozen output column of a view (see Relation.Frozen).