postgres

package
v0.2.0 Latest Latest
Warning

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

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

Documentation

Overview

Package postgres implements PostgreSQL-specific introspection, DDL rendering, advisory locking, and shadow schema compilation.

Index

Constants

View Source
const (
	ManagedKindPublication  = "publication"
	ManagedKindEventTrigger = "event trigger"
	ManagedKindSubscription = "subscription"
)

Managed catalog object kinds accepted by ObjectHasManagedMarker.

Variables

This section is empty.

Functions

func AcquireSchemaLocks

func AcquireSchemaLocks(ctx context.Context, dbtx dialect.DBTX, namespace string, schemas []string) ([]string, error)

AcquireSchemaLocks acquires session-level advisory locks for the given schemas in sorted, deduped order using the two-int form (hash32(namespace), hash32(schema)). If any lock acquisition fails, all locks acquired so far are released in reverse order before returning the error.

func AcquireSessionAdvisoryLock

func AcquireSessionAdvisoryLock(ctx context.Context, dbtx dialect.DBTX, lockID int64) error

AcquireSessionAdvisoryLock acquires a PostgreSQL session-level exclusive advisory lock on a dedicated connection. It uses pg_try_advisory_lock in a non-blocking loop to avoid holding open server-side lock wait queues that would cause PostgreSQL deadlock detection against concurrent non-transactional DDL such as CREATE INDEX CONCURRENTLY.

func AcquireSessionAdvisoryLock2

func AcquireSessionAdvisoryLock2(ctx context.Context, dbtx dialect.DBTX, key1, key2 int32) error

AcquireSessionAdvisoryLock2 acquires a PostgreSQL session-level advisory lock using two 32-bit keys (namespace, key).

func ComputeShadowSchemas

func ComputeShadowSchemas(shadowPrefix string, targetSchemas []string) map[string]string

ComputeShadowSchemas returns a mapping from each target schema to its mirroring shadow schema. Names are bounded to PostgreSQL's 63-byte identifier limit. When truncation would collide, a deterministic FNV-1a suffix keyed on the full target name disambiguates. Single schema "public" with the default prefix stays "_grizzle_shadow" for backward compatibility when the prefix is exactly that default (unique per-run prefixes always include the target disambiguator).

func DiscoverSchemas added in v0.2.0

func DiscoverSchemas(ctx context.Context, dbtx dialect.DBTX, pattern string) ([]string, error)

DiscoverSchemas queries pg_namespace for schemas matching a LIKE pattern, excluding system schemas (pg_*, information_schema, and _grizzle*). The returned schema names are deduplicated and sorted deterministically.

func DropShadowSchema

func DropShadowSchema(ctx context.Context, dbtx dialect.DBTX, shadowSchema string) error

DropShadowSchema safely destroys the temporary shadow schema.

func DropShadowSchemas

func DropShadowSchemas(ctx context.Context, dbtx dialect.DBTX, shadowSchemas []string) error

DropShadowSchemas destroys all temporary shadow schemas.

func Dump

func Dump(s *schema.Schema) string

Dump transforms a PostgreSQL Schema IR into canonical DDL statements.

func DumpSchema

func DumpSchema(ctx context.Context, dbtx dialect.DBTX, targetSchema string) (string, error)

DumpSchema introspects the PostgreSQL schema and renders canonical DDL SQL.

func EventTriggerFunctionExists

func EventTriggerFunctionExists(ctx context.Context, dbtx dialect.DBTX, functionName string, lookupSchemas ...string) (bool, error)

EventTriggerFunctionExists reports whether the exact desired no-argument event-trigger function exists. PostgreSQL event triggers require a regular function returning event_trigger; procedures, aggregates, and similarly named routines are not compatible.

func EventTriggerFunctionExistsWithShadowMap

func EventTriggerFunctionExistsWithShadowMap(ctx context.Context, dbtx dialect.DBTX, functionName string, shadowMap map[string]string, lookupSchemas ...string) (bool, error)

EventTriggerFunctionExistsWithShadowMap is the multi-schema form of EventTriggerFunctionExists. A qualified target-schema routine is resolved in its corresponding shadow schema, matching RewriteShadowSQL and the schema diff's target/shadow mapping.

func GenerateAddCheckSQL

