schema

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 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

schema

Layers schema.sql over the bootstrap catalog. Parsed with libpg_query (pg_query_go).

  • Load(sql) → *Schema: relations (tables / views / matviews / composite types) with columns, constraints (PK / UNIQUE / FK / CHECK, unique indexes incl. partial), user types (enum labels, domain checks, composites + their array and row types with synthetic OIDs from 16384), function signatures, COMMENT ON
  • Expression bodies (view queries, DEFAULT, CHECK, generated) stay as AST for the analyzer
  • Types.Format reproduces format_type() spelling; Types.BaseOf flattens domains the way PG's wire protocol does
  • ddl.go: partitions and INHERITS (parent columns / constraints copied), LIKE ... INCLUDING, RENAME (relations, columns, constraints, types, functions, triggers), DROP, ALTER TABLE DROP COLUMN / CONSTRAINT and the no-op actions, ALTER TYPE ADD / RENAME VALUE, ALTER DOMAIN, CREATE TYPE AS RANGE (+ multirange), CREATE COLLATION (COLLATE names are validated against built-ins, declarations and locale-style names), CREATE AGGREGATE / OPERATOR / CAST (resolved like catalog ones), SET search_path (lookup order and where unqualified CREATE lands), interval field / precision typmods
  • seed.go: INSERT ... VALUES into a table records its rows as Relation.Seed (a lookup table's fixed content, keyed by the PK or a NOT NULL unique constraint the rows give as constants); non-idempotent INSERTs (no key, volatile values, DEFAULT, ON CONFLICT, duplicate keys, differing column lists) are Problems, and the analyzer type-checks each INSERT through CheckStatement. -- sqlshape: seed marks the rows additive
  • Unsupported DDL lands in Problems with a byte offset; loading never aborts on it
  • TestAgainstOracle boots real PG on the same file and diffs every table's columns

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

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

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

View Source
var ErrNeedsReload = errors.New("schema: statement needs a full reload")

ErrNeedsReload is Apply's answer to DDL that only Load can take.

View Source
var PartitionKeyProblem func(s *Schema, rel *Relation, expr *pgparse.Node) string

PartitionKeyProblem checks one PARTITION BY expression against the table (the analyzer installs it): the message PG would give, or "" when the expression is acceptable.

View Source
var QueryColumns func(s *Schema, query *pgparse.Node) ([]*Column, error)

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 AddWaiver added in v1.1.0

func AddWaiver(m map[string][]string, table string, specs ...string) map[string][]string

AddWaiver appends specs to the table's waivers.

func ColumnRefs

func ColumnRefs(e Expr) []string

ColumnRefs lists the distinct unqualified column names an expression references, in order.

func DeclaredVersion added in v1.2.0

func DeclaredVersion(schemaSQL string) (pgparse.Version, error)

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

func Deparse(e Expr) string

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

func DeparseBody(body Expr) string

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

func DeparseStmt(n *pgparse.Node) string

DeparseStmt renders a whole statement (a view's query, a rule) back to SQL text.

func NumericTypmod

func NumericTypmod(m int32) (precision, scale int32, ok bool)

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

func ReadSource(path string) (string, error)

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

func Waivers(list string) map[string][]string

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 ("*").

func WalkNodes

func WalkNodes(m proto.Message, f func(*pgparse.Node))

WalkNodes visits every Node in a protobuf tree.

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 Expr

type Expr = *pgparse.Node

Expr is an unanalyzed expression from the DDL (kept as libpg_query AST).

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 Problem

type Problem struct {
	Location int32 // byte offset into the source, 0 if unknown
	Message  string
}

Problem is a DDL statement (or part) that was skipped or rejected.

func (Problem) String

func (p Problem) String() string

type RaisedError

type RaisedError struct {
	Code string
	Name string
}

RaisedError is a custom SQLSTATE a function raises, with its application-side name.

type RelKind

type RelKind byte

RelKind distinguishes tables from views.

const (
	Table    RelKind = 'r'
	View     RelKind = 'v'
	MatView  RelKind = 'm'
	Sequence RelKind = 'S'
)

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) Column

func (r *Relation) Column(name string) *Column

Column finds a column by name.

func (*Relation) FullName

func (r *Relation) FullName() string

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

func (rel *Relation) InheritsFrom(anc *Relation) bool

InheritsFrom reports whether rel is anc or descends from it.

func (*Relation) Policy

func (r *Relation) Policy(name string) *Policy

Policy finds a policy by name.

func (*Relation) Rules

func (rel *Relation) Rules() map[string]RuleDef

Rules returns the relation's rules by name (CREATE RULE, minus DROP RULE).

type RuleDef

type RuleDef struct {
	Stmt    *pgparse.RuleStmt
	Enabled bool
}

RuleDef is one rule of a relation as declared, with whether it is enabled.

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 Load

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

Load parses schemaSQL and builds the Schema over the embedded bootstrap catalog.

func LoadWith

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

LoadWith is Load with an explicit catalog.

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

func (s *Schema) Apply(schemaSQL string) error

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

func (s *Schema) DateTimeSettings() (dateOrder, intervalStyle, timeZone string)

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

func (s *Schema) DependentViews(rel *Relation) []*Relation

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) Function

