analyze

package
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 24 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

analyze

Pure-Go PostgreSQL semantic analyzer. Analyze(schema, sql) → parameter types, result columns (type, nullability, provenance) or a PG-style *Error (SQLSTATE + position). No PostgreSQL at lint time.

Load the schema with analyze.Load (not schema.Load): it installs the loader's ViewHook, which analyzes each view body as the view is created and freezes the output columns on schema.Relation.Frozen — PG fixes a view's columns at CREATE VIEW (a later RENAME COLUMN / ADD COLUMN on a base table does not reach SELECT *, and a matview keeps its names), so readers take the frozen list and re-analyze the body only for the cardinality proof. Frozen columns keep the base column they reference (SrcRel / Src) so writes through the view still land on the base table.

The column list is the only part PG really freezes; NOT NULL is not — a view rechecks the referenced column's attnotnull live, on every query, the same as any other read of the table. analyze.Load also installs a NotNullHook, fired whenever an ALTER TABLE ... ALTER COLUMN SET/DROP NOT NULL (or a PRIMARY KEY added after the fact) changes a table's column (schema.Schema.notifyNotNullChange, check/postgres/schema/schema.go). The hook (refreezeDependentNullability, analyze.go) finds every (plain, not materialized) view that depends on that table, transitively, via schema.DependentViews, and re-analyzes each one fresh in declaration order (freshViewColumns, scope.go — it bypasses viewColumns' shortcut of trusting whatever is already frozen, which is exactly what is being replaced), overwriting only its Frozen columns' Nullable in place (Type stays frozen: PG refuses to alter the type of a column a view depends on). The column list itself, and everything else about Frozen, is left alone: only PG's own asymmetry (column list fixed, NOT NULL live) is modeled, nothing more. Declaration order matters for a view-of-view: a base is refrozen before the views built on it, so by the time a nested view is revisited, resolving its FROM already reads the inner view's just-updated Frozen. A materialized view is its own physical snapshot (PG never copies attnotnull into one, confirmed against a real embedded PG), so it is skipped, not refrozen.

Result.Notes carries findings PG itself would accept and so never appear in a golden: domains as opaque units (domain.go — a domain value only meets the same domain or a literal / parameter; mixing with another domain or the plain base type is a note; unit-preserving operations keep the domain on their result so the check follows the value). Covered by TestDomainNotes; the golden test asserts that parity fixtures produce no notes.

Result.AtMostOne / ManyRowsWhy is the cardinality proof (card.go): a functional-dependency fixpoint over the FROM leaves — a leaf is single once a unique key is fixed by equalities to known values (literals, $n, outer refs, uncorrelated scalar subqueries), a single leaf makes its columns known, outer-join ON clauses only fix their nullable side, views / subqueries / CTEs are proved recursively with the outer-fixed output columns as seeds. Covered by TestCardinality.

Result.Violations lists the constraints a write may violate (violation.go): every unique key on INSERT, those touching SET columns on UPDATE, referencing FKs with NO ACTION / RESTRICT on DELETE and key changes, CHECKs referencing written columns, domain CHECKs, NOT NULL when the value is nullable (with the parameter number so the checker can drop it for non-nullable Go types); ON CONFLICT absorbs its arbiter. Unnamed constraints are named by schema.addConstraint the way PG names them. Covered by TestViolations.

Implements manual chapter 10: operator resolution (§10.2), function resolution (§10.3) incl. variadic / defaults / polymorphic consistency, implicit / assignment / explicit coercion via pg_cast + array / domain / record rules, select_common_type for UNION / CASE / COALESCE / ARRAY / IN / VALUES (§10.5), $n inference from context with text fallback, parse-time literal validation (22P02). Scopes: JOIN (USING / NATURAL / LATERAL), subqueries, CTEs (incl. recursive), set operations, VALUES, functions in FROM, views (analyzed once), whole-row refs, ROWS FROM, data-modifying CTEs, CALL, INSERT / UPDATE / DELETE with RETURNING and ON CONFLICT, MERGE (WHEN MATCHED / NOT MATCHED [BY SOURCE], RETURNING with merge_action()), SQL/JSON (json.go: JSON_OBJECT / JSON_ARRAY / JSON_ARRAYAGG / JSON_OBJECTAGG, JSON_EXISTS / JSON_QUERY / JSON_VALUE, JSON() / JSON_SCALAR / JSON_SERIALIZE, JSON_TABLE in FROM), SQL/XML expressions, (expr).*, functions with OUT parameters in FROM, WHERE CURRENT OF, and utility statements (TRUNCATE / LOCK / REFRESH MATERIALIZED VIEW / NOTIFY / SET / SHOW / transaction control / DO / VACUUM / ANALYZE / COPY / DECLARE CURSOR / CREATE TABLE AS). FETCH stays 0A000: a cursor's columns are not known statically.

  • Aggregate levels (aggFrame, check_agg_arguments): an aggregate belongs to the nearest query level its aggregated arguments' columns resolve to; that level becomes grouped, an aggregate of the same level inside the arguments is nested (42803), an aggregate may not sit in a FROM item of its own level, an ordered-set aggregate's direct arguments may not reach below its level and are checked as per-group expressions, GROUPING's arguments must belong to a grouped level
  • Name spaces: a LATERAL item sees the earlier FROM items of its level; the left side of a RIGHT / FULL join and an UPDATE / DELETE target are in scope for a LATERAL item but illegal to reference (42P10); two items of one name at one level are ambiguous (42P09) as soon as a LATERAL item names them, excluded against a table named excluded too
  • Recursive CTEs: forward references, a WITH nested on the recursive union, a nested WITH of the same name hiding the outer one, mutual recursion between items (0A000), SEARCH / CYCLE columns and their name rules (the recursive reference then has to sit in the recursive term's own FROM), and checkWellFormedRecursion (recursive.go: the query name once, not in a subquery / the nullable side of an outer join / EXCEPT / INTERSECT / the non-recursive term, no aggregates, no data-modifying body)
  • Windows: named windows (duplicates, unknown references), RANGE offset frames need one ORDER BY column, GROUPS needs ORDER BY, no window functions inside window definitions / GROUP BY / RETURNING / JOIN conditions
  • Writes through views (viewdml.go): INSERT / UPDATE / DELETE / MERGE on an automatically updatable view (one table in FROM, no set operation / DISTINCT / GROUP BY / HAVING / LIMIT / OFFSET / WITH / window / aggregate / set-returning target) are typed and their violations computed against the base table under the view's column names; a computed column is not writable (0A000, also when the view's own default on it fills an INSERT), any other view is 55000, a view with INSTEAD OF triggers takes any write. MERGE is checked down the stack of auto-updatable views: a rule for one of its actions refuses it (0A000, disabled rules do not count), triggers must cover all actions or none, a non-updatable view fails for the first uncovered action (55000); a materialized view is 0A000. System columns (ctid, xmin, xmax, cmin, cmax, tableoid) resolve on tables; system relations (pg_catalog, information_schema) come from the catalog (see catalog/README)
  • Function calls: named arguments (f(x => 1)) map onto parameter names with defaults filling the rest; a variadic and a non-variadic candidate with the same effective argument list are one (the non-variadic wins), the same signature in two schemas goes to the earlier on the search path, one reached through defaults against one that is not is ambiguous (42725); a VARIADIC parameter with a default takes zero arguments; f(x) on a composite value with a field f is the field. type-name(x) is a cast only where the coercion is a relabeling or goes through I/O (func_get_detail), and an unqualified name never means a pg_temp type; ROW(..) op ROW(..) needs a btree comparison operator (0A000 otherwise). Result column names follow FigureColname (a cast names the column only when what it casts has no name of its own; SQL/JSON and XML constructors, merge_action(); a function in FROM names its one column by its single OUT parameter, then the alias, then the function)
  • testdata/queries/*.sql + .golden: goldens come from the real PG (go test ./check/postgres/analyze -update); the default run compares the analyzer to them without starting PG
  • regress_test.go: -regress /path/to/postgres/src/test/regress replays PG's own regression corpus against a live PG and the analyzer side by side and writes every disagreement to -regress-report, grouped by kind. SQLSHAPE_PG=18 probes another major version: its oracle, its corpus checkout (regress-18), its catalog (the probe writes the version declaration above the corpus DDL) and its baseline (testdata/regress_baseline_<major>.txt) (DIFF column name / type / nullability, STRICT = analyzer rejects what PG takes, LENIENT = the reverse, CODE = different SQLSTATE). A discovery tool, not a gate: -regress-tests select,join limits it to some files. A full run takes about half a minute: the schedule's first 8 lines build the shared database in order (schema.Apply extends the analyzer's schema statement by statement; each file's session ends with DISCARD ALL on the oracle and the matching temp-table drops / RESETs in the replay, as pg_regress gives every file its own session), every later file runs in its own copy of it, -regress-jobs (default NumCPU, at most 8) of them at a time on a server started with fsync off. psql's \set variables mean what they were set to at that point (\set filename before each COPY), \c is a DISCARD ALL, and DISCARD / DEALLOCATE ALL reset pgx's statement cache so the oracle's helper queries survive them. SQLSHAPE_ORACLE_LOG=/path keeps the server log (one MERGE in merge.sql segfaults PG 17's Prepare and is skipped by reCrash on 17; 18 takes it). testdata/tools/bucket.sh / hits.py slice a report by bucket. The oracle is PG's Describe, so errors PG only raises at execution (assignment length coercion of a literal into varchar(n) / bit(n) / numeric(p,s), view updatability decided by view-column defaults) count as STRICT there even though the analyzer is right
  • probe_test.go runs one statement against one schema (PROBE_SCHEMA=f PROBE_SQL=f [PROBE_ORACLE=1]) for one-off checks while chasing a hit
  • literal_oracle_test.go: with -regress, every 'literal'::type in the corpus goes through the real input function and the analyzer (-literal-types narrows it); seconds, not minutes. The input functions are ported from PG's C: datetime.go (ParseDateTime / DecodeDateTime / DecodeTimeOnly / DecodeInterval / DecodeISO8601Interval with the token tables and the default time zone abbreviations; SET datestyle / intervalstyle / timezone in schema.sql are honoured), literal_compound.go (array_in with dimensions and element input by type, range / multirange, record, geo_ops, pg_lsn, bytea, inet / cidr, macaddr, bit), jsonpath.go (the jsonpath scanner / grammar acceptance rules), literal.go (numbers, money, macaddr8, tid, xid, snapshots, xml, json surrogates, regtype / regproc / regclass names)
  • Error fixtures agree on SQLSTATE; the message text is informative only
  • GROUP BY validity (grouping.go): grouping expressions matched by deparsed text, aggregate arguments exempt, ungrouped columns allowed when their table's primary key is grouped; GROUPING SETS / ROLLUP / CUBE checked against the union of their expressions, grouped columns become nullable
  • Nullability is refined by null-rejecting predicates (IS NOT NULL, strict comparisons, inner-join ON), also inside a searched CASE branch under its WHEN; non-strict built-ins that never return NULL and nullary functions are not null
  • Collations (collation.go): explicit / implicit derivation per §24.2.2; conflicting COLLATE clauses and UNION / INTERSECT / EXCEPT over conflicting implicit collations are the PG errors (42P21), an indeterminate collation reaching a comparison, lower() / max(), ORDER BY, GROUP BY or DISTINCT is a Note (PG fails at run time). Collation names are not validated against pg_collation
  • Extensions: CREATE EXTENSION in schema.sql merges the extension's dumped catalog (see catalog/README), so its types, functions, operators and casts resolve like pg_catalog's, in the schema it was created in

Documentation

Overview

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.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(schemaSQL string) (*schema.Schema, error)

Analyze analyzes exactly one SQL statement against s. A statement PG would reject returns an *Error; other failures are ordinary errors. Load parses schema DDL the way schema.Load does and freezes every view's output columns as the view is created (PG fixes them at CREATE VIEW; see schema.Relation.Frozen). Use this rather than schema.Load for a schema the analyzer will read.

func LoadWith

func LoadWith(cat *catalog.Catalog, schemaSQL string) (*schema.Schema, error)

LoadWith is Load with an explicit catalog.

func Lower

func Lower(s *schema.Schema, expr string, rel *schema.Relation) ([]facts.Pred, error)

Lower reads a declared predicate over rel in the facts language: the expression is parsed and type-checked against the table alone (an error is the declaration's), and each conjunct becomes a facts.Pred whose ColRef.Leaf is 0, standing for the subject. This is x/obligation's Lowerer for PostgreSQL.

func SettingReads

func SettingReads(pol *schema.Policy) []string

SettingReads lists the current_setting(name, true) calls in a policy's predicates: a setting the session never set makes the predicate NULL, which hides every row without an error.

Types

type Column

type Column struct {
	Name string
	Type schema.TypeRef
	// Nullable is the analyzer's own inference (NOT NULL constraints, join shape, expression rules).
	Nullable bool
	// ElemNotNull: for an array-typed column, the analyzer proved its elements can never
	// be NULL (see rteCol.elemNotNull / expr.elemNotNull for how). False otherwise,
	// including for a plain array column, which PostgreSQL never declares this about.
	ElemNotNull bool
	// Source mirrors what PG's Describe reports (stops at views), for oracle parity.
	Source *Source
	// Fields describes a record / composite column (or an array of them): the columns of
	// the row type, or the positional f1.. fields of an anonymous row(...). Nil otherwise.
	Fields []Column
}

Column is one result column.

type Error

type Error struct {
	Code     string
	Message  string
	Position int32
}

Error is a PG-style semantic error with SQLSTATE and 1-based position (0 if none).

func (*Error) Error

func (e *Error) Error() string

type FunctionResult

type FunctionResult struct {
	// Relations the body references directly (dependency graph through functions).
	Relations []RelationRef
	// Notes from the body's statements (domain mixing etc.).
	Notes []Note
	// Violations the body's writes may cause (PL/pgSQL bodies; SQL bodies are walked
	// per call in functionViolations).
	Violations []Violation
	// Statements are the body's statements as facts, for the obligations the schema
	// declares (x/obligation); Line is the PL/pgSQL line, 0 for a SQL body.
	Statements []FunctionStatement
}

FunctionResult is the analysis of a function body.

func AnalyzeFunction

func AnalyzeFunction(s *schema.Schema, fn *schema.Function) (*FunctionResult, error)

AnalyzeFunction checks a LANGUAGE sql function's body against its signature. Functions without an analyzable body return an empty result.

type FunctionStatement

type FunctionStatement struct {
	Line  int
	Facts *facts.Facts
}

FunctionStatement is one statement of a function body, as facts.

type Note

type Note struct {
	Code     string
	Message  string
	Position int32 // 1-based, 0 if none
	// Param is the parameter the note is about (1-based), 0 for none: the checker names it
	// by its Go path where the message writes "$n".
	Param int32
}

Note is a finding that PostgreSQL itself would not report.

func AnalyzePolicy

func AnalyzePolicy(s *schema.Schema, rel *schema.Relation, pol *schema.Policy) ([]Note, error)

AnalyzePolicy type-checks a row-level security policy's USING and WITH CHECK predicates the way CREATE POLICY does: an expression over the table's columns that yields boolean, with no aggregates, window functions or set-returning functions. Notes are the analyzer's own findings inside the predicates (domain mixing, and so on).

func (Note) Advisory

func (n Note) Advisory() bool

Advisory reports whether a note is advice rather than a likely bug.

type RelationRef

type RelationRef struct {
	Schema   string
	Name     string
	Kind     byte // 'r' table, 'v' view, 'm' materialized view
	Position int32
	// Target: the relation an INSERT / UPDATE / DELETE / MERGE writes (a read elsewhere in
	// the same statement, in a subquery or a USING, does not count).
	Target bool
}

RelationRef is a direct reference to a relation, with its position in the SQL.

type Result

type Result struct {
	Params  []schema.TypeRef
	Columns []Column
	// ParamSources, indexed like Params, is the table column a parameter was compared
	// with or assigned to (nil when it met an expression). It carries "which identity"
	// a value stands for, beyond its type.
	ParamSources []*Source
	// Notes are findings PG itself would accept, e.g. mixing domains (domain.go).
	Notes []Note
	// AtMostOne is whether the statement provably returns at most one row (x/cardinality
	// over Facts); ManyRowsWhy says what blocks the proof otherwise.
	AtMostOne   bool
	ManyRowsWhy string
	// Violations are the constraints a write may violate (violation.go).
	Violations []Violation
	// Relations are the tables and views the statement references directly (FROM, JOIN,
	// DML target, subqueries; views are listed but not expanded). Each once, in order.
	Relations []RelationRef
	// Fixed are the table columns the statement pins to one value: by equality with a
	// literal / parameter / outer reference in WHERE or ON (at any select level), or by
	// assignment in an INSERT (Assigned set). Row-ownership policies check against it.
	Fixed []Source
	// Uses are the relation columns the statement depends on (see Use).
	Uses []Use
	// Facts is what the statement provably does, in the form x/obligation judges
	// (facts.go); nil for statements that are not SELECT / INSERT / UPDATE / DELETE / MERGE.
	Facts *facts.Facts
}

Result is the analysis of one statement.

func Analyze

func Analyze(s *schema.Schema, sql string) (*Result, error)

func AnalyzeView

func AnalyzeView(s *schema.Schema, rel *schema.Relation) (*Result, error)

AnalyzeView analyzes a view's defining query as a statement of its own, so its findings (policy, domain mixing) are reported once at the view rather than at every reader.

func (*Result) String

func (r *Result) String(types *schema.Types) string

String renders the result in the oracle's golden format (domains flattened as on the wire).

type Source

type Source struct {
	Table   string
	Column  string
	NotNull bool
	// Assigned is set when a parameter was stored into the column (INSERT / UPDATE), as
	// opposed to compared with it.
	Assigned bool
}

Source is the table column a result column comes straight from.

type Use

type Use struct {
	Table    string // schema-qualified unless public, like Source.Table
	Column   string
	Position int32
}

Use is a relation column the statement depends on: read by name or by *, assigned by INSERT / UPDATE / MERGE, or taken in a whole-row reference. Dropping or changing the column changes what the statement means. A view's columns count as the view's (its base tables are the view's business, and the schema knows them). Each once, at its first position; nothing is recorded inside view definitions.

type Violation

type Violation struct {
	Code       string   // SQLSTATE: 23505 unique, 23503 foreign key, 23514 check, 23502 not null
	Constraint string   // constraint name; "" for NOT NULL (PG 17 does not name them)
	Table      string   // table the constraint belongs to (referencing table for FKs)
	Columns    []string // constrained columns
	RefTable   string   // FK: referenced table
	Param      int32    // NOT NULL: the bare parameter whose NULL would violate (0 otherwise)
	// Trigger / Name: a custom SQLSTATE raised by a trigger function (Constraint holds the code)
	Trigger string
	Name    string
	// Function is the user function whose body (or `-- sqlshape: error` annotation) this
	// violation comes from, when the statement reaches it through a call.
	Function string
}

Violation is one constraint a statement may violate.

func (Violation) Key

func (v Violation) Key() string

Key identifies a violation the way the expect line spells it.

Jump to

Keyboard shortcuts

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