func GenerateAddCheckSQL(targetSchema, tableName, checkName, normalizedCheckDef string) string

GenerateAddCheckSQL constructs an ALTER TABLE ... ADD CONSTRAINT ... CHECK statement with NOT VALID for safe zero-lock addition.

func GenerateAddColumnSQL

func GenerateAddColumnSQL(targetSchema, tableName string, col *schema.Column) string

GenerateAddColumnSQL constructs an ALTER TABLE ... ADD COLUMN statement.

func GenerateAddEnumValueSQL

func GenerateAddEnumValueSQL(targetSchema, enumName, val string) string

GenerateAddEnumValueSQL constructs an ALTER TYPE ... ADD VALUE statement.

func GenerateAddFKSQL

func GenerateAddFKSQL(targetSchema, tableName, fkName, normalizedFKDef string) string

GenerateAddFKSQL constructs an ALTER TABLE ... ADD CONSTRAINT statement with NOT VALID for safe zero-lock addition.

func GenerateAlterColumnSQL

func GenerateAlterColumnSQL(targetSchema, tableName string, live, desired *schema.Column) string

GenerateAlterColumnSQL constructs an ALTER TABLE ... ALTER COLUMN statement for modified columns.

func GenerateAlterCompositeTypeSQL

func GenerateAlterCompositeTypeSQL(targetSchema, typeName string, attr *schema.CompositeAttribute, destructive, typeChanged bool) string

GenerateAlterCompositeTypeSQL constructs an ALTER TYPE statement for composite type attribute changes.

func GenerateAlterDomainSQL

func GenerateAlterDomainSQL(targetSchema, domainName string, c *schema.CheckConstraint) string

GenerateAlterDomainSQL renders ALTER DOMAIN ... ADD CONSTRAINT. Dropping a domain constraint has its own change type and generator.

func GenerateAlterEventTriggerEnabledSQL

func GenerateAlterEventTriggerEnabledSQL(e *schema.EventTrigger) string

GenerateAlterEventTriggerEnabledSQL renders ENABLE/DISABLE for the desired enabled state.

func GenerateAlterEventTriggerSQL

func GenerateAlterEventTriggerSQL(want, old *schema.EventTrigger) string

GenerateAlterEventTriggerSQL renders drift reconciliation for one event trigger. PostgreSQL has no ALTER EVENT TRIGGER for event/tags/function, so definition drift renders a DROP+CREATE replacement pair; enabled-only drift renders ALTER EVENT TRIGGER ENABLE/DISABLE.

func GenerateAlterPolicySQL

func GenerateAlterPolicySQL(targetSchema, tableName string, p *schema.Policy, oldPolicy ...*schema.Policy) string

GenerateAlterPolicySQL constructs an ALTER POLICY statement for expression and role updates.

func GenerateAlterPublicationSQL

func GenerateAlterPublicationSQL(want, old *schema.Publication) string

GenerateAlterPublicationSQL renders the drift reconciliation statements (membership and publish-flag changes) for one publication.

func GenerateAlterRoleApplySQL

func GenerateAlterRoleApplySQL(role *schema.Role) string

GenerateAlterRoleApplySQL rebuilds executable ALTER ROLE SQL including the real password from IR. Used only at apply time.

func GenerateAlterRoleAttrsSQL

func GenerateAlterRoleAttrsSQL(role *schema.Role) string

GenerateAlterRoleAttrsSQL renders ALTER ROLE ... WITH attr clauses (no password).

func GenerateAlterRolePasswordSQL

func GenerateAlterRolePasswordSQL(roleName, password string) string

GenerateAlterRolePasswordSQL builds ALTER ROLE ... PASSWORD with the real plaintext. Callers must not persist the result on Step.SQL.

func GenerateAlterRolePasswordSQLRedacted

func GenerateAlterRolePasswordSQLRedacted(roleName string) string

GenerateAlterRolePasswordSQLRedacted is the Step.SQL form of a password change.

func GenerateAlterRoleSetSQL

func GenerateAlterRoleSetSQL(roleName, param, value string, reset bool) string

GenerateAlterRoleSetSQL renders ALTER ROLE ... SET/RESET for config drift.

func GenerateAlterRoleStepSQL

