Documentation
¶
Overview ¶
Package postgres implements PostgreSQL-specific introspection, DDL rendering, advisory locking, and shadow schema compilation.
Index ¶
- Constants
- func AcquireSchemaLocks(ctx context.Context, dbtx dialect.DBTX, namespace string, schemas []string) ([]string, error)
- func AcquireSessionAdvisoryLock(ctx context.Context, dbtx dialect.DBTX, lockID int64) error
- func AcquireSessionAdvisoryLock2(ctx context.Context, dbtx dialect.DBTX, key1, key2 int32) error
- func ComputeShadowSchemas(shadowPrefix string, targetSchemas []string) map[string]string
- func DiscoverSchemas(ctx context.Context, dbtx dialect.DBTX, pattern string) ([]string, error)
- func DropShadowSchema(ctx context.Context, dbtx dialect.DBTX, shadowSchema string) error
- func DropShadowSchemas(ctx context.Context, dbtx dialect.DBTX, shadowSchemas []string) error
- func Dump(s *schema.Schema) string
- func DumpSchema(ctx context.Context, dbtx dialect.DBTX, targetSchema string) (string, error)
- func EventTriggerFunctionExists(ctx context.Context, dbtx dialect.DBTX, functionName string, ...) (bool, error)
- func EventTriggerFunctionExistsWithShadowMap(ctx context.Context, dbtx dialect.DBTX, functionName string, ...) (bool, error)
- func GenerateAddCheckSQL(targetSchema, tableName, checkName, normalizedCheckDef string) string
- func GenerateAddColumnSQL(targetSchema, tableName string, col *schema.Column) string
- func GenerateAddEnumValueSQL(targetSchema, enumName, val string) string
- func GenerateAddFKSQL(targetSchema, tableName, fkName, normalizedFKDef string) string
- func GenerateAlterColumnSQL(targetSchema, tableName string, live, desired *schema.Column) string
- func GenerateAlterCompositeTypeSQL(targetSchema, typeName string, attr *schema.CompositeAttribute, ...) string
- func GenerateAlterDomainSQL(targetSchema, domainName string, c *schema.CheckConstraint) string
- func GenerateAlterEventTriggerEnabledSQL(e *schema.EventTrigger) string
- func GenerateAlterEventTriggerSQL(want, old *schema.EventTrigger) string
- func GenerateAlterPolicySQL(targetSchema, tableName string, p *schema.Policy, oldPolicy ...*schema.Policy) string
- func GenerateAlterPublicationSQL(want, old *schema.Publication) string
- func GenerateAlterRoleApplySQL(role *schema.Role) string
- func GenerateAlterRoleAttrsSQL(role *schema.Role) string
- func GenerateAlterRolePasswordSQL(roleName, password string) string
- func GenerateAlterRolePasswordSQLRedacted(roleName string) string
- func GenerateAlterRoleSetSQL(roleName, param, value string, reset bool) string
- func GenerateAlterRoleStepSQL(role *schema.Role) string
- func GenerateAlterSequenceSQL(targetSchema, seqName string, oldSeq, newSeq *schema.Sequence) string
- func GenerateAlterSubscriptionSQL(want, old *schema.Subscription) string
- func GenerateAttachPartitionSQL(targetSchema, parentTable, childTable, bounds string) string
- func GenerateCommentSQL(targetSchema, tableName, columnName, comment string) string
- func GenerateCreateCompositeTypeSQL(targetSchema string, ct *schema.CompositeType) string
- func GenerateCreateDomainSQL(targetSchema string, d *schema.Domain) string
- func GenerateCreateEnumSQL(targetSchema string, e *schema.Enum) string
- func GenerateCreateEventTriggerSQL(e *schema.EventTrigger) string
- func GenerateCreateExtensionSQL(ext *schema.Extension) string
- func GenerateCreateFunctionSQL(r *schema.Routine) string
- func GenerateCreateIndexSQL(normalizedIndexDef string, concurrently bool) string
- func GenerateCreatePolicySQL(targetSchema, tableName string, p *schema.Policy) string
- func GenerateCreatePublicationSQL(p *schema.Publication) string
- func GenerateCreateRangeTypeSQL(targetSchema string, r *schema.RangeType) string
- func GenerateCreateReplicationSlotSQL(s *schema.ReplicationSlot) string
- func GenerateCreateRoleSQL(role *schema.Role) string
- func GenerateCreateRoleSQLRedacted(role *schema.Role) string
- func GenerateCreateSequenceSQL(targetSchema string, seq *schema.Sequence) string
- func GenerateCreateSubscriptionApplySQL(s *schema.Subscription) string
- func GenerateCreateSubscriptionSQL(s *schema.Subscription) string
- func GenerateCreateTableSQL(targetSchema string, tbl *schema.Table) string
- func GenerateCreateTriggerSQL(t *schema.Trigger) string
- func GenerateCreateViewSQL(targetSchema string, v *schema.View, replace bool) string
- func GenerateDetachPartitionConcurrentlySQL(targetSchema, parentTable, childTable string) string
- func GenerateDetachPartitionFinalizeSQL(targetSchema, parentTable, childTable string) string
- func GenerateDetachPartitionSQL(targetSchema, parentTable, childTable string) string
- func GenerateDropCheckSQL(targetSchema, tableName, checkName string) string
- func GenerateDropDomainConstraintSQL(targetSchema, domainName, constraintName string) string
- func GenerateDropDomainSQL(targetSchema, domainName string) string
- func GenerateDropEventTriggerSQL(name string) string
- func GenerateDropFKSQL(targetSchema, tableName, fkName string) string
- func GenerateDropFunctionSQL(targetSchema string, r *schema.Routine) string
- func GenerateDropIndexSQL(targetSchema, indexName string, concurrently bool) string
- func GenerateDropPolicySQL(targetSchema, tableName, policyName string) string
- func GenerateDropPublicationSQL(name string) string
- func GenerateDropReplicationSlotSQL(name string) string
- func GenerateDropRoleSQL(roleName string) string
- func GenerateDropSequenceSQL(targetSchema, seqName string) string
- func GenerateDropSubscriptionSQL(name string) string
- func GenerateDropTriggerSQL(targetSchema, tableName, triggerName string) string
- func GenerateDropTypeSQL(targetSchema, typeName string) string
- func GenerateDropViewSQL(targetSchema, viewName string, isMatView bool) string
- func GenerateEventTriggerCommentSQL(name string) string
- func GenerateGrantSQL(g *schema.Grant) string
- func GenerateLockID(schema string) int64
- func GeneratePublicationCommentSQL(name string) string
- func GenerateRLSSQL(targetSchema, tableName string, typ plan.ChangeType) string
- func GenerateRefreshMatViewSQL(targetSchema, viewName string) string
- func GenerateRenameEnumValueSQL(targetSchema, enumName, oldVal, newVal string) string
- func GenerateRevokeSQL(g *schema.Grant, privileges []string) string
- func GenerateRoleCommentSQL(roleName string) string
- func GenerateSubscriptionCommentSQL(name string) string
- func GenerateValidateConstraintSQL(targetSchema, tableName, constraintName string) string
- func Hash32(s string) int32
- func Inspect(ctx context.Context, dbtx dialect.DBTX, schemaName string) (*schema.Schema, error)
- func InspectSchemas(ctx context.Context, dbtx dialect.DBTX, schemaNames []string) (map[string]*schema.Schema, error)
- func IsSerialColumn(tableName string, col *schema.Column) (string, bool)
- func ObjectHasManagedMarker(ctx context.Context, dbtx dialect.DBTX, kind, name string) (bool, error)
- func PreflightLockContention(ctx context.Context, dbtx dialect.DBTX, tables []SchemaTable, ...) error
- func QueryTableLockContention(ctx context.Context, dbtx dialect.DBTX, schema, table string) ([]plan.LockConflict, error)
- func ReleaseSchemaLocks(ctx context.Context, dbtx dialect.DBTX, namespace string, schemas []string) error
- func ReleaseSessionAdvisoryLock(ctx context.Context, dbtx dialect.DBTX, lockID int64) error
- func ReleaseSessionAdvisoryLock2(ctx context.Context, dbtx dialect.DBTX, key1, key2 int32) error
- func Render(step plan.Step) ([]dialect.Stmt, error)
- func RenderChange(targetSchema string, c diff.Change, nonConcurrent ...bool) plan.Step
- func RenderChangeWithOpts(targetSchema string, c diff.Change, opts RenderOpts) plan.Step
- func RenderChanges(targetSchema string, changes []diff.Change, nonConcurrent ...bool) []plan.Step
- func RenderChangesWithOpts(targetSchema string, changes []diff.Change, opts RenderOpts) []plan.Step
- func ReplicationSlotIsActive(ctx context.Context, dbtx dialect.DBTX, name string) (bool, error)
- func RewriteShadowSQL(sqlStr string, shadowMap map[string]string) string
- func RoleHasManagedMarker(ctx context.Context, dbtx dialect.DBTX, roleName string) (bool, error)
- func RoleHasUnhandledACLs(ctx context.Context, dbtx dialect.DBTX, roleName string, ...) (bool, error)
- func RoleHasUnhandledDependencies(ctx context.Context, dbtx dialect.DBTX, roleName string) (bool, error)
- func RoleOwnsObjects(ctx context.Context, dbtx dialect.DBTX, roleName string) (bool, error)
- func RunMultiShadowDDL(ctx context.Context, dbtx dialect.DBTX, shadowMap map[string]string, ...) error
- func RunShadowDDL(ctx context.Context, dbtx dialect.DBTX, ...) error
- func SetupShadowSchema(ctx context.Context, dbtx dialect.DBTX, shadowSchema string) error
- func SetupShadowSchemas(ctx context.Context, dbtx dialect.DBTX, shadowSchemas []string) error
- func ValidateFunctionGrantTargets(ctx context.Context, dbtx dialect.DBTX, spec *schema.RolesSpec, ...) error
- func ValidateIdentifier(ident string) error
- func VerifySessionDedicated(ctx context.Context, dbtx dialect.DBTX) error
- func WrapShadowCompileError(err error, sqlStr string) error
- type LiveCatalog
- type LiveGrant
- type LiveRoles
- type Postgres
- type RenderOpts
- type SchemaTable
Constants ¶
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 ¶
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 ¶
AcquireSessionAdvisoryLock2 acquires a PostgreSQL session-level advisory lock using two 32-bit keys (namespace, key).
func ComputeShadowSchemas ¶
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
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 ¶
DropShadowSchema safely destroys the temporary shadow schema.
func DropShadowSchemas ¶
DropShadowSchemas destroys all temporary shadow schemas.
func DumpSchema ¶
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 ¶
GenerateAddCheckSQL constructs an ALTER TABLE ... ADD CONSTRAINT ... CHECK statement with NOT VALID for safe zero-lock addition.
func GenerateAddColumnSQL ¶
GenerateAddColumnSQL constructs an ALTER TABLE ... ADD COLUMN statement.
func GenerateAddEnumValueSQL ¶
GenerateAddEnumValueSQL constructs an ALTER TYPE ... ADD VALUE statement.
func GenerateAddFKSQL ¶
GenerateAddFKSQL constructs an ALTER TABLE ... ADD CONSTRAINT statement with NOT VALID for safe zero-lock addition.
func GenerateAlterColumnSQL ¶
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 ¶
GenerateAlterRoleApplySQL rebuilds executable ALTER ROLE SQL including the real password from IR. Used only at apply time.
func GenerateAlterRoleAttrsSQL ¶
GenerateAlterRoleAttrsSQL renders ALTER ROLE ... WITH attr clauses (no password).
func GenerateAlterRolePasswordSQL ¶
GenerateAlterRolePasswordSQL builds ALTER ROLE ... PASSWORD with the real plaintext. Callers must not persist the result on Step.SQL.
func GenerateAlterRolePasswordSQLRedacted ¶
GenerateAlterRolePasswordSQLRedacted is the Step.SQL form of a password change.
func GenerateAlterRoleSetSQL ¶
GenerateAlterRoleSetSQL renders ALTER ROLE ... SET/RESET for config drift.
func GenerateAlterRoleStepSQL ¶
GenerateAlterRoleStepSQL renders redacted ALTER ROLE SQL for plan steps. Password plaintext is never included; apply rebuilds it from Role IR.
func GenerateAlterSequenceSQL ¶
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 ¶
GenerateAttachPartitionSQL constructs an ALTER TABLE ... ATTACH PARTITION statement.
func GenerateCommentSQL ¶
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 ¶
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 ¶
GenerateCreateEnumSQL constructs a CREATE TYPE ... AS ENUM statement.
func GenerateCreateEventTriggerSQL ¶
func GenerateCreateEventTriggerSQL(e *schema.EventTrigger) string
GenerateCreateEventTriggerSQL renders the desired event trigger.
func GenerateCreateExtensionSQL ¶
GenerateCreateExtensionSQL constructs a CREATE EXTENSION IF NOT EXISTS statement.
func GenerateCreateFunctionSQL ¶
GenerateCreateFunctionSQL returns the canonical CREATE OR REPLACE FUNCTION statement produced by pg_get_functiondef (schema names already unmapped by the diff stage).
func GenerateCreateIndexSQL ¶
GenerateCreateIndexSQL constructs a CREATE [UNIQUE] INDEX statement with terminating semicolon.
func GenerateCreatePolicySQL ¶
GenerateCreatePolicySQL constructs a CREATE POLICY statement.
func GenerateCreatePublicationSQL ¶
func GenerateCreatePublicationSQL(p *schema.Publication) string
GenerateCreatePublicationSQL renders the desired publication.
func GenerateCreateRangeTypeSQL ¶
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 ¶
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 ¶
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 ¶
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 ¶
GenerateCreateTableSQL constructs a CREATE TABLE statement including columns and primary key.
func GenerateCreateTriggerSQL ¶
GenerateCreateTriggerSQL returns the canonical CREATE TRIGGER statement produced by pg_get_triggerdef (schema-qualified table references already unmapped by the diff stage).
func GenerateCreateViewSQL ¶
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 ¶
GenerateDetachPartitionConcurrentlySQL constructs an ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY statement.
func GenerateDetachPartitionFinalizeSQL ¶
GenerateDetachPartitionFinalizeSQL constructs an ALTER TABLE ... DETACH PARTITION ... FINALIZE statement.
func GenerateDetachPartitionSQL ¶
GenerateDetachPartitionSQL constructs an ALTER TABLE ... DETACH PARTITION statement.
func GenerateDropCheckSQL ¶
GenerateDropCheckSQL constructs an ALTER TABLE ... DROP CONSTRAINT statement for a CHECK constraint.
func GenerateDropDomainConstraintSQL ¶
GenerateDropDomainConstraintSQL renders ALTER DOMAIN ... DROP CONSTRAINT.
func GenerateDropDomainSQL ¶
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 ¶
GenerateDropEventTriggerSQL renders DROP EVENT TRIGGER.
func GenerateDropFKSQL ¶
GenerateDropFKSQL constructs an ALTER TABLE ... DROP CONSTRAINT statement.
func GenerateDropFunctionSQL ¶
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 ¶
GenerateDropIndexSQL constructs a DROP INDEX statement with optional CONCURRENTLY.
func GenerateDropPolicySQL ¶
GenerateDropPolicySQL constructs a DROP POLICY statement.
func GenerateDropPublicationSQL ¶
GenerateDropPublicationSQL renders DROP PUBLICATION.
func GenerateDropReplicationSlotSQL ¶
GenerateDropReplicationSlotSQL renders pg_drop_replication_slot.
func GenerateDropRoleSQL ¶
GenerateDropRoleSQL renders DROP ROLE.
func GenerateDropSequenceSQL ¶
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 ¶
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 ¶
GenerateDropTriggerSQL constructs a DROP TRIGGER statement.
func GenerateDropTypeSQL ¶
GenerateDropTypeSQL constructs a DROP TYPE statement.
func GenerateDropViewSQL ¶
GenerateDropViewSQL constructs a DROP VIEW or DROP MATERIALIZED VIEW statement.
func GenerateEventTriggerCommentSQL ¶
GenerateEventTriggerCommentSQL stamps the managed-event-trigger marker.
func GenerateGrantSQL ¶
GenerateGrantSQL renders a GRANT statement from desired IR.
func GenerateLockID ¶
GenerateLockID produces a deterministic 64-bit integer hash from a schema identifier.
func GeneratePublicationCommentSQL ¶
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 ¶
GenerateRefreshMatViewSQL constructs a REFRESH MATERIALIZED VIEW statement.
func GenerateRenameEnumValueSQL ¶
GenerateRenameEnumValueSQL constructs an ALTER TYPE ... RENAME VALUE statement.
func GenerateRevokeSQL ¶
GenerateRevokeSQL renders a REVOKE statement. A grant IR flagged GrantOption revokes only the delegation (REVOKE GRANT OPTION FOR), keeping the base privilege.
func GenerateRoleCommentSQL ¶
GenerateRoleCommentSQL stamps the managed-role marker used to distinguish Grizzle-owned roles from operator-created ones.
func GenerateSubscriptionCommentSQL ¶
GenerateSubscriptionCommentSQL stamps the managed-subscription marker.
func GenerateValidateConstraintSQL ¶
GenerateValidateConstraintSQL constructs an ALTER TABLE ... VALIDATE CONSTRAINT statement. It is shared by foreign key and CHECK constraint validation steps.
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 ¶
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 ¶
ReleaseSessionAdvisoryLock releases a PostgreSQL session-level exclusive advisory lock on a dedicated connection.
func ReleaseSessionAdvisoryLock2 ¶
ReleaseSessionAdvisoryLock2 releases a PostgreSQL session-level advisory lock using two 32-bit keys (namespace, key).
func RenderChange ¶
RenderChange converts a pure diff.Change into an executable plan.Step with PostgreSQL DDL.
func RenderChangeWithOpts ¶
RenderChangeWithOpts converts a pure diff.Change into an executable plan.Step using RenderOpts.
func RenderChanges ¶
RenderChanges converts a list of pure changes into sequenced, topologically ordered plan steps.
func RenderChangesWithOpts ¶
RenderChangesWithOpts converts a list of pure changes into sequenced, topologically ordered plan steps using RenderOpts.
func ReplicationSlotIsActive ¶
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 ¶
RewriteShadowSQL redirects references to target schemas in SQL to their corresponding shadow schemas.
func RoleHasManagedMarker ¶
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 ¶
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 ¶
SetupShadowSchema creates a clean, isolated temporary schema for DDL compilation.
func SetupShadowSchemas ¶
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 ¶
ValidateIdentifier ensures schema names contain only safe SQL identifier characters.
func VerifySessionDedicated ¶
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 ¶
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 ¶
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).
type Postgres ¶
type Postgres struct{}
Postgres implements the dialect.Dialect interface for PostgreSQL.
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.
type RenderOpts ¶
RenderOpts configures DDL rendering behavior such as concurrency and server version-specific syntax.
type SchemaTable ¶ added in v0.2.0
SchemaTable identifies a table within a specific PostgreSQL schema.