postgres

package
v1.163.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 58 Imported by: 0

Documentation

Overview

Package postgres provides the application database connection kind (appdb): an application's own PostgreSQL database, which the scripts and endpoints an application is built from read and write (#2400, #2428).

It is not a data source and registers no agent tool. Trino is the platform's analytical engine and holds no transaction, row lock or enforced constraint; this kind is an application's operational store. The script host calls Query (one statement in a READ ONLY transaction) and Execute (one statement committed in a transaction of its own) directly, for platform.query and platform.execute, so an application's request path pays no tool call per statement.

Parameters are bound natively by the driver (jackc/pgx/v5) and never rendered into the SQL text, and a PostgreSQL error's DETAIL, which can repeat a value, goes to the script alone (direct.go).

Index

Constants

View Source
const (
	// Kind is the connection-instance kind discriminator. Operators see it in
	// the admin UI's connection picker.
	Kind = "appdb"

	// DefaultPort is PostgreSQL's port.
	DefaultPort = 5432

	// DefaultMaxConns is the pool size per replica when none is configured.
	DefaultMaxConns = 5
	// MaxMaxConns is the largest pool a connection may ask for per replica.
	MaxMaxConns = 100
	// DefaultStatementTimeout bounds one statement when the caller names no
	// timeout of their own.
	DefaultStatementTimeout = 30 * time.Second
	// MaxStatementTimeout is the most a connection's statement timeout, or a
	// caller's timeout_seconds, may be.
	MaxStatementTimeout = 10 * time.Minute
	// DefaultMaxRows is the row cap of one result when none is configured.
	DefaultMaxRows = 1000
	// MaxMaxRows is the largest row cap a connection may set.
	MaxMaxRows = 100000
	// DefaultConnectTimeout bounds the dial and the TLS handshake.
	DefaultConnectTimeout = 10 * time.Second
	// DefaultPoolWait is how long a statement waits for a free connection
	// from its pool before it fails naming the pool (#2402).
	DefaultPoolWait = 5 * time.Second
	// MaxPoolWait is the most pool_wait_timeout may be.
	MaxPoolWait = time.Minute
	// DefaultTransactionIdle is how long a script's transaction may sit with
	// no statement before it is rolled back (#2402).
	DefaultTransactionIdle = 10 * time.Second
	// MaxTransactionIdle is the most transaction_idle_timeout may be.
	MaxTransactionIdle = 10 * time.Minute

	// DefaultLedgerSchema is the schema in the target database that holds
	// the ledger of applied migrations (#2404).
	DefaultLedgerSchema = "mcp_schema"
)
View Source
const (
	SSLModeDisable    = "disable"
	SSLModeRequire    = "require"
	SSLModeVerifyCA   = "verify-ca"
	SSLModeVerifyFull = "verify-full"
)

The TLS modes a connection takes, as libpq names them. The default is verify-full: a database reached over a network the platform does not own is otherwise one DNS answer away from a stranger holding the password.

View Source
const (

	// CfgKeyPersonaRoles maps a persona to the login role its statements run
	// as (#2403).
	CfgKeyPersonaRoles = "persona_roles"
	// CfgKeyPersonaRolePasswords maps a persona to its role's password. Its
	// values are encrypted at rest and redacted on read by the nested-map key
	// set pkg/platform/fieldcrypt holds.
	CfgKeyPersonaRolePasswords = "persona_role_passwords" // #nosec G101 -- a config key, not a credential
)

Config keys a postgres connection is stored under. The TLS keys are the ones the HTTP-based kinds use (internal/apigwtls), so the client key is encrypted at rest by the key set pkg/platform/fieldcrypt already holds and redacted on read by the same rule.

View Source
const (
	CopyFormatCSV  = "csv"
	CopyFormatText = "text"
)

The formats copy_out writes.

View Source
const (
	CodeUnknownConnection = "unknown_connection"
	CodeReadOnly          = "read_only_connection"
	CodeInvalidStatement  = "invalid_statement"
	CodeStatementFailed   = "statement_failed"
	CodeUnavailable       = "database_unavailable"
	CodePoolWait          = "pool_wait_timeout"
	CodeTransactionEnded  = "transaction_ended"
)

Error codes a direct statement is refused with.

View Source
const (
	CodeSchemaDrift = "schema_drift"
	CodeApplyLocked = "migration_locked"
)

Error codes a schema command is refused with.

View Source
const (
	SourceEndpoint = "endpoint"
	SourceScript   = "script"
)

The values Identity.Source takes.

View Source
const (
	EventAdded    = "added"
	EventEdited   = "edited"
	EventApplied  = "applied"
	EventReverted = "reverted"
	EventFailed   = "failed"
)

The events a migration's history records.

View Source
const (
	StateApplied = "applied"
	StatePending = "pending"
	StateDrift   = "drift"
)

The states a migration is reported in.

View Source
const (
	// TestSweepLockKey is the platform-database advisory lock the sweep holds.
	TestSweepLockKey int64 = 4713210601
	// DefaultTestSweepInterval is how often the sweep runs.
	DefaultTestSweepInterval = 10 * time.Minute
	// DefaultTestMaxAge is how old a build or clone is before the sweep
	// drops it: far longer than any test runs.
	DefaultTestMaxAge = time.Hour
)

