statement

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 10 Imported by: 2 modules, 3 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.

Documentation

Overview

Package statement parses SQL through the real PostgreSQL grammar (wasilibs/go-pgquery, Wasm libpg_query) and reports the facts the engine's front door needs. In Phase 1 that is a statement-type gate only: which kind of statement this is and, for ALTER TABLE, which table it targets. No schema model, no classification.

Two canonical forms coexist deliberately: this package's deparser prints grammar-canonical SQL (e.g. varchar(50)) for formatting, while pkg/schemadiff models carry server-decompiled text (character varying(50)) for comparison. The two canons never mix: models only ever compare server output against server output, and deparser output must not feed a model comparison or a schema fingerprint.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrConversionRendering is returned when a USING expression, rendered
	// through the deparser, does not come back as the expression it was
	// rendered from: the rendering cannot be proven to be the user's
	// expression, so it is not handed to anything that would run it.
	ErrConversionRendering = errors.New("USING expression does not round-trip through the deparser")
	// ErrConversionRepeated is returned when one ALTER TABLE retypes the
	// same column with USING more than once; the copy can carry only one
	// expression per column, and the server itself refuses the statement.
	ErrConversionRepeated = errors.New("column is retyped with USING more than once")
	// ErrConversionForeignColumn is returned when a USING expression refers
	// to anything but the bare name of the column it retypes: another
	// column, a qualified name, or a whole-row reference. The copy runs the
	// expression over the source row, where every column is in reach, but
	// the stream's catch-up writes one column value at a time, and a value
	// that depends on a neighbouring column cannot be converted from the
	// column alone.
	ErrConversionForeignColumn = errors.New("USING expression refers to a column other than the one it retypes")
)
View Source
var (
	// ErrParseDesired is returned when the input is not valid PostgreSQL
	// syntax, before any admission rule runs. It separates a syntax error
	// from an admission refusal; the parser's own message is joined to it.
	ErrParseDesired = errors.New("parse desired schema")
	// ErrEmptyDesired is returned when the input contains no statements.
	ErrEmptyDesired = errors.New("desired schema contains no statements")
	// ErrNoCreateTable is returned when the input has no CREATE TABLE.
	ErrNoCreateTable = errors.New("desired schema must contain a CREATE TABLE")
	// ErrMultipleCreateTables is returned for more than one CREATE TABLE:
	// the engine is single-table scoped.
	ErrMultipleCreateTables = errors.New("desired schema must contain exactly one CREATE TABLE")
	// ErrDisallowedStatement is returned for any statement kind other than
	// CREATE TABLE / CREATE INDEX. The desired file is executed verbatim on
	// a scratch schema, so only pure schema definition is admitted.
	ErrDisallowedStatement = errors.New("statement kind not allowed in a desired schema")
	// ErrQualifiedName is returned when a statement schema-qualifies its
	// target. Desired files are schema-relative; the live schema comes from
	// the caller, and qualification could escape the scratch schema.
	ErrQualifiedName = errors.New("desired schema statements must use unqualified names")
	// ErrConcurrentIndex is returned for CREATE INDEX CONCURRENTLY, which
	// cannot run inside the scratch transaction.
	ErrConcurrentIndex = errors.New("CONCURRENTLY cannot be used in a desired schema")
	// ErrWrongIndexTarget is returned when an index targets a table other
	// than the desired CREATE TABLE.
	ErrWrongIndexTarget = errors.New("index must target the desired table")
	// ErrExtensionSchema is returned by [DesiredSchema.WithExtensionSchemas]
	// for a name that cannot hold extension objects the file resolves: an
	// empty name, a duplicate, or a system schema PostgreSQL searches on its
	// own terms.
	ErrExtensionSchema = errors.New("invalid extension schema")
)

Typed refusals for desired-state schema files. Each names one rule of the declarative front door; the caller branches with errors.Is, never on text.

View Source
var (
	// ErrNotAlterTable is returned when relation retargeting is requested for
	// anything other than a single ALTER TABLE.
	ErrNotAlterTable = errors.New("statement is not ALTER TABLE")
	// ErrRetargetMismatch is returned when the retargeted statement, re-parsed,
	// differs from the gated statement in anything but its target relation.
	ErrRetargetMismatch = errors.New("retargeted statement differs beyond its target relation")
)
View Source
var (
	// ErrNotRewritable is returned when the statement kind has no
	// CONCURRENTLY form to rewrite to.
	ErrNotRewritable = errors.New("statement has no concurrent form")
	// ErrNotValidNotApplicable is returned when the statement is not a
	// single ADD CHECK / ADD FOREIGN KEY that could take NOT VALID.
	ErrNotValidNotApplicable = errors.New("statement cannot take NOT VALID")
)

Typed refusals for advisory rewrites. The rewriters flip one syntactic flag and deparse — no semantics are derived; a statement that cannot be rewritten that way is refused with one of these.

View Source
var ErrCommentLoss = errors.New("input contains comments, which formatting would discard")

ErrCommentLoss is returned when an operation that reprints SQL through the deparser would silently discard comments. The parser drops comments at parse time, so a formatter cannot carry them; refusing is the fail-closed alternative to destroying documentation in a source-of-truth file.

View Source
var ErrNotCreateTable = errors.New("statement is not a CREATE TABLE")

ErrNotCreateTable is returned when the statement handed to ImplicitRelationNames is not a single CREATE TABLE.

View Source
var ErrNotOneStatement = errors.New("input must contain exactly one SQL statement")

ErrNotOneStatement is returned by ParseOne when the input does not contain exactly one SQL statement.

View Source
var ErrPolicyLocksRows = errors.New("a policy cannot lock the rows it reads, such as with FOR SHARE or FOR UPDATE")

ErrPolicyLocksRows refuses a policy expression whose query locks the rows it reads (FOR UPDATE, FOR SHARE, and their weaker forms). PostgreSQL takes ROW SHARE on such a table while it builds the policy, which waits behind a session holding EXCLUSIVE, where a plain read takes only ACCESS SHARE.

View Source
var ErrPolicyReadsCatalog = errors.New("a policy cannot read a pg_catalog table")

ErrPolicyReadsCatalog refuses a policy expression that reads a pg_catalog table. pg_catalog is always searched, so introspection prints such a table unqualified, and the file pull would export from the live policy could not be admitted again.

View Source
var ErrPolicyReadsOwnTable = errors.New("a policy cannot read the table it is defined on")

ErrPolicyReadsOwnTable refuses a policy expression that reads a relation with its own table's name. The scratch build would bind the name to the live table rather than to the desired one, and PostgreSQL reports infinite recursion for a policy that reads the table it protects. The file does not say which schema the table lives in, so the name is refused in every schema.

View Source
var ErrPolicyRelationDependency = errors.New("a policy must name every table it reads schema-qualified, such as public.team_members")