func GenerateAlterRoleStepSQL(role *schema.Role) string

GenerateAlterRoleStepSQL renders redacted ALTER ROLE SQL for plan steps. Password plaintext is never included; apply rebuilds it from Role IR.

func GenerateAlterSequenceSQL

func GenerateAlterSequenceSQL(targetSchema, seqName string, oldSeq, newSeq *schema.Sequence) string

GenerateAlterSequenceSQL constructs an ALTER SEQUENCE statement for parameter or ownership changes.

func GenerateAlterSubscriptionSQL

func GenerateAlterSubscriptionSQL(want, old *schema.Subscription) string

GenerateAlterSubscriptionSQL renders CONNECTION / ENABLE / DISABLE / SET PUBLICATION drift for one subscription. Connection strings in the returned SQL are redacted.

func GenerateAttachPartitionSQL

func GenerateAttachPartitionSQL(targetSchema, parentTable, childTable, bounds string) string

GenerateAttachPartitionSQL constructs an ALTER TABLE ... ATTACH PARTITION statement.

func GenerateCommentSQL

func GenerateCommentSQL(targetSchema, tableName, columnName, comment string) string

GenerateCommentSQL renders a COMMENT ON statement for a table or column. An empty comment renders IS NULL (clearing the comment).

func GenerateCreateCompositeTypeSQL

func GenerateCreateCompositeTypeSQL(targetSchema string, ct *schema.CompositeType) string

GenerateCreateCompositeTypeSQL constructs a CREATE TYPE ... AS (...) statement.

func GenerateCreateDomainSQL

func GenerateCreateDomainSQL(targetSchema string, d *schema.Domain) string

GenerateCreateDomainSQL renders CREATE DOMAIN from inspected IR. BaseType and Default are already normalized (shadow schema unmapped) by the diff stage; constraint definitions are canonical pg_get_constraintdef output.

func GenerateCreateEnumSQL

func GenerateCreateEnumSQL(targetSchema string, e *schema.Enum) string

GenerateCreateEnumSQL constructs a CREATE TYPE ... AS ENUM statement.

func GenerateCreateEventTriggerSQL

func GenerateCreateEventTriggerSQL(e *schema.EventTrigger) string

GenerateCreateEventTriggerSQL renders the desired event trigger.

func GenerateCreateExtensionSQL

func GenerateCreateExtensionSQL(ext *schema.Extension) string

GenerateCreateExtensionSQL constructs a CREATE EXTENSION IF NOT EXISTS statement.

func GenerateCreateFunctionSQL

func GenerateCreateFunctionSQL(r *schema.Routine) string

GenerateCreateFunctionSQL returns the canonical CREATE OR REPLACE FUNCTION statement produced by pg_get_functiondef (schema names already unmapped by the diff stage).

func GenerateCreateIndexSQL

func GenerateCreateIndexSQL(normalizedIndexDef string, concurrently bool) string

GenerateCreateIndexSQL constructs a CREATE [UNIQUE] INDEX statement with terminating semicolon.

func GenerateCreatePolicySQL

func GenerateCreatePolicySQL(targetSchema, tableName string, p *schema.Policy) string

GenerateCreatePolicySQL constructs a CREATE POLICY statement.

func GenerateCreatePublicationSQL

func GenerateCreatePublicationSQL(p *schema.Publication) string

GenerateCreatePublicationSQL renders the desired publication.

func GenerateCreateRangeTypeSQL

func GenerateCreateRangeTypeSQL(targetSchema string, r *schema.RangeType) string

GenerateCreateRangeTypeSQL constructs a CREATE TYPE ... AS RANGE statement.

func GenerateCreateReplicationSlotSQL

func GenerateCreateReplicationSlotSQL(s *schema.ReplicationSlot) string

GenerateCreateReplicationSlotSQL renders pg_create_logical_replication_slot.

func GenerateCreateRoleSQL

func GenerateCreateRoleSQL(role *schema.Role) string

GenerateCreateRoleSQL renders CREATE ROLE with declared attributes. When Login is unset or false the PostgreSQL default NOLOGIN is rendered. Password plaintext is never included; use GenerateAlterRolePasswordSQL at apply time when Role.HasPassword is set.

func GenerateCreateRoleSQLRedacted