The sweep of throwaway databases a dead script test left behind (#2407). Every replica runs it; an advisory lock on the platform's database lets one sweep at a time.

View Source
const (
	EnvTestSweepInterval = "MCP_PLATFORM_APPDB_TEST_SWEEP_INTERVAL"
	EnvTestMaxAge        = "MCP_PLATFORM_APPDB_TEST_MAX_AGE"
)

The environment the sweep reads, beside the other MCP_PLATFORM_* operational knobs.

View Source
const (
	// CodeCreateDBRequired is a test server whose user lacks CREATEDB.
	CodeCreateDBRequired = "createdb_required"
	// CodeFromZeroFailed is a migration set that does not apply from zero.
	CodeFromZeroFailed = "migration_from_zero_failed"
)

Codes a throwaway database is refused with.

View Source
const (
	IsolationReadCommitted  = "read_committed"
	IsolationRepeatableRead = "repeatable_read"
	IsolationSerializable   = "serializable"
)

The isolation levels a script's transaction takes.

View Source
const CodeApplyNotAllowed = "apply_not_allowed"

CodeApplyNotAllowed refuses an apply to a caller without the grant.

View Source
const CodeMigrationApplied = "migration_applied"

CodeMigrationApplied refuses a change to an applied migration.

View Source
const CodeStatementRefused = "statement_refused"

CodeStatementRefused refuses a migration holding a statement that needs a privilege an application's role must not hold, or reaches outside the database (#2449).

View Source
const CodeSummaryRequired = "summary_required"

CodeSummaryRequired refuses a migration that removes data without an agreed summary of what it removes.

View Source
const ConfigSchemaJSON = `` /* 4637-byte string literal not displayed */

ConfigSchemaJSON declares what a postgres connection's config takes. See the same constant on the trino kind for why a kind declares this at all (#1805).

View Source
const DefaultSchema = "public"

DefaultSchema is the namespace a migration belongs to when none is named.

View Source
const MaxBatch = 1000

MaxBatch is the most statements one batch may carry.

View Source
const MaxParams = 1000

MaxParams is the most parameters one statement may bind. PostgreSQL's own limit is 65535; a statement binding more than this is not one a script author wrote.

View Source
const MinServerMajor = 17

MinServerMajor is the oldest PostgreSQL major an application database may be on (#2447). A connection to an older server is refused when it is saved, when it is tested and on every physical connection its pool opens, so a connection configured in a file is held to it as one saved through the admin API is.

View Source
const OutboxTemplateName = "outbox"

OutboxTemplateName is the manage_schema add template that writes an outbox.

View Source
const SchemaToolName = "manage_schema"

SchemaToolName is the one agent tool this kind registers (#2404): the versioned migrations an application database's schema is built from. It is part of building an application, not a data tool, and acts only on connections of this kind.

Variables

View Source
var (
	// ErrConnectionExists is returned when AddConnection names a connection
	// already registered.
	ErrConnectionExists = errors.New("postgres: connection already exists")
	// ErrConnectionNotFound is returned for a connection that is not
	// registered.
	ErrConnectionNotFound = errors.New("postgres: connection not found")
)

Errors the connection registry answers with.

View Source
var ErrNoMigrationStore = errors.New("appdb: this deployment keeps no migrations")

ErrNoMigrationStore is returned where the deployment keeps no migrations.

View Source
var ErrPlatformDatabase = errors.New("postgres: this connection reaches the platform's own database, which is never a connection target")

ErrPlatformDatabase refuses a connection that reached the platform's own database. A script with platform.execute there could rewrite personas, grants and the audit log.

View Source
var SecretKeys = []string{cfgKeyPassword}

SecretKeys are the configuration keys a postgres connection may name a stored secret in as {{secret:<name>}}. The value is read as the connection's pool is built (internal/connsecretref lists the same keys).

Functions

func ChecksumOf

func ChecksumOf(up, down string, transactional bool) string

ChecksumOf is a migration's checksum: what it runs up and down, and whether it runs in a transaction.

func Compare

func Compare(migrations []Migration, applied []Applied) (pending []Migration, drift []Drift)

Compare reads the ledger against the platform's migrations: the ones still to apply, in version order, and every disagreement. A migration the ledger holds with another checksum was changed after it was applied (or the ledger was edited by hand); a version the ledger holds that the platform does not was applied by something else.

func HeadOf

func HeadOf(migrations []Migration) string

HeadOf is the hash naming a migration set's template: each migration's schema, version and checksum.

func NameClash

func NameClash(kind, name string, held func(kind string) bool) string

NameClash refuses a name an application database and a Trino connection would share, and returns "" for any other save. A script's platform.query names its connection alone and goes to the application database of that name, so a Trino connection sharing it would be out of every script's reach (#2428). held reports whether a connection of the given kind holds the name.

func OutboxChannel

func OutboxChannel(schema, table string) string

OutboxChannel is the channel an outbox's trigger notifies and its webhook source listens on: the table's qualified name.

func OutboxIdentifier

func OutboxIdentifier(name string) (string, error)

OutboxIdentifier is an outbox table, named "schema.table", as SQL: its two identifiers checked and quoted. It refuses a name whose channel PostgreSQL would not take.

func OutboxTemplate

func OutboxTemplate(schema, table string, capture []string, notify bool) (up, down string, err error)

OutboxTemplate is the migration that creates an outbox table in schema, the trigger function that writes a changed row to it and, when notify is set, notifies its channel, and a trigger on each table in capture (a bare name is in schema). down removes the triggers, the function and the table.

func WithIdentity

func WithIdentity(ctx context.Context, id Identity) context.Context

WithIdentity returns ctx carrying who its statements run for.

Types

type Applied

type Applied struct {
	Version    int       `json:"version"`
	Name       string    `json:"name"`
	Checksum   string    `json:"checksum"`
	AppliedAt  time.Time `json:"applied_at"`
	AppliedBy  string    `json:"applied_by"`
	DurationMS int64     `json:"duration_ms"`
}

Applied is one row of the target's ledger.

type ApplyOptions

type ApplyOptions struct {
	Connection, Schema string
	// Actor is who applies, recorded in the ledger.
	Actor string
	// Timeout bounds each statement of a migration; zero is the
	// connection's statement timeout.
	Timeout time.Duration
	// OnDone is told each migration as it is applied or reverted, with how
	// long it took, or why it failed.
	OnDone func(m Migration, took time.Duration, err error)
	// UpTo stops an apply at this version; nil applies everything pending.
	UpTo *int
	// MarkOnly writes each migration's ledger row without running it: a
	// baseline adopted from a schema that already exists (#2406).
	MarkOnly bool
}

ApplyOptions is one apply or revert.

type AvailableExtension

type AvailableExtension struct {
	Name           string `json:"name"`
	DefaultVersion string `json:"default_version"`
	Comment        string `json:"comment,omitempty"`
}

AvailableExtension is an extension the server offers that the database has not installed.

type Column

type Column struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

Column is one result column: its name and the type PostgreSQL gave it.

type Config

type Config struct {
	// ConnectionName is the name a tool's connection argument binds, set from
	// the instance name.
	ConnectionName string
	// Description is what list_connections and the admin UI show under the
	// name. Empty is shown as nothing.
	Description string

	Host     string
	Port     int
	Database string
	User     string
	// Password is the database user's password. It may be a
	// {{secret:<name>}} reference, which the platform fills before the
	// connection is parsed (internal/connsecretref).
	Password string

	SSLMode       string
	CABundlePEM   string
	ClientCertPEM string
	ClientKeyPEM  string

	// MaxConns is the pool size on each replica.
	MaxConns int
	// StatementTimeout is the default bound of one statement.
	StatementTimeout time.Duration
	// MaxRows caps the rows one result returns.
	MaxRows int
	// ReadOnly refuses platform.execute on this connection for every script.
	ReadOnly bool
	// StatementCache keeps each statement prepared on the physical
	// connection that first ran it, so it is described once rather than on
	// every call (#2402). Off for PgBouncer in transaction mode, which hands
	// a session's statements to whichever server connection is free.
	StatementCache bool
	// PoolWait is how long a statement waits for a free pooled connection
	// before it fails naming the pool.
	PoolWait time.Duration
	// TransactionIdle is how long a script's transaction may go without a
	// statement before it is rolled back.
	TransactionIdle time.Duration
	// IterMaxRows is the most rows one platform.query_iter loop reads before
	// it ends with an error naming the bound (#2454).
	IterMaxRows int64
	// CopyMaxRows and CopyMaxBytes bound one copy_in or copy_out call
	// (#2453); a copy_in past either is refused before its first row is sent.
	CopyMaxRows  int64
	CopyMaxBytes int64
	// SchemaApplyPersonas are the personas that may apply and revert this
	// connection's migrations (#2404). Empty is administrators only.
	SchemaApplyPersonas []string
	// LedgerSchema is the schema in the target database holding the ledger
	// of applied migrations.
	LedgerSchema string
	// TestConnection names the application database whose server the
	// throwaway databases of this connection's migration checks and script
	// tests are created on (#2407). Empty is this connection itself. Its
	// user needs CREATEDB.
	TestConnection string
	// PersonaRoles maps a persona to the database login role a statement
	// for it runs as (#2403). A persona it does not name runs as User.
	PersonaRoles map[string]string
	// PersonaRolePasswords maps a persona to its role's password; each may
	// be a {{secret:<name>}} reference.
	PersonaRolePasswords map[string]string
}

Config is one PostgreSQL connection.

func ParseConfig

func ParseConfig(cfg map[string]any) (Config, error)

ParseConfig reads a Config from the map a connection is stored as, applies the defaults and validates it.

func (Config) Validate

func (c Config) Validate() error

Validate refuses a configuration the toolkit could not open, or one whose bounds no operator intends.

type ConnectGuard

type ConnectGuard func(ctx context.Context, conn *pgx.Conn) error

ConnectGuard is asked about every physical connection a pool opens, before the connection serves a statement. A non-nil error closes the connection and fails the call that needed it. The platform's guard refuses a connection that reached the platform's own database (ownguard.go).

func OwnDatabaseGuard

func OwnDatabaseGuard(platform *sql.DB) ConnectGuard

OwnDatabaseGuard is the ConnectGuard that refuses a connection to the platform's own database, platform. It takes a random advisory lock on the platform's database for the length of one question, asks the connection whether it can see that lock in its own database, and releases it.

Comparing host, port and database name is not enough: a DNS alias, an address instead of a name, or a connection pooler in front of the same server all name the platform's database differently. The lock is the database's own answer.

The guard runs on every physical connection a pool opens, so a connection saved while the platform's database was unreachable, or whose host name is later pointed at it, is refused at its first statement rather than trusted from its save. A failure to take the lock or to ask is a refusal: the guard cannot say the connection is safe.

type ConnectionStore added in v1.162.2

type ConnectionStore interface {
	// GetConnection returns the stored configuration of one appdb
	// connection, reporting a name it does not hold with an error
	// satisfying ErrConnectionNotFound.
	GetConnection(ctx context.Context, name string) (map[string]any, error)
}

ConnectionStore reads the connections an operator saved. The platform wires its database-backed store, narrowed to this kind; a deployment that keeps connections in its configuration file alone wires none.

type Constraint

type Constraint struct {
	Name       string `json:"name"`
	Kind       string `json:"kind"`
	Definition string `json:"definition"`
}

Constraint is a primary key, unique, foreign key, check or exclusion constraint, as PostgreSQL writes its definition.

type CopyIn

type CopyIn struct {
	Connection string
	// Table is the table, schema-qualified or not ("orders",
	// "shop.orders"). It and Columns are quoted as identifiers, never
	// written into the statement as given.
	Table   string
	Columns []string
	// Rows are the values, each row in Columns' order, in the JSON forms a
	// bound parameter takes.
	Rows [][]any
}

CopyIn is one copy_in call (#2453): rows written into a table's columns through PostgreSQL's COPY protocol.

type CopyOutResult

type CopyOutResult struct {
	Rows    int64
	Bytes   int64
	Columns []Column
}

CopyOutResult is what one copy_out wrote.

type Cursor

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

Cursor reads one query's result in pages from a server-side cursor (#2454), so a script processes a result larger than max_rows holding one page at a time. It is declared in the script's transaction (tx.query_iter) or in a READ ONLY transaction of its own (platform.query_iter), which it ends when it closes.

func (*Cursor) Close

func (k *Cursor) Close()

Close closes the cursor, and ends the transaction it opened for itself. Closing a closed cursor does nothing.

func (*Cursor) Columns

func (k *Cursor) Columns() []Column

Columns is the result's columns, known once the cursor is declared.

func (*Cursor) Next

func (k *Cursor) Next(ctx context.Context) (page *Result, done bool, err error)

Next reads the next page. done is true when the result has no rows after this page; a page past iter_max_rows is refused.

type Description

type Description struct {
	Server              Server               `json:"server"`
	Extensions          []Extension          `json:"extensions"`
	AvailableExtensions []AvailableExtension `json:"available_extensions"`
	Tables              []Table              `json:"tables"`
	Functions           []Function           `json:"functions"`
	Enums               []Enum               `json:"enums"`
	Domains             []Domain             `json:"domains"`
}

Description is what describe reports of one schema: the server, the database's extensions, and every object the applied migrations produced. An empty list is [], never null.

type Domain

type Domain struct {
	Name     string   `json:"name"`
	BaseType string   `json:"base_type"`
	Nullable bool     `json:"nullable"`
	Default  string   `json:"default,omitempty"`
	Checks   []string `json:"checks"`
}

Domain is a domain over a base type and its checks.

type Drift

type Drift struct {
	Version int    `json:"version"`
	Reason  string `json:"reason"`
}

Drift is a disagreement between the ledger and the migrations the platform holds, which stops an apply.

type Enum

type Enum struct {
	Name   string   `json:"name"`
	Values []string `json:"values"`
}

Enum is an enum type and its values in their order.

type Extension

type Extension struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Schema  string `json:"schema"`
}

Extension is an extension installed in the database.

type FailedError

type FailedError struct {
	Code string
	// Summary is the value-free account of the failure, and the error's text.
	Summary   string
	Statement *StatementError
}

FailedError is a statement the database refused or could not run. Error() is the value-free summary (the SQLSTATE and the objects the server named), which is what a run's error, its audit record and the logs may carry. Statement holds what the server said, DETAIL included, which can repeat a bound value and so is handed to the script alone.

func (*FailedError) CallerText

func (e *FailedError) CallerText() string

CallerText is the server's own account of the failure, DETAIL and HINT included, for the script that ran the statement and nothing else.

func (*FailedError) Error

func (e *FailedError) Error() string

Error implements error.

type Function

type Function struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
	Returns   string `json:"returns,omitempty"`
	// Kind is function or procedure.
	Kind     string `json:"kind"`
	Language string `json:"language"`
	// Volatility is immutable, stable or volatile.
	Volatility      string `json:"volatility"`
	SecurityDefiner bool   `json:"security_definer"`
	// SearchPath is the search_path the function pins with SET, empty when
	// it pins none.
	SearchPath string `json:"search_path,omitempty"`
	Body       string `json:"body"`
}

Function is a function or a procedure.

type Identity

type Identity struct {
	// Persona chooses the login role: the one persona_roles maps it to, or
	// the connection's user when it maps none. It is also mcp.persona.
	Persona string
	// UserID and Email are mcp.user_id and mcp.email: an authenticated
	// endpoint's caller, or the author of the script a run executes.
	UserID string
	Email  string
	// Source is mcp.source: "endpoint" for an endpoint request, "script" for
	// a run.
	Source string
	// Application is the application whose run role the statement logs in as
	// (#2539): set when the script running it is a part of an application
	// holding a schema on the statement's connection. It wins over Persona's
	// role, and is not a claim.
	Application string
}

Identity is who a statement runs for (#2403): the persona whose login role the statement runs as, and the caller claims every transaction sets. The script host puts it on the context of each call (WithIdentity); a context without one runs as the connection's own role with every claim empty.

func IdentityOf

func IdentityOf(ctx context.Context) Identity

IdentityOf is the identity on ctx, the zero value when none.

type IterLimitError

type IterLimitError struct {
	Connection string
	Limit      int64
}

IterLimitError is a loop that read past the connection's iter_max_rows.

func (*IterLimitError) Error

func (e *IterLimitError) Error() string

type LedgerStatus

type LedgerStatus struct {
	Applied []Applied
	Pending []Migration
	Drift   []Drift
}

LedgerStatus is what the ledger records, what is pending, and where the two disagree, for one connection and schema.

type Listener

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

Listener is a connection of its own listening on channels, outside the connection's pool and as the connection's role. It is not safe for concurrent use: one goroutine waits on it.

func (*Listener) Close

func (l *Listener) Close()

Close ends the listener's connection.

func (*Listener) Wait

func (l *Listener) Wait(ctx context.Context) (Notification, error)

Wait blocks until a notification arrives or ctx ends.

type Lock

type Lock struct {
	Relation string `json:"relation"`
	Mode     string `json:"mode"`
}

Lock is a relation lock a planned migration took.

type Migration

type Migration struct {
	Connection string `json:"connection"`
	// Schema is the namespace the migration belongs to and runs in: its
	// search_path, created when the first migration applies.
	Schema  string `json:"schema"`
	Version int    `json:"version"`
	Name    string `json:"name"`
	Up      string `json:"up"`
	Down    string `json:"down,omitempty"`
	// Transactional is false for a migration holding a statement that cannot
	// run in a transaction (CREATE INDEX CONCURRENTLY), which runs alone.
	Transactional bool      `json:"transactional"`
	Checksum      string    `json:"checksum"`
	Author        string    `json:"author,omitempty"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

Migration is one versioned change to an application database's schema (#2404): the SQL that moves it up and, optionally, back down. The platform keeps it; the target's ledger records that it was applied.

type MigrationEvent

type MigrationEvent struct {
	Connection string    `json:"connection"`
	Schema     string    `json:"schema"`
	Version    int       `json:"version"`
	Event      string    `json:"event"`
	Actor      string    `json:"actor,omitempty"`
	Checksum   string    `json:"checksum,omitempty"`
	DurationMS int64     `json:"duration_ms"`
	Detail     string    `json:"detail,omitempty"`
	At         time.Time `json:"at"`
}

MigrationEvent is one entry of a migration's history.

type MigrationState

type MigrationState struct {
	Migration
	// State is applied, pending or drift.
	State     string     `json:"state"`
	AppliedAt *time.Time `json:"applied_at,omitempty"`
	AppliedBy string     `json:"applied_by,omitempty"`
}

MigrationState is one migration with where it stands in the target, for the portal's connection page.

type MigrationStore

type MigrationStore interface {
	// List is every migration of a connection's schema, oldest version first.
	// An empty schema is every schema of the connection, in schema order.
	List(ctx context.Context, connection, schema string) ([]Migration, error)
	// Put adds a migration or replaces a pending one, reporting whether it
	// replaced one.
	Put(ctx context.Context, m Migration) (replaced bool, err error)
	// Record appends to a migration's history.
	Record(ctx context.Context, e MigrationEvent) error
	// Events is a schema's history, newest first.
	Events(ctx context.Context, connection, schema string, limit int) ([]MigrationEvent, error)
}

MigrationStore keeps the migrations and their history in the platform's database.

type MultiConfig

type MultiConfig struct {
	DefaultName string
	Instances   map[string]Config
}

MultiConfig is every configured instance of the kind.

func ParseMultiConfig

func ParseMultiConfig(defaultName string, raw map[string]map[string]any) (MultiConfig, error)

ParseMultiConfig parses every instance. An instance that does not parse is logged and skipped, so one misconfigured connection cannot block startup.

type Notification

type Notification struct {
	Channel string
	Payload string
	// PID is the server process that sent it.
	PID uint32
}

Notification is one notification a listener received.

type OutboxRow

type OutboxRow struct {
	ID int64
	// Table is the schema-qualified table whose change wrote the row.
	Table string
	// Op is the change: INSERT, UPDATE or DELETE.
	Op string
	// Payload is the row as JSON: the new row, or the old one for a DELETE.
	Payload   string
	CreatedAt time.Time
}

OutboxRow is one row of an outbox table.

type Partition

type Partition struct {
	Name  string `json:"name"`
	Bound string `json:"bound"`
}

Partition is one partition of a partitioned table and its bound.

type Plan

type Plan struct {
	// Migrations are the versions planned, in order.
	Migrations []int `json:"migrations"`
	// Changed are the relations and columns the migrations created or
	// altered, read from the system catalog rows the transaction wrote.
	Changed []string `json:"changed"`
	// Locks are the relation locks the transaction held at its end, with
	// their modes: the locks the apply takes.
	Locks []Lock `json:"locks"`
	// Unplanned are migrations that run outside a transaction, which cannot
	// be rolled back and so are not planned.
	Unplanned []int `json:"unplanned"`
}

Plan is what applying the pending migrations would do.

type Policy

type Policy struct {
	Name string `json:"name"`
	// Command is ALL, SELECT, INSERT, UPDATE or DELETE.
	Command string   `json:"command"`
	Roles   []string `json:"roles"`
	// Permissive is false on a restrictive policy.
	Permissive bool   `json:"permissive"`
	Using      string `json:"using,omitempty"`
	WithCheck  string `json:"with_check,omitempty"`
}

Policy is a row-level security policy on a table.

type RefusedError

type RefusedError struct {
	// Code is the platform error code a script branches on.
	Code string
	// contains filtered or unexported fields
}

RefusedError is the toolkit's refusal of a statement before or instead of the database's answer: an unknown connection, a write on a read_only connection, params that do not fit the statement. Its text names no bound value.

func (*RefusedError) Error

func (e *RefusedError) Error() string

Error implements error.

type Result

type Result struct {
	Connection string
	// Command is the command tag's first word: SELECT, INSERT, UPDATE.
	Command      string
	RowsAffected int64
	Columns      []Column
	Rows         [][]any
	// Truncated is whether the statement returned more rows than Limit.
	Truncated bool
	Limit     int
}

Result is what a statement returned.

type SchemaReport

type SchemaReport struct {
	Connection     string           `json:"connection"`
	Schema         string           `json:"schema"`
	Ledger         string           `json:"ledger"`
	CurrentVersion int              `json:"current_version"`
	Migrations     []MigrationState `json:"migrations"`
	Drift          []Drift          `json:"drift"`
	Events         []MigrationEvent `json:"events"`
	// Application is the application holding the schema, empty for none
	// (#2539). UnheldSchemas is every schema of the connection with
	// migrations that no application holds, whose migrations are refused
	// until one does. UnheldSchemas is absent when the platform governs no
	// schema, and [] when it does and every schema is held.
	Application   string          `json:"application"`
	UnheldSchemas *[]unheldSchema `json:"unheld_schemas,omitempty"`
}

SchemaReport is a connection schema's migrations, what the ledger says of each, and the history.

type ScriptReferences

type ScriptReferences func(ctx context.Context, connection string, names []string) (map[string][]string, error)

ScriptReferences finds the saved scripts that name each of names in the statements they run on connection, by name.

type Server

type Server struct {
	Major   int    `json:"major"`
	Version string `json:"version"`
}

Server is the server's version: Major is what the version rules of a migration's review are read against.

type Statement

type Statement struct {
	Connection string
	// SQL is one statement. Placeholders are $1, $2, ... when Params is a
	// list and @name when it is a map.
	SQL string
	// Params are the values bound to the placeholders: a []any binds $n in
	// order, a map[string]any binds @name. Values are JSON-compatible (string,
	// json.Number or a Go number, bool, nil, []any, map[string]any) and are
	// read by the type PostgreSQL gives each parameter.
	Params any
	// Limit caps the rows read; zero or more than the connection's max_rows
	// is the connection's max_rows.
	Limit int
	// TimeoutSeconds lowers the connection's statement_timeout for this
	// statement; zero keeps it.
	TimeoutSeconds int
}

Statement is one statement a script or an endpoint runs on an application database (#2428). The script host calls the toolkit directly rather than through an MCP tool: an application's request path runs many statements and cannot pay a tool call, its middleware and an audit row for each.

type StatementError

type StatementError struct {
	SQLState   string `json:"sqlstate"`
	Condition  string `json:"condition,omitempty"`
	Message    string `json:"message"`
	Detail     string `json:"detail,omitempty"`
	Hint       string `json:"hint,omitempty"`
	Where      string `json:"where,omitempty"`
	Schema     string `json:"schema,omitempty"`
	Table      string `json:"table,omitempty"`
	Column     string `json:"column,omitempty"`
	Constraint string `json:"constraint,omitempty"`
	DataType   string `json:"data_type,omitempty"`
	Position   int32  `json:"position,omitempty"`
	// Statement is the index of the failed statement in a statements list.
	Statement *int `json:"statement,omitempty"`
}

StatementError is a PostgreSQL error as the caller reads it: everything the server said about the failure, under the field names its protocol uses.

It is returned to the caller alone. Message, Detail, Hint and Where can repeat a value from the data or from a bound parameter ("Key (email)=(...) already exists", "invalid input syntax for type integer: \"...\""), so none of them reaches the result's first text block, which is what the audit row's error text, the reflexive capture and the logs read: those carry Summary, built from the SQLSTATE and the names of the objects involved.

type Table

type Table struct {
	Name string `json:"name"`
	// Kind is table, partitioned_table, view or materialized_view.
	Kind        string        `json:"kind"`
	Comment     string        `json:"comment,omitempty"`
	Columns     []TableColumn `json:"columns"`
	Constraints []Constraint  `json:"constraints"`
	Indexes     []TableIndex  `json:"indexes"`
	// RowSecurity and ForceRowSecurity are the table's row-level security:
	// enabled, and applied to its owner as well (#2447).
	RowSecurity      bool        `json:"row_security"`
	ForceRowSecurity bool        `json:"force_row_security"`
	Policies         []Policy    `json:"policies"`
	Triggers         []Trigger   `json:"triggers"`
	PartitionKey     string      `json:"partition_key,omitempty"`
	Partitions       []Partition `json:"partitions"`
	// View is a view's or materialized view's definition.
	View *View `json:"view,omitempty"`
}

Table is one relation of an application's schema as describe reports it (#2404): what the applied migrations produced, read from the target's pg_catalog.

type TableColumn

type TableColumn struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Nullable bool   `json:"nullable"`
	Default  string `json:"default,omitempty"`
	Comment  string `json:"comment,omitempty"`
}

TableColumn is one column.

type TableIndex

type TableIndex struct {
	Name       string `json:"name"`
	Definition string `json:"definition"`
}

TableIndex is one index, as PostgreSQL writes its definition.

type TestDB

type TestDB struct {
	*Toolkit
	// Database is the clone's name.
	Database string
	// contains filtered or unexported fields
}

TestDB is a clone a script test runs against: a toolkit serving one connection, under the original connection's name, on the clone.

func (*TestDB) Close

func (d *TestDB) Close()

Close rolls back what the test left open, closes the pool and drops the clone.

type Toolkit

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

Toolkit is the postgres toolkit. One Toolkit serves every registered PostgreSQL connection, each with a pool of its own on each replica.

func NewMulti

func NewMulti(cfg MultiConfig) *Toolkit

NewMulti builds the toolkit from every configured instance. Building a pool opens no connection, so an unreachable database does not hold up startup; a connection that cannot be built (its TLS material does not load) is logged and skipped.

func (*Toolkit) AddConnection

func (t *Toolkit) AddConnection(name string, config map[string]any) error

AddConnection implements toolkit.ConnectionManager.

func (*Toolkit) Apply

func (t *Toolkit) Apply(ctx context.Context, o ApplyOptions, migrations []Migration) ([]Migration, error)

Apply applies the pending migrations in version order, each in a transaction of its own that also writes its ledger row, so a migration that fails leaves neither a partial change nor a row. An advisory lock in the target database is held for the whole apply, so two replicas or two callers never apply at once: the second waits, then finds nothing pending. A migration that is not transactional runs alone, outside a transaction.

migrations is everything the platform holds for the schema; the ledger is read again under the lock and compared with it, and any drift stops the apply before a migration runs.

func (*Toolkit) ApplyPersonas

func (t *Toolkit) ApplyPersonas(connection string) []string

ApplyPersonas are the personas connection's schema_apply_personas names, which may apply its migrations and maintain it (#2410).

func (*Toolkit) Batch

func (t *Toolkit) Batch(ctx context.Context, connection string, stmts []Statement) ([]*Result, error)

Batch runs statements on a connection pipelined in one transaction of their own, which commits only when every statement in it succeeded (#2402). On a read_only connection the transaction is READ ONLY and rolled back.

func (*Toolkit) Begin

func (t *Toolkit) Begin(ctx context.Context, o TxOptions) (*Tx, error)

Begin opens a transaction on an application database. ctx is the run's: the transaction is rolled back when it ends.

func (*Toolkit) CheckFromZero

func (t *Toolkit) CheckFromZero(ctx context.Context, connection, schema string, migrations []Migration) error

CheckFromZero builds the template of one schema's migrations, every one the schema would hold, which applies each of them from zero on a new database. The template is kept: once the migrations save it is the head a test of that schema clones.

func (*Toolkit) CheckOutbox

func (t *Toolkit) CheckOutbox(ctx context.Context, connection, table string) error

CheckOutbox refuses an outbox table that does not exist on connection, or that the connection's role cannot read and delete from, which a drain does.

func (*Toolkit) Close

func (t *Toolkit) Close() error

Close rolls back every transaction in progress and closes every pool.

func (*Toolkit) Connection

func (t *Toolkit) Connection() string

Connection implements registry.Toolkit: the default connection's name.

func (*Toolkit) ConnectionRoles

func (t *Toolkit) ConnectionRoles(connection string) []string

ConnectionRoles are the login roles connection's statements run as: its own user and each persona's role, sorted. A backend of another role is not the platform's to cancel or terminate (#2410). Nil for an unknown connection.

func (*Toolkit) CopyIn

func (t *Toolkit) CopyIn(ctx context.Context, in CopyIn) (int64, error)

CopyIn writes in's rows in a transaction of its own and commits it, returning the rows written. It runs as the persona's role with the caller's claims set, as every statement does.

func (*Toolkit) CopyOut

func (t *Toolkit) CopyOut(ctx context.Context, s Statement, format string, w io.Writer, maxBytes int64) (*CopyOutResult, error)

CopyOut writes the rows of s's query to w (#2453), as CSV with a header or in COPY's text format, in a READ ONLY transaction. The rows stream from the server to w a row at a time and are never held together. maxBytes lowers copy_max_bytes; a result past either bound, or past copy_max_rows, fails.

The query is read through the extended protocol rather than COPY (query) TO STDOUT, which takes no parameters: its values stay bound. Each value is the text PostgreSQL wrote for it, which is what COPY writes.

func (*Toolkit) CreateRunRole added in v1.154.2

func (t *Toolkit) CreateRunRole(ctx context.Context, connection, schema string) (role, password string, err error)

CreateRunRole creates the login role an application holding schema runs its scripts' statements as (#2539): LOGIN, and none of SUPERUSER, CREATEDB, CREATEROLE, REPLICATION or BYPASSRLS, with a password generated here. The role is sent its SCRAM-SHA-256 verifier, never the password, so no statement text the server keeps (pg_stat_statements, the server log) holds it. It is made a member of the schema's write role when the schema's migrations define one. The connection's user needs CREATEROLE. It answers the role and the password it logs in with, which the caller stores sealed and never shows.

func (*Toolkit) Describe

func (t *Toolkit) Describe(ctx context.Context, connection, schema string) (*Description, error)

Describe reads what schema holds from the target's catalog: its tables and their parts, functions, enums and domains, with the server's version and the database's extensions.

func (*Toolkit) DescribeBuilt

func (t *Toolkit) DescribeBuilt(ctx context.Context, connection, schema string, migrations []Migration) (*Description, error)

DescribeBuilt describes schema as migrations build it from zero, on a clone of their template dropped when it returns (#2406): what the live schema holds when nothing was changed outside migrations.

func (*Toolkit) DrainOutbox

func (t *Toolkit) DrainOutbox(ctx context.Context, connection, table string, limit int, write func([]OutboxRow) error) (int, error)

DrainOutbox reads up to limit of table's oldest rows, hands them to write, and deletes them in the same transaction once write returned nil. A row another session holds is skipped (FOR UPDATE SKIP LOCKED). It returns how many rows it read; write is not called when there were none. A write that fails leaves every row where it was, for the next drain.

func (*Toolkit) DropRunRole added in v1.154.2

func (t *Toolkit) DropRunRole(ctx context.Context, connection, schema string) error

DropRunRole drops the run role of schema on connection: the pools logged in as it on this process are closed, and what it owns and was granted in the database goes with it. A role already gone is not an error.

func (*Toolkit) Execute

func (t *Toolkit) Execute(ctx context.Context, s Statement) (*Result, error)

Execute runs one statement in a transaction of its own and commits it. Its RETURNING rows are read to the end and the ones past max_rows dropped.

func (*Toolkit) GrantRunRole added in v1.154.2

func (t *Toolkit) GrantRunRole(ctx context.Context, connection, schema string) (string, error)

GrantRunRole makes the run role of schema a member of the schema's write role when the schema's migrations define one and the run role is not yet, naming the role granted; "" when there was nothing to grant. A release calls it after applying migrations, since the migration that defines the write role usually comes after the schema was added.

func (*Toolkit) HasConnection

func (t *Toolkit) HasConnection(name string) bool

HasConnection implements toolkit.ConnectionManager.

func (*Toolkit) InvalidateStatements

func (t *Toolkit) InvalidateStatements(connection string)

InvalidateStatements makes every physical connection of connection deallocate its prepared statements at its next use: its schema changed (#2404 applies a migration through it).

func (*Toolkit) IsMember added in v1.154.2

func (t *Toolkit) IsMember(ctx context.Context, connection, member, role string) (bool, error)

IsMember reports whether member is a member of role on connection; false when either does not exist.

func (*Toolkit) Kind

func (*Toolkit) Kind() string

Kind implements registry.Toolkit.

func (*Toolkit) ListConnections

func (t *Toolkit) ListConnections() []toolkit.ConnectionDetail

ListConnections implements toolkit.ConnectionLister.

func (*Toolkit) Listen

func (t *Toolkit) Listen(ctx context.Context, connection string, channels []string) (*Listener, error)

Listen opens a connection to connection's database, passing the guard every connection passes, and listens on channels. A database reached through PgBouncer in transaction mode accepts the LISTEN and never delivers: the probe says so (ProbeConnection).

func (*Toolkit) Name

func (t *Toolkit) Name() string

Name implements registry.Toolkit.

func (*Toolkit) OpenCursor

func (t *Toolkit) OpenCursor(ctx context.Context, s Statement, pageRows int) (*Cursor, error)

OpenCursor declares a cursor over s in a READ ONLY transaction of its own. ctx is the run's: the transaction ends when it does.

func (*Toolkit) PendingPlan

func (t *Toolkit) PendingPlan(ctx context.Context, connection, schema string) (*Plan, error)

PendingPlan plans a connection schema's pending migrations, for the portal's connection page: the migrations planned and the plan.

func (*Toolkit) PlanMigrations

func (t *Toolkit) PlanMigrations(ctx context.Context, connection, schema string, pending []Migration) (*Plan, error)

PlanMigrations runs the pending migrations in one transaction, reads the objects they changed and the locks they took, and rolls back. PostgreSQL's DDL is transactional, so the plan is exactly what an apply would do, against the database as it is now.

func (*Toolkit) PlatformQueryIDs added in v1.154.2

func (t *Toolkit) PlatformQueryIDs(ctx context.Context, connection string, extra []string) ([]string, error)

PlatformQueryIDs is the pg_stat_statements query id of every statement the toolkit runs on connection for its own bookkeeping, and of each of extra (#2536). pg_stat_statements keys an entry by the query id, which a comment does not change, and keeps the text of the first execution it saw: a statement first recorded before the platform tagged its statements keeps its untagged text, so the health report recognizes the platform's own statements by these ids as well as by the tag.

Each id is read from EXPLAIN (GENERIC_PLAN, VERBOSE), which plans the statement with its placeholders unbound and runs nothing. A statement that does not plan here (an outbox table since dropped) is skipped. The ids are decimal text, as pg_stat_statements' queryid::text writes them. No id is read when the server does not compute them (compute_query_id off).

func (*Toolkit) ProbeConnection

func (t *Toolkit) ProbeConnection(ctx context.Context, name string) connprobe.Result

ProbeConnection implements connprobe.Prober: it opens a connection, asks the server its version and the database and user it reached, and reports them.

func (*Toolkit) Query

func (t *Toolkit) Query(ctx context.Context, s Statement) (*Result, error)

Query runs one statement in a READ ONLY transaction and reads up to the limit's rows. A statement that writes fails in that transaction.

func (*Toolkit) RegisterTools

func (t *Toolkit) RegisterTools(s *mcp.Server)

RegisterTools implements registry.Toolkit: manage_schema, when a migration store is installed (see Tools).

func (*Toolkit) RemoveConnection

func (t *Toolkit) RemoveConnection(name string) error

RemoveConnection implements toolkit.ConnectionManager.

func (*Toolkit) Report

func (t *Toolkit) Report(ctx context.Context, connection, schema string) (*SchemaReport, error)

Report is the portal's view of a connection schema's migrations.

func (*Toolkit) Revert

func (t *Toolkit) Revert(ctx context.Context, o ApplyOptions, migrations []Migration, toVersion int) ([]Migration, error)

Revert reverts applied migrations, newest first, down to and excluding toVersion, each with its down SQL in a transaction that also deletes its ledger row. toVersion below zero reverts only the latest.

func (*Toolkit) RunMaintenance

func (t *Toolkit) RunMaintenance(ctx context.Context, connection, stmt string, lockTimeout, timeout time.Duration) error

RunMaintenance runs one ANALYZE, VACUUM or REINDEX statement outside a transaction on the connection's own pool (#2410), under lockTimeout and timeout (zero is the connection's statement_timeout). The reset a released connection runs undoes both settings.

func (*Toolkit) ServesConnection added in v1.162.2

func (t *Toolkit) ServesConnection(ctx context.Context, name string) bool

ServesConnection reports whether this toolkit serves the named connection, taking on one another replica saved when the announcement of that save has not reached this instance yet. HasConnection answers from this instance's live set alone, which is what the reload reconcile reads.

func (*Toolkit) SetApplications added in v1.154.2

func (t *Toolkit) SetApplications(
	holder func(ctx context.Context, connection, schema string) (string, error),
	runRole func(ctx context.Context, connection, application string) (role, password string, err error),
)

SetApplications installs what the toolkit asks about applications: holder, the name of the application holding a schema ("" for none), and runRole, the login role and password an application's scripts run as on a connection (role "" for none). Either nil leaves every schema governed by no application, as before #2539.

func (*Toolkit) SetConnectGuard

func (t *Toolkit) SetConnectGuard(g ConnectGuard)

SetConnectGuard installs the check every new physical connection passes: the platform's refusal of its own database (OwnDatabaseGuard).

func (*Toolkit) SetConnectionStore added in v1.162.2

func (t *Toolkit) SetConnectionStore(s ConnectionStore)

SetConnectionStore wires the store a request for a connection this instance does not serve is answered from. Passing nil leaves this instance serving only the connections it was handed.

func (*Toolkit) SetMetrics

func (t *Toolkit) SetMetrics(m *observability.Metrics)

SetMetrics installs the recorder statements are counted through, for the pools built before it as well as after.

func (*Toolkit) SetMigrationStore

func (t *Toolkit) SetMigrationStore(s MigrationStore)

SetMigrationStore installs the store manage_schema keeps migrations in. Without one the kind registers no tool. It is set before tools register.

func (*Toolkit) SetQueryProvider

func (*Toolkit) SetQueryProvider(query.Provider)

SetQueryProvider implements registry.Toolkit.

func (*Toolkit) SetSchemaChecks

func (t *Toolkit) SetSchemaChecks(drift func(ctx context.Context, connection, schema string) any,
	findings func(ctx context.Context, connection, schema string, d *Description) any,
)

SetSchemaChecks installs what status and describe add to their answers (#2406, #2409): drift, the live schema against the one its applied migrations build, and findings over a description (an unused index, a dead tuple ratio). Each answers a JSON value; nil adds nothing.

func (*Toolkit) SetScriptReferences

func (t *Toolkit) SetScriptReferences(f ScriptReferences)

SetScriptReferences installs the lookup the rename rule reads saved scripts through. Without one a rename is not checked against them.

func (*Toolkit) SetSemanticProvider

func (*Toolkit) SetSemanticProvider(semantic.Provider)

SetSemanticProvider implements registry.Toolkit. Postgres tables are enriched once the catalog scans them (#2401).

func (*Toolkit) StartTestSweep

func (t *Toolkit) StartTestSweep(platform *sql.DB)

StartTestSweep runs the sweep every MCP_PLATFORM_APPDB_TEST_SWEEP_INTERVAL, dropping builds and clones older than MCP_PLATFORM_APPDB_TEST_MAX_AGE, until the toolkit closes. The first pass runs at once, so a restart clears what the process it replaced left. It starts once.

func (*Toolkit) Status

func (t *Toolkit) Status(ctx context.Context, connection, schema string, migrations []Migration) (*LedgerStatus, error)

Status reads the ledger and compares it with the platform's migrations.

func (*Toolkit) SweepTestDatabases

func (t *Toolkit) SweepTestDatabases(ctx context.Context, olderThan time.Duration) (int, error)

SweepTestDatabases drops every build and clone older than olderThan on each connection's test server that the server's user owns: the ones a run that died never dropped. It returns how many it dropped.

func (*Toolkit) TestDatabase

func (t *Toolkit) TestDatabase(ctx context.Context, connection string, schemas []string) (*TestDB, error)

TestDatabase clones the template of connection's migrations in schemas (every schema they name when empty), building it first when the head has none, and returns a toolkit serving the clone under the connection's name.

func (*Toolkit) TestServerOf

func (t *Toolkit) TestServerOf(connection string) string

TestServerOf is the connection whose server and credentials connection's throwaway databases are made with: its test_connection, or itself. A caller running statements there runs them as that connection's user, so the platform authorizes it as well.

func (*Toolkit) Tools

func (t *Toolkit) Tools() []string

Tools implements registry.Toolkit. An application database has no agent tool for its data: scripts and endpoints reach it through the host's platform.query, platform.execute, platform.transaction and platform.batch, which call the toolkit directly (#2428, #2402). The one tool is manage_schema (#2404), which builds the schema, when a migration store is installed.

func (*Toolkit) UpdateConnection

func (t *Toolkit) UpdateConnection(name string, config map[string]any) error

UpdateConnection implements toolkit.ConnectionUpdater: the connection's new pool replaces the old one, which closes once its statements in flight end. The same configuration again keeps the live pool: a replica that took a connection on from the store hears the saving replica's announcement next, and closing the pool then fails a call that had looked it up.

func (*Toolkit) ValidateConnection

func (t *Toolkit) ValidateConnection(name string, config map[string]any) error

ValidateConnection implements toolkit.ConnectionValidator: a save is refused when its configuration does not parse, and when its database answers and is the platform's own or on a server older than MinServerMajor. A database that does not answer is not refused here: both checks run again on every connection the pool opens.

type Trigger

type Trigger struct {
	Name string `json:"name"`
	// Timing is before, after or instead_of.
	Timing string `json:"timing"`
	// Events are insert, update, delete and truncate, in that order.
	Events []string `json:"events"`
	// Level is row or statement.
	Level    string `json:"level"`
	When     string `json:"when,omitempty"`
	Function string `json:"function"`
	// Enabled is enabled, disabled, replica or always (session_replication_role).
	Enabled    string `json:"enabled"`
	Definition string `json:"definition"`
}

Trigger is a trigger on one of the schema's tables.

type Tx

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

Tx is one transaction a script holds across its calls (#2402): opened by platform.transaction, used by tx.query, tx.execute and tx.batch, and committed when the script's function returns. It is held by the run that opened it and never by an agent.

It holds a pooled connection for its whole life, so it ends on its own when it should not keep one: when the run that opened it ends (finished, failed, timed out, shed by admission, drained at shutdown), when it goes transaction_idle_timeout without a statement, when a statement in it fails, and when the toolkit closes. Each rolls it back, and the next call on it fails naming the reason.

func (*Tx) Abandon

func (x *Tx) Abandon()

Abandon rolls the transaction back because the toolkit or the run is going away.

func (*Tx) Batch

func (x *Tx) Batch(ctx context.Context, stmts []Statement) ([]*Result, error)

Batch runs statements in the transaction pipelined: sent together and answered in one round trip, none reading another's result. Each result is read to its end and the rows past max_rows dropped.

func (*Tx) Commit

func (x *Tx) Commit(ctx context.Context) error

Commit commits the transaction. A serialization failure or deadlock found at commit is the commit's error, which the script's retry reads.

func (*Tx) Connection

func (x *Tx) Connection() string

Connection is the connection the transaction is on.

func (*Tx) CopyIn

func (x *Tx) CopyIn(ctx context.Context, in CopyIn) (int64, error)

CopyIn writes in's rows in the transaction; they commit with it.

func (*Tx) Execute

func (x *Tx) Execute(ctx context.Context, s Statement) (*Result, error)

Execute runs one statement in the transaction. Its RETURNING rows are read to the end and the ones past max_rows dropped.

func (*Tx) OpenCursor

func (x *Tx) OpenCursor(ctx context.Context, s Statement, pageRows int) (*Cursor, error)

OpenCursor declares a cursor over s in the transaction. It ends with the transaction, and a failure reading it ends the transaction as a failed statement does.

func (*Tx) Query

func (x *Tx) Query(ctx context.Context, s Statement) (*Result, error)

Query runs one statement in the transaction and keeps up to the limit's rows. The rest are read and dropped rather than canceled at the server: a canceled statement fails, and a failure ends the transaction.

func (*Tx) Release

func (x *Tx) Release(ctx context.Context, name string) error

Release ends savepoint name, keeping what was done in it. When a statement in it failed, the transaction is rolled back to it instead, and that failure is returned: its work is not kept, and the transaction goes on.

func (*Tx) Rollback

func (x *Tx) Rollback()

Rollback rolls the transaction back. Rolling back a transaction that already ended does nothing.

func (*Tx) RollbackTo

func (x *Tx) RollbackTo(ctx context.Context, name string) error

RollbackTo undoes what was done in savepoint name and ends it, whether or not a statement in it failed. The transaction goes on.

func (*Tx) Savepoint

func (x *Tx) Savepoint(ctx context.Context) (string, error)

Savepoint opens a savepoint inside the transaction (#2452), named by the platform and returned for Release or RollbackTo. Savepoints nest; each is released or rolled back before the one it is inside.

type TxOptions

type TxOptions struct {
	Connection string
	// Isolation is read_committed (the default), repeatable_read or
	// serializable.
	Isolation string
	// ReadOnly opens a READ ONLY transaction, the only kind a read_only
	// connection opens.
	ReadOnly bool
	// Attempt numbers the tries of a retried transaction from 1; a later try
	// is counted as a retry.
	Attempt int
}

TxOptions is how a script's transaction is opened (#2402).

type View

type View struct {
	Definition      string `json:"definition"`
	SecurityInvoker bool   `json:"security_invoker"`
	SecurityBarrier bool   `json:"security_barrier"`
	// CheckOption is local or cascaded, empty when the view has none.
	CheckOption string `json:"check_option,omitempty"`
}

View is what a view or materialized view is defined as.

Jump to

Keyboard shortcuts

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