ErrPolicyRelationDependency refuses a policy expression that reads a table it does not name schema-qualified. Policy expressions resolve against nothing but the scratch schema and PostgreSQL's built-ins, so an unqualified name either fails to resolve or binds an object nobody meant. A CTE name is refused the same way, because the grammar cannot tell it from a table name.

View Source
var ErrRepeatedAddColumn = errors.New("the statement adds the same column more than once")

ErrRepeatedAddColumn means an ALTER TABLE adds the same column name in more than one subcommand. Each addition can rewrite the table or not on its own terms, so one proof cannot stand for both.

View Source
var ErrRowSecurityChange = errors.New("invalid row security operation")

ErrRowSecurityChange identifies SQL outside a table-local RLS operation.

View Source
var ErrRowSecurityDeclaration = errors.New("desired row security requires one explicit ENABLE or DISABLE on the desired table")

ErrRowSecurityDeclaration reports an incomplete or contradictory RLS declaration.

View Source
var ErrRowSecurityForeignKey = errors.New("foreign keys are not supported in desired row security")

ErrRowSecurityForeignKey refuses a foreign key in a row-security desired file. The row-security scratch build creates no stand-in for a referenced table, so a foreign key there would bind to the live table and lock it.

View Source
var ErrRowSecurityTableDefinitionRequired = errors.New("desired row security requires a CREATE TABLE definition")

ErrRowSecurityTableDefinitionRequired identifies a missing table definition in an RLS file.

Functions

func AddColumnProbes added in v0.4.0

func AddColumnProbes(sql, schema, table string) (map[string]AddColumnProbe, error)

AddColumnProbes returns, for each ADD COLUMN of an ALTER TABLE, a single-command ALTER TABLE that adds the same column to schema.table, keyed by column name. A probe keeps everything that decides whether the server rewrites the table to add the column, or refuses it for leaving an existing row NULL: its type and collation, its DEFAULT, NOT NULL, and identity. An inline PRIMARY KEY becomes the NOT NULL it implies. The probe drops the inline CHECK, UNIQUE, REFERENCES, and EXCLUDE constraints and the rest of a PRIMARY KEY, which scan the table or build an index but never rewrite it, and which a probe table cannot always carry, and an identity's SEQUENCE NAME, so the probe's sequence is created beside the probe table rather than in the named schema. A generated column gets no probe: the planner routes it by its generation alone, and its expression may name a column the same change adds, which the probe table does not have. A statement other than ALTER TABLE returns ErrNotAlterTable, and one that adds a column name twice returns ErrRepeatedAddColumn; an ALTER TABLE that adds no column, or only generated ones, returns an empty map.

func AddNotValid

func AddNotValid(sql string, naming ConstraintNaming) (rewritten, constraint string, err error)

AddNotValid rewrites a single-command ALTER TABLE ... ADD CONSTRAINT (CHECK or FOREIGN KEY) to its NOT VALID form and returns the rewritten statement plus the constraint name for the follow-up VALIDATE CONSTRAINT step.

The VALIDATE step has to name the constraint, so an unnamed constraint is given the name PostgreSQL would choose (defaultConstraintName) and the rewrite states it. The server takes its first choice unless a constraint in the schema already holds it, and then tries the label with 1, 2, ... appended; naming.Taken lets the rewrite make the same moves. A name the rewrite states that the table already uses fails the NOT VALID step with a duplicate-object error, before anything is added.

func Canonical

func Canonical(sql string) (string, error)

Canonical reprints one statement through the PostgreSQL deparser: grammar-canonical spelling, unnecessary quoting dropped. Commented input is refused (ErrCommentLoss): the parser drops comments, and reprinting must never silently discard content. It is the rendering the plan report carries, so both front doors describe the same change with the same string. Deparser output never feeds a model comparison or a schema fingerprint (see the package comment); the plan report's fingerprint is a plan identity, not a schema fingerprint.

func CheckNoComments

func CheckNoComments(sql string) error

CheckNoComments scans sql with the PostgreSQL lexer and returns ErrCommentLoss when it contains any SQL (--) or C-style (/* */) comment. A scan failure is surfaced to the caller, never guessed around.

func ColumnConversions added in v0.4.0

func ColumnConversions(sql string) (map[string]string, error)

ColumnConversions returns, for each column that sql's ALTER TABLE retypes with a USING clause, the USING expression as the deparser renders it: the SQL text a SELECT list can carry in the column's place. The map is keyed by column name and is empty when no subcommand carries USING.

PostgreSQL keeps no record of a USING expression once ALTER COLUMN TYPE has run: the catalog describes the column's new type, not how the old values became it. The copy of a retyped column therefore has nowhere to take the conversion from but the statement itself, and this is the one place that reads it. The expression is extracted, not edited: the parse tree's node is rendered as the single target of a SELECT and the SELECT keyword removed, and the result is proven by parsing it back as a SELECT target and rendering it again to the same text. Nothing is derived from the expression's meaning, but one thing is read off its shape: every column reference in it must be the bare name of the column it retypes, because the catch-up that follows the copy converts one column value at a time and has no neighbouring column to hand the expression (ErrConversionForeignColumn). A statement that is not a single ALTER TABLE is ErrNotAlterTable.

func Concurrently

func Concurrently(sql string) (string, error)

Concurrently returns sql rewritten to its CONCURRENTLY form: CREATE INDEX, DROP INDEX, REINDEX, or ALTER TABLE ... DETACH PARTITION. The rewrite flips the grammar's concurrency flag and deparses — nothing else changes. A statement already concurrent comes back canonicalized.

func FormatDesired added in v0.5.4

func FormatDesired(sql string) (string, error)

FormatDesired returns the canonical text of a desired-state schema file: sql is admitted by ParseDesiredFile and every admitted statement is printed in the deparser's canonical form followed by ";\n", in the order DesiredFile.Statements reports them, which can differ from the input's (indexes after the table, policy comments last).

The file is the one ParseDesiredFile admits: exactly one CREATE TABLE (ErrMultipleCreateTables for a second), unqualified names (ErrQualifiedName), the table's indexes, and its row-security statements; any other statement kind is ErrDisallowedStatement. Input that is not valid SQL, an unterminated quote or comment included, is ErrParseDesired.

A lexical comment (-- or /* */) is refused with ErrCommentLoss before any admission rule runs: the parser drops comments, and formatting must never silently discard content. An admitted statement such as COMMENT ON POLICY is content, not a comment, and is printed. On any refusal the text is empty.

The text is stable across calls and formats to itself, but it is the canonical form of the PostgreSQL parser this version of pg-sprite builds with: it can change when that parser is upgraded, though what the statements mean does not.

Example

ExampleFormatDesired formats a desired-state schema file the way the fmt command does. A file is printed in canonical form; a commented one is refused, since the parser would drop the comment; a syntax error is told from a refusal by ErrParseDesired. On any error the text is empty.

package main

import (
	"errors"
	"fmt"

	"github.com/block/pg-sprite/pkg/statement"
)