func GenerateCreateRoleSQLRedacted(role *schema.Role) string

GenerateCreateRoleSQLRedacted renders CREATE ROLE for plan steps. Passwords are applied via a follow-up ALTER_ROLE step so CREATE SQL never embeds secrets.

func GenerateCreateSequenceSQL

func GenerateCreateSequenceSQL(targetSchema string, seq *schema.Sequence) string

GenerateCreateSequenceSQL constructs a CREATE SEQUENCE statement.

func GenerateCreateSubscriptionApplySQL

func GenerateCreateSubscriptionApplySQL(s *schema.Subscription) string

GenerateCreateSubscriptionApplySQL renders CREATE SUBSCRIPTION with the plaintext connection string from IR for apply.

func GenerateCreateSubscriptionSQL

func GenerateCreateSubscriptionSQL(s *schema.Subscription) string

GenerateCreateSubscriptionSQL renders CREATE SUBSCRIPTION with a redacted connection string suitable for Step.SQL / plan documents.

func GenerateCreateTableSQL

func GenerateCreateTableSQL(targetSchema string, tbl *schema.Table) string

GenerateCreateTableSQL constructs a CREATE TABLE statement including columns and primary key.

func GenerateCreateTriggerSQL

func GenerateCreateTriggerSQL(t *schema.Trigger) string

GenerateCreateTriggerSQL returns the canonical CREATE TRIGGER statement produced by pg_get_triggerdef (schema-qualified table references already unmapped by the diff stage).

func GenerateCreateViewSQL

func GenerateCreateViewSQL(targetSchema string, v *schema.View, replace bool) string

GenerateCreateViewSQL constructs a CREATE [OR REPLACE] [MATERIALIZED] VIEW statement from the canonical pg_get_viewdef definition (schema references already unmapped by the diff stage).

func GenerateDetachPartitionConcurrentlySQL

func GenerateDetachPartitionConcurrentlySQL(targetSchema, parentTable, childTable string) string

GenerateDetachPartitionConcurrentlySQL constructs an ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY statement.

func GenerateDetachPartitionFinalizeSQL

func GenerateDetachPartitionFinalizeSQL(targetSchema, parentTable, childTable string) string

GenerateDetachPartitionFinalizeSQL constructs an ALTER TABLE ... DETACH PARTITION ... FINALIZE statement.

func GenerateDetachPartitionSQL

func GenerateDetachPartitionSQL(targetSchema, parentTable, childTable string) string

GenerateDetachPartitionSQL constructs an ALTER TABLE ... DETACH PARTITION statement.

func GenerateDropCheckSQL

func GenerateDropCheckSQL(targetSchema, tableName, checkName string) string

GenerateDropCheckSQL constructs an ALTER TABLE ... DROP CONSTRAINT statement for a CHECK constraint.

func GenerateDropDomainConstraintSQL

func GenerateDropDomainConstraintSQL(targetSchema, domainName, constraintName string) string

GenerateDropDomainConstraintSQL renders ALTER DOMAIN ... DROP CONSTRAINT.

func GenerateDropDomainSQL

func GenerateDropDomainSQL(targetSchema, domainName string) string

GenerateDropDomainSQL renders DROP DOMAIN without CASCADE: domains with dependent columns fail at apply time, which surfaces the dependency instead of silently destroying it.

func GenerateDropEventTriggerSQL

func GenerateDropEventTriggerSQL(name string) string

GenerateDropEventTriggerSQL renders DROP EVENT TRIGGER.

func GenerateDropFKSQL

func GenerateDropFKSQL(targetSchema, tableName, fkName string) string

GenerateDropFKSQL constructs an ALTER TABLE ... DROP CONSTRAINT statement.

func GenerateDropFunctionSQL

func GenerateDropFunctionSQL(targetSchema string, r *schema.Routine) string

GenerateDropFunctionSQL constructs a DROP FUNCTION/PROCEDURE/AGGREGATE statement using the routine's identity arguments, which uniquely identify it (including overloads) without default values.

func GenerateDropIndexSQL

func GenerateDropIndexSQL(targetSchema, indexName string, concurrently bool) string

GenerateDropIndexSQL constructs a DROP INDEX statement with optional CONCURRENTLY.

func GenerateDropPolicySQL