func (s *Schema) Function(schema, name string) *Function

Function finds a user function by (schema, name); schema "" means public.

func (*Schema) HasSchema

func (s *Schema) HasSchema(name string) bool

HasSchema is whether a schema of that name exists: built in, created with CREATE SCHEMA, or holding an object.

func (*Schema) KnownCollation

func (s *Schema) KnownCollation(name string) bool

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

func (s *Schema) OnSearchPath(schema string) bool

OnSearchPath reports whether an unqualified name may resolve into schema.

func (*Schema) Relation

func (s *Schema) Relation(schema, name string) *Relation

Relation finds a table or view by (schema, name); schema "" means public.

func (*Schema) ResolveType

func (s *Schema) ResolveType(tn *pgparse.TypeName) (TypeRef, error)

ResolveType resolves a TypeName AST node against this schema (exported for the analyzer).

func (*Schema) Schemas

func (s *Schema) Schemas() []string

Schemas lists the names created with CREATE SCHEMA, sorted.

func (*Schema) SearchPath

func (s *Schema) SearchPath() []string

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

func (s *Schema) ViewsRestricted() bool

ViewsRestricted reports SET restrict_nonsystem_relation_kind = view: user views may not be accessed.

func (*Schema) XMLOptionDocument

func (s *Schema) XMLOptionDocument() bool

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.

func (*Seed) ByKey

func (sd *Seed) ByKey() map[string][]Expr

ByKey indexes the rows by KeyText.

func (*Seed) KeyText

func (sd *Seed) KeyText(row []Expr) string

KeyText renders the key of a row for identity comparison.

func (*Seed) RowText

func (sd *Seed) RowText(row []Expr) string

RowText renders a whole row for comparison.

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 TypeRef

type TypeRef struct {
	OID    catalog.OID
	Typmod int32
}

TypeRef is a resolved type: an OID in the Types universe plus a typmod.

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) ArrayOf

func (ts *Types) ArrayOf(elem catalog.OID) catalog.OID

ArrayOf returns the array type over elem, or 0 if none exists.

func (*Types) BaseOf

func (ts *Types) BaseOf(r TypeRef) TypeRef

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) ByOID

func (ts *Types) ByOID(oid catalog.OID) *catalog.Type

ByOID finds a type in the catalog or among user types.

func (*Types) Format

func (ts *Types) Format(r TypeRef) string

Format renders a TypeRef the way PostgreSQL's format_type() does (the oracle's golden files use this spelling).

func (*Types) Lookup

func (ts *Types) Lookup(schema, name string) *catalog.Type

Lookup resolves a possibly qualified type name against the search path (public, pg_catalog).

func (*Types) RangeForSubtype

func (ts *Types) RangeForSubtype(sub catalog.OID) *catalog.Range

RangeForSubtype is the (first) range type over sub.

func (*Types) RangeOf

func (ts *Types) RangeOf(rng catalog.OID) *catalog.Range

RangeOf is the pg_range row of a range type, user-defined or catalog.

func (*Types) RangeOfMulti

func (ts *Types) RangeOfMulti(multi catalog.OID) *catalog.Range

RangeOfMulti is the pg_range row of a multirange type.

func (*Types) User

func (ts *Types) User() []*catalog.Type

User lists the types declared by the schema text (CREATE TYPE / DOMAIN and the row types of relations), in declaration order.

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).

Jump to

Keyboard shortcuts

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