func main() {
	for _, sql := range []string{
		"create table documents (id bigint primary key);\n" +
			"create index documents_id_idx on documents (id);",
		"CREATE TABLE documents (id bigint PRIMARY KEY); -- keep me",
		"CREATE TABLE documents (title text DEFAULT 'oops);",
		"CREATE TABLE documents (id bigint);\nALTER TABLE documents ADD COLUMN title text;",
	} {
		formatted, err := statement.FormatDesired(sql)
		switch {
		case errors.Is(err, statement.ErrCommentLoss):
			fmt.Println("refused: commented input")
		case errors.Is(err, statement.ErrParseDesired):
			fmt.Println("not valid SQL")
		case errors.Is(err, statement.ErrDisallowedStatement):
			fmt.Println("refused:", statement.ErrDisallowedStatement)
		case err != nil:
			fmt.Println("refused:", err)
		default:
			fmt.Print(formatted)
		}
	}
}
Output:
CREATE TABLE documents (id bigint PRIMARY KEY);
CREATE INDEX documents_id_idx ON documents USING btree (id);
refused: commented input
not valid SQL
refused: statement kind not allowed in a desired schema

func HasRowSecurityDeclaration added in v0.4.0

func HasRowSecurityDeclaration(sql string) (bool, error)

HasRowSecurityDeclaration reports whether sql declares row security without admitting it. Use it to ask that question alone, for example to skip input that declares no row security, or to inspect a single statement rather than a desired file. To route a desired file to its planner, use ParseDesiredFile, which makes this check and applies the matching front door in one parse. The result is not an admission: execution still needs a value from ParseDesiredWithRowSecurity or ParseDesiredFile.

func ImplicitRelationNames added in v0.3.0

func ImplicitRelationNames(sql string) ([]string, error)

ImplicitRelationNames returns the first-choice relation names PostgreSQL will use for one CREATE TABLE statement, in the table's own schema: indexes for PRIMARY KEY, UNIQUE, and EXCLUDE constraints, and sequences for serial and identity columns. A named constraint's index takes the constraint name verbatim; an unnamed one takes the server's generated name (`<table>_pkey`, `<table>_<cols>_key`, `<table>_<cols>_excl`, truncated to the identifier byte budget the way the server truncates), where `<cols>` covers every index column — the INCLUDE columns too — with a repeated column or expression name numbered the way the server numbers it. A sequence takes `<table>_<column>_seq` under the same truncation rules, or the name an identity column's SEQUENCE NAME option states; a SEQUENCE NAME qualified into another schema is born outside the table's schema and is not one of its names. Names are returned in definition order and are not de-duplicated: two constraints whose first choices coincide both appear, so a claim map sees the conflict.

func Qualify

func Qualify(sql, schema string) (string, error)