func GenerateDropPolicySQL(targetSchema, tableName, policyName string) string

GenerateDropPolicySQL constructs a DROP POLICY statement.

func GenerateDropPublicationSQL

func GenerateDropPublicationSQL(name string) string

GenerateDropPublicationSQL renders DROP PUBLICATION.

func GenerateDropReplicationSlotSQL

func GenerateDropReplicationSlotSQL(name string) string

GenerateDropReplicationSlotSQL renders pg_drop_replication_slot.

func GenerateDropRoleSQL

func GenerateDropRoleSQL(roleName string) string

GenerateDropRoleSQL renders DROP ROLE.

func GenerateDropSequenceSQL

func GenerateDropSequenceSQL(targetSchema, seqName string) string

GenerateDropSequenceSQL constructs a DROP SEQUENCE IF EXISTS statement. IF EXISTS prevents errors if a table drop previously cascaded and dropped an owned sequence.

func GenerateDropSubscriptionSQL

func GenerateDropSubscriptionSQL(name string) string

GenerateDropSubscriptionSQL renders a drop that keeps the remote replication slot: DISABLE, disassociate slot_name, then DROP. Per PostgreSQL docs, DROP SUBSCRIPTION alone drops the remote slot by default.

func GenerateDropTriggerSQL

func GenerateDropTriggerSQL(targetSchema, tableName, triggerName string) string

GenerateDropTriggerSQL constructs a DROP TRIGGER statement.

func GenerateDropTypeSQL

func GenerateDropTypeSQL(targetSchema, typeName string) string

GenerateDropTypeSQL constructs a DROP TYPE statement.

func GenerateDropViewSQL

func GenerateDropViewSQL(targetSchema, viewName string, isMatView bool) string

GenerateDropViewSQL constructs a DROP VIEW or DROP MATERIALIZED VIEW statement.

func GenerateEventTriggerCommentSQL

func GenerateEventTriggerCommentSQL(name string) string

GenerateEventTriggerCommentSQL stamps the managed-event-trigger marker.

func GenerateGrantSQL

func GenerateGrantSQL(g *schema.Grant) string

GenerateGrantSQL renders a GRANT statement from desired IR.

func GenerateLockID

func GenerateLockID(schema string) int64

GenerateLockID produces a deterministic 64-bit integer hash from a schema identifier.

func GeneratePublicationCommentSQL

func GeneratePublicationCommentSQL(name string) string

GeneratePublicationCommentSQL stamps the managed-publication marker.

func GenerateRLSSQL

func GenerateRLSSQL(targetSchema, tableName string, typ plan.ChangeType) string

GenerateRLSSQL constructs an ALTER TABLE ... [ENABLE|DISABLE|FORCE|NO FORCE] ROW LEVEL SECURITY statement.

func GenerateRefreshMatViewSQL

func GenerateRefreshMatViewSQL(targetSchema, viewName string) string

GenerateRefreshMatViewSQL constructs a REFRESH MATERIALIZED VIEW statement.

func GenerateRenameEnumValueSQL

func GenerateRenameEnumValueSQL(targetSchema, enumName, oldVal, newVal string) string

GenerateRenameEnumValueSQL constructs an ALTER TYPE ... RENAME VALUE statement.

func GenerateRevokeSQL

func GenerateRevokeSQL(g *schema.Grant, privileges []string) string

GenerateRevokeSQL renders a REVOKE statement. A grant IR flagged GrantOption revokes only the delegation (REVOKE GRANT OPTION FOR), keeping the base privilege.

func GenerateRoleCommentSQL

func GenerateRoleCommentSQL(roleName string) string

GenerateRoleCommentSQL stamps the managed-role marker used to distinguish Grizzle-owned roles from operator-created ones.

func GenerateSubscriptionCommentSQL

func GenerateSubscriptionCommentSQL(name string) string

GenerateSubscriptionCommentSQL stamps the managed-subscription marker.

func GenerateValidateConstraintSQL

func GenerateValidateConstraintSQL(targetSchema, tableName, constraintName string) string

GenerateValidateConstraintSQL constructs an ALTER TABLE ... VALIDATE CONSTRAINT statement. It is shared by foreign key and CHECK constraint validation steps.

func Hash32

