Help us shape the future of Go! Take the 2026 Go Developer Survey

postgres

package
v1.13.3 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package postgres provides PostgreSQL functionality for desired state management. This file defines the interface for desired state providers (embedded or external databases).

Package postgres provides embedded PostgreSQL functionality for production use. This package is used by the plan command to create temporary PostgreSQL instances for validating desired state schemas.

Package postgres provides external PostgreSQL database functionality for desired state management.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractDefaultPrivilegeRoles added in v1.12.4

func ExtractDefaultPrivilegeRoles(sql string) []string

ExtractDefaultPrivilegeRoles returns distinct role names that appear in ALTER DEFAULT PRIVILEGES FOR { ROLE | USER } <role> [, <role> ...] statements. String literals, comments, and dollar-quoted bodies are skipped.

func ExtractReferencedRoles added in v1.13.1

func ExtractReferencedRoles(sql string) []string

ExtractReferencedRoles returns the distinct role names the SQL needs to exist: grantees of GRANT ... TO and REVOKE ... FROM, roles named by CREATE/ALTER POLICY ... TO, and grantors of ALTER DEFAULT PRIVILEGES FOR ROLE. Pseudo-roles (PUBLIC, CURRENT_USER, CURRENT_ROLE, SESSION_USER) and the predefined pg_* roles are excluded. String literals, comments, and dollar-quoted bodies are skipped, so a role created inside a DO block is invisible here — only its later use is (issue #450).

func GenerateTempSchemaName

func GenerateTempSchemaName() string

GenerateTempSchemaName creates a unique temporary schema name for plan operations. The format is: pgschema_tmp_YYYYMMDD_HHMMSS_RRRRRRRR where RRRRRRRR is a random 8-character hex string for uniqueness. The "_tmp_" marker makes it distinctive and prevents accidental matching with user schemas.

Example: pgschema_tmp_20251030_154501_a3f9d2e1

Panics if random number generation fails (indicates serious system issue).

Types

type DesiredStateProvider

type DesiredStateProvider interface {
	// GetConnectionDetails returns connection details for IR inspection
	// Returns: host, port, database, username, password
	GetConnectionDetails() (string, int, string, string, string)

	// GetSchemaName returns the actual schema name to inspect.
	// For embedded postgres: returns the temporary schema name (pgschema_tmp_*)
	// For external database: returns the temporary schema name (pgschema_tmp_*)
	GetSchemaName() string

	// ApplySchema applies the desired state SQL to a schema.
	// For embedded postgres: resets the schema (drop/recreate)
	// For external database: creates temporary schema with timestamp suffix
	ApplySchema(ctx context.Context, schema string, sql string) error

	// Stop performs cleanup.
	// For embedded postgres: stops instance and removes temp directory
	// For external database: drops temporary schema (best effort) and closes connection
	Stop() error
}

DesiredStateProvider is an interface that abstracts the desired state database provider. It can be implemented by either embedded PostgreSQL or an external database connection.

type EmbeddedPostgres

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

EmbeddedPostgres manages a temporary embedded PostgreSQL instance. This is used by the plan command to validate desired state schemas.

func StartEmbeddedPostgres

func StartEmbeddedPostgres(config *EmbeddedPostgresConfig) (*EmbeddedPostgres, error)

StartEmbeddedPostgres starts a temporary embedded PostgreSQL instance

func (*EmbeddedPostgres) ApplySchema

func (ep *EmbeddedPostgres) ApplySchema(ctx context.Context, schema string, sql string) error

ApplySchema resets a schema (drops and recreates it) and applies SQL to it. This ensures a clean state before applying the desired schema definition. Note: The schema parameter is ignored - we always use the temporary schema name.

func (*EmbeddedPostgres) GetConnectionDetails

func (ep *EmbeddedPostgres) GetConnectionDetails() (host string, port int, database, username, password string)

GetConnectionDetails returns all connection details needed to connect to the embedded PostgreSQL instance

func (*EmbeddedPostgres) GetSchemaName

func (ep *EmbeddedPostgres) GetSchemaName() string

GetSchemaName returns the temporary schema name used for desired state validation. This returns the timestamped schema name that was created by ApplySchema.

func (*EmbeddedPostgres) Stop

func (ep *EmbeddedPostgres) Stop() error

Stop stops and cleans up the embedded PostgreSQL instance

type EmbeddedPostgresConfig

type EmbeddedPostgresConfig struct {
	Version  PostgresVersion
	Database string
	Username string
	Password string
	// Extensions maps extension name to its installation schema on the target
	// database. ApplySchema installs each one into the embedded database before
	// applying the desired state, so desired-state SQL can reference extension
	// types without a CREATE EXTENSION statement (issue #584). Optional.
	Extensions map[string]string
}

EmbeddedPostgresConfig holds configuration for starting embedded PostgreSQL

type ExternalDatabase

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

ExternalDatabase manages an external PostgreSQL database for desired state validation. It creates temporary schemas with timestamp suffixes to avoid conflicts.

func NewExternalDatabase

func NewExternalDatabase(config *ExternalDatabaseConfig) (*ExternalDatabase, error)

NewExternalDatabase creates a new external database connection for desired state validation. It validates the connection, checks version compatibility, and generates a temporary schema name.

func (*ExternalDatabase) ApplySchema

func (ed *ExternalDatabase) ApplySchema(ctx context.Context, schema string, sql string) error

ApplySchema creates a temporary schema and applies SQL to it. The temporary schema name includes a timestamp to avoid conflicts.

func (*ExternalDatabase) GetConnectionDetails

func (ed *ExternalDatabase) GetConnectionDetails() (host string, port int, database, username, password string)

GetConnectionDetails returns all connection details needed to connect to the external database

func (*ExternalDatabase) GetSchemaName

func (ed *ExternalDatabase) GetSchemaName() string

GetSchemaName returns the temporary schema name used for desired state validation

func (*ExternalDatabase) Stop

func (ed *ExternalDatabase) Stop() error

Stop closes the connection and drops the temporary schema (best effort). Errors during cleanup are logged but don't cause failures.

type ExternalDatabaseConfig

type ExternalDatabaseConfig struct {
	Host               string
	Port               int
	Database           string
	Username           string
	Password           string
	SSLMode            string
	TargetMajorVersion int // Expected major version to match
	// TargetExtensions maps extension name to its installation schema on the
	// target database. Optional: when populated (typically from querying the
	// target database), NewExternalDatabase validates that extensions installed
	// on both databases live in the same schema on each side; when empty or nil,
	// the validation is skipped. Without it, extension-owned types (e.g.
	// pgvector's vector) installed in different schemas resolve to different
	// schema-qualified names and the generated plan is silently wrong (issue #518).
	TargetExtensions map[string]string
}

ExternalDatabaseConfig holds configuration for connecting to an external database

type NoEffectKind added in v1.13.1

type NoEffectKind string

NoEffectKind names a kind of statement pgschema accepts in a schema file but never plans, because the state it sets is outside what inspection reads.

const (
	// NoEffectOwner is ALTER <object> ... OWNER TO: object ownership follows the
	// pg_dump --no-owner model and is never compared (issue #602).
	NoEffectOwner NoEffectKind = "owner"
	// NoEffectGlobalDefaultPrivileges is ALTER DEFAULT PRIVILEGES without
	// IN SCHEMA: a database-wide default ACL, not schema-level state (issue #603).
	NoEffectGlobalDefaultPrivileges NoEffectKind = "global_default_privileges"
)

type NoEffectStatement added in v1.13.1

type NoEffectStatement struct {
	Kind NoEffectKind
	SQL  string // statement text with whitespace collapsed, without the trailing ';'
	// Partial is set when only one action of the statement has no effect: an
	// OWNER TO sharing an ALTER TABLE with other actions. The rest still plans.
	Partial bool
}

NoEffectStatement is one statement in the desired-state SQL that cannot change the plan.

func StripNoEffectStatements added in v1.13.1

func StripNoEffectStatements(sql string) (string, []NoEffectStatement)

StripNoEffectStatements finds the statements in sql that cannot affect the plan and returns sql without them, so they neither fail nor leave state behind in the plan database. A global ALTER DEFAULT PRIVILEGES would otherwise persist on an external plan database, and an OWNER TO role is not stubbed there.

The scan is textual and best-effort: string literals, comments and dollar-quoted bodies are skipped, so statements inside a DO block or function body are not seen. When OWNER TO shares an ALTER TABLE with other actions, only that action is removed.

type PostgresVersion

type PostgresVersion = embeddedpostgres.PostgresVersion

PostgresVersion is an alias for the embedded-postgres version type.

func DetectPostgresVersionAndExtensionsFromDB added in v1.12.4

func DetectPostgresVersionAndExtensionsFromDB(host string, port int, database, user, password, sslmode string) (PostgresVersion, map[string]string, error)

DetectPostgresVersionAndExtensionsFromDB connects to a database and detects its version along with the installation schema of every installed extension (keyed by extension name). Gathering both over a single connection avoids a second connect/close round trip during plan generation.

type QualifiedName added in v1.12.4

type QualifiedName struct {
	Schema string
	Table  string
}

QualifiedName is a schema-qualified table name extracted from SQL.

func ExtractCreateTableNames added in v1.12.4

func ExtractCreateTableNames(sql, defaultSchema string) []QualifiedName

ExtractCreateTableNames returns schema-qualified table names from CREATE TABLE statements in sql. Unqualified names use defaultSchema.

func ExtractForeignKeyTargets added in v1.12.4

func ExtractForeignKeyTargets(sql, defaultSchema string) []QualifiedName

ExtractForeignKeyTargets returns schema-qualified table names that appear as REFERENCES targets in sql. Unqualified names use defaultSchema. String literals, comments, and dollar-quoted bodies are skipped.

func ExtractPartitionOfTargets added in v1.12.4

func ExtractPartitionOfTargets(sql, defaultSchema string) []QualifiedName

ExtractPartitionOfTargets returns schema-qualified table names that appear as PARTITION OF targets in sql. Unqualified names use defaultSchema. String literals, comments, and dollar-quoted bodies are skipped.

Jump to

Keyboard shortcuts

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