Qualify returns sql with its target relation qualified by schema; an empty schema strips an existing qualification instead. It supports exactly one CREATE TABLE, CREATE INDEX, or ALTER TABLE statement. This touches qualification only — no semantics are ever derived or transformed at the AST level (that is execute-and-introspect's job).

func QualifyForeignKeyReferences added in v0.4.0

func QualifyForeignKeyReferences(sql, schema string) (string, error)

QualifyForeignKeyReferences returns an ALTER TABLE statement with every unqualified table its added foreign keys reference qualified by schema. A planned foreign-key add names its referenced table as the desired file does, unqualified, which resolves through the search_path of whatever session runs it; the referenced table lives in the target schema, so the plan names it there and the statement binds the same table wherever it runs. An already-qualified reference is left as written. Like Qualify, this touches qualification only.

func RetargetRelation added in v0.4.0

func RetargetRelation(sql, schema, table string) (string, error)

RetargetRelation returns sql with its ALTER TABLE target relation replaced by schema.table and reprinted through the PostgreSQL deparser. It is the one AST edit the copy-and-swap route permits: the gated statement names the source table, and the shadow builder needs the same operations against the empty shadow. Only the target RangeVar changes — every other node, including a REFERENCES or expression that names the source table, is left exactly as the user wrote it.

func SameOpsExceptTarget added in v0.4.0

func SameOpsExceptTarget(gated, retargeted string) error

SameOpsExceptTarget proves that two ALTER TABLE syntax trees deparse identically after normalizing the gated target to the retargeted relation. The shadow builder runs it on the gated statement and its retargeted form before executing anything on the shadow (ST-7 with the shadow as the sole permitted target).

Types

type AddColumnProbe added in v0.4.0

type AddColumnProbe struct {
	SQL         string
	IfNotExists bool
}

AddColumnProbe is the probe for one ADD COLUMN: SQL adds the same column to the probe table, and IfNotExists records that the subcommand is skipped when the column already exists.

type AddColumnProof added in v0.4.0

type AddColumnProof string

AddColumnProof is what the server proved about adding one column to a table by its probe: whether the table is rewritten, and if so what rewrites it.

const (
	// AddColumnInPlace means the column is added without rewriting the table;
	// any default it has is stored in the catalog.
	AddColumnInPlace AddColumnProof = "in-place"
	// AddColumnDefaultRewrites means the table is rewritten to compute the
	// column's default for every row; the column's type alone adds in
	// place.
	AddColumnDefaultRewrites AddColumnProof = "default-rewrites"
	// AddColumnTypeRewrites means the column's type alone rewrites the table,
	// because a domain with constraints is checked against every row.
	AddColumnTypeRewrites AddColumnProof = "type-rewrites"
	// AddColumnUnproven means the proof needed a lock another session held, so
	// the server answered neither way.
	AddColumnUnproven AddColumnProof = "unproven"
)

type ConstraintKind

type ConstraintKind int

ConstraintKind names the constraint families the classifier routes differently.

const (
	ConstraintUnrecognized ConstraintKind = iota
	ConstraintPrimaryKey
	ConstraintUnique
	ConstraintCheck
	ConstraintForeignKey
	ConstraintNotNull
)

The constraint families ParseOps distinguishes. ConstraintUnrecognized (e.g. EXCLUDE) has no known safe pattern and is refused.

type ConstraintNaming added in v0.4.0

type ConstraintNaming struct {
	// Columns are the table's live columns. A bare name in a CHECK reads
	// as a column when the table has one by that name and otherwise, when
	// it is the table's own name, as the table's whole row. Nil reads every
	// bare name as a column.
	Columns map[string]bool
	// Taken are the names of the constraints already in the table's
	// schema, every table's and domain's alike: the server passes over each
	// of them when it picks a name.
	Taken map[string]bool
}

ConstraintNaming is what the server consults when it names an unnamed constraint, read from the live table. The zero value knows nothing: a bare name reads as a column and no name counts as taken, which yields the server's first choice.

type ConversionNames added in v0.4.0

type ConversionNames struct {
	Functions  []QualifiedName
	Operators  []QualifiedName
	Types      []QualifiedName
	Collations []QualifiedName
}

ConversionNames are the names a USING expression leaves to the catalog to resolve, by kind, each list sorted and without repeats. They are what a resolution of the expression depends on: the function names it calls, the operator names it applies, the type names it casts to, and the collations it names. The lists say which names the expression spells, not which catalog objects they resolved to; resolving them is the server's job, and what the server would resolve them to is what a fingerprint of the catalog entries under these names pins.

func ConversionNamesOf added in v0.4.0

func ConversionNamesOf(expr string) (ConversionNames, error)

ConversionNamesOf reads the names out of a USING expression as ColumnConversions rendered it: the expression is parsed as the one target of a SELECT and its tree walked for every function call, operator, type cast, and COLLATE clause. The walk reads the tree's shape, not its meaning, so it reports what the grammar wrote down and nothing the server adds while it resolves: a BETWEEN is the two comparison operators the server rewrites it to, a CASE with an operand compares with the unqualified `=`, and the grammar's own spellings — `integer` parsed as pg_catalog.int4, LIKE as the `~~` operator — appear as the grammar spells them. What the server resolves without a name the expression spelled — an implicit cast between two types, the comparison GREATEST and LEAST pick for a type — is not in the result.

func (ConversionNames) Empty added in v0.4.0

func (n ConversionNames) Empty() bool

Empty reports whether the expression spelled no name of any kind.

type DeclaredIndexConstraints added in v0.5.1

type DeclaredIndexConstraints struct {
	// Names holds one entry per constraint, table-level and column-inline,
	// in definition order: the name the statement states, or "" when the
	// server chooses one.
	Names []string
	// IndexesCopiedFrom names, in definition order, the table each LIKE
	// clause that includes indexes copies from. The server creates the
	// copies after the table, so they are kept beside the declared
	// constraints rather than merged with them, and the table built holds
	// the declared constraints plus every PRIMARY KEY, UNIQUE, and EXCLUDE
	// constraint these tables hold. A LIKE clause that excludes indexes
	// copies none and is not listed.
	IndexesCopiedFrom []QualifiedName
}

DeclaredIndexConstraints are the PRIMARY KEY, UNIQUE, and EXCLUDE constraints a CREATE TABLE declares.

func IndexConstraints added in v0.5.1

func IndexConstraints(sql string) (DeclaredIndexConstraints, error)

IndexConstraints returns the PRIMARY KEY, UNIQUE, and EXCLUDE constraints a CREATE TABLE declares.

type DefaultKind

type DefaultKind int

DefaultKind classifies the DEFAULT expression shape of an added column. The shape alone cannot settle whether PostgreSQL rewrites the table: a constant still rewrites every row when the column's type is a domain with constraints, and a non-volatile expression such as now() does not. The server answers that (preflight.AddColumnRewrites); without its answer, any expression is treated as volatile, conservatively.

const (
	// DefaultNone: no DEFAULT clause.
	DefaultNone DefaultKind = iota
	// DefaultConstant: a literal (possibly type-cast), which the catalog
	// stores unless the column's type forces a rewrite.
	DefaultConstant
	// DefaultExpression: anything else — function calls, identity, serial.
	// The engine does not evaluate volatility offline; without the
	// server's answer it assumes the worst.
	DefaultExpression
)

The default shapes an added column can carry.

type DesiredFile added in v0.4.0

type DesiredFile struct {
	// contains filtered or unexported fields
}

DesiredFile is one desired-state schema file admitted through exactly one of the two declarative front doors: ParseDesired for a table with its indexes, or ParseDesiredWithRowSecurity for a table that also declares row security. The choice is made once, by ParseDesiredFile, so a consumer never re-derives which planner owns a file. Only ParseDesiredFile constructs a non-zero value, and exactly one of Schema and RowSecurity reports ok.

DesiredFile is a router over those two proof types, not a proof type itself: no planner or executor accepts it. Hand the value Schema or RowSecurity returns to the matching planner.

func ParseDesiredFile added in v0.4.0

func ParseDesiredFile(sql string) (DesiredFile, error)

ParseDesiredFile parses sql once and admits it through the front door its statements select. A file that declares row security (a policy, a policy comment, or ENABLE, DISABLE, FORCE or NO FORCE ROW LEVEL SECURITY) must pass ParseDesiredWithRowSecurity's rules; any other file must pass ParseDesired's. Refusals are those front doors' typed errors, unchanged; input that is not valid SQL is refused with ErrParseDesired.

Example

ExampleParseDesiredFile routes a desired-state schema file to the planner that owns it. Exactly one of RowSecurity and Schema reports ok after a nil error; hand that value to diffplan.PlanWithRowSecurity or diffplan.Plan.

package main

import (
	"errors"
	"fmt"

	"github.com/block/pg-sprite/pkg/statement"
)

func main() {
	for _, sql := range []string{
		"CREATE TABLE documents (id bigint PRIMARY KEY);\n" +
			"CREATE INDEX documents_id_idx ON documents (id);",
		"CREATE TABLE documents (id bigint PRIMARY KEY);\n" +
			"ALTER TABLE documents ENABLE ROW LEVEL SECURITY;",
		"CREATE TABLE documents (id bigint PRIMARY KEY);\n" +
			"ALTER TABLE documents ADD COLUMN title text;",
		"CREATE TABLE documents (",
	} {
		file, err := statement.ParseDesiredFile(sql)
		switch {
		case errors.Is(err, statement.ErrParseDesired):
			fmt.Println("not valid SQL")
			continue
		case errors.Is(err, statement.ErrDisallowedStatement):
			fmt.Println("refused:", statement.ErrDisallowedStatement)
			continue
		case err != nil:
			fmt.Println("refused:", err)
			continue
		}
		if _, ok := file.RowSecurity(); ok {
			fmt.Printf("row-security planner: %s, %d statements\n", file.Table(), len(file.Statements()))
			continue
		}
		if _, ok := file.Schema(); ok {
			fmt.Printf("ordinary planner: %s, %d statements\n", file.Table(), len(file.Statements()))
		}
	}
}
Output:
ordinary planner: documents, 2 statements
row-security planner: documents, 2 statements
refused: statement kind not allowed in a desired schema
not valid SQL

func (DesiredFile) RowSecurity added in v0.4.0

func (f DesiredFile) RowSecurity() (DesiredWithRowSecurity, bool)

RowSecurity returns the row-security planner input when the file declares row security.

func (DesiredFile) Schema added in v0.4.0

func (f DesiredFile) Schema() (DesiredSchema, bool)

Schema returns the ordinary planner input when the file declares no row security. The zero DesiredFile admitted nothing, so it reports neither.

func (DesiredFile) Statements added in v0.4.0

func (f DesiredFile) Statements() []Statement

Statements returns the admitted statements in the order the admitted value's Statements reports them. For a row-security file that is the table and its indexes, then the settings and policies in the order the file wrote them, then the policy comments. The slice is a copy.

func (DesiredFile) Table added in v0.4.0

func (f DesiredFile) Table() string

Table returns the unqualified desired table, the same name the admitted value's Table reports.

type DesiredSchema

type DesiredSchema struct {
	// contains filtered or unexported fields
}

DesiredSchema proves a desired-state schema file passed the set-level admission rules: exactly one unqualified CREATE TABLE plus any number of CREATE INDEX statements on that table, none of them CONCURRENTLY, and every table a foreign key references named unqualified. Only ParseDesired produces a non-zero value.

Statement SQL is canonical (parsed and deparsed through the PostgreSQL grammar), one statement per entry, held in execution order: the CREATE TABLE first, the indexes in input order after it.

func ParseDesired

func ParseDesired(sql string) (DesiredSchema, error)

ParseDesired parses a desired-state schema file and admits only what the declarative front door can execute on a scratch schema: one unqualified CREATE TABLE and unqualified, non-concurrent CREATE INDEX statements on it. Foreign keys are admitted for planning when the table they reference is unqualified; desired-state execution refuses every foreign-key change (see docs/limitations.md). Anything else is refused with a typed error.

func (DesiredSchema) ExtensionSchemas added in v0.5.1

func (ds DesiredSchema) ExtensionSchemas() []string

ExtensionSchemas returns the schemas, in search order, that the file's unqualified type, function, and operator names also resolve against after the target schema and public. It is empty unless DesiredSchema.WithExtensionSchemas set it. The slice is a copy.

func (DesiredSchema) HasForeignKeys added in v0.4.0

func (ds DesiredSchema) HasForeignKeys() bool

HasForeignKeys reports whether the CREATE TABLE declares a foreign key, a self-reference included.

func (DesiredSchema) ReferencedTables added in v0.4.0

func (ds DesiredSchema) ReferencedTables() []string

ReferencedTables returns the unqualified names of the other tables the CREATE TABLE's foreign keys reference, sorted and distinct; a self-reference is not listed. The slice is a copy.

func (DesiredSchema) Statements

func (ds DesiredSchema) Statements() []Statement

Statements returns the admitted statements in execution order: the CREATE TABLE first, the indexes in input order after it — an index cannot be built before its table exists, and every consumer replays this order verbatim. The slice is a copy: mutating it cannot invalidate the admission proof the value carries.

func (DesiredSchema) Table

func (ds DesiredSchema) Table() string

Table returns the unqualified name of the single CREATE TABLE target.

func (DesiredSchema) WithExtensionSchemas added in v0.5.1

func (ds DesiredSchema) WithExtensionSchemas(schemas ...string) (DesiredSchema, error)

WithExtensionSchemas returns a copy of ds whose unqualified type, function, and operator names also resolve against schemas, in order, after the target schema and public: `email citext` then finds the type an extension installed in a schema such as extensions. The schemas only widen what the file's names resolve to when pg-sprite builds and creates the table; introspection still prints each such name qualified, so a plan states exactly which object it means. Unqualified names are a choice the caller makes explicitly, because with more schemas searched an unqualified function call can resolve to a different overload.

A name must be non-empty, listed once, and not a system schema (pg_catalog, information_schema, or any pg_ name): pg_catalog is searched first regardless, and the others never hold an extension the file should name. An empty schemas clears the list.

type DesiredWithRowSecurity added in v0.4.0

type DesiredWithRowSecurity struct {
	// contains filtered or unexported fields
}

DesiredWithRowSecurity proves declaration syntax for scratch inspection and the dedicated atomic RLS executor. It is distinct from DesiredSchema; generic native and create executors cannot accept it. Live safety needs executor checks. The explicit parse entry point owns the complete table-local RLS definition, including an empty policy set. Only ParseDesiredWithRowSecurity constructs it.

func ParseDesiredWithRowSecurity added in v0.4.0

func ParseDesiredWithRowSecurity(sql string) (DesiredWithRowSecurity, error)

ParseDesiredWithRowSecurity admits table/index definitions followed by RLS settings, policies, and policy comments. It requires explicit ENABLE/DISABLE; FORCE/NO FORCE is optional and cannot be declared twice. Other ALTER commands, qualified targets, and policy queries reading a table unqualified or reading their own table are refused.

func (DesiredWithRowSecurity) ExtensionSchemas added in v0.5.1

func (d DesiredWithRowSecurity) ExtensionSchemas() []string

ExtensionSchemas returns the schemas the table definition's unqualified names also resolve against, as DesiredSchema.ExtensionSchemas does. It is empty unless DesiredWithRowSecurity.WithExtensionSchemas set it. The slice is a copy.

func (DesiredWithRowSecurity) PolicyReads added in v0.5.1

func (d DesiredWithRowSecurity) PolicyReads() []QualifiedName

PolicyReads returns the tables the policies' expressions read, each schema-qualified as the file names it, sorted and without duplicates. The slice is a copy.

func (DesiredWithRowSecurity) Statements added in v0.4.0

func (d DesiredWithRowSecurity) Statements() []Statement

Statements returns a defensive copy in scratch execution order.

func (DesiredWithRowSecurity) Table added in v0.4.0

func (d DesiredWithRowSecurity) Table() string

Table returns the declaration's unqualified table name.

func (DesiredWithRowSecurity) TableDefinition added in v0.5.1

func (d DesiredWithRowSecurity) TableDefinition() DesiredSchema

TableDefinition returns the CREATE TABLE and its indexes without the row security that follows them. Running it on its own creates a table without its row security, so only the executor that creates the table and its row security in one transaction consumes it.

func (DesiredWithRowSecurity) WithExtensionSchemas added in v0.5.1

func (d DesiredWithRowSecurity) WithExtensionSchemas(schemas ...string) (DesiredWithRowSecurity, error)

WithExtensionSchemas returns a copy of d whose table definition resolves unqualified type, function, and operator names against schemas as well, under DesiredSchema.WithExtensionSchemas's rules. Only the CREATE TABLE and its indexes widen. Policy expressions still resolve nothing but the table and PostgreSQL's built-ins, so every helper and table a policy names stays qualified, and an extension schema can never change which function a policy calls.

type IndexRelation added in v0.4.0

type IndexRelation struct {
	Schema string
	Name   string
	Kind   IndexRelationKind
}

IndexRelation is the one relation a single-relation index-maintenance statement maintains, as the grammar spelled it. Schema is empty when the name was unqualified, so the session search_path resolves it. The acknowledgement of an accepted blocking statement resolves this name to the table whose lock the operator accepts; the parse boundary itself never consults a catalog.

type IndexRelationKind added in v0.4.0

type IndexRelationKind int

IndexRelationKind says whether a single-relation index-maintenance statement names an index or a table.

const (
	// IndexRelationNone is carried by statements that name no single
	// maintained relation.
	IndexRelationNone IndexRelationKind = iota
	// IndexRelationIndex means the statement names an index: DROP INDEX,
	// REINDEX INDEX, and ALTER INDEX ... RENAME TO.
	IndexRelationIndex
	// IndexRelationTable means the statement names a table: REINDEX TABLE.
	IndexRelationTable
)

type IndexTarget added in v0.3.3

type IndexTarget int

IndexTarget identifies whether an index-maintenance statement's scope stays within one relation. IndexTargetOther means the scope is wider than one relation, for any reason — several indexes, a schema or database scope, or a cascading drop (see Cascades()) — so it is not a count of the relations the statement names. The gate uses this parse-only fact to keep forms requiring more than one lock acknowledgement out of accepted-blocking eligibility.

const (
	// IndexTargetNone is carried by statements outside index maintenance.
	IndexTargetNone IndexTarget = iota
	// IndexTargetSingleRelation covers one DROP INDEX (without CASCADE),
	// REINDEX INDEX or TABLE, and ALTER INDEX ... RENAME TO.
	IndexTargetSingleRelation
	// IndexTargetOther covers the DROP and REINDEX scopes that do not stay
	// within one relation: several indexes in one DROP INDEX, DROP INDEX with
	// CASCADE (which also drops dependent objects), and REINDEX SCHEMA,
	// DATABASE, and SYSTEM.
	IndexTargetOther
)

func IndexTargets added in v0.3.3

func IndexTargets() []IndexTarget

IndexTargets returns the closed set of index-maintenance target shapes.

func (IndexTarget) String added in v0.3.3

func (t IndexTarget) String() string

String returns the stable name of an index target shape.

type Kind

type Kind int

Kind is the statement-type bucket the Phase 1 gate branches on.

const (
	KindOther Kind = iota
	KindAlterTable
	KindCreateIndex
	KindDropIndex
	KindReindex
	KindCreateTable
	KindDataChange
	KindProvisioning
	KindCatalogWork
	// KindRenameIndex is ALTER INDEX ... RENAME TO. It names an index, not
	// a table, so it carries the index as its IndexRelation and no table
	// target.
	KindRenameIndex
	// KindAddEnumValue is ALTER TYPE ... ADD VALUE. It names an enum type,
	// not a table, so it carries the type as its EnumType and no table
	// target.
	KindAddEnumValue
)

The kinds the gate distinguishes. Everything the engine does not recognize as one of the named kinds is KindOther and is refused by the front door.

func Kinds added in v0.3.3

func Kinds() []Kind

Kinds returns the closed set of statement kinds, KindOther first. The front door's refusal classification registry walks it to prove every kind it does not admit is classified.

func (Kind) String

func (k Kind) String() string

String returns the human-readable name of the kind.

type Op

type Op struct {
	// Kind is the operation shape.
	Kind OpKind
	// Column is the target column for column operations.
	Column string
	// Name is the constraint or index name where the operation has one,
	// or the new name for renames.
	Name string
	// Only reports that an ALTER TABLE names its table with ONLY, so the
	// operation stops at the table and does not recurse into the tables
	// below it.
	Only bool
	// Cascade reports a drop with CASCADE (DROP COLUMN, DROP CONSTRAINT,
	// or DROP INDEX), which also drops the objects that depend on what it
	// drops, such as a view or another table's foreign key, where the
	// default RESTRICT refuses while any exist.
	Cascade bool
	// Indexes are the unqualified names of the indexes an OpDropIndex
	// drops, in statement order, so a classifier can match each one
	// without parsing Name's display form, or the one index an
	// ADD CONSTRAINT ... USING INDEX takes over.
	Indexes []string
	// Columns are the plain key columns of an ADD PRIMARY KEY / UNIQUE;
	// empty when the keys are expressions.
	Columns []string
	// IncludeColumns are the INCLUDE columns of an ADD PRIMARY KEY /
	// UNIQUE: carried in the index, not part of the key.
	IncludeColumns []string
	// NullsNotDistinct is true for an ADD UNIQUE NULLS NOT DISTINCT, which
	// rejects a second row whose key is NULL.
	NullsNotDistinct bool
	// Deferrable and InitiallyDeferred are an ADD PRIMARY KEY / UNIQUE's
	// DEFERRABLE and INITIALLY DEFERRED: when the uniqueness check runs.
	Deferrable        bool
	InitiallyDeferred bool
	// IndexTablespace is the USING INDEX TABLESPACE of an ADD PRIMARY KEY
	// / UNIQUE: where its index is built.
	IndexTablespace string
	// IndexStorageParams are the WITH (...) storage parameters of an ADD
	// PRIMARY KEY / UNIQUE's index, in statement order.
	IndexStorageParams []StorageParam
	// IndexOptionsUnrenderable is true when an ADD PRIMARY KEY / UNIQUE's
	// WITH (...) carries a parameter IndexStorageParams cannot hold
	// faithfully: one whose value is not a plain word, number, or string,
	// or holds a backslash.
	IndexOptionsUnrenderable bool
	// Constraint is the constraint family for OpAddConstraint.
	Constraint ConstraintKind
	// NotValid is true for ADD CONSTRAINT ... NOT VALID.
	NotValid bool
	// UsingIndex is true for ADD CONSTRAINT ... USING INDEX.
	UsingIndex bool
	// Concurrent is true when the statement carries CONCURRENTLY.
	Concurrent bool
	// Unique is true for CREATE UNIQUE INDEX.
	Unique bool
	// IfNotExists is true for CREATE TABLE IF NOT EXISTS and
	// CREATE INDEX IF NOT EXISTS.
	IfNotExists bool
	// GeneratedStored is true for ADD COLUMN ... GENERATED ... STORED.
	GeneratedStored bool
	// ColumnStorage is true for the OpSetColumnOptions that is ALTER
	// COLUMN ... SET STORAGE, which takes ACCESS EXCLUSIVE where SET
	// STATISTICS and the column's SET / RESET options take SHARE UPDATE
	// EXCLUSIVE.
	ColumnStorage bool
	// RelOptions are the storage parameters an OpSetRelOptions sets or
	// resets, in statement order, each named as written, with its
	// namespace prefix ("toast.autovacuum_enabled") where it has one.
	RelOptions []string
	// InlineConstraints are the table-constraint families an added column
	// carries inline (UNIQUE, PRIMARY KEY, REFERENCES, CHECK) — each does
	// the same index build or validation scan as its ADD CONSTRAINT form.
	// An inline constraint the engine does not model is reported as
	// ConstraintUnrecognized so the classifier can refuse it.
	InlineConstraints []ConstraintKind
	// PartitionOf is true for CREATE TABLE ... PARTITION OF, which locks
	// the partitioned parent, not just the new relation.
	PartitionOf bool
	// Inherits is true for CREATE TABLE ... INHERITS, which locks each
	// named parent — an existing relation, resolved via search_path when
	// unqualified. Disjoint from PartitionOf: the grammar carries the
	// partitioned parent in the same clause, but only PARTITION OF sets a
	// partition bound.
	Inherits bool
	// Like is true for a CREATE TABLE with a LIKE clause, which reads an
	// existing source table — resolved via search_path when unqualified.
	Like bool
	// OfType is true for CREATE TABLE ... OF type, which binds the table
	// to an existing composite type — resolved via search_path when
	// unqualified.
	OfType bool
	// ForeignKey is true for a CREATE TABLE that declares a foreign key, in
	// either the column or the table-constraint form; creating it locks
	// each referenced table in SHARE ROW EXCLUSIVE mode.
	ForeignKey bool
	// Default is the DEFAULT shape for OpAddColumn.
	Default DefaultKind
	// NewType is the target type for OpAlterColumnType and the column type
	// for OpAddColumn, as the bare grammar type name (e.g. "varchar",
	// "numeric") without the pg_catalog qualification.
	NewType string
	// NewTypeMods are the target type's modifiers (e.g. 50 in varchar(50),
	// 12 and 2 in numeric(12,2)); empty when unconstrained.
	NewTypeMods []int32
	// NewTypeSchema is the schema the target type is qualified with, empty
	// when it is unqualified or qualified with pg_catalog. A qualified type
	// is a user type that may share a built-in's name.
	NewTypeSchema string
	// NewTypeArray is true when the target type is an array of NewType
	// (varchar(50)[], text ARRAY).
	NewTypeArray bool
	// NewTypeCollation is the collation the target's COLLATE clause names,
	// as the statement spells it with any schema (C, pg_catalog.C); empty
	// when there is no clause. A collation change rebuilds every index on
	// the column, so a consumer comparing NewType to a live type must not
	// read a collated target as a relabel.
	NewTypeCollation string
	// HasUsing is true for ALTER COLUMN TYPE ... USING <expr>, which always
	// means a conversion, never a binary-coercible relabel.
	HasUsing bool
}

Op is one parsed operation: the shape facts the classifier needs, nothing executable. Fields beyond Kind are populated only where meaningful for that kind; see each field's comment.

func ParseOps

func ParseOps(sql string) ([]Op, error)

ParseOps parses one SQL statement and returns its typed operations. An ALTER TABLE yields one Op per subcommand; every other supported statement yields exactly one. Statements and subcommands the engine does not recognize come back as OpUnrecognized — never an error — so the classifier can refuse them with context. A parse failure is surfaced to the caller.

func (Op) Describe

func (o Op) Describe() string

Describe returns a short operator-facing label for the operation, e.g. "ADD COLUMN age" — for plan rendering, never for branching.

func (Op) TakesShareUpdateExclusiveOnly added in v0.5.0

func (op Op) TakesShareUpdateExclusiveOnly() bool

TakesShareUpdateExclusiveOnly reports an ALTER TABLE operation whose lock on the table is SHARE UPDATE EXCLUSIVE, which blocks neither reads nor writes: VALIDATE CONSTRAINT, SET STATISTICS and a column's SET / RESET options, and SET / RESET of the storage parameters PostgreSQL changes under that lock. SET STORAGE, user_catalog_table, and a parameter not listed here count as blocking.

type OpKind

type OpKind int

OpKind names one operation shape the classifier distinguishes. A single ALTER TABLE statement yields one Op per subcommand; index, rename, and schema statements yield exactly one.

const (
	OpUnrecognized OpKind = iota
	OpCreateTable
	OpAddColumn
	OpDropColumn
	OpAlterColumnType
	OpSetDefault
	OpDropDefault
	OpSetNotNull
	OpDropNotNull
	OpSetColumnOptions
	OpRenameColumn
	OpRenameTable
	OpRenameIndex
	OpSetSchema
	OpSetTablespace
	OpSetRelOptions
	OpAddConstraint
	OpValidateConstraint
	OpDropConstraint
	OpAttachPartition
	OpDetachPartition
	OpCreateIndex
	OpDropIndex
	OpReindex
	OpAddEnumValue
)

The operation shapes ParseOps reports. OpUnrecognized is everything the engine does not recognize; the classifier refuses it.

func OpKinds added in v0.4.0

func OpKinds() []OpKind

OpKinds returns the closed set of operation shapes, OpUnrecognized first. A registry keyed on the operation shape walks it to prove every shape is classified, so a shape added here cannot go unclassified.

type QualifiedName added in v0.4.0

type QualifiedName struct {
	Schema string
	Name   string
}

QualifiedName is a name an expression spells, with the schema it was qualified with or the empty string when the search_path is left to resolve it. For a name of more than two parts the schema is the parts before the last, joined as written.

func (QualifiedName) String added in v0.4.0

func (n QualifiedName) String() string

String renders the name as the expression would spell it.

type RowSecurityChange added in v0.4.0

type RowSecurityChange struct {
	// contains filtered or unexported fields
}

RowSecurityChange is an ordered SQL operation for comparison, not execution authority. Parsing checks statement kinds and one fully qualified target; it does not check privileges, policy dependencies, or whether access widens. It deliberately stays separate from Statement and ordinary native DDL. The PostgreSQL executor must still admit and execute the operation atomically.

func ParseRowSecurityChange added in v0.4.0

func ParseRowSecurityChange(sql string) (RowSecurityChange, error)

ParseRowSecurityChange admits the SQL shapes emitted by a complete atomic RLS replacement: policy drops/creates/comments and RLS settings on one table. The complete script must contain only these statements. Empty input is not a change. This parser does not admit statements to the native executor.

func (RowSecurityChange) CanonicalSQL added in v0.4.0

func (c RowSecurityChange) CanonicalSQL() string

CanonicalSQL preserves order and duplicates for a single operation's comparison key. It preserves physical schema qualifiers, roles, predicates, and comments; namespace mapping is a separate concern. A zero value is not a parsed operation.

func (RowSecurityChange) CanonicalSQLForNamespace added in v0.4.0

func (c RowSecurityChange) CanonicalSQLForNamespace(schema, table string) (string, error)

CanonicalSQLForNamespace omits only the operation's target schema qualifier. The expected physical schema and table must come from the caller’s target configuration, not from this operation. A mismatch refuses normalization. Use it when the comparison key already contains a canonical namespace and table. Qualified policy helpers and all expressions remain unchanged. This is a comparison representation, never executable SQL.

func (RowSecurityChange) Schema added in v0.4.0

func (c RowSecurityChange) Schema() string

Schema returns the physical schema named by every target statement.

func (RowSecurityChange) Statements added in v0.4.0

func (c RowSecurityChange) Statements() []string

Statements returns a copy of the original statements in their original order.

func (RowSecurityChange) Table added in v0.4.0

func (c RowSecurityChange) Table() string

Table returns the table named by every target statement.

type SourceStatement

type SourceStatement struct {
	// SQL is the statement's verbatim source text, without the trailing
	// semicolon, so it can be found in the source by exact match.
	SQL string
	// Line is the 1-based source line of the statement's first token.
	Line int
	// Column is the 1-based source column of the statement's first token.
	Column int
}

SourceStatement is one script statement located in its source: the verbatim text plus the position of its first token, so a consumer can point a finding back at the exact place in the file it came from.

func Split

func Split(sql string) ([]SourceStatement, error)

Split parses a script with the PostgreSQL grammar and returns each statement with its verbatim text and source position, in input order. Every statement is also reprinted through the deparser as a validation gate: a statement the grammar cannot roundtrip is an error, never a guess. An empty script returns no statements; a parse failure anywhere in the script is surfaced to the caller, never guessed around.

type Statement

type Statement struct {
	// contains filtered or unexported fields
}

Statement proves the SQL it carries parsed as exactly one statement through the PostgreSQL grammar — the proof the executor requires before running anything (invariant ST-7). It can only be constructed by ParseOne and carries the facts the gate needs about that one statement.

func ParseOne

func ParseOne(sql string) (Statement, error)

ParseOne parses sql with the PostgreSQL grammar and requires exactly one statement. A parse failure is surfaced to the caller, never guessed around.

func (Statement) AddedEnumValue added in v0.5.1

func (s Statement) AddedEnumValue() string

AddedEnumValue returns the label an ALTER TYPE ... ADD VALUE adds, as the grammar spelled it; empty for every other statement.

func (Statement) BuildsIndex

func (s Statement) BuildsIndex() bool

BuildsIndex reports whether executing the statement creates a new index: every CREATE INDEX, and the ALTER TABLE shapes that build one as a side effect — ADD CONSTRAINT UNIQUE / PRIMARY KEY / EXCLUDE without USING INDEX, and ADD COLUMN with an inline UNIQUE or PRIMARY KEY. The server requires CREATE on the schema for these (the engine-role contract's index build tier), unlike in-place ALTERs — including USING INDEX adoption and rewrites that rebuild existing indexes, which are owner-gated only.

func (Statement) Cascades added in v0.4.0

func (s Statement) Cascades() bool

Cascades reports whether a DROP INDEX used CASCADE, which also drops the objects that depend on the index. It is always false for other statements.

func (Statement) Concurrent

func (s Statement) Concurrent() bool

Concurrent reports whether an index statement used its CONCURRENTLY form. It is always false for non-index kinds.

func (Statement) EnumType added in v0.5.1

func (s Statement) EnumType() TypeName

EnumType returns the enum type an ALTER TYPE ... ADD VALUE adds a value to; the zero value for every other statement.

func (Statement) IndexRelation added in v0.4.0

func (s Statement) IndexRelation() IndexRelation

IndexRelation returns the relation an IndexTargetSingleRelation statement names; the zero value for every other statement, including an IndexTargetOther statement that names one index but whose scope is wider, such as DROP INDEX ... CASCADE (see Cascades()).

func (Statement) IndexTarget added in v0.3.3

func (s Statement) IndexTarget() IndexTarget

IndexTarget returns the typed target shape of an index-maintenance statement.

func (Statement) Kind

func (s Statement) Kind() Kind

Kind returns the statement-type bucket.

func (Statement) RenamedTo added in v0.4.0

func (s Statement) RenamedTo() string

RenamedTo returns the name an ALTER INDEX ... RENAME TO gives its index, as the grammar spelled it; empty for every other statement. The renamed index keeps its schema, so the name is never qualified.

func (Statement) SQL

func (s Statement) SQL() string

SQL returns the original statement text as submitted.

func (Statement) Schema

func (s Statement) Schema() string

Schema returns the target table's schema qualification for ALTER TABLE, CREATE TABLE, and CREATE INDEX statements; empty when the statement was unqualified (search_path resolves it) or when the kind has no single table target.

func (Statement) Table

func (s Statement) Table() string

Table returns the target table name for ALTER TABLE, CREATE TABLE, and CREATE INDEX statements; empty for other kinds.

type StorageParam added in v0.4.0

type StorageParam struct {
	Name     string
	Value    string
	HasValue bool
}

StorageParam is one WITH (...) storage parameter. The server reads every parameter's value as text, so Value holds that text whatever literal spelled it; HasValue is false for a bare name, which the server reads as true.

type TableName added in v0.5.0

type TableName struct {
	Schema string
	Name   string
}

TableName is a table as a statement spells it: its schema qualification, empty when the statement leaves it unqualified, and its name.

func TablesLockedAgainstWrites added in v0.5.0

func TablesLockedAgainstWrites(sql string) ([]TableName, error)

TablesLockedAgainstWrites returns the tables a LOCK TABLE or TRUNCATE statement locks in a mode that blocks writes, each as the statement spells it, and none for any other statement. LOCK TABLE without a mode takes ACCESS EXCLUSIVE, SHARE and every stronger mode block writes, and the weaker modes block neither reads nor writes. TRUNCATE takes ACCESS EXCLUSIVE.

type Transaction added in v0.5.0

type Transaction struct {
	Control TransactionControl
	// Savepoint is the savepoint a TransactionSavepoint,
	// TransactionRelease, or TransactionRollbackTo names.
	Savepoint string
}

Transaction is what one statement does to an explicit transaction block, with the savepoint it names, if any.

func TransactionControlOf added in v0.4.0

func TransactionControlOf(sql string) (Transaction, error)

TransactionControlOf reports what sql, exactly one statement, does to an explicit transaction block.

type TransactionControl added in v0.4.0

type TransactionControl int

TransactionControl is what a statement does to an explicit transaction block, read from the parse tree.

const (
	// TransactionNone: the statement neither opens nor closes a block,
	// and sets no savepoint.
	TransactionNone TransactionControl = iota
	// TransactionBegin: BEGIN or START TRANSACTION opens a block.
	TransactionBegin
	// TransactionEnd: COMMIT, END, ROLLBACK, ABORT, or PREPARE
	// TRANSACTION closes the open block.
	TransactionEnd
	// TransactionChain: COMMIT or ROLLBACK AND CHAIN closes one block and
	// opens the next at once. The script stays inside a block, but the
	// locks the closed block held are released.
	TransactionChain
	// TransactionSavepoint: SAVEPOINT marks a point inside the block.
	TransactionSavepoint
	// TransactionRelease: RELEASE SAVEPOINT forgets a savepoint and every
	// later one; the locks taken since stay held.
	TransactionRelease
	// TransactionRollbackTo: ROLLBACK TO SAVEPOINT undoes the work since
	// a savepoint and releases the locks taken since it; the savepoint
	// stays, and every later one is forgotten.
	TransactionRollbackTo
)

The effects a statement can have on an explicit transaction block.

type TypeName added in v0.5.1

type TypeName struct {
	Schema string
	Name   string
}

TypeName is a type a statement names: its schema as written, empty when the name is unqualified and resolves on the session search_path, and the type's own name.

Jump to

Keyboard shortcuts

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