func Hash32(s string) int32

Hash32 computes a deterministic 32-bit signed integer hash from a string.

func Inspect

func Inspect(ctx context.Context, dbtx dialect.DBTX, schemaName string) (*schema.Schema, error)

Inspect reads the relational state of the specified schema directly from pg_catalog.

func InspectSchemas

func InspectSchemas(ctx context.Context, dbtx dialect.DBTX, schemaNames []string) (map[string]*schema.Schema, error)

InspectSchemas reads the relational states across all specified schema names.

func IsSerialColumn

func IsSerialColumn(tableName string, col *schema.Column) (string, bool)

IsSerialColumn checks whether a column is an implicit serial sequence column.

func ObjectHasManagedMarker

func ObjectHasManagedMarker(ctx context.Context, dbtx dialect.DBTX, kind, name string) (bool, error)

ObjectHasManagedMarker reports whether the named catalog object still carries the exact grizzle-managed COMMENT immediately before a destructive drop. Plans are computed earlier; the marker may have been removed since, so apply re-verifies it under the advisory lock.

func PreflightLockContention added in v0.2.0

func PreflightLockContention(ctx context.Context, dbtx dialect.DBTX, tables []SchemaTable, timeout time.Duration, failOnContention bool, logger *slog.Logger) error

PreflightLockContention inspects pg_locks and pg_stat_activity on target tables before DDL execution. If failOnContention is false (advisory mode), warnings are logged for any conflicting holders and execution proceeds. If failOnContention is true (gating mode), backoff retries occur up to timeout; if contention persists, an error wrapping plan.ErrLockContention is returned.

NOTE: Pre-flight lock inspection is inherently racy: concurrent transactions may acquire locks between the pre-flight check and subsequent DDL execution. Always configure lock_timeout alongside fail_on_contention to bound wait duration if a race occurs.

func QueryTableLockContention added in v0.2.0

func QueryTableLockContention(ctx context.Context, dbtx dialect.DBTX, schema, table string) ([]plan.LockConflict, error)

QueryTableLockContention queries pg_locks and pg_stat_activity for concurrent sessions holding granted locks on the target schema.table, excluding the current backend.

NOTE: Pre-flight lock inspection is inherently racy: concurrent transactions may acquire locks between the pre-flight check and subsequent DDL execution.

func ReleaseSchemaLocks

func ReleaseSchemaLocks(ctx context.Context, dbtx dialect.DBTX, namespace string, schemas []string) error

ReleaseSchemaLocks releases session-level advisory locks for the given schemas in reverse order.

func ReleaseSessionAdvisoryLock

func ReleaseSessionAdvisoryLock(ctx context.Context, dbtx dialect.DBTX, lockID int64) error

ReleaseSessionAdvisoryLock releases a PostgreSQL session-level exclusive advisory lock on a dedicated connection.

func ReleaseSessionAdvisoryLock2

func ReleaseSessionAdvisoryLock2(ctx context.Context, dbtx dialect.DBTX, key1, key2 int32) error

ReleaseSessionAdvisoryLock2 releases a PostgreSQL session-level advisory lock using two 32-bit keys (namespace, key).

func Render

func Render(step plan.Step) ([]dialect.Stmt, error)

Render implements dialect.Dialect for single steps.

func RenderChange

func RenderChange(targetSchema string, c diff.Change, nonConcurrent ...bool) plan.Step

RenderChange converts a pure diff.Change into an executable plan.Step with PostgreSQL DDL.

func RenderChangeWithOpts

func RenderChangeWithOpts(targetSchema string, c diff.Change, opts RenderOpts) plan.Step

RenderChangeWithOpts converts a pure diff.Change into an executable plan.Step using RenderOpts.

func RenderChanges

func RenderChanges(targetSchema string, changes []diff.Change, nonConcurrent ...bool) []plan.Step

RenderChanges converts a list of pure changes into sequenced, topologically ordered plan steps.

func RenderChangesWithOpts

func RenderChangesWithOpts(targetSchema string, changes []diff.Change, opts RenderOpts) []plan.Step

RenderChangesWithOpts converts a list of pure changes into sequenced, topologically ordered plan steps using RenderOpts.

func ReplicationSlotIsActive

func ReplicationSlotIsActive(ctx context.Context, dbtx dialect.DBTX, name string) (bool, error)

ReplicationSlotIsActive reports whether a logical slot in the current database is held by a backend (active_pid IS NOT NULL). An absent slot reports false; the DROP itself then fails with PostgreSQL's own error.

func RewriteShadowSQL

func RewriteShadowSQL(sqlStr string, shadowMap map[string]string) string

RewriteShadowSQL redirects references to target schemas in SQL to their corresponding shadow schemas.

func RoleHasManagedMarker

func RoleHasManagedMarker(ctx context.Context, dbtx dialect.DBTX, roleName string) (bool, error)

RoleHasManagedMarker verifies the exact catalog marker immediately before a DROP ROLE. Direct plan application cannot rely on the marker snapshot captured during planning.

func RoleHasUnhandledACLs

func RoleHasUnhandledACLs(ctx context.Context, dbtx dialect.DBTX, roleName string, targetSchemas []string) (bool, error)

RoleHasUnhandledACLs reports ACL entries that the RolesSQL inspector does not reconcile for a managed role. In-scope relation/function/schema/current database ACLs are deliberately excluded because RolesDiff emits revokes for those entries before DROP ROLE. Everything else is a conservative refusal rather than a DROP ROLE that may fail after schema steps.

func RoleHasUnhandledDependencies

func RoleHasUnhandledDependencies(ctx context.Context, dbtx dialect.DBTX, roleName string) (bool, error)

RoleHasUnhandledDependencies checks shared-catalog dependencies that are not ACL rows. ACL dependencies are handled separately so in-scope grants can be revoked before DROP ROLE; every other dependency fails closed.

func RoleOwnsObjects

func RoleOwnsObjects(ctx context.Context, dbtx dialect.DBTX, roleName string) (bool, error)

RoleOwnsObjects reports whether the named role owns any catalog object or dependency that makes DROP ROLE unsafe. The check is intentionally conservative: default ACLs, memberships, and ownership in catalogs not managed by Grizzle all refuse the drop.

func RunMultiShadowDDL

func RunMultiShadowDDL(ctx context.Context, dbtx dialect.DBTX, shadowMap map[string]string, targetSchemas []string, schemaSQL string) error

RunMultiShadowDDL configures search_path across all shadow schemas, rewrites schema references, executes the desired schema SQL in shadow, and restores search_path.

func RunShadowDDL

func RunShadowDDL(ctx context.Context, dbtx dialect.DBTX, shadowSchema, targetSchema, schemaSQL string) error

RunShadowDDL sets search_path to the shadow schema, runs the user's schemaSQL, and restores search_path.

func SetupShadowSchema

func SetupShadowSchema(ctx context.Context, dbtx dialect.DBTX, shadowSchema string) error

SetupShadowSchema creates a clean, isolated temporary schema for DDL compilation.

func SetupShadowSchemas

func SetupShadowSchemas(ctx context.Context, dbtx dialect.DBTX, shadowSchemas []string) error

SetupShadowSchemas creates clean, isolated temporary shadow schemas for DDL compilation.

func ValidateFunctionGrantTargets

func ValidateFunctionGrantTargets(ctx context.Context, dbtx dialect.DBTX, spec *schema.RolesSpec, targetSchema string, shadowMap map[string]string) error

ValidateFunctionGrantTargets rejects FUNCTION grants that cannot be represented by the inspected ACL contract. PostgreSQL distinguishes functions from procedures and aggregates even though all have pg_proc rows; only prokind='f' is valid for GRANT ... ON FUNCTION.

func ValidateIdentifier

func ValidateIdentifier(ident string) error

ValidateIdentifier ensures schema names contain only safe SQL identifier characters.

func VerifySessionDedicated

func VerifySessionDedicated(ctx context.Context, dbtx dialect.DBTX) error

VerifySessionDedicated probes whether the connection preserves session state across queries. Connection poolers operating in transaction pooling mode (such as PgBouncer with pool_mode = transaction) reassign or reset (DISCARD ALL) the underlying server connection between statements, which breaks session-level advisory locks and leads to orphaned locks or hangs.

func WrapShadowCompileError

func WrapShadowCompileError(err error, sqlStr string) error

