pgmeta

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package pgmeta reads a PostgreSQL database's catalog, reads and edits rows, and renders schema changes as goose migrations, for the Dev Portal's Table Editor and Schema pages (ADR-0067).

Three rules hold everywhere:

  • Identifiers come from the catalog, never from the request as they are: a column named in a query must exist in the table, and every identifier is quoted with pgx.Identifier.
  • Values travel as parameters, as text the server casts to the column's type, and come back as text (every column is cast to text), so any type round-trips unchanged and nothing is lost to JSON numbers.
  • Schema changes are written, never run directly: Render turns a Plan into a migration file; the app's migrate command applies it.

Catalog queries are adapted from supabase/postgres-meta (Apache-2.0), src/lib/sql/*.sql.ts, without information_schema and with the PostgreSQL 18 catalog changes (NOT NULL constraints in pg_constraint, virtual generated columns) taken into account.

Index

Constants

View Source
const (
	DefaultLimit = 100
	MaxLimit     = 1000
)

Limits of a row query.

View Source
const (
	// ModeRollback runs the script and rolls back: see what it would do.
	ModeRollback = "rollback"
	// ModeCommit runs the script and commits.
	ModeCommit = "commit"
	// ModeReadOnly runs in a read-only transaction: writes fail.
	ModeReadOnly = "readonly"
)

Run modes.

View Source
const (
	// DefaultRunTimeout bounds a script; MaxRunTimeout is the most a
	// request may ask for.
	DefaultRunTimeout = 30 * time.Second
	MaxRunTimeout     = 5 * time.Minute
	// DefaultRowLimit is how many rows of each result set come back
	// without a limit; MaxRowLimit the most.
	DefaultRowLimit = 500
	MaxRowLimit     = 10_000
)

Limits of a run.

Variables

View Source
var (
	// ErrUnknownColumn reports a column a query names that the table lacks.
	ErrUnknownColumn = errors.New("pgmeta: unknown column")
	// ErrUnknownOperator reports a filter operator outside the allowed set.
	ErrUnknownOperator = errors.New("pgmeta: unknown operator")
	// ErrNoPrimaryKey reports an edit on a table without a primary key.
	ErrNoPrimaryKey = errors.New("pgmeta: the table has no primary key, so rows can't be edited")
	// ErrRowCount reports an edit that would touch a different number of
	// rows than expected; nothing is written.
	ErrRowCount = errors.New("pgmeta: the edit would change an unexpected number of rows")
	// ErrNotFound reports a schema or table that doesn't exist.
	ErrNotFound = errors.New("pgmeta: not found")
	// ErrSystemTable reports a schema change on a system or managed table.
	ErrSystemTable = errors.New("pgmeta: the table belongs to a tool or to gorbital; change it with its own migrations")
	// ErrInvalidInput reports a value the server refused for its column, or
	// a malformed request; the message names the problem.
	ErrInvalidInput = errors.New("pgmeta: invalid input")
)

Errors of the package.

View Source
var DefaultManagedPrefixes = []string{
	"auth_", "settings_", "audit_events", "jobs_definition", "release_instances", "flags_",
	"idempotency_keys", "mail_", "observability_", "incidents", "incident_updates", "ratelimit_",
}

DefaultManagedPrefixes are the table name prefixes of gorbital's modules in a Full app: their rows can be edited with a warning, their schema is the framework's.

View Source
var ErrScriptControlsTransaction = errors.New("pgmeta: the script controls its own transaction (BEGIN, COMMIT, ROLLBACK, END); run it in commit mode")

ErrScriptControlsTransaction reports a script with its own transaction control in rollback mode.

Functions

func IsDDL

func IsDDL(script string) bool

IsDDL reports whether script has a statement that changes the schema (ADR-0080). It splits statements as Check does, so a DDL statement hidden inside a dollar-quoted body after a semicolon is missed; the statement that opens the body is not.

func Render

func Render(p Plan) []byte

Render writes a plan as a goose migration file.

Types

type Activity

type Activity struct {
	PID         int     `json:"pid"`
	Application string  `json:"application"`
	State       string  `json:"state"`
	Query       string  `json:"query"`
	DurationMS  float64 `json:"duration_ms"`
	WaitEvent   string  `json:"wait_event,omitempty"`
}

Activity is one session's current statement.

type Advice

type Advice struct {
	// MissingFKIndexes are foreign keys whose referencing columns have no
	// index: deletes and updates on the referenced table scan them.
	MissingFKIndexes []IndexAdvice `json:"missing_fk_indexes"`
	// UnusedIndexes were never scanned since the statistics reset and
	// aren't unique or primary keys.
	UnusedIndexes []IndexAdvice `json:"unused_indexes"`
	// SeqScanned are tables with many rows read mostly by sequential scans.
	SeqScanned []IndexAdvice `json:"seq_scanned"`
	// DeadRows are tables waiting for a vacuum.
	DeadRows []IndexAdvice `json:"dead_rows"`
}

Advice is what the catalog and statistics suggest.

type Cell

type Cell = *string

Cell is one value, as PostgreSQL prints it; nil is NULL.

type Change

type Change struct {
	// Kind: create_table, drop_table, rename_table, add_column, drop_column,
	// rename_column, alter_column, add_foreign_key, add_unique, add_check,
	// drop_constraint, set_primary_key, create_index, drop_index, create_enum,
	// add_enum_value, rename_enum_value, drop_enum, comment, rls,
	// create_extension, drop_extension, create_function, drop_function,
	// create_trigger, drop_trigger, create_view, drop_view.
	Kind   string `json:"kind"`
	Schema string `json:"schema"`
	Table  string `json:"table,omitempty"`
	// NewName: rename_table, rename_column (with Column.Name the old one),
	// rename_enum_value (with Value the old one).
	NewName string `json:"new_name,omitempty"`
	// Columns: create_table. Column: add_column, drop_column (Name),
	// rename_column (Name), alter_column (the target state; unset fields
	// keep their value), comment on a column (Name).
	Columns []ColumnSpec `json:"columns,omitempty"`
	Column  *ColumnSpec  `json:"column,omitempty"`
	// Constraints: create_table's table-level unique constraints
	// (Columns each) and foreign keys.
	Uniques     [][]string `json:"uniques,omitempty"`
	ForeignKeys []FKSpec   `json:"foreign_keys,omitempty"`
	// ForeignKey: add_foreign_key. Unique: add_unique. Check: add_check
	// (with Name optional). ConstraintName: drop_constraint. PrimaryKey:
	// set_primary_key.
	ForeignKey     *FKSpec  `json:"foreign_key,omitempty"`
	Unique         []string `json:"unique,omitempty"`
	Check          string   `json:"check,omitempty"`
	Name           string   `json:"name,omitempty"`
	ConstraintName string   `json:"constraint_name,omitempty"`
	PrimaryKey     []string `json:"primary_key,omitempty"`
	// Index: create_index; IndexName: drop_index.
	Index     *IndexSpec `json:"index,omitempty"`
	IndexName string     `json:"index_name,omitempty"`
	// Enum: create_enum (Name, Values), add_enum_value (Name, Value, After),
	// rename_enum_value (Name, Value, NewName).
	Values []string `json:"values,omitempty"`
	Value  string   `json:"value,omitempty"`
	After  string   `json:"after,omitempty"`
	// Comment: comment (on the table, or Column.Name).
	Comment *string `json:"comment,omitempty"`
	// Enabled, Forced: rls.
	Enabled *bool `json:"enabled,omitempty"`
	Forced  *bool `json:"forced,omitempty"`
	// Cascade allows drop_table and drop_column to cascade.
	Cascade bool `json:"cascade,omitempty"`
	// Definition: create_function (the whole CREATE FUNCTION statement),
	// create_trigger (the whole CREATE TRIGGER statement), create_view (the
	// SELECT the view is defined as). Signature: drop_function and the Down
	// of create_function, as "name(argument types)" from the catalog's
	// identity_args. Materialized: create_view and drop_view.
	Definition   string `json:"definition,omitempty"`
	Signature    string `json:"signature,omitempty"`
	Materialized bool   `json:"materialized,omitempty"`
}

Change is one schema change. Kind says which fields apply.

type Client

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

Client reads and edits one database. It is safe for concurrent use.

func Open

func Open(ctx context.Context, url string) (*Client, error)

Open connects to url with a small pool for the portal: two connections, UTC, and statement timeouts set per query.

func (*Client) Advise

func (c *Client) Advise(ctx context.Context) (Advice, error)

Advise reads the statistics for index suggestions.

func (*Client) Close

func (c *Client) Close()

Close releases the connections.

func (*Client) Columns

func (c *Client) Columns(ctx context.Context, schema, table string) ([]Column, error)

Columns lists a relation's columns.

func (*Client) Constraints

func (c *Client) Constraints(ctx context.Context, tableID int64) ([]Constraint, error)

Constraints lists a relation's constraints, by its ID.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, e RowEdit) (int64, error)

Delete removes the rows Keys name and returns how many it removed. It refuses, writing nothing, when a key matches no row.

func (*Client) Detail

func (c *Client) Detail(ctx context.Context, schema, table string) (TableDetail, error)

Detail returns everything about one relation, read in one snapshot.

func (*Client) Enums

func (c *Client) Enums(ctx context.Context, schemas []string) ([]Enum, error)

Enums lists the enumerated types of schemas.

func (*Client) Explain

func (c *Client) Explain(ctx context.Context, sql string, analyze bool) (json.RawMessage, error)

Explain returns the plan of one statement as EXPLAIN (FORMAT JSON) prints it; with analyze it runs the statement in a rolled-back transaction.

func (*Client) Extensions

func (c *Client) Extensions(ctx context.Context) ([]Extension, error)

Extensions lists the available extensions, installed ones first.

func (*Client) ForeignKeys

func (c *Client) ForeignKeys(ctx context.Context, schemas []string) ([]ForeignKey, error)

ForeignKeys lists every foreign key of schemas, for the schema graph.

func (*Client) Functions

func (c *Client) Functions(ctx context.Context, schemas []string) ([]Function, error)

Functions lists the functions of schemas.

func (*Client) Indexes

func (c *Client) Indexes(ctx context.Context, tableID int64) ([]Index, error)

Indexes lists a relation's indexes, by its ID.

func (*Client) Insert

func (c *Client) Insert(ctx context.Context, e RowEdit) ([]Cell, error)

Insert adds one row and returns it as stored.

func (*Client) InsertMany

func (c *Client) InsertMany(ctx context.Context, schema, table string, rows []map[string]Cell) (int64, error)

InsertMany adds rows in one transaction: every row's Values, in the order given, or nothing. It returns how many it added. CSV imports use it in batches.

func (*Client) Migrations

func (c *Client) Migrations(ctx context.Context, dir string) ([]Migration, error)

Migrations lists the files under dir/db/migrations with their state in goose's version table, oldest first. Files goose doesn't know are pending; versions in the table without a file are listed with an empty path.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks the connection.

func (*Client) Plan

func (c *Client) Plan(ctx context.Context, ch Change) (Plan, error)

Plan renders a change as SQL against the database as it is now: the change is validated (names, types, that the table is the app's own), and the Down side comes from the current definitions.

func (*Client) Query

func (c *Client) Query(ctx context.Context, q RowQuery) (RowPage, error)

Query returns a page of rows and a count.

func (*Client) ResetStatements

func (c *Client) ResetStatements(ctx context.Context) error

ResetStatements forgets pg_stat_statements' counters.

func (*Client) Run

func (c *Client) Run(ctx context.Context, req RunRequest) (RunResult, error)

Run runs a script in one transaction.

func (*Client) Schemas

func (c *Client) Schemas(ctx context.Context) ([]Schema, error)

Schemas lists every schema, system ones flagged.

func (*Client) ServerVersion

func (c *Client) ServerVersion(ctx context.Context) (int, error)

ServerVersion returns the server's version number, such as 180001.

func (*Client) Statements

func (c *Client) Statements(ctx context.Context, sort string, limit int) (Statements, error)

Statements reads pg_stat_statements for the current database, sorted by sort (total_time, mean_time, calls, rows, max_time), at most limit.

func (*Client) Stats

func (c *Client) Stats(ctx context.Context) (DatabaseStats, error)

Stats reads the database's statistics.

func (*Client) Tables

func (c *Client) Tables(ctx context.Context, schemas []string) ([]Table, error)

Tables lists the relations of schemas, with their ownership.

func (*Client) Triggers

func (c *Client) Triggers(ctx context.Context, tableID int64) ([]Trigger, error)

Triggers lists a relation's triggers, by its ID.

func (*Client) Types

func (c *Client) Types(ctx context.Context, schemas []string) ([]TypeOption, error)

Types returns the type picker: the built-in types and the enums of schemas.

func (*Client) Update

func (c *Client) Update(ctx context.Context, e RowEdit) ([]Cell, error)

Update changes the columns in Values of the one row Keys[0] names and returns it as stored.

func (*Client) Views

func (c *Client) Views(ctx context.Context, schemas []string) ([]View, error)

Views lists the views and materialized views of schemas.

type ClientUse

type ClientUse struct {
	Application string `json:"application"`
	State       string `json:"state"`
	Count       int    `json:"count"`
}

ClientUse is one application's connections in one state.

type Column

type Column struct {
	Ordinal int32  `json:"ordinal"`
	Name    string `json:"name"`
	// DataType is the SQL type as format_type prints it, such as
	// "character varying(100)" or "integer[]".
	DataType   string `json:"data_type"`
	TypeName   string `json:"type_name"`
	TypeSchema string `json:"type_schema"`
	IsArray    bool   `json:"is_array"`
	// EnumValues are the allowed values when the type (or the array's
	// element type) is an enum.
	EnumValues []string `json:"enum_values,omitempty"`
	IsNullable bool     `json:"is_nullable"`
	// DefaultExpr is the DEFAULT expression, if any; GenerationExpr the
	// expression of a generated column.
	DefaultExpr    *string `json:"default_expr"`
	GenerationExpr *string `json:"generation_expr"`
	// Identity is "" (none), "a" (ALWAYS) or "d" (BY DEFAULT); Generated
	// is "" (no), "s" (STORED) or "v" (VIRTUAL, PostgreSQL 18).
	Identity     string  `json:"identity"`
	Generated    string  `json:"generated"`
	Comment      *string `json:"comment"`
	IsPrimaryKey bool    `json:"is_primary_key"`
	IsUnique     bool    `json:"is_unique"`
	// FKTargets are the tables the column references, as "schema.table".
	FKTargets []string `json:"fk_targets,omitempty"`
}

Column is one column of a relation.

type ColumnSpec

type ColumnSpec struct {
	Name string `json:"name"`
	// Type is a picker name (int8, text, timestamptz, numeric(10,2),
	// varchar(100)…) or an enum as schema.name.
	Type  string `json:"type"`
	Array bool   `json:"array,omitempty"`
	// Nullable defaults to true for added columns.
	Nullable *bool `json:"nullable,omitempty"`
	// Default is a literal, or an expression when DefaultIsExpr (now(),
	// gen_random_uuid()).
	Default       *string `json:"default,omitempty"`
	DefaultIsExpr bool    `json:"default_is_expr,omitempty"`
	// Identity is "", "always" or "by_default".
	Identity   string  `json:"identity,omitempty"`
	PrimaryKey bool    `json:"primary_key,omitempty"`
	Unique     bool    `json:"unique,omitempty"`
	Check      string  `json:"check,omitempty"`
	Comment    string  `json:"comment,omitempty"`
	References *FKSpec `json:"references,omitempty"`
}

ColumnSpec describes a column to create or the target of an alteration.

type Constraint

type Constraint struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	// Type is p (primary key), u (unique), f (foreign key), c (check) or x
	// (exclusion).
	Type string `json:"type"`
	// Definition is the constraint as pg_get_constraintdef prints it.
	Definition string   `json:"definition"`
	Deferrable bool     `json:"deferrable"`
	Deferred   bool     `json:"deferred"`
	Validated  bool     `json:"validated"`
	Columns    []string `json:"columns"`
	// The referenced table and columns of a foreign key.
	RefSchema  *string  `json:"ref_schema"`
	RefTable   *string  `json:"ref_table"`
	RefColumns []string `json:"ref_columns,omitempty"`
	OnDelete   *string  `json:"on_delete"`
	OnUpdate   *string  `json:"on_update"`
}

Constraint is a primary key, unique, foreign key, check or exclusion constraint.

type DatabaseStats

type DatabaseStats struct {
	Database string `json:"database"`
	Version  string `json:"version"`
	// Size of the database in bytes.
	Size int64 `json:"size"`
	// Connections against max_connections, by application and state.
	Connections    int         `json:"connections"`
	MaxConnections int         `json:"max_connections"`
	Clients        []ClientUse `json:"clients"`
	// CacheHitRatio is shared buffer hits over reads, 0 to 1, since the
	// statistics were last reset; IndexHitRatio the same for indexes.
	CacheHitRatio float64 `json:"cache_hit_ratio"`
	IndexHitRatio float64 `json:"index_hit_ratio"`
	// Transactions committed and rolled back since the reset.
	Commits   int64 `json:"commits"`
	Rollbacks int64 `json:"rollbacks"`
	Deadlocks int64 `json:"deadlocks"`
	TempBytes int64 `json:"temp_bytes"`
	// StatsSince is when the database's statistics were reset.
	StatsSince *time.Time `json:"stats_since"`
	// Tables by total size, largest first (at most 50).
	Tables []RelationSize `json:"tables"`
	// Locks are the sessions waiting on a lock, with what they wait for.
	Locks []LockWait `json:"locks"`
	// LongRunning are sessions in a statement for more than a second.
	LongRunning []Activity `json:"long_running"`
}

DatabaseStats is the database's health at a glance (ADR-0073): who is connected, how well the cache serves reads, what takes space, and what waits.

type Enum

type Enum struct {
	ID      int64    `json:"id"`
	Schema  string   `json:"schema"`
	Name    string   `json:"name"`
	Values  []string `json:"values"`
	Comment *string  `json:"comment"`
}

Enum is an enumerated type.

type Extension

type Extension struct {
	Name             string  `json:"name"`
	DefaultVersion   *string `json:"default_version"`
	InstalledVersion *string `json:"installed_version"`
	Schema           *string `json:"schema"`
	Comment          *string `json:"comment"`
	Installed        bool    `json:"installed"`
}

Extension is an available or installed extension.

type FKSpec

type FKSpec struct {
	Name       string   `json:"name,omitempty"`
	Columns    []string `json:"columns"`
	RefSchema  string   `json:"ref_schema"`
	RefTable   string   `json:"ref_table"`
	RefColumns []string `json:"ref_columns"`
	// OnDelete and OnUpdate are NO ACTION, RESTRICT, CASCADE, SET NULL or
	// SET DEFAULT; empty means NO ACTION.
	OnDelete string `json:"on_delete,omitempty"`
	OnUpdate string `json:"on_update,omitempty"`
}

FKSpec describes a foreign key.

type Filter

type Filter struct {
	Column string `json:"column"`
	// Operator is one of = <> > < >= <= ~~ ~~* in is.
	Operator string `json:"operator"`
	// Value is the operand as text; for "in", a list; for "is", one of
	// null, not null, true, false.
	Value  string   `json:"value,omitempty"`
	Values []string `json:"values,omitempty"`
}

Filter is one condition of a row query.

type ForeignKey

type ForeignKey struct {
	Name       string   `json:"name"`
	Schema     string   `json:"schema"`
	Table      string   `json:"table"`
	Columns    []string `json:"columns"`
	RefSchema  string   `json:"ref_schema"`
	RefTable   string   `json:"ref_table"`
	RefColumns []string `json:"ref_columns"`
	OnDelete   string   `json:"on_delete"`
	OnUpdate   string   `json:"on_update"`
}

ForeignKey is one edge of the schema graph.

type Function

type Function struct {
	ID       int64  `json:"id"`
	Schema   string `json:"schema"`
	Name     string `json:"name"`
	Language string `json:"language"`
	Kind     string `json:"kind"`
	// Args is the argument list for display; IdentityArgs the one DROP
	// FUNCTION needs.
	Args         string  `json:"args"`
	IdentityArgs string  `json:"identity_args"`
	ReturnType   *string `json:"return_type"`
	ReturnsSet   bool    `json:"returns_set"`
	Volatility   string  `json:"volatility"`
	// SecurityDefiner reports a function that runs with its owner's rights.
	SecurityDefiner bool `json:"security_definer"`
	// Definition is the whole CREATE FUNCTION statement, for functions and
	// procedures in languages other than internal.
	Definition    *string `json:"definition"`
	Comment       *string `json:"comment"`
	FromExtension bool    `json:"from_extension"`
}

Function is a function, procedure, aggregate or window function.

type Index

type Index struct {
	ID         int64      `json:"id"`
	Name       string     `json:"name"`
	Definition string     `json:"definition"`
	Method     string     `json:"method"`
	IsUnique   bool       `json:"is_unique"`
	IsPrimary  bool       `json:"is_primary"`
	IsValid    bool       `json:"is_valid"`
	IsPartial  bool       `json:"is_partial"`
	Columns    []string   `json:"columns"`
	Bytes      int64      `json:"bytes"`
	Scans      int64      `json:"scans"`
	LastScan   *time.Time `json:"last_scan"`
}

Index is one index of a relation.

type IndexAdvice

type IndexAdvice struct {
	Schema  string   `json:"schema"`
	Table   string   `json:"table"`
	Index   string   `json:"index,omitempty"`
	Columns []string `json:"columns,omitempty"`
	// Reason says why, with the numbers; SQL is what to run, when there
	// is something to run.
	Reason string `json:"reason"`
	SQL    string `json:"sql,omitempty"`
	Size   int64  `json:"size,omitempty"`
}

IndexAdvice is one suggestion.

type IndexSpec

type IndexSpec struct {
	Name string `json:"name,omitempty"`
	// Columns are column names or expressions in parentheses.
	Columns      []string `json:"columns"`
	Unique       bool     `json:"unique,omitempty"`
	Method       string   `json:"method,omitempty"`
	Where        string   `json:"where,omitempty"`
	Concurrently bool     `json:"concurrently,omitempty"`
}

IndexSpec describes an index.

type LockWait

type LockWait struct {
	PID         int    `json:"pid"`
	Application string `json:"application"`
	Waiting     string `json:"waiting"` // the waiting statement
	LockType    string `json:"lock_type"`
	Mode        string `json:"mode"`
	Relation    string `json:"relation,omitempty"`
	BlockedBy   []int  `json:"blocked_by"`
	WaitingFor  string `json:"waiting_for_ms"`
}

LockWait is a session waiting for a lock another session holds.

type Migration

type Migration struct {
	Version int64  `json:"version"`
	Name    string `json:"name"`
	// Path is the file relative to the app.
	Path      string     `json:"path"`
	SQL       string     `json:"sql"`
	Applied   bool       `json:"applied"`
	AppliedAt *time.Time `json:"applied_at"`
	// HasDown reports a Down section, so the file can be rolled back.
	HasDown bool `json:"has_down"`
}

Migration is one file under db/migrations and whether the database has it, for the Migrations page (ADR-0069).

type Ownership

type Ownership string

Ownership says who may change a table from the portal.

const (
	// OwnershipUser: the app's own table; rows and schema can be edited.
	OwnershipUser Ownership = "user"
	// OwnershipManaged: a gorbital module's table; rows can be edited with
	// a warning, the schema belongs to the framework's migrations.
	OwnershipManaged Ownership = "managed"
	// OwnershipSystem: a tool's or extension's table; read-only.
	OwnershipSystem Ownership = "system"
)

Ownerships.

type Plan

type Plan struct {
	// Summary is one line for the migration's first comment and its name.
	Summary string   `json:"summary"`
	Up      []string `json:"up"`
	Down    []string `json:"down"`
	// Irreversible reports a change with no complete Down (data loss, an
	// enum value); Notes say why, and go into the file as comments.
	Irreversible bool     `json:"irreversible"`
	Notes        []string `json:"notes,omitempty"`
	// NoTransaction marks a file goose must run outside a transaction
	// (CREATE INDEX CONCURRENTLY).
	NoTransaction bool `json:"no_transaction,omitempty"`
}

Plan is a schema change rendered as SQL: the statements to run, the statements that undo them, and what can't be undone.

type RelationSize

type RelationSize struct {
	Schema  string `json:"schema"`
	Name    string `json:"name"`
	Total   int64  `json:"total"`
	Table   int64  `json:"table"`
	Indexes int64  `json:"indexes"`
	Toast   int64  `json:"toast"`
	// Rows is the planner's estimate.
	Rows int64 `json:"rows"`
	// SeqScans and IndexScans since the statistics reset; DeadRows waits
	// for vacuum.
	SeqScans   int64      `json:"seq_scans"`
	IndexScans int64      `json:"index_scans"`
	DeadRows   int64      `json:"dead_rows"`
	LastVacuum *time.Time `json:"last_vacuum"`
}

RelationSize is a table's size.

type RowEdit

type RowEdit struct {
	Schema string `json:"schema"`
	Table  string `json:"table"`
	// Values are the columns to write (Insert and Update).
	Values map[string]Cell `json:"values,omitempty"`
	// Keys are the primary keys of the rows to change (Update: exactly
	// one; Delete: one or more), each as column → value.
	Keys []map[string]Cell `json:"keys,omitempty"`
}

RowEdit identifies and changes rows of one table. Values are text as PostgreSQL would print them; a nil value is NULL. Keys identify rows by every primary key column.

type RowPage

type RowPage struct {
	Columns []Column `json:"columns"`
	// PrimaryKey names the key columns; empty when rows can't be edited.
	PrimaryKey []string `json:"primary_key"`
	Rows       [][]Cell `json:"rows"`
	// Count is the number of matching rows; Estimated says it comes from
	// the planner rather than count(*).
	Count     int64 `json:"count"`
	Estimated bool  `json:"estimated"`
	Limit     int   `json:"limit"`
	Offset    int   `json:"offset"`
}

RowPage is the answer to a RowQuery.

type RowQuery

type RowQuery struct {
	Schema  string   `json:"schema"`
	Table   string   `json:"table"`
	Filters []Filter `json:"filters,omitempty"`
	Sorts   []Sort   `json:"sorts,omitempty"`
	Limit   int      `json:"limit"`
	Offset  int      `json:"offset"`
}

RowQuery selects rows of one table.

type RunError

type RunError struct {
	Message string `json:"message"`
	Code    string `json:"code,omitempty"`
	Detail  string `json:"detail,omitempty"`
	Hint    string `json:"hint,omitempty"`
	// Position is the 1-based byte offset in the script; Line the line.
	Position int `json:"position,omitempty"`
	Line     int `json:"line,omitempty"`
}

RunError is the server's error for a script, with where it happened.

type RunRequest

type RunRequest struct {
	SQL  string `json:"sql"`
	Mode string `json:"mode,omitempty"`
	// RowLimit caps the rows of each result set (DefaultRowLimit, at most
	// MaxRowLimit); 0 means the default.
	RowLimit int `json:"row_limit,omitempty"`
	// TimeoutSeconds bounds the script (DefaultRunTimeout, at most
	// MaxRunTimeout).
	TimeoutSeconds int `json:"timeout_seconds,omitempty"`
}

RunRequest is a script to run.

type RunResult

type RunResult struct {
	Mode       string            `json:"mode"`
	Statements []StatementResult `json:"statements"`
	Error      *RunError         `json:"error,omitempty"`
	// Committed reports the transaction was committed; RolledBack that it
	// was rolled back (by the mode, or because of the error).
	Committed  bool    `json:"committed"`
	RolledBack bool    `json:"rolled_back"`
	DurationMS float64 `json:"duration_ms"`
	// Warnings are what Check found before the run.
	Warnings []Warning `json:"warnings,omitempty"`
}

RunResult is a script's outcome.

type Schema

type Schema struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Owner string `json:"owner"`
	// Comment is the schema's comment, if any.
	Comment *string `json:"comment"`
	// System reports pg_catalog, information_schema and pg_* schemas.
	System        bool `json:"system"`
	HasExtensions bool `json:"has_extensions"`
}

Schema is a namespace.

type Sort

type Sort struct {
	Column     string `json:"column"`
	Descending bool   `json:"descending"`
	NullsFirst bool   `json:"nulls_first"`
}

Sort is one ORDER BY term.

type Statement

type Statement struct {
	QueryID int64  `json:"query_id"`
	Query   string `json:"query"`
	Calls   int64  `json:"calls"`
	// Times in milliseconds.
	TotalMS  float64 `json:"total_ms"`
	MeanMS   float64 `json:"mean_ms"`
	MinMS    float64 `json:"min_ms"`
	MaxMS    float64 `json:"max_ms"`
	StddevMS float64 `json:"stddev_ms"`
	Rows     int64   `json:"rows"`
	// HitRatio is shared buffer hits over reads for the statement.
	HitRatio float64 `json:"hit_ratio"`
	// TotalShare is the statement's share of every statement's total time.
	TotalShare float64 `json:"total_share"`
}

Statement is one entry of pg_stat_statements.

type StatementResult

type StatementResult struct {
	// Command is the command tag, such as SELECT 3 or UPDATE 1.
	Command string `json:"command"`
	// Columns and Rows are the result set, when the statement returns one;
	// Truncated reports rows beyond the limit were dropped.
	Columns      []string `json:"columns,omitempty"`
	Rows         [][]Cell `json:"rows,omitempty"`
	RowsAffected int64    `json:"rows_affected"`
	Truncated    bool     `json:"truncated,omitempty"`
}

StatementResult is one statement's outcome.

type Statements

type Statements struct {
	// Available reports pg_stat_statements loaded; Reason says why not.
	Available bool   `json:"available"`
	Reason    string `json:"reason,omitempty"`
	// Since is when the statistics were last reset.
	Since      *time.Time  `json:"since"`
	Statements []Statement `json:"statements"`
	Sort       string      `json:"sort"`
}

Statements is the answer to a statements request.

type Table

type Table struct {
	ID     int64  `json:"id"`
	Schema string `json:"schema"`
	Name   string `json:"name"`
	// Kind is table, partitioned_table, view, materialized_view or
	// foreign_table.
	Kind        string `json:"kind"`
	IsPartition bool   `json:"is_partition"`
	RLSEnabled  bool   `json:"rls_enabled"`
	RLSForced   bool   `json:"rls_forced"`
	// RowEstimate is the planner's estimate (0 when never analysed);
	// LiveRows is the statistics collector's count.
	RowEstimate int64 `json:"row_estimate"`
	LiveRows    int64 `json:"live_rows"`
	Bytes       int64 `json:"bytes"`
	// Size is Bytes for humans, such as "48 kB".
	Size    string  `json:"size"`
	Comment *string `json:"comment"`
	Owner   string  `json:"owner"`
	// FromExtension reports a table an extension owns.
	FromExtension bool      `json:"from_extension"`
	Ownership     Ownership `json:"ownership" db:"-"`
}

Table is a relation: a table, partitioned table, view, materialized view or foreign table.

type TableDetail

type TableDetail struct {
	Table       Table        `json:"table"`
	Columns     []Column     `json:"columns"`
	Constraints []Constraint `json:"constraints"`
	Indexes     []Index      `json:"indexes"`
	Triggers    []Trigger    `json:"triggers"`
	// PrimaryKey lists the primary key's columns, in order; empty when the
	// table has none (its rows can't be edited).
	PrimaryKey []string `json:"primary_key"`
}

TableDetail is everything the Table Editor shows about one relation.

type Template

type Template struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	SQL         string `json:"sql"`
	// Needs names an extension the template needs, if any.
	Needs string `json:"needs,omitempty"`
}

Template is a ready-made query.

func Templates

func Templates() []Template

Templates returns the built-in queries.

type Trigger

type Trigger struct {
	ID         int64  `json:"id"`
	Name       string `json:"name"`
	Definition string `json:"definition"`
	// Enabled is origin, disabled, replica or always.
	Enabled string `json:"enabled"`
	// Timing is BEFORE, AFTER or INSTEAD OF; Orientation ROW or STATEMENT.
	Timing         string   `json:"timing"`
	Orientation    string   `json:"orientation"`
	Events         []string `json:"events"`
	FunctionSchema string   `json:"function_schema"`
	FunctionName   string   `json:"function_name"`
}

Trigger is one trigger of a relation.

type TypeOption

type TypeOption struct {
	Name        string   `json:"name"`
	SQL         string   `json:"sql"`
	Group       string   `json:"group"`
	Description string   `json:"description"`
	Suggestions []string `json:"suggestions,omitempty"`
	// EnumValues are the values of an enum type.
	EnumValues []string `json:"enum_values,omitempty"`
}

TypeOption is one entry of the type picker.

type View

type View struct {
	ID             int64   `json:"id"`
	Schema         string  `json:"schema"`
	Name           string  `json:"name"`
	IsMaterialized bool    `json:"is_materialized"`
	Definition     string  `json:"definition"`
	IsUpdatable    bool    `json:"is_updatable"`
	IsPopulated    *bool   `json:"is_populated"`
	Comment        *string `json:"comment"`
}

View is a view or materialized view.

type Warning

type Warning struct {
	// Kind: drop, truncate, delete_without_where, update_without_where,
	// drop_column, alter_type.
	Kind    string `json:"kind"`
	Message string `json:"message"`
	// Line is where the statement starts.
	Line int `json:"line"`
}

Warning is something Check found in a script.

func Check

func Check(script string) []Warning

Check finds statements a developer should confirm before running: drops, truncates, deletes and updates without WHERE, dropped columns and type changes. It splits on semicolons outside strings and comments, so it misses dollar-quoted bodies; it is a warning, not a guard.

Jump to

Keyboard shortcuts

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