WrapShadowCompileError maps shadow compile failures to the failing object/statement and an actionable hint.

Types

type LiveCatalog

type LiveCatalog struct {
	// Publications maps canonical publication identity -> live state.
	Publications map[string]*diff.PublicationState
	// EventTriggers maps canonical event-trigger identity -> live state.
	EventTriggers map[string]*diff.EventTriggerState
	// Subscriptions maps canonical subscription identity -> live state.
	Subscriptions map[string]*diff.SubscriptionState
	// ReplicationSlots maps canonical logical slot identity -> live state.
	ReplicationSlots map[string]*diff.ReplicationSlotState
}

LiveCatalog captures the publication/event-trigger/subscription/slot state relevant to a CatalogSQL diff.

func InspectLiveCatalog

func InspectLiveCatalog(ctx context.Context, dbtx dialect.DBTX) (*LiveCatalog, error)

InspectLiveCatalog reads publications (with table membership and publish flags), event triggers, subscriptions, and logical replication slots plus grizzle-managed marker comments where COMMENT ON is supported.

func (*LiveCatalog) CatalogState

func (l *LiveCatalog) CatalogState() *diff.CatalogLiveState

CatalogState adapts the inspected live state to the dialect-independent diff.CatalogLiveState shape consumed by diff.CatalogDiff.

type LiveGrant

type LiveGrant struct {
	Grantee     string
	ObjectKind  string
	ObjectName  string
	Privileges  map[string]bool // privilege_type -> present
	GrantOption map[string]bool // privilege_type -> is_grantable
}

LiveGrant is one live (grantee, object) ACL entry. Only explicitly granted privileges appear: relacl/nspacl/datacl are NULL when nothing was ever granted, and implicit owner privileges are not ACL rows — both are skipped.

type LiveRoles

type LiveRoles struct {
	// RoleNames is every non-system role name in the database, keyed by exact
	// PostgreSQL role identity.
	RoleNames map[string]string
	// ManagedRoles are roles stamped with the grizzle-managed catalog comment.
	ManagedRoles map[string]bool
	// RoleAttrs holds live login/limit/config attributes keyed by canonical
	// role identity.
	RoleAttrs map[string]*diff.LiveRoleAttrs
	// Grants maps schema.GrantKey(kind, object, grantee) -> privileges with
	// grant option tracking. Object names retain quoted identity components.
	Grants map[string]*LiveGrant
}

LiveRoles captures the role/privilege state relevant to a RolesSQL diff.

func InspectLiveRoles

func InspectLiveRoles(ctx context.Context, dbtx dialect.DBTX, targetSchemas []string, desiredPasswords map[string]string) (*LiveRoles, error)

InspectLiveRoles reads managed-role markers, role attributes, role-level settings, and object ACLs. Tables and sequences are scoped to the target schemas; schema ACLs cover the target schemas; the database ACL covers the current database. desiredPasswords maps canonical role identity -> plaintext password for server-side hash comparison (never returned to callers).

func (*LiveRoles) RoleState

func (l *LiveRoles) RoleState() *diff.RoleState

RoleState adapts the inspected live state to the dialect-independent diff.RoleState shape consumed by diff.RolesDiff.

type Postgres

type Postgres struct{}

Postgres implements the dialect.Dialect interface for PostgreSQL.

func New

func New() *Postgres

New instantiates a new PostgreSQL dialect handler.

func (*Postgres) Introspect

func (p *Postgres) Introspect(ctx context.Context, dbtx dialect.DBTX, targetSchema string) (*schema.Schema, error)

Introspect extracts the relational schema from the live PostgreSQL database.

func (*Postgres) Name

func (p *Postgres) Name() string

Name returns the canonical name of the dialect.

func (*Postgres) Render

func (p *Postgres) Render(step plan.Step) ([]dialect.Stmt, error)

Render compiles an individual migration step into execution statements.

type RenderOpts

type RenderOpts struct {
	NonConcurrentIndexes bool
	ServerVersion        int
}

RenderOpts configures DDL rendering behavior such as concurrency and server version-specific syntax.

type SchemaTable added in v0.2.0

type SchemaTable struct {
	Schema string
	Table  string
}

SchemaTable identifies a table within a specific PostgreSQL schema.

Jump to

Keyboard shortcuts

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