From 570cf32f09bb68ba0a9455cf226ab8d529923080 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:20:47 +0000 Subject: [PATCH 1/9] fix: preserve extension schema qualifiers in dump and plan (#725) Co-Authored-By: Tianzhou --- cmd/dump/extension_integration_test.go | 65 +++++++++++++++++++ cmd/plan/extension_integration_test.go | 86 ++++++++++++++++++++++++++ cmd/plan/partition_stubs.go | 36 ++++++++--- cmd/plan/plan.go | 15 +++-- cmd/util/connection.go | 9 +++ ir/inspector.go | 4 ++ ir/queries/queries.sql | 12 ++-- ir/queries/queries.sql.go | 12 ++-- ir/stub.go | 13 +++- 9 files changed, 229 insertions(+), 23 deletions(-) diff --git a/cmd/dump/extension_integration_test.go b/cmd/dump/extension_integration_test.go index d8eddc88a..94eee78a9 100644 --- a/cmd/dump/extension_integration_test.go +++ b/cmd/dump/extension_integration_test.go @@ -53,6 +53,71 @@ func TestDumpExtensionMembers(t *testing.T) { require.Equal(t, dumped, roundtrip) } +// Issue #725: extension objects outside the managed schema must stay qualified, +// even when the database search_path makes them visible to the inspector. +func TestDumpExtensionQualifiers(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + pg := testutil.SetupPostgres(t) + defer pg.Stop() + db, host, port, name, user, password := testutil.ConnectToPostgres(t, pg) + defer db.Close() + ctx := context.Background() + _, err := db.ExecContext(ctx, ` + CREATE ROLE extension_reader; + CREATE SCHEMA extensions; + CREATE EXTENSION pg_trgm SCHEMA extensions; + CREATE EXTENSION hstore SCHEMA extensions; + CREATE TABLE images (id bigint PRIMARY KEY, image_name text NOT NULL, attrs extensions.hstore, history extensions.hstore[]); + CREATE INDEX images_gin ON images USING gin (image_name extensions.gin_trgm_ops); + CREATE INDEX images_gist ON images USING gist (image_name extensions.gist_trgm_ops); + CREATE FUNCTION get_attrs(p extensions.hstore) RETURNS extensions.hstore LANGUAGE sql AS $$ SELECT p $$; + COMMENT ON FUNCTION get_attrs(extensions.hstore) IS 'qualified extension type'; + REVOKE EXECUTE ON FUNCTION get_attrs(extensions.hstore) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION get_attrs(extensions.hstore) TO extension_reader; + CREATE PROCEDURE set_attrs(IN p extensions.hstore) LANGUAGE sql AS $$ SELECT 1 $$; + COMMENT ON PROCEDURE set_attrs(extensions.hstore) IS 'qualified procedure'; + REVOKE EXECUTE ON PROCEDURE set_attrs(extensions.hstore) FROM PUBLIC; + GRANT EXECUTE ON PROCEDURE set_attrs(extensions.hstore) TO extension_reader; + `) + require.NoError(t, err) + _, err = db.ExecContext(ctx, fmt.Sprintf(`ALTER DATABASE %s SET search_path TO public, extensions`, ir.QuoteIdentifier(name))) + require.NoError(t, err) + config := &DumpConfig{Host: host, Port: port, DB: name, User: user, Password: password, + Schema: "public", NoComments: true} + dumped, err := ExecuteDump(config) + require.NoError(t, err) + for _, expected := range []string{ + "image_name extensions.gin_trgm_ops", + "image_name extensions.gist_trgm_ops", + "attrs extensions.hstore", + "history extensions.hstore[]", + "p extensions.hstore", + "RETURNS extensions.hstore", + "COMMENT ON FUNCTION get_attrs(extensions.hstore)", + "REVOKE EXECUTE ON FUNCTION get_attrs(p extensions.hstore)", + "GRANT EXECUTE ON FUNCTION get_attrs(p extensions.hstore) TO extension_reader", + "COMMENT ON PROCEDURE set_attrs(extensions.hstore)", + "REVOKE EXECUTE ON PROCEDURE set_attrs(IN p extensions.hstore)", + "GRANT EXECUTE ON PROCEDURE set_attrs(IN p extensions.hstore) TO extension_reader", + } { + require.Contains(t, dumped, expected) + } + _, err = db.ExecContext(ctx, ` + DROP TABLE images; + DROP FUNCTION get_attrs(extensions.hstore); + DROP PROCEDURE set_attrs(extensions.hstore); + SET search_path TO public; + `) + require.NoError(t, err) + _, err = db.ExecContext(ctx, dumped) + require.NoError(t, err, dumped) + roundtrip, err := ExecuteDump(config) + require.NoError(t, err) + require.Equal(t, dumped, roundtrip) +} + // An application partition remains managed even when its parent is an // extension member. Replaying its dump must preserve its own column rules. func TestDumpExtensionPartitionOverrides(t *testing.T) { diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index e64904259..dd5900434 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -2,14 +2,100 @@ package plan import ( "context" + "fmt" "os" "path/filepath" "testing" + "github.com/pgplex/pgschema/cmd/dump" + "github.com/pgplex/pgschema/ir" "github.com/pgplex/pgschema/testutil" "github.com/stretchr/testify/require" ) +// Issue #725: replaying dumps must resolve extension types and operator classes +// regardless of the target's search_path or the desired-state database provider. +func TestPlan_ExtensionQualifiers(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + ctx := context.Background() + target := testutil.SetupPostgres(t) + defer target.Stop() + db, host, port, name, user, password := testutil.ConnectToPostgres(t, target) + defer db.Close() + const setup = ` + CREATE ROLE extension_reader; + CREATE SCHEMA extensions; + CREATE EXTENSION pg_trgm SCHEMA extensions; + CREATE EXTENSION hstore SCHEMA extensions; + ` + _, err := db.ExecContext(ctx, setup+` + CREATE TABLE images (id integer PRIMARY KEY, image_name text, attrs extensions.hstore, history extensions.hstore[]); + CREATE INDEX images_gin ON images USING gin (image_name extensions.gin_trgm_ops); + CREATE MATERIALIZED VIEW image_names AS SELECT image_name FROM images; + CREATE INDEX image_names_gin ON image_names USING gin (image_name extensions.gin_trgm_ops); + CREATE FUNCTION get_attrs(p extensions.hstore) RETURNS extensions.hstore LANGUAGE sql AS $$ SELECT p $$; + COMMENT ON FUNCTION get_attrs(extensions.hstore) IS 'qualified type'; + REVOKE EXECUTE ON FUNCTION get_attrs(extensions.hstore) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION get_attrs(extensions.hstore) TO extension_reader; + CREATE PROCEDURE set_attrs(IN p extensions.hstore) LANGUAGE sql AS $$ SELECT 1 $$; + REVOKE EXECUTE ON PROCEDURE set_attrs(extensions.hstore) FROM PUBLIC; + GRANT EXECUTE ON PROCEDURE set_attrs(extensions.hstore) TO extension_reader; + CREATE TABLE events (id integer, attrs extensions.hstore NOT NULL, history extensions.hstore[], label varchar(12)) PARTITION BY RANGE (id); + CREATE SCHEMA archive; + CREATE TABLE archive.events_2026 PARTITION OF public.events FOR VALUES FROM (0) TO (100); + `) + require.NoError(t, err) + _, err = db.ExecContext(ctx, fmt.Sprintf(`ALTER DATABASE %s SET search_path TO public, extensions`, ir.QuoteIdentifier(name))) + require.NoError(t, err) + _, err = db.ExecContext(ctx, `SET search_path TO public, extensions`) + require.NoError(t, err) + t.Run("partition parent stub", func(t *testing.T) { + stub, err := ir.BuildPartitionedTableStubSQL(ctx, db, "public", "events", "events_stub") + require.NoError(t, err) + require.Contains(t, stub, "attrs extensions.hstore NOT NULL") + require.Contains(t, stub, "history extensions.hstore[]") + require.Contains(t, stub, "label character varying(12)") + }) + planDB := testutil.SetupPostgres(t) + defer planDB.Stop() + planConn, planHost, planPort, planName, planUser, planPassword := testutil.ConnectToPostgres(t, planDB) + defer planConn.Close() + _, err = planConn.ExecContext(ctx, setup) + require.NoError(t, err) + for _, extensionSchema := range []string{"extensions", "Extension Space", "public"} { + if extensionSchema != "extensions" { + move := fmt.Sprintf(`CREATE SCHEMA IF NOT EXISTS %[1]s; ALTER EXTENSION pg_trgm SET SCHEMA %[1]s; ALTER EXTENSION hstore SET SCHEMA %[1]s;`, ir.QuoteIdentifier(extensionSchema)) + _, err = db.ExecContext(ctx, move) + require.NoError(t, err) + _, err = planConn.ExecContext(ctx, move) + require.NoError(t, err) + } + for _, external := range []bool{false, true} { + for _, schema := range []string{"public", "archive"} { + t.Run(fmt.Sprintf("extensions=%s/external=%t/schema=%s", extensionSchema, external, schema), func(t *testing.T) { + dumped, err := dump.ExecuteDump(&dump.DumpConfig{Host: host, Port: port, DB: name, User: user, Password: password, Schema: schema, NoComments: true}) + require.NoError(t, err) + file := filepath.Join(t.TempDir(), "schema.sql") + require.NoError(t, os.WriteFile(file, []byte(dumped), 0644)) + config := &PlanConfig{Host: host, Port: port, DB: name, User: user, Password: password, Schema: schema, File: file, ApplicationName: "pgschema-test"} + if external { + config.PlanDBHost, config.PlanDBPort, config.PlanDBDatabase = planHost, planPort, planName + config.PlanDBUser, config.PlanDBPassword = planUser, planPassword + } + provider, err := CreateDesiredStateProvider(config) + require.NoError(t, err) + defer provider.Stop() + p, err := GeneratePlan(config, provider) + require.NoError(t, err) + require.False(t, p.HasAnyChanges(), p.HumanColored(false)) + }) + } + } + } +} + // TestEmbeddedPlanDB_InstallsTargetExtensions verifies that the embedded plan // database mirrors the extensions installed on the target database (issue #584). // diff --git a/cmd/plan/partition_stubs.go b/cmd/plan/partition_stubs.go index f027b51ee..25357c954 100644 --- a/cmd/plan/partition_stubs.go +++ b/cmd/plan/partition_stubs.go @@ -27,10 +27,10 @@ func partitionStubName(schema, table string) string { // collisions with real tables or other stubs, and PARTITION OF references // are rewritten to point to the stub name. Everything stays inside the // temp schema via search_path. -func prependPartitionParentStubs(ctx context.Context, cfg *util.ConnectionConfig, targetSchema, desiredSQL string) (string, error) { +func prependPartitionParentStubs(ctx context.Context, cfg *util.ConnectionConfig, targetSchema, desiredSQL string) (string, map[string]postgres.QualifiedName, error) { refs := postgres.ExtractPartitionOfTargets(desiredSQL, targetSchema) if len(refs) == 0 { - return desiredSQL, nil + return desiredSQL, nil, nil } created := make(map[string]bool) @@ -52,37 +52,59 @@ func prependPartitionParentStubs(ctx context.Context, cfg *util.ConnectionConfig toStub = append(toStub, ref) } if len(toStub) == 0 { - return desiredSQL, nil + return desiredSQL, nil, nil } conn, err := util.Connect(cfg) if err != nil { - return "", err + return "", nil, err } defer conn.Close() var stubs strings.Builder + parents := make(map[string]postgres.QualifiedName) rewritten := desiredSQL for _, ref := range toStub { stubName := partitionStubName(ref.Schema, ref.Table) ddl, err := ir.BuildPartitionedTableStubSQL(ctx, conn, ref.Schema, ref.Table, stubName) if err != nil { - return "", err + return "", nil, err } if ddl == "" { logger.Get().Warn("cross-schema partition parent not found or not partitioned", "schema", ref.Schema, "table", ref.Table) - return "", fmt.Errorf("cross-schema partition parent %s.%s not found or not a partitioned table on the target database", ref.Schema, ref.Table) + return "", nil, fmt.Errorf("cross-schema partition parent %s.%s not found or not a partitioned table on the target database", ref.Schema, ref.Table) } logger.Get().Debug("prepending stub for cross-schema partition parent", "schema", ref.Schema, "table", ref.Table, "stubName", stubName) stubs.WriteString(ddl) + parents[stubName] = ref // Rewrite PARTITION OF references to point to the stub name. rewritten = rewritePartitionOfRef(rewritten, ref.Schema, ref.Table, stubName) } - return stubs.String() + rewritten, nil + return stubs.String() + rewritten, parents, nil +} + +// restorePartitionParents removes planning-only stubs from the desired IR and +// restores each child's real cross-schema parent before comparison. +func restorePartitionParents(schema *ir.Schema, parents map[string]postgres.QualifiedName) { + for _, table := range schema.Tables { + if table.PartitionOfSchema != schema.Name { + continue + } + if parent, ok := parents[table.PartitionOf]; ok { + if stub := schema.Tables[table.PartitionOf]; stub != nil { + table.PartitionParentColumns = stub.Columns + } + table.PartitionOfSchema = parent.Schema + table.PartitionOf = parent.Table + } + } + for stubName := range parents { + delete(schema.Tables, stubName) + } } // rewritePartitionOfRef rewrites "PARTITION OF schema.table" to diff --git a/cmd/plan/plan.go b/cmd/plan/plan.go index 10677920c..bde4156f4 100644 --- a/cmd/plan/plan.go +++ b/cmd/plan/plan.go @@ -326,7 +326,7 @@ func GeneratePlan(config *PlanConfig, provider postgres.DesiredStateProvider) (* // Stub cross-schema partition parents so PARTITION OF references resolve // in the plan database (issue #552). - desiredState, err = prependPartitionParentStubs(ctx, targetConnCfg, config.Schema, desiredState) + desiredState, partitionParents, err := prependPartitionParentStubs(ctx, targetConnCfg, config.Schema, desiredState) if err != nil { return nil, fmt.Errorf("failed to stub cross-schema partition parents: %w", err) } @@ -381,6 +381,9 @@ func GeneratePlan(config *PlanConfig, provider postgres.DesiredStateProvider) (* if schemaToInspect != config.Schema { normalizeSchemaNames(desiredStateIR, schemaToInspect, config.Schema) } + if desiredSchema, ok := desiredStateIR.GetSchema(config.Schema); ok { + restorePartitionParents(desiredSchema, partitionParents) + } // Extract the target database's major version (e.g. "PostgreSQL 18.1" -> 18) // to gate version-specific DDL and rewrites. Zero (unknown) is handled @@ -621,8 +624,9 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { } } index.Where = stripQualifiers(replaceString(index.Where)) - if index.IsExpression { - for _, col := range index.Columns { + for _, col := range index.Columns { + col.Operator = ir.StripSchemaQualifiers(replaceString(col.Operator), toSchema) + if index.IsExpression { col.Name = stripQualifiers(replaceString(col.Name)) } } @@ -658,8 +662,9 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { index.Schema = toSchema } index.Where = stripQualifiers(replaceString(index.Where)) - if index.IsExpression { - for _, col := range index.Columns { + for _, col := range index.Columns { + col.Operator = ir.StripSchemaQualifiers(replaceString(col.Operator), toSchema) + if index.IsExpression { col.Name = stripQualifiers(replaceString(col.Name)) } } diff --git a/cmd/util/connection.go b/cmd/util/connection.go index 6496fdead..b2076d2bc 100644 --- a/cmd/util/connection.go +++ b/cmd/util/connection.go @@ -21,6 +21,7 @@ type ConnectionConfig struct { Password string SSLMode string ApplicationName string + SearchPath string } // Connect establishes a database connection using the provided configuration @@ -76,6 +77,10 @@ func buildDSN(config *ConnectionConfig) string { if config.ApplicationName != "" { parts = append(parts, fmt.Sprintf("application_name=%s", config.ApplicationName)) } + if config.SearchPath != "" { + escaped := strings.NewReplacer(`\`, `\\`, "'", `\'`).Replace(config.SearchPath) + parts = append(parts, "search_path='"+escaped+"'") + } // Set connect_timeout to fail fast if the database is unreachable. // This is a libpq parameter that pgx respects for TCP connection establishment. @@ -113,6 +118,10 @@ func GetIRFromDatabase(host string, port int, db, user, password, sslmode, schem Password: password, SSLMode: sslmode, ApplicationName: applicationName, + // Deparsers qualify all user-defined types and operators independently + // of the target database's search_path, as pg_dump does. The startup + // parameter applies to every connection the inspection pool opens. + SearchPath: "pg_catalog", } conn, err := Connect(config) diff --git a/ir/inspector.go b/ir/inspector.go index 0ed1714fa..4ee2f4863 100644 --- a/ir/inspector.go +++ b/ir/inspector.go @@ -2946,6 +2946,10 @@ func (i *Inspector) buildRevokedDefaultPrivileges(ctx context.Context, targetSch objectName := row.ObjectName.String objectType := row.ObjectType.String + if objectType == "FUNCTION" || objectType == "PROCEDURE" { + objectName = i.stripSameSchemaPrefixFromList(objectName, targetSchema) + } + // Skip revoked default privileges for ignored objects if i.ignoreConfig != nil && i.ignoreConfig.ShouldIgnorePrivilegeByObjectType(objectName, objectType) { continue diff --git a/ir/queries/queries.sql b/ir/queries/queries.sql index 3bb4d9d23..cfe6f0eee 100644 --- a/ir/queries/queries.sql +++ b/ir/queries/queries.sql @@ -141,9 +141,9 @@ WITH column_base AS ( c.udt_name::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') WHEN dn.nspname = 'pg_catalog' THEN c.udt_name::text WHEN dn.nspname = c.table_schema THEN - dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') ELSE - dn.nspname::text || '.' || dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dn.nspname) || '.' || quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') END WHEN dt.typtype IN ('r', 'm') THEN -- Range and multirange types: built-in ones (int4range, int4multirange) @@ -301,9 +301,9 @@ WITH column_base AS ( c.udt_name::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') WHEN dn.nspname = 'pg_catalog' THEN c.udt_name::text WHEN dn.nspname = c.table_schema THEN - dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') ELSE - dn.nspname::text || '.' || dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dn.nspname) || '.' || quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') END WHEN dt.typtype IN ('r', 'm') THEN -- Range and multirange types: built-in ones (int4range, int4multirange) @@ -656,10 +656,12 @@ WITH index_base AS ( ARRAY( SELECT CASE WHEN opc.opcdefault THEN '' -- Omit default operator classes - ELSE COALESCE(opc.opcname, '') + WHEN opn.nspname IN ('pg_catalog', n.nspname) THEN quote_ident(opc.opcname) + ELSE quote_ident(opn.nspname) || '.' || quote_ident(opc.opcname) END FROM generate_series(1, idx.indnkeyatts) k LEFT JOIN pg_opclass opc ON opc.oid = idx.indclass[k-1] + LEFT JOIN pg_namespace opn ON opn.oid = opc.opcnamespace ) as column_opclasses, ARRAY( SELECT pg_get_indexdef(idx.indexrelid, k::int, true) diff --git a/ir/queries/queries.sql.go b/ir/queries/queries.sql.go index 0232a7c5f..9ba546b91 100644 --- a/ir/queries/queries.sql.go +++ b/ir/queries/queries.sql.go @@ -479,9 +479,9 @@ WITH column_base AS ( c.udt_name::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') WHEN dn.nspname = 'pg_catalog' THEN c.udt_name::text WHEN dn.nspname = c.table_schema THEN - dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') ELSE - dn.nspname::text || '.' || dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dn.nspname) || '.' || quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') END WHEN dt.typtype IN ('r', 'm') THEN -- Range and multirange types: built-in ones (int4range, int4multirange) @@ -715,9 +715,9 @@ WITH column_base AS ( c.udt_name::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') WHEN dn.nspname = 'pg_catalog' THEN c.udt_name::text WHEN dn.nspname = c.table_schema THEN - dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') ELSE - dn.nspname::text || '.' || dt.typname::text || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') + quote_ident(dn.nspname) || '.' || quote_ident(dt.typname) || COALESCE(substring(format_type(a.atttypid, a.atttypmod) FROM '\([^)]*\)'), '') END WHEN dt.typtype IN ('r', 'm') THEN -- Range and multirange types: built-in ones (int4range, int4multirange) @@ -2452,10 +2452,12 @@ WITH index_base AS ( ARRAY( SELECT CASE WHEN opc.opcdefault THEN '' -- Omit default operator classes - ELSE COALESCE(opc.opcname, '') + WHEN opn.nspname IN ('pg_catalog', n.nspname) THEN quote_ident(opc.opcname) + ELSE quote_ident(opn.nspname) || '.' || quote_ident(opc.opcname) END FROM generate_series(1, idx.indnkeyatts) k LEFT JOIN pg_opclass opc ON opc.oid = idx.indclass[k-1] + LEFT JOIN pg_namespace opn ON opn.oid = opc.opcnamespace ) as column_opclasses, ARRAY( SELECT pg_get_indexdef(idx.indexrelid, k::int, true) diff --git a/ir/stub.go b/ir/stub.go index d10a60e13..02683e54c 100644 --- a/ir/stub.go +++ b/ir/stub.go @@ -182,7 +182,18 @@ WHERE n.nspname = $1 AND NOT a.attisdropped ORDER BY a.attnum` - rows, err := db.QueryContext(ctx, q, schema, table) + // format_type omits a type's schema when it is visible on search_path. + // Stubs are replayed in a different database, so use pg_dump's catalog-only + // lookup path. Keep the setting local to this connection and transaction. + tx, err := db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return nil, fmt.Errorf("begin stub column inspection: %w", err) + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, "SET LOCAL search_path TO pg_catalog"); err != nil { + return nil, fmt.Errorf("set stub column search_path: %w", err) + } + rows, err := tx.QueryContext(ctx, q, schema, table) if err != nil { return nil, fmt.Errorf("query columns for %s.%s: %w", schema, table, err) } From f51a1449daff9c3b0fbb0b711fdd543ab8607ab0 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:26:40 +0000 Subject: [PATCH 2/9] fix: scope extension routine deparsing to catalog queries Co-Authored-By: Tianzhou --- cmd/plan/extension_integration_test.go | 2 ++ cmd/util/connection.go | 9 ------ ir/queries/queries.sql | 43 +++++++++++++++++++------- ir/queries/queries.sql.go | 43 +++++++++++++++++++------- 4 files changed, 64 insertions(+), 33 deletions(-) diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index dd5900434..fa5811ae0 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -42,6 +42,8 @@ func TestPlan_ExtensionQualifiers(t *testing.T) { CREATE PROCEDURE set_attrs(IN p extensions.hstore) LANGUAGE sql AS $$ SELECT 1 $$; REVOKE EXECUTE ON PROCEDURE set_attrs(extensions.hstore) FROM PUBLIC; GRANT EXECUTE ON PROCEDURE set_attrs(extensions.hstore) TO extension_reader; + CREATE SEQUENCE image_id_seq; + CREATE FUNCTION next_image_id() RETURNS bigint LANGUAGE sql RETURN nextval('image_id_seq'); CREATE TABLE events (id integer, attrs extensions.hstore NOT NULL, history extensions.hstore[], label varchar(12)) PARTITION BY RANGE (id); CREATE SCHEMA archive; CREATE TABLE archive.events_2026 PARTITION OF public.events FOR VALUES FROM (0) TO (100); diff --git a/cmd/util/connection.go b/cmd/util/connection.go index b2076d2bc..6496fdead 100644 --- a/cmd/util/connection.go +++ b/cmd/util/connection.go @@ -21,7 +21,6 @@ type ConnectionConfig struct { Password string SSLMode string ApplicationName string - SearchPath string } // Connect establishes a database connection using the provided configuration @@ -77,10 +76,6 @@ func buildDSN(config *ConnectionConfig) string { if config.ApplicationName != "" { parts = append(parts, fmt.Sprintf("application_name=%s", config.ApplicationName)) } - if config.SearchPath != "" { - escaped := strings.NewReplacer(`\`, `\\`, "'", `\'`).Replace(config.SearchPath) - parts = append(parts, "search_path='"+escaped+"'") - } // Set connect_timeout to fail fast if the database is unreachable. // This is a libpq parameter that pgx respects for TCP connection establishment. @@ -118,10 +113,6 @@ func GetIRFromDatabase(host string, port int, db, user, password, sslmode, schem Password: password, SSLMode: sslmode, ApplicationName: applicationName, - // Deparsers qualify all user-defined types and operators independently - // of the target database's search_path, as pg_dump does. The startup - // parameter applies to every connection the inspection pool opens. - SearchPath: "pg_catalog", } conn, err := Connect(config) diff --git a/ir/queries/queries.sql b/ir/queries/queries.sql index cfe6f0eee..412ebd479 100644 --- a/ir/queries/queries.sql +++ b/ir/queries/queries.sql @@ -1754,17 +1754,17 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(p.oid), + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, - COALESCE(pg_get_function_result(p.oid), r.data_type) AS data_type, + COALESCE(pg_get_function_result(deparse.oid), r.data_type) AS data_type, r.external_language, COALESCE(desc_func.description, '') AS function_comment, - oidvectortypes(p.proargtypes) AS function_arguments, - pg_get_function_arguments(p.oid) AS function_signature, + deparse.arguments AS function_arguments, + pg_get_function_arguments(deparse.oid) AS function_signature, -- Identity form of the arguments, as the privilege queries name a function - pg_get_function_identity_arguments(p.oid) AS function_identity_arguments, + pg_get_function_identity_arguments(deparse.oid) AS function_identity_arguments, CASE p.provolatile WHEN 'i' THEN 'IMMUTABLE' WHEN 's' THEN 'STABLE' @@ -1784,6 +1784,12 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = r.routine_schema) AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_func ON desc_func.objoid = p.oid AND desc_func.classoid = 'pg_proc'::regclass +JOIN LATERAL ( + -- Deparse bodies and signatures with only the routine schema visible. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL + OFFSET 0 +) deparse ON true WHERE r.routine_schema = $1 AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( @@ -1813,19 +1819,24 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(p.oid), + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, r.external_language, COALESCE(desc_proc.description, '') AS procedure_comment, - oidvectortypes(p.proargtypes) AS procedure_arguments, - pg_get_function_arguments(p.oid) AS procedure_signature + deparse.arguments AS procedure_arguments, + pg_get_function_arguments(deparse.oid) AS procedure_signature FROM information_schema.routines r LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = r.routine_schema) AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_proc ON desc_proc.objoid = p.oid AND desc_proc.classoid = 'pg_proc'::regclass +JOIN LATERAL ( + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL + OFFSET 0 +) deparse ON true WHERE r.routine_schema = $1 AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( @@ -2426,7 +2437,9 @@ WITH acl_data AS ( -- Functions SELECT n.nspname AS schema_name, - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'FUNCTION' AS object_type, p.proacl AS acl, pg_get_userbyid(p.proowner) AS owner @@ -2458,7 +2471,9 @@ WITH acl_data AS ( -- Procedures SELECT n.nspname AS schema_name, - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'PROCEDURE' AS object_type, p.proacl AS acl, pg_get_userbyid(p.proowner) AS owner @@ -2548,7 +2563,9 @@ ORDER BY e.object_type, e.object_name, e.grantee, e.privilege_type; WITH objects_with_acl AS ( -- Functions (ACL may be NULL for default permissions; filtering happens in public_grants CTE) SELECT - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'FUNCTION' AS object_type, p.proacl AS acl FROM pg_proc p @@ -2577,7 +2594,9 @@ WITH objects_with_acl AS ( -- Procedures SELECT - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'PROCEDURE' AS object_type, p.proacl AS acl FROM pg_proc p diff --git a/ir/queries/queries.sql.go b/ir/queries/queries.sql.go index 9ba546b91..65acb6e5e 100644 --- a/ir/queries/queries.sql.go +++ b/ir/queries/queries.sql.go @@ -2156,17 +2156,17 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(p.oid), + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, - COALESCE(pg_get_function_result(p.oid), r.data_type) AS data_type, + COALESCE(pg_get_function_result(deparse.oid), r.data_type) AS data_type, r.external_language, COALESCE(desc_func.description, '') AS function_comment, - oidvectortypes(p.proargtypes) AS function_arguments, - pg_get_function_arguments(p.oid) AS function_signature, + deparse.arguments AS function_arguments, + pg_get_function_arguments(deparse.oid) AS function_signature, -- Identity form of the arguments, as the privilege queries name a function - pg_get_function_identity_arguments(p.oid) AS function_identity_arguments, + pg_get_function_identity_arguments(deparse.oid) AS function_identity_arguments, CASE p.provolatile WHEN 'i' THEN 'IMMUTABLE' WHEN 's' THEN 'STABLE' @@ -2186,6 +2186,12 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = r.routine_schema) AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_func ON desc_func.objoid = p.oid AND desc_func.classoid = 'pg_proc'::regclass +JOIN LATERAL ( + -- Deparse bodies and signatures with only the routine schema visible. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL + OFFSET 0 +) deparse ON true WHERE r.routine_schema = $1 AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( @@ -3160,7 +3166,9 @@ WITH acl_data AS ( -- Functions SELECT n.nspname AS schema_name, - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'FUNCTION' AS object_type, p.proacl AS acl, pg_get_userbyid(p.proowner) AS owner @@ -3192,7 +3200,9 @@ WITH acl_data AS ( -- Procedures SELECT n.nspname AS schema_name, - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'PROCEDURE' AS object_type, p.proacl AS acl, pg_get_userbyid(p.proowner) AS owner @@ -3411,19 +3421,24 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(p.oid), + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, r.external_language, COALESCE(desc_proc.description, '') AS procedure_comment, - oidvectortypes(p.proargtypes) AS procedure_arguments, - pg_get_function_arguments(p.oid) AS procedure_signature + deparse.arguments AS procedure_arguments, + pg_get_function_arguments(deparse.oid) AS procedure_signature FROM information_schema.routines r LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = r.routine_schema) AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_proc ON desc_proc.objoid = p.oid AND desc_proc.classoid = 'pg_proc'::regclass +JOIN LATERAL ( + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL + OFFSET 0 +) deparse ON true WHERE r.routine_schema = $1 AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( @@ -3935,7 +3950,9 @@ const getRevokedDefaultPrivilegesForSchema = `-- name: GetRevokedDefaultPrivileg WITH objects_with_acl AS ( -- Functions (ACL may be NULL for default permissions; filtering happens in public_grants CTE) SELECT - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'FUNCTION' AS object_type, p.proacl AS acl FROM pg_proc p @@ -3964,7 +3981,9 @@ WITH objects_with_acl AS ( -- Procedures SELECT - p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS object_name, + p.proname || '(' || pg_get_function_identity_arguments( + CASE WHEN set_config('search_path', quote_ident(n.nspname), true) IS NOT NULL THEN p.oid END + ) || ')' AS object_name, 'PROCEDURE' AS object_type, p.proacl AS acl FROM pg_proc p From 0b0263d1608f49e603be1f710a9390eb6e3410cb Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:31:38 +0000 Subject: [PATCH 3/9] fix: align routine dependency argument qualification Co-Authored-By: Tianzhou --- cmd/plan/extension_integration_test.go | 36 ++++++++++++++++++++++++++ ir/queries/queries.sql | 12 ++++++--- ir/queries/queries.sql.go | 12 ++++++--- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index fa5811ae0..1ea06844a 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -98,6 +98,42 @@ func TestPlan_ExtensionQualifiers(t *testing.T) { } } +func TestPlan_DropsExtensionTypedRoutineDependencies(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + ctx := context.Background() + target := testutil.SetupPostgres(t) + defer target.Stop() + db, host, port, name, user, password := testutil.ConnectToPostgres(t, target) + defer db.Close() + _, err := db.ExecContext(ctx, ` + CREATE SCHEMA extensions; + CREATE EXTENSION hstore SCHEMA extensions; + CREATE FUNCTION z_callee(p extensions.hstore) RETURNS text LANGUAGE sql RETURN 'value'; + CREATE FUNCTION a_caller(p extensions.hstore) RETURNS text LANGUAGE sql RETURN z_callee(p); + `) + require.NoError(t, err) + _, err = db.ExecContext(ctx, fmt.Sprintf(`ALTER DATABASE %s SET search_path TO public, extensions`, ir.QuoteIdentifier(name))) + require.NoError(t, err) + + file := filepath.Join(t.TempDir(), "schema.sql") + require.NoError(t, os.WriteFile(file, []byte("CREATE TABLE marker (id integer);"), 0644)) + config := &PlanConfig{Host: host, Port: port, DB: name, User: user, Password: password, Schema: "public", File: file} + provider, err := CreateDesiredStateProvider(config) + require.NoError(t, err) + defer provider.Stop() + p, err := GeneratePlan(config, provider) + require.NoError(t, err) + + for _, group := range p.Groups { + for _, step := range group.Steps { + _, err = db.ExecContext(ctx, step.SQL) + require.NoError(t, err) + } + } +} + // TestEmbeddedPlanDB_InstallsTargetExtensions verifies that the embedded plan // database mirrors the extensions installed on the target database (issue #584). // diff --git a/ir/queries/queries.sql b/ir/queries/queries.sql index 412ebd479..065a67f02 100644 --- a/ir/queries/queries.sql +++ b/ir/queries/queries.sql @@ -2724,7 +2724,9 @@ ORDER BY e.table_name, e.column_name, e.grantee, e.privilege_type; SELECT fn.nspname AS function_schema, p.proname AS function_name, - oidvectortypes(p.proargtypes) AS function_args, + oidvectortypes(CASE + WHEN set_config('search_path', quote_ident(fn.nspname), true) IS NOT NULL THEN p.proargtypes + END) AS function_args, tn.nspname AS type_schema, t.typname AS type_name FROM pg_depend d @@ -2745,10 +2747,14 @@ WHERE d.classid = 'pg_proc'::regclass SELECT dependent_ns.nspname AS dependent_schema, dependent_proc.proname AS dependent_name, - oidvectortypes(dependent_proc.proargtypes) AS dependent_args, + oidvectortypes(CASE + WHEN set_config('search_path', quote_ident(dependent_ns.nspname), true) IS NOT NULL THEN dependent_proc.proargtypes + END) AS dependent_args, referenced_ns.nspname AS referenced_schema, referenced_proc.proname AS referenced_name, - oidvectortypes(referenced_proc.proargtypes) AS referenced_args + oidvectortypes(CASE + WHEN set_config('search_path', quote_ident(referenced_ns.nspname), true) IS NOT NULL THEN referenced_proc.proargtypes + END) AS referenced_args FROM pg_depend d JOIN pg_proc dependent_proc ON d.objid = dependent_proc.oid JOIN pg_namespace dependent_ns ON dependent_proc.pronamespace = dependent_ns.oid diff --git a/ir/queries/queries.sql.go b/ir/queries/queries.sql.go index 65acb6e5e..095138890 100644 --- a/ir/queries/queries.sql.go +++ b/ir/queries/queries.sql.go @@ -1926,10 +1926,14 @@ const getFunctionDependencies = `-- name: GetFunctionDependencies :many SELECT dependent_ns.nspname AS dependent_schema, dependent_proc.proname AS dependent_name, - oidvectortypes(dependent_proc.proargtypes) AS dependent_args, + oidvectortypes(CASE + WHEN set_config('search_path', quote_ident(dependent_ns.nspname), true) IS NOT NULL THEN dependent_proc.proargtypes + END) AS dependent_args, referenced_ns.nspname AS referenced_schema, referenced_proc.proname AS referenced_name, - oidvectortypes(referenced_proc.proargtypes) AS referenced_args + oidvectortypes(CASE + WHEN set_config('search_path', quote_ident(referenced_ns.nspname), true) IS NOT NULL THEN referenced_proc.proargtypes + END) AS referenced_args FROM pg_depend d JOIN pg_proc dependent_proc ON d.objid = dependent_proc.oid JOIN pg_namespace dependent_ns ON dependent_proc.pronamespace = dependent_ns.oid @@ -1987,7 +1991,9 @@ const getFunctionTypeDependencies = `-- name: GetFunctionTypeDependencies :many SELECT fn.nspname AS function_schema, p.proname AS function_name, - oidvectortypes(p.proargtypes) AS function_args, + oidvectortypes(CASE + WHEN set_config('search_path', quote_ident(fn.nspname), true) IS NOT NULL THEN p.proargtypes + END) AS function_args, tn.nspname AS type_schema, t.typname AS type_name FROM pg_depend d From 2230cf78c7a89b6bc2839a7090bb2ff272b81466 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:34:06 +0000 Subject: [PATCH 4/9] fix: deparse external routine bodies with the managed extension schema Co-Authored-By: Tianzhou --- cmd/plan/extension_integration_test.go | 2 ++ ir/inspector.go | 23 ++++++++++++-- ir/queries/extension_members_test.go | 12 +++++-- ir/queries/queries.sql | 25 ++++++++++----- ir/queries/queries.sql.go | 43 +++++++++++++++++++------- 5 files changed, 82 insertions(+), 23 deletions(-) diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index 1ea06844a..a0d5340a7 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -44,6 +44,8 @@ func TestPlan_ExtensionQualifiers(t *testing.T) { GRANT EXECUTE ON PROCEDURE set_attrs(extensions.hstore) TO extension_reader; CREATE SEQUENCE image_id_seq; CREATE FUNCTION next_image_id() RETURNS bigint LANGUAGE sql RETURN nextval('image_id_seq'); + CREATE FUNCTION extract_attr(p extensions.hstore) RETURNS text LANGUAGE sql + RETURN p OPERATOR(extensions.->) 'key'; CREATE TABLE events (id integer, attrs extensions.hstore NOT NULL, history extensions.hstore[], label varchar(12)) PARTITION BY RANGE (id); CREATE SCHEMA archive; CREATE TABLE archive.events_2026 PARTITION OF public.events FOR VALUES FROM (0) TO (100); diff --git a/ir/inspector.go b/ir/inspector.go index 4ee2f4863..b62c6c197 100644 --- a/ir/inspector.go +++ b/ir/inspector.go @@ -1305,8 +1305,24 @@ func (i *Inspector) buildSequences(ctx context.Context, schema *IR, targetSchema return nil } +// routineBodySearchPath mirrors resolution in the external plan database when +// the managed schema still hosts extensions outside the comparison schema. +// The routine's actual schema comes first so local references stay portable. +func (i *Inspector) routineBodySearchPath(targetSchema string) sql.NullString { + if targetSchema != i.managedSchema && i.extensionSchemas[i.managedSchema] { + return sql.NullString{ + String: QuoteIdentifier(targetSchema) + ", " + QuoteIdentifier(i.managedSchema), + Valid: true, + } + } + return sql.NullString{} +} + func (i *Inspector) buildFunctions(ctx context.Context, schema *IR, targetSchema string) error { - functions, err := i.queries.GetFunctionsForSchema(ctx, sql.NullString{String: targetSchema, Valid: true}) + functions, err := i.queries.GetFunctionsForSchema(ctx, queries.GetFunctionsForSchemaParams{ + SchemaName: sql.NullString{String: targetSchema, Valid: true}, + BodySearchPath: i.routineBodySearchPath(targetSchema), + }) if err != nil { return err } @@ -1932,7 +1948,10 @@ func (i *Inspector) lookupTypeNameFromOID(oid int64) string { } func (i *Inspector) buildProcedures(ctx context.Context, schema *IR, targetSchema string) error { - procedures, err := i.queries.GetProceduresForSchema(ctx, sql.NullString{String: targetSchema, Valid: true}) + procedures, err := i.queries.GetProceduresForSchema(ctx, queries.GetProceduresForSchemaParams{ + SchemaName: sql.NullString{String: targetSchema, Valid: true}, + BodySearchPath: i.routineBodySearchPath(targetSchema), + }) if err != nil { return err } diff --git a/ir/queries/extension_members_test.go b/ir/queries/extension_members_test.go index c89347839..6b67dfb9c 100644 --- a/ir/queries/extension_members_test.go +++ b/ir/queries/extension_members_test.go @@ -105,9 +105,13 @@ func TestExtensionMembers(t *testing.T) { {"GetSequences", func() (string, error) { return extensionRows(q.GetSequences(ctx)) }}, {"GetSequencesForSchema", func() (string, error) { return extensionRows(q.GetSequencesForSchema(ctx, schema)) }}, {"GetFunctions", func() (string, error) { return extensionRows(q.GetFunctions(ctx)) }}, - {"GetFunctionsForSchema", func() (string, error) { return extensionRows(q.GetFunctionsForSchema(ctx, schema)) }}, + {"GetFunctionsForSchema", func() (string, error) { + return extensionRows(q.GetFunctionsForSchema(ctx, queries.GetFunctionsForSchemaParams{SchemaName: schema})) + }}, {"GetProcedures", func() (string, error) { return extensionRows(q.GetProcedures(ctx)) }}, - {"GetProceduresForSchema", func() (string, error) { return extensionRows(q.GetProceduresForSchema(ctx, schema)) }}, + {"GetProceduresForSchema", func() (string, error) { + return extensionRows(q.GetProceduresForSchema(ctx, queries.GetProceduresForSchemaParams{SchemaName: schema})) + }}, {"GetAggregates", func() (string, error) { return extensionRows(q.GetAggregates(ctx)) }}, {"GetAggregatesForSchema", func() (string, error) { return extensionRows(q.GetAggregatesForSchema(ctx, schema)) }}, {"GetViews", func() (string, error) { return extensionRows(q.GetViews(ctx)) }}, @@ -222,7 +226,9 @@ func TestExtensionMembershipCatalogIdentity(t *testing.T) { global, err := extensionRows(q.GetFunctions(ctx)) require.NoError(t, err) require.Contains(t, global, "app595_identity") - scoped, err := extensionRows(q.GetFunctionsForSchema(ctx, sql.NullString{String: "public", Valid: true})) + scoped, err := extensionRows(q.GetFunctionsForSchema(ctx, queries.GetFunctionsForSchemaParams{ + SchemaName: sql.NullString{String: "public", Valid: true}, + })) require.NoError(t, err) require.Contains(t, scoped, "app595_identity") }) diff --git a/ir/queries/queries.sql b/ir/queries/queries.sql index 065a67f02..500f036be 100644 --- a/ir/queries/queries.sql +++ b/ir/queries/queries.sql @@ -1754,7 +1754,7 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(deparse.oid), + deparse.body, CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, @@ -1785,12 +1785,17 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_func ON desc_func.objoid = p.oid AND desc_func.classoid = 'pg_proc'::regclass JOIN LATERAL ( - -- Deparse bodies and signatures with only the routine schema visible. - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + SELECT pg_get_function_sqlbody(p.oid) AS definition + WHERE set_config('search_path', COALESCE(sqlc.narg(body_search_path)::text, quote_ident(r.routine_schema)), true) IS NOT NULL + OFFSET 0 +) body ON true +JOIN LATERAL ( + -- Keep the body's fallback schemas out of signature deparsing. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = $1 +WHERE r.routine_schema = sqlc.narg(schema_name) AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep @@ -1819,7 +1824,7 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(deparse.oid), + deparse.body, CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, @@ -1833,11 +1838,17 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_proc ON desc_proc.objoid = p.oid AND desc_proc.classoid = 'pg_proc'::regclass JOIN LATERAL ( - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + SELECT pg_get_function_sqlbody(p.oid) AS definition + WHERE set_config('search_path', COALESCE(sqlc.narg(body_search_path)::text, quote_ident(r.routine_schema)), true) IS NOT NULL + OFFSET 0 +) body ON true +JOIN LATERAL ( + -- Keep the body's fallback schemas out of signature deparsing. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = $1 +WHERE r.routine_schema = sqlc.narg(schema_name) AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep diff --git a/ir/queries/queries.sql.go b/ir/queries/queries.sql.go index 095138890..150ff2869 100644 --- a/ir/queries/queries.sql.go +++ b/ir/queries/queries.sql.go @@ -2162,7 +2162,7 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(deparse.oid), + deparse.body, CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, @@ -2193,12 +2193,17 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_func ON desc_func.objoid = p.oid AND desc_func.classoid = 'pg_proc'::regclass JOIN LATERAL ( - -- Deparse bodies and signatures with only the routine schema visible. - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + SELECT pg_get_function_sqlbody(p.oid) AS definition + WHERE set_config('search_path', COALESCE($1::text, quote_ident(r.routine_schema)), true) IS NOT NULL + OFFSET 0 +) body ON true +JOIN LATERAL ( + -- Keep the body's fallback schemas out of signature deparsing. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = $1 +WHERE r.routine_schema = $2 AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep @@ -2220,6 +2225,11 @@ WHERE r.routine_schema = $1 ORDER BY r.routine_schema, r.routine_name ` +type GetFunctionsForSchemaParams struct { + BodySearchPath sql.NullString `db:"body_search_path" json:"body_search_path"` + SchemaName sql.NullString `db:"schema_name" json:"schema_name"` +} + type GetFunctionsForSchemaRow struct { RoutineSchema interface{} `db:"routine_schema" json:"routine_schema"` RoutineName interface{} `db:"routine_name" json:"routine_name"` @@ -2242,8 +2252,8 @@ type GetFunctionsForSchemaRow struct { } // GetFunctionsForSchema retrieves all user-defined functions for a specific schema -func (q *Queries) GetFunctionsForSchema(ctx context.Context, dollar_1 sql.NullString) ([]GetFunctionsForSchemaRow, error) { - rows, err := q.db.QueryContext(ctx, getFunctionsForSchema, dollar_1) +func (q *Queries) GetFunctionsForSchema(ctx context.Context, arg GetFunctionsForSchemaParams) ([]GetFunctionsForSchemaRow, error) { + rows, err := q.db.QueryContext(ctx, getFunctionsForSchema, arg.BodySearchPath, arg.SchemaName) if err != nil { return nil, err } @@ -3427,7 +3437,7 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - pg_get_function_sqlbody(deparse.oid), + deparse.body, CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, r.routine_type, @@ -3441,11 +3451,17 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_proc ON desc_proc.objoid = p.oid AND desc_proc.classoid = 'pg_proc'::regclass JOIN LATERAL ( - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments + SELECT pg_get_function_sqlbody(p.oid) AS definition + WHERE set_config('search_path', COALESCE($1::text, quote_ident(r.routine_schema)), true) IS NOT NULL + OFFSET 0 +) body ON true +JOIN LATERAL ( + -- Keep the body's fallback schemas out of signature deparsing. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = $1 +WHERE r.routine_schema = $2 AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep @@ -3467,6 +3483,11 @@ WHERE r.routine_schema = $1 ORDER BY r.routine_schema, r.routine_name ` +type GetProceduresForSchemaParams struct { + BodySearchPath sql.NullString `db:"body_search_path" json:"body_search_path"` + SchemaName sql.NullString `db:"schema_name" json:"schema_name"` +} + type GetProceduresForSchemaRow struct { RoutineSchema interface{} `db:"routine_schema" json:"routine_schema"` RoutineName interface{} `db:"routine_name" json:"routine_name"` @@ -3479,8 +3500,8 @@ type GetProceduresForSchemaRow struct { } // GetProceduresForSchema retrieves all user-defined procedures for a specific schema -func (q *Queries) GetProceduresForSchema(ctx context.Context, dollar_1 sql.NullString) ([]GetProceduresForSchemaRow, error) { - rows, err := q.db.QueryContext(ctx, getProceduresForSchema, dollar_1) +func (q *Queries) GetProceduresForSchema(ctx context.Context, arg GetProceduresForSchemaParams) ([]GetProceduresForSchemaRow, error) { + rows, err := q.db.QueryContext(ctx, getProceduresForSchema, arg.BodySearchPath, arg.SchemaName) if err != nil { return nil, err } From 35ff84509246aba501f497dbde4904c1790291bb Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:40:15 +0000 Subject: [PATCH 5/9] fix: compare qualified routine bodies without changing migration resolution Co-Authored-By: Tianzhou --- cmd/plan/extension_integration_test.go | 20 +++++ cmd/plan/plan.go | 3 + internal/diff/function.go | 19 +++-- internal/diff/procedure.go | 4 +- ir/inspector.go | 67 ++++++--------- ir/ir.go | 48 ++++++----- ir/queries/extension_members_test.go | 12 +-- ir/queries/queries.sql | 38 +++++---- ir/queries/queries.sql.go | 112 +++++++++++++------------ 9 files changed, 170 insertions(+), 153 deletions(-) diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index a0d5340a7..e02df2b65 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/pgplex/pgschema/cmd/dump" + internalplan "github.com/pgplex/pgschema/internal/plan" "github.com/pgplex/pgschema/ir" "github.com/pgplex/pgschema/testutil" "github.com/stretchr/testify/require" @@ -98,6 +99,25 @@ func TestPlan_ExtensionQualifiers(t *testing.T) { } } } + t.Run("plan-only extension operator stays qualified", func(t *testing.T) { + _, err := planConn.ExecContext(ctx, "CREATE EXTENSION intarray SCHEMA public") + require.NoError(t, err) + file := filepath.Join(t.TempDir(), "schema.sql") + require.NoError(t, os.WriteFile(file, []byte(` + CREATE FUNCTION arrays_overlap(a integer[], b integer[]) RETURNS boolean LANGUAGE sql + RETURN a OPERATOR(public.&&) b; + `), 0644)) + config := &PlanConfig{ + Host: host, Port: port, DB: name, User: user, Password: password, Schema: "public", File: file, + PlanDBHost: planHost, PlanDBPort: planPort, PlanDBDatabase: planName, PlanDBUser: planUser, PlanDBPassword: planPassword, + } + provider, err := CreateDesiredStateProvider(config) + require.NoError(t, err) + defer provider.Stop() + p, err := GeneratePlan(config, provider) + require.NoError(t, err) + require.Contains(t, p.ToSQL(internalplan.SQLFormatRaw), "OPERATOR(public.&&)") + }) } func TestPlan_DropsExtensionTypedRoutineDependencies(t *testing.T) { diff --git a/cmd/plan/plan.go b/cmd/plan/plan.go index bde4156f4..4cd1335dc 100644 --- a/cmd/plan/plan.go +++ b/cmd/plan/plan.go @@ -511,6 +511,7 @@ func processOutput(migrationPlan *plan.Plan, output outputSpec, cmd *cobra.Comma // and fail when applied to the target database. func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { replaceString := newSchemaStringReplacer(fromSchema, toSchema) + replaceQualifiedBodySchema := strings.NewReplacer(ir.QuoteIdentifier(fromSchema)+".", ir.QuoteIdentifier(toSchema)+".").Replace // stripQualifiers removes same-schema function/type qualifiers from expressions. // After replaceString converts temp schema references to toSchema, expressions may // contain "toSchema.func_name(" or "::toSchema.type" which are redundant same-schema @@ -686,6 +687,7 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { fn.IdentityArguments = replaceString(fn.IdentityArguments) fn.ReturnType = replaceString(fn.ReturnType) fn.Definition = replaceString(fn.Definition) + fn.QualifiedDefinition = replaceQualifiedBodySchema(fn.QualifiedDefinition) for i := range fn.SetConfig { fn.SetConfig[i] = replaceString(fn.SetConfig[i]) } @@ -710,6 +712,7 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { for _, proc := range schema.Procedures { proc.Schema = toSchema proc.Definition = replaceString(proc.Definition) + proc.QualifiedDefinition = replaceQualifiedBodySchema(proc.QualifiedDefinition) for _, param := range proc.Parameters { param.DataType = replaceString(param.DataType) if param.DefaultValue != nil { diff --git a/internal/diff/function.go b/internal/diff/function.go index 7a9c5876a..9927a0091 100644 --- a/internal/diff/function.go +++ b/internal/diff/function.go @@ -436,7 +436,7 @@ func functionsEqualExceptAttributes(old, new *ir.Function) bool { if old.Name != new.Name { return false } - if !definitionsEqualIgnoringSchema(old.Definition, new.Definition, old.Schema) { + if !routineDefinitionsEqual(old.Definition, new.Definition, old.QualifiedDefinition, new.QualifiedDefinition, old.Schema) { return false } if old.ReturnType != new.ReturnType { @@ -474,7 +474,7 @@ func functionsEqual(old, new *ir.Function) bool { if old.Name != new.Name { return false } - if !definitionsEqualIgnoringSchema(old.Definition, new.Definition, old.Schema) { + if !routineDefinitionsEqual(old.Definition, new.Definition, old.QualifiedDefinition, new.QualifiedDefinition, old.Schema) { return false } if old.ReturnType != new.ReturnType { @@ -526,7 +526,7 @@ func functionsEqualExceptComment(old, new *ir.Function) bool { if old.Name != new.Name { return false } - if !definitionsEqualIgnoringSchema(old.Definition, new.Definition, old.Schema) { + if !routineDefinitionsEqual(old.Definition, new.Definition, old.QualifiedDefinition, new.QualifiedDefinition, old.Schema) { return false } if old.ReturnType != new.ReturnType { @@ -593,12 +593,13 @@ func functionRequiresRecreate(old, new *ir.Function) bool { return false } -// definitionsEqualIgnoringSchema compares two function/procedure definitions, -// stripping the given schema qualifier from both before comparing. This allows -// definitions that differ only in schema qualification (e.g., "public.test" vs "test") -// to be treated as equal, while preserving the original qualifiers in the IR for -// correct DDL generation. (Issue #354) -func definitionsEqualIgnoringSchema(a, b, schema string) bool { +// routineDefinitionsEqual compares the fully qualified forms of parsed SQL +// bodies so differences in search_path cannot hide a change of bound objects. +// For text bodies retain the schema-insensitive comparison from issue #354. +func routineDefinitionsEqual(a, b, qualifiedA, qualifiedB, schema string) bool { + if qualifiedA != "" && qualifiedB != "" { + return qualifiedA == qualifiedB + } return ir.StripSchemaPrefixFromBody(a, schema) == ir.StripSchemaPrefixFromBody(b, schema) } diff --git a/internal/diff/procedure.go b/internal/diff/procedure.go index 6ad2b964d..39208cfa5 100644 --- a/internal/diff/procedure.go +++ b/internal/diff/procedure.go @@ -264,7 +264,7 @@ func proceduresEqual(old, new *ir.Procedure) bool { if old.Name != new.Name { return false } - if !definitionsEqualIgnoringSchema(old.Definition, new.Definition, old.Schema) { + if !routineDefinitionsEqual(old.Definition, new.Definition, old.QualifiedDefinition, new.QualifiedDefinition, old.Schema) { return false } if old.Language != new.Language { @@ -300,7 +300,7 @@ func proceduresEqualExceptComment(old, new *ir.Procedure) bool { if old.Name != new.Name { return false } - if !definitionsEqualIgnoringSchema(old.Definition, new.Definition, old.Schema) { + if !routineDefinitionsEqual(old.Definition, new.Definition, old.QualifiedDefinition, new.QualifiedDefinition, old.Schema) { return false } if old.Language != new.Language { diff --git a/ir/inspector.go b/ir/inspector.go index b62c6c197..a2d53d138 100644 --- a/ir/inspector.go +++ b/ir/inspector.go @@ -1305,24 +1305,8 @@ func (i *Inspector) buildSequences(ctx context.Context, schema *IR, targetSchema return nil } -// routineBodySearchPath mirrors resolution in the external plan database when -// the managed schema still hosts extensions outside the comparison schema. -// The routine's actual schema comes first so local references stay portable. -func (i *Inspector) routineBodySearchPath(targetSchema string) sql.NullString { - if targetSchema != i.managedSchema && i.extensionSchemas[i.managedSchema] { - return sql.NullString{ - String: QuoteIdentifier(targetSchema) + ", " + QuoteIdentifier(i.managedSchema), - Valid: true, - } - } - return sql.NullString{} -} - func (i *Inspector) buildFunctions(ctx context.Context, schema *IR, targetSchema string) error { - functions, err := i.queries.GetFunctionsForSchema(ctx, queries.GetFunctionsForSchemaParams{ - SchemaName: sql.NullString{String: targetSchema, Valid: true}, - BodySearchPath: i.routineBodySearchPath(targetSchema), - }) + functions, err := i.queries.GetFunctionsForSchema(ctx, sql.NullString{String: targetSchema, Valid: true}) if err != nil { return err } @@ -1396,21 +1380,22 @@ func (i *Inspector) buildFunctions(ctx context.Context, schema *IR, targetSchema setConfig := fn.SetConfig function := &Function{ - Schema: schemaName, - Name: functionName, - Definition: definition, - ReturnType: i.stripSameSchemaPrefixFromReturnType(i.safeInterfaceToString(fn.DataType), schemaName), - Language: i.safeInterfaceToString(fn.ExternalLanguage), - Comment: comment, - Parameters: parameters, - IdentityArguments: identityArguments, - Volatility: volatility, - IsStrict: isStrict, - IsSecurityDefiner: isSecurityDefiner, - IsLeakproof: isLeakproof, - Parallel: parallelMode, - Rows: rows, - SetConfig: setConfig, + Schema: schemaName, + Name: functionName, + Definition: definition, + QualifiedDefinition: fn.QualifiedRoutineDefinition.String, + ReturnType: i.stripSameSchemaPrefixFromReturnType(i.safeInterfaceToString(fn.DataType), schemaName), + Language: i.safeInterfaceToString(fn.ExternalLanguage), + Comment: comment, + Parameters: parameters, + IdentityArguments: identityArguments, + Volatility: volatility, + IsStrict: isStrict, + IsSecurityDefiner: isSecurityDefiner, + IsLeakproof: isLeakproof, + Parallel: parallelMode, + Rows: rows, + SetConfig: setConfig, } // Use name(arguments) as key to support function overloading @@ -1948,10 +1933,7 @@ func (i *Inspector) lookupTypeNameFromOID(oid int64) string { } func (i *Inspector) buildProcedures(ctx context.Context, schema *IR, targetSchema string) error { - procedures, err := i.queries.GetProceduresForSchema(ctx, queries.GetProceduresForSchemaParams{ - SchemaName: sql.NullString{String: targetSchema, Valid: true}, - BodySearchPath: i.routineBodySearchPath(targetSchema), - }) + procedures, err := i.queries.GetProceduresForSchema(ctx, sql.NullString{String: targetSchema, Valid: true}) if err != nil { return err } @@ -1979,12 +1961,13 @@ func (i *Inspector) buildProcedures(ctx context.Context, schema *IR, targetSchem parameters := i.parseParametersFromSignature(signature, schemaName) procedure := &Procedure{ - Schema: schemaName, - Name: procedureName, - Definition: definition, - Language: i.safeInterfaceToString(proc.ExternalLanguage), - Comment: comment, - Parameters: parameters, + Schema: schemaName, + Name: procedureName, + Definition: definition, + QualifiedDefinition: proc.QualifiedRoutineDefinition.String, + Language: i.safeInterfaceToString(proc.ExternalLanguage), + Comment: comment, + Parameters: parameters, } // Use name(arguments) as key to support procedure overloading diff --git a/ir/ir.go b/ir/ir.go index b8f39a07d..634fc2a6f 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -237,23 +237,24 @@ type View struct { // Function represents a database function type Function struct { - Schema string `json:"schema"` - Name string `json:"name"` - Definition string `json:"definition"` - ReturnType string `json:"return_type"` - Language string `json:"language"` - Parameters []*Parameter `json:"parameters,omitempty"` - IdentityArguments string `json:"-"` // pg_get_function_identity_arguments form, qualified as privileges name functions; derived from Parameters, so kept out of JSON - Comment string `json:"comment,omitempty"` - Volatility string `json:"volatility,omitempty"` // IMMUTABLE, STABLE, VOLATILE - IsStrict bool `json:"is_strict,omitempty"` // STRICT or null behavior - IsSecurityDefiner bool `json:"is_security_definer,omitempty"` // SECURITY DEFINER - IsLeakproof bool `json:"is_leakproof,omitempty"` // LEAKPROOF - Parallel string `json:"parallel,omitempty"` // SAFE, UNSAFE, RESTRICTED - Rows string `json:"rows,omitempty"` // ROWS n planner estimate of a set-returning function; empty when default (1000) or not set-returning - SetConfig []string `json:"set_config,omitempty"` // SET clauses from pg_proc.proconfig (e.g., "search_path=public", "TimeZone=UTC") - Dependencies []string `json:"dependencies,omitempty"` // Function keys (name(args)) this function depends on - TypeDependencies []string `json:"-"` // schema.name of the types this function depends on per pg_depend (signature, SQL-standard body, defaults); ordering data, kept out of the fingerprint + Schema string `json:"schema"` + Name string `json:"name"` + Definition string `json:"definition"` + QualifiedDefinition string `json:"-"` // SQL-standard body with fully qualified references, used for comparison + ReturnType string `json:"return_type"` + Language string `json:"language"` + Parameters []*Parameter `json:"parameters,omitempty"` + IdentityArguments string `json:"-"` // pg_get_function_identity_arguments form, qualified as privileges name functions; derived from Parameters, so kept out of JSON + Comment string `json:"comment,omitempty"` + Volatility string `json:"volatility,omitempty"` // IMMUTABLE, STABLE, VOLATILE + IsStrict bool `json:"is_strict,omitempty"` // STRICT or null behavior + IsSecurityDefiner bool `json:"is_security_definer,omitempty"` // SECURITY DEFINER + IsLeakproof bool `json:"is_leakproof,omitempty"` // LEAKPROOF + Parallel string `json:"parallel,omitempty"` // SAFE, UNSAFE, RESTRICTED + Rows string `json:"rows,omitempty"` // ROWS n planner estimate of a set-returning function; empty when default (1000) or not set-returning + SetConfig []string `json:"set_config,omitempty"` // SET clauses from pg_proc.proconfig (e.g., "search_path=public", "TimeZone=UTC") + Dependencies []string `json:"dependencies,omitempty"` // Function keys (name(args)) this function depends on + TypeDependencies []string `json:"-"` // schema.name of the types this function depends on per pg_depend (signature, SQL-standard body, defaults); ordering data, kept out of the fingerprint } // GetArguments returns the function arguments string (types only) for function identification. @@ -598,12 +599,13 @@ type Aggregate struct { // Procedure represents a database procedure type Procedure struct { - Schema string `json:"schema"` - Name string `json:"name"` - Definition string `json:"definition"` - Language string `json:"language"` - Parameters []*Parameter `json:"parameters,omitempty"` - Comment string `json:"comment,omitempty"` + Schema string `json:"schema"` + Name string `json:"name"` + Definition string `json:"definition"` + QualifiedDefinition string `json:"-"` // SQL-standard body with fully qualified references, used for comparison + Language string `json:"language"` + Parameters []*Parameter `json:"parameters,omitempty"` + Comment string `json:"comment,omitempty"` } // GetArguments returns the procedure arguments string (types only) for procedure identification. diff --git a/ir/queries/extension_members_test.go b/ir/queries/extension_members_test.go index 6b67dfb9c..c89347839 100644 --- a/ir/queries/extension_members_test.go +++ b/ir/queries/extension_members_test.go @@ -105,13 +105,9 @@ func TestExtensionMembers(t *testing.T) { {"GetSequences", func() (string, error) { return extensionRows(q.GetSequences(ctx)) }}, {"GetSequencesForSchema", func() (string, error) { return extensionRows(q.GetSequencesForSchema(ctx, schema)) }}, {"GetFunctions", func() (string, error) { return extensionRows(q.GetFunctions(ctx)) }}, - {"GetFunctionsForSchema", func() (string, error) { - return extensionRows(q.GetFunctionsForSchema(ctx, queries.GetFunctionsForSchemaParams{SchemaName: schema})) - }}, + {"GetFunctionsForSchema", func() (string, error) { return extensionRows(q.GetFunctionsForSchema(ctx, schema)) }}, {"GetProcedures", func() (string, error) { return extensionRows(q.GetProcedures(ctx)) }}, - {"GetProceduresForSchema", func() (string, error) { - return extensionRows(q.GetProceduresForSchema(ctx, queries.GetProceduresForSchemaParams{SchemaName: schema})) - }}, + {"GetProceduresForSchema", func() (string, error) { return extensionRows(q.GetProceduresForSchema(ctx, schema)) }}, {"GetAggregates", func() (string, error) { return extensionRows(q.GetAggregates(ctx)) }}, {"GetAggregatesForSchema", func() (string, error) { return extensionRows(q.GetAggregatesForSchema(ctx, schema)) }}, {"GetViews", func() (string, error) { return extensionRows(q.GetViews(ctx)) }}, @@ -226,9 +222,7 @@ func TestExtensionMembershipCatalogIdentity(t *testing.T) { global, err := extensionRows(q.GetFunctions(ctx)) require.NoError(t, err) require.Contains(t, global, "app595_identity") - scoped, err := extensionRows(q.GetFunctionsForSchema(ctx, queries.GetFunctionsForSchemaParams{ - SchemaName: sql.NullString{String: "public", Valid: true}, - })) + scoped, err := extensionRows(q.GetFunctionsForSchema(ctx, sql.NullString{String: "public", Valid: true})) require.NoError(t, err) require.Contains(t, scoped, "app595_identity") }) diff --git a/ir/queries/queries.sql b/ir/queries/queries.sql index 500f036be..ac8588c08 100644 --- a/ir/queries/queries.sql +++ b/ir/queries/queries.sql @@ -1754,9 +1754,10 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - deparse.body, + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, + deparse.qualified_body::text AS qualified_routine_definition, r.routine_type, COALESCE(pg_get_function_result(deparse.oid), r.data_type) AS data_type, r.external_language, @@ -1785,17 +1786,21 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_func ON desc_func.objoid = p.oid AND desc_func.classoid = 'pg_proc'::regclass JOIN LATERAL ( - SELECT pg_get_function_sqlbody(p.oid) AS definition - WHERE set_config('search_path', COALESCE(sqlc.narg(body_search_path)::text, quote_ident(r.routine_schema)), true) IS NOT NULL + -- Compare parsed bodies with user-defined objects fully qualified. + SELECT pg_get_function_sqlbody( + CASE WHEN p.prosqlbody IS NOT NULL + AND set_config('search_path', 'pg_catalog', true) IS NOT NULL + THEN p.oid END + ) AS definition OFFSET 0 -) body ON true +) qualified ON true JOIN LATERAL ( - -- Keep the body's fallback schemas out of signature deparsing. - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body + -- Keep local objects visible in the emitted body so it can be replayed. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, qualified.definition AS qualified_body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = sqlc.narg(schema_name) +WHERE r.routine_schema = $1 AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep @@ -1824,9 +1829,10 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - deparse.body, + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, + deparse.qualified_body::text AS qualified_routine_definition, r.routine_type, r.external_language, COALESCE(desc_proc.description, '') AS procedure_comment, @@ -1838,17 +1844,21 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_proc ON desc_proc.objoid = p.oid AND desc_proc.classoid = 'pg_proc'::regclass JOIN LATERAL ( - SELECT pg_get_function_sqlbody(p.oid) AS definition - WHERE set_config('search_path', COALESCE(sqlc.narg(body_search_path)::text, quote_ident(r.routine_schema)), true) IS NOT NULL + -- Compare parsed bodies with user-defined objects fully qualified. + SELECT pg_get_function_sqlbody( + CASE WHEN p.prosqlbody IS NOT NULL + AND set_config('search_path', 'pg_catalog', true) IS NOT NULL + THEN p.oid END + ) AS definition OFFSET 0 -) body ON true +) qualified ON true JOIN LATERAL ( - -- Keep the body's fallback schemas out of signature deparsing. - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body + -- Keep local objects visible in the emitted body so it can be replayed. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, qualified.definition AS qualified_body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = sqlc.narg(schema_name) +WHERE r.routine_schema = $1 AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep diff --git a/ir/queries/queries.sql.go b/ir/queries/queries.sql.go index 150ff2869..1253fd27b 100644 --- a/ir/queries/queries.sql.go +++ b/ir/queries/queries.sql.go @@ -2162,9 +2162,10 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - deparse.body, + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, + deparse.qualified_body::text AS qualified_routine_definition, r.routine_type, COALESCE(pg_get_function_result(deparse.oid), r.data_type) AS data_type, r.external_language, @@ -2193,17 +2194,21 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_func ON desc_func.objoid = p.oid AND desc_func.classoid = 'pg_proc'::regclass JOIN LATERAL ( - SELECT pg_get_function_sqlbody(p.oid) AS definition - WHERE set_config('search_path', COALESCE($1::text, quote_ident(r.routine_schema)), true) IS NOT NULL + -- Compare parsed bodies with user-defined objects fully qualified. + SELECT pg_get_function_sqlbody( + CASE WHEN p.prosqlbody IS NOT NULL + AND set_config('search_path', 'pg_catalog', true) IS NOT NULL + THEN p.oid END + ) AS definition OFFSET 0 -) body ON true +) qualified ON true JOIN LATERAL ( - -- Keep the body's fallback schemas out of signature deparsing. - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body + -- Keep local objects visible in the emitted body so it can be replayed. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, qualified.definition AS qualified_body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = $2 +WHERE r.routine_schema = $1 AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep @@ -2225,35 +2230,31 @@ WHERE r.routine_schema = $2 ORDER BY r.routine_schema, r.routine_name ` -type GetFunctionsForSchemaParams struct { - BodySearchPath sql.NullString `db:"body_search_path" json:"body_search_path"` - SchemaName sql.NullString `db:"schema_name" json:"schema_name"` -} - type GetFunctionsForSchemaRow struct { - RoutineSchema interface{} `db:"routine_schema" json:"routine_schema"` - RoutineName interface{} `db:"routine_name" json:"routine_name"` - RoutineDefinition sql.NullString `db:"routine_definition" json:"routine_definition"` - RoutineType interface{} `db:"routine_type" json:"routine_type"` - DataType sql.NullString `db:"data_type" json:"data_type"` - ExternalLanguage interface{} `db:"external_language" json:"external_language"` - FunctionComment sql.NullString `db:"function_comment" json:"function_comment"` - FunctionArguments sql.NullString `db:"function_arguments" json:"function_arguments"` - FunctionSignature sql.NullString `db:"function_signature" json:"function_signature"` - FunctionIdentityArguments sql.NullString `db:"function_identity_arguments" json:"function_identity_arguments"` - Volatility sql.NullString `db:"volatility" json:"volatility"` - IsStrict bool `db:"is_strict" json:"is_strict"` - IsSecurityDefiner bool `db:"is_security_definer" json:"is_security_definer"` - IsLeakproof bool `db:"is_leakproof" json:"is_leakproof"` - ParallelMode interface{} `db:"parallel_mode" json:"parallel_mode"` - ReturnsSet bool `db:"returns_set" json:"returns_set"` - ResultRows sql.NullString `db:"result_rows" json:"result_rows"` - SetConfig []string `db:"set_config" json:"set_config"` + RoutineSchema interface{} `db:"routine_schema" json:"routine_schema"` + RoutineName interface{} `db:"routine_name" json:"routine_name"` + RoutineDefinition sql.NullString `db:"routine_definition" json:"routine_definition"` + QualifiedRoutineDefinition sql.NullString `db:"qualified_routine_definition" json:"qualified_routine_definition"` + RoutineType interface{} `db:"routine_type" json:"routine_type"` + DataType sql.NullString `db:"data_type" json:"data_type"` + ExternalLanguage interface{} `db:"external_language" json:"external_language"` + FunctionComment sql.NullString `db:"function_comment" json:"function_comment"` + FunctionArguments sql.NullString `db:"function_arguments" json:"function_arguments"` + FunctionSignature sql.NullString `db:"function_signature" json:"function_signature"` + FunctionIdentityArguments sql.NullString `db:"function_identity_arguments" json:"function_identity_arguments"` + Volatility sql.NullString `db:"volatility" json:"volatility"` + IsStrict bool `db:"is_strict" json:"is_strict"` + IsSecurityDefiner bool `db:"is_security_definer" json:"is_security_definer"` + IsLeakproof bool `db:"is_leakproof" json:"is_leakproof"` + ParallelMode interface{} `db:"parallel_mode" json:"parallel_mode"` + ReturnsSet bool `db:"returns_set" json:"returns_set"` + ResultRows sql.NullString `db:"result_rows" json:"result_rows"` + SetConfig []string `db:"set_config" json:"set_config"` } // GetFunctionsForSchema retrieves all user-defined functions for a specific schema -func (q *Queries) GetFunctionsForSchema(ctx context.Context, arg GetFunctionsForSchemaParams) ([]GetFunctionsForSchemaRow, error) { - rows, err := q.db.QueryContext(ctx, getFunctionsForSchema, arg.BodySearchPath, arg.SchemaName) +func (q *Queries) GetFunctionsForSchema(ctx context.Context, dollar_1 sql.NullString) ([]GetFunctionsForSchemaRow, error) { + rows, err := q.db.QueryContext(ctx, getFunctionsForSchema, dollar_1) if err != nil { return nil, err } @@ -2265,6 +2266,7 @@ func (q *Queries) GetFunctionsForSchema(ctx context.Context, arg GetFunctionsFor &i.RoutineSchema, &i.RoutineName, &i.RoutineDefinition, + &i.QualifiedRoutineDefinition, &i.RoutineType, &i.DataType, &i.ExternalLanguage, @@ -3437,9 +3439,10 @@ SELECT -- Use pg_get_function_sqlbody for RETURN clause syntax (PG14+) -- Fall back to prosrc for traditional AS $$ ... $$ syntax COALESCE( - deparse.body, + pg_get_function_sqlbody(deparse.oid), CASE WHEN p.prosrc ~ E'\n$' THEN p.prosrc ELSE p.prosrc || E'\n' END ) AS routine_definition, + deparse.qualified_body::text AS qualified_routine_definition, r.routine_type, r.external_language, COALESCE(desc_proc.description, '') AS procedure_comment, @@ -3451,17 +3454,21 @@ LEFT JOIN pg_proc p ON p.proname = r.routine_name AND p.oid = (regexp_match(r.specific_name, '_(\d+)$'))[1]::oid LEFT JOIN pg_description desc_proc ON desc_proc.objoid = p.oid AND desc_proc.classoid = 'pg_proc'::regclass JOIN LATERAL ( - SELECT pg_get_function_sqlbody(p.oid) AS definition - WHERE set_config('search_path', COALESCE($1::text, quote_ident(r.routine_schema)), true) IS NOT NULL + -- Compare parsed bodies with user-defined objects fully qualified. + SELECT pg_get_function_sqlbody( + CASE WHEN p.prosqlbody IS NOT NULL + AND set_config('search_path', 'pg_catalog', true) IS NOT NULL + THEN p.oid END + ) AS definition OFFSET 0 -) body ON true +) qualified ON true JOIN LATERAL ( - -- Keep the body's fallback schemas out of signature deparsing. - SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, body.definition AS body + -- Keep local objects visible in the emitted body so it can be replayed. + SELECT p.oid, oidvectortypes(p.proargtypes) AS arguments, qualified.definition AS qualified_body WHERE set_config('search_path', quote_ident(r.routine_schema), true) IS NOT NULL OFFSET 0 ) deparse ON true -WHERE r.routine_schema = $2 +WHERE r.routine_schema = $1 AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( SELECT 1 FROM pg_catalog.pg_depend dep @@ -3483,25 +3490,21 @@ WHERE r.routine_schema = $2 ORDER BY r.routine_schema, r.routine_name ` -type GetProceduresForSchemaParams struct { - BodySearchPath sql.NullString `db:"body_search_path" json:"body_search_path"` - SchemaName sql.NullString `db:"schema_name" json:"schema_name"` -} - type GetProceduresForSchemaRow struct { - RoutineSchema interface{} `db:"routine_schema" json:"routine_schema"` - RoutineName interface{} `db:"routine_name" json:"routine_name"` - RoutineDefinition sql.NullString `db:"routine_definition" json:"routine_definition"` - RoutineType interface{} `db:"routine_type" json:"routine_type"` - ExternalLanguage interface{} `db:"external_language" json:"external_language"` - ProcedureComment sql.NullString `db:"procedure_comment" json:"procedure_comment"` - ProcedureArguments sql.NullString `db:"procedure_arguments" json:"procedure_arguments"` - ProcedureSignature sql.NullString `db:"procedure_signature" json:"procedure_signature"` + RoutineSchema interface{} `db:"routine_schema" json:"routine_schema"` + RoutineName interface{} `db:"routine_name" json:"routine_name"` + RoutineDefinition sql.NullString `db:"routine_definition" json:"routine_definition"` + QualifiedRoutineDefinition sql.NullString `db:"qualified_routine_definition" json:"qualified_routine_definition"` + RoutineType interface{} `db:"routine_type" json:"routine_type"` + ExternalLanguage interface{} `db:"external_language" json:"external_language"` + ProcedureComment sql.NullString `db:"procedure_comment" json:"procedure_comment"` + ProcedureArguments sql.NullString `db:"procedure_arguments" json:"procedure_arguments"` + ProcedureSignature sql.NullString `db:"procedure_signature" json:"procedure_signature"` } // GetProceduresForSchema retrieves all user-defined procedures for a specific schema -func (q *Queries) GetProceduresForSchema(ctx context.Context, arg GetProceduresForSchemaParams) ([]GetProceduresForSchemaRow, error) { - rows, err := q.db.QueryContext(ctx, getProceduresForSchema, arg.BodySearchPath, arg.SchemaName) +func (q *Queries) GetProceduresForSchema(ctx context.Context, dollar_1 sql.NullString) ([]GetProceduresForSchemaRow, error) { + rows, err := q.db.QueryContext(ctx, getProceduresForSchema, dollar_1) if err != nil { return nil, err } @@ -3513,6 +3516,7 @@ func (q *Queries) GetProceduresForSchema(ctx context.Context, arg GetProceduresF &i.RoutineSchema, &i.RoutineName, &i.RoutineDefinition, + &i.QualifiedRoutineDefinition, &i.RoutineType, &i.ExternalLanguage, &i.ProcedureComment, From e6bcbfcf07eb628e920bb46a6b1990f646d3d9b8 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:44:04 +0000 Subject: [PATCH 6/9] fix: preserve padding in parsed SQL routine literals Co-Authored-By: Tianzhou --- cmd/plan/extension_integration_test.go | 28 ++++++++++++++++++++++++++ ir/normalize.go | 7 +++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index e02df2b65..81351900b 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -156,6 +156,34 @@ func TestPlan_DropsExtensionTypedRoutineDependencies(t *testing.T) { } } +func TestPlan_SQLStandardRoutinePreservesLiteralPadding(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + ctx := context.Background() + target := testutil.SetupPostgres(t) + defer target.Stop() + db, host, port, name, user, password := testutil.ConnectToPostgres(t, target) + defer db.Close() + _, err := db.ExecContext(ctx, `CREATE FUNCTION public.example() RETURNS text LANGUAGE sql RETURN E'one\ntwo';`) + require.NoError(t, err) + + file := filepath.Join(t.TempDir(), "schema.sql") + require.NoError(t, os.WriteFile(file, []byte(`CREATE FUNCTION example() RETURNS text LANGUAGE sql RETURN E'one \ntwo';`), 0644)) + config := &PlanConfig{Host: host, Port: port, DB: name, User: user, Password: password, Schema: "public", File: file} + provider, err := CreateDesiredStateProvider(config) + require.NoError(t, err) + defer provider.Stop() + p, err := GeneratePlan(config, provider) + require.NoError(t, err) + require.True(t, p.HasAnyChanges()) + _, err = db.ExecContext(ctx, p.ToSQL(internalplan.SQLFormatRaw)) + require.NoError(t, err) + var got string + require.NoError(t, db.QueryRowContext(ctx, `SELECT public.example()`).Scan(&got)) + require.Equal(t, "one \ntwo", got) +} + // TestEmbeddedPlanDB_InstallsTargetExtensions verifies that the embedded plan // database mirrors the extensions installed on the target database (issue #584). // diff --git a/ir/normalize.go b/ir/normalize.go index 960db44e5..b40e6ac90 100644 --- a/ir/normalize.go +++ b/ir/normalize.go @@ -489,8 +489,11 @@ func normalizeFunction(function *Function, shadowed, shadowedTypes map[string]bo } } } - // Normalize function body to handle whitespace differences - function.Definition = normalizeFunctionDefinition(function.Definition) + // Parsed SQL bodies are already formatted by PostgreSQL. Whitespace + // inside a multiline literal is part of its value. + if function.QualifiedDefinition == "" { + function.Definition = normalizeFunctionDefinition(function.Definition) + } // Note: We intentionally do NOT strip schema qualifiers from function bodies here. // Functions may have SET search_path that excludes their own schema, making // qualified references (e.g., public.test) necessary. Stripping is done at From cad02f1a9ba519bb6bb599d132d1d2d1942de3ca Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:45:36 +0000 Subject: [PATCH 7/9] fix: preserve server quoting in routine body comparison Co-Authored-By: Tianzhou --- cmd/plan/extension_integration_test.go | 30 ++++++++++++++++++++++++++ cmd/plan/plan.go | 10 ++++++--- cmd/plan/plan_test.go | 16 +++++++------- ir/inspector.go | 13 +++++------ ir/ir.go | 3 ++- 5 files changed, 54 insertions(+), 18 deletions(-) diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index 81351900b..5ac0d7cc5 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -184,6 +184,36 @@ func TestPlan_SQLStandardRoutinePreservesLiteralPadding(t *testing.T) { require.Equal(t, "one \ntwo", got) } +func TestPlan_SQLStandardRoutineInUnicodeSchema(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + ctx := context.Background() + target := testutil.SetupPostgres(t) + defer target.Stop() + db, host, port, name, user, password := testutil.ConnectToPostgres(t, target) + defer db.Close() + _, err := db.ExecContext(ctx, ` + CREATE SCHEMA café; + CREATE FUNCTION café.local_value() RETURNS integer LANGUAGE sql RETURN 1; + CREATE FUNCTION café.get_value() RETURNS integer LANGUAGE sql RETURN café.local_value(); + `) + require.NoError(t, err) + + file := filepath.Join(t.TempDir(), "schema.sql") + require.NoError(t, os.WriteFile(file, []byte(` + CREATE FUNCTION local_value() RETURNS integer LANGUAGE sql RETURN 1; + CREATE FUNCTION get_value() RETURNS integer LANGUAGE sql RETURN local_value(); + `), 0644)) + config := &PlanConfig{Host: host, Port: port, DB: name, User: user, Password: password, Schema: "café", File: file} + provider, err := CreateDesiredStateProvider(config) + require.NoError(t, err) + defer provider.Stop() + p, err := GeneratePlan(config, provider) + require.NoError(t, err) + require.False(t, p.HasAnyChanges(), p.HumanColored(false)) +} + // TestEmbeddedPlanDB_InstallsTargetExtensions verifies that the embedded plan // database mirrors the extensions installed on the target database (issue #584). // diff --git a/cmd/plan/plan.go b/cmd/plan/plan.go index 4cd1335dc..6fea450ae 100644 --- a/cmd/plan/plan.go +++ b/cmd/plan/plan.go @@ -379,7 +379,7 @@ func GeneratePlan(config *PlanConfig, provider postgres.DesiredStateProvider) (* // schema name (e.g., "public") so that generated DDL references the correct schema. // Without this normalization, DDL would reference non-existent temporary schemas and fail. if schemaToInspect != config.Schema { - normalizeSchemaNames(desiredStateIR, schemaToInspect, config.Schema) + normalizeSchemaNames(desiredStateIR, schemaToInspect, config.Schema, currentStateIR.Metadata.QuotedSchemaName) } if desiredSchema, ok := desiredStateIR.GetSchema(config.Schema); ok { restorePartitionParents(desiredSchema, partitionParents) @@ -509,9 +509,13 @@ func processOutput(migrationPlan *plan.Plan, output outputSpec, cmd *cobra.Comma // // Without this normalization, generated DDL would reference non-existent temporary schemas // and fail when applied to the target database. -func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { +func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema, quotedToSchema string) { replaceString := newSchemaStringReplacer(fromSchema, toSchema) - replaceQualifiedBodySchema := strings.NewReplacer(ir.QuoteIdentifier(fromSchema)+".", ir.QuoteIdentifier(toSchema)+".").Replace + quotedFromSchema := irData.Metadata.QuotedSchemaName + if quotedFromSchema == "" { + quotedFromSchema = ir.QuoteIdentifier(fromSchema) + } + replaceQualifiedBodySchema := strings.NewReplacer(quotedFromSchema+".", quotedToSchema+".").Replace // stripQualifiers removes same-schema function/type qualifiers from expressions. // After replaceString converts temp schema references to toSchema, expressions may // contain "toSchema.func_name(" or "::toSchema.type" which are redundant same-schema diff --git a/cmd/plan/plan_test.go b/cmd/plan/plan_test.go index 814f24e48..587ae5ed5 100644 --- a/cmd/plan/plan_test.go +++ b/cmd/plan/plan_test.go @@ -221,7 +221,7 @@ func TestNormalizeSchemaNames_StripsSameSchemaQualifiersFromViewDefinitions(t *t }, } - normalizeSchemaNames(irData, "pgschema_tmp_20260326_123456_abcd1234", "public") + normalizeSchemaNames(irData, "pgschema_tmp_20260326_123456_abcd1234", "public", "public") schema := irData.Schemas["public"] if schema == nil { @@ -267,7 +267,7 @@ func TestNormalizeSchemaNames_StripsQuotedSchemaQualifiers(t *testing.T) { }, } - normalizeSchemaNames(irData, tempSchema, "My Schema") + normalizeSchemaNames(irData, tempSchema, "My Schema", `"My Schema"`) expected := " SELECT nlevel(path) AS depth,\n" + " \"Fn Name\"(path) AS named,\n" + @@ -294,7 +294,7 @@ func TestNormalizeSchemaNames_PreservesInheritedPartitionDefault(t *testing.T) { desired := &ir.IR{Schemas: map[string]*ir.Schema{ tempSchema: {Name: tempSchema, Tables: map[string]*ir.Table{"app_child": child}}, }} - normalizeSchemaNames(desired, tempSchema, "public") + normalizeSchemaNames(desired, tempSchema, "public", "public") changes := diff.GenerateMigration(ir.NewIR(), desired, "public") var statements []string for _, change := range changes { @@ -324,7 +324,7 @@ func TestNormalizeSchemaNames_PreservesViewTableAliasesMatchingTargetSchema(t *t }, } - normalizeSchemaNames(irData, "pgschema_tmp_20260326_123456_abcd1234", "public") + normalizeSchemaNames(irData, "pgschema_tmp_20260326_123456_abcd1234", "public", "public") view := irData.Schemas["public"].Views["categories_valid"] expected := " SELECT public.id, 'public.nlevel(path)' AS label\n FROM categories public\n WHERE public.id > 0" @@ -349,7 +349,7 @@ func TestNormalizeSchemaNames_IndexAttachment(t *testing.T) { }, }}, }} - normalizeSchemaNames(data, temporary, "public") + normalizeSchemaNames(data, temporary, "public", "public") if local.Schema != "public" || local.ParentIndexSchema != "public" || local.ParentIndex != "parent" { t.Fatalf("Same-schema index attachment was not normalized: %+v", local) } @@ -403,7 +403,7 @@ func TestNormalizeSchemaNames_StripsSameSchemaOperatorQualifiers(t *testing.T) { }, } - normalizeSchemaNames(irData, tempSchema, "public") + normalizeSchemaNames(irData, tempSchema, "public", "public") expected := " SELECT id,\n" + " h -> 'a'::text AS ha,\n" + @@ -442,7 +442,7 @@ func TestNormalizeSchemaNames_MapsShadowedTypeRoutineSignatures(t *testing.T) { }, } - normalizeSchemaNames(irData, tempSchema, "public") + normalizeSchemaNames(irData, tempSchema, "public", "public") schema := irData.Schemas["public"] if schema.Functions["nc_core(public.name)"] != fn { @@ -471,7 +471,7 @@ func TestNormalizeSchemaNames_QuotesKeptShadowedTypeCast(t *testing.T) { }, } - normalizeSchemaNames(irData, tempSchema, "My Schema") + normalizeSchemaNames(irData, tempSchema, "My Schema", `"My Schema"`) if want := `'main'::"My Schema".name`; *fn.Parameters[0].DefaultValue != want { t.Errorf("default = %q, want %q", *fn.Parameters[0].DefaultValue, want) diff --git a/ir/inspector.go b/ir/inspector.go index a2d53d138..9339c5bd8 100644 --- a/ir/inspector.go +++ b/ir/inspector.go @@ -124,7 +124,9 @@ func (i *Inspector) BuildIR(ctx context.Context, targetSchema string) (*IR, erro return nil, fmt.Errorf("failed to build metadata: %w", err) } - if err := traced(ctx, "validate schema", func(ctx context.Context) error { return i.validateSchemaExists(ctx, targetSchema) }); err != nil { + if err := traced(ctx, "validate schema", func(ctx context.Context) error { + return i.validateSchema(ctx, targetSchema, &schema.Metadata.QuotedSchemaName) + }); err != nil { return nil, err } @@ -2772,18 +2774,17 @@ func (i *Inspector) shouldAddPgCatalogPrefix(funcCall string) bool { return pgCatalogTriggerFunctions[funcName] } -// validateSchemaExists checks if a schema exists in the database -func (i *Inspector) validateSchemaExists(ctx context.Context, schemaName string) error { +// validateSchema checks that the schema exists and records its quoted name. +func (i *Inspector) validateSchema(ctx context.Context, schemaName string, quotedName *string) error { query := ` - SELECT 1 + SELECT pg_catalog.quote_ident(schema_name) FROM information_schema.schemata WHERE schema_name = $1 AND schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast') AND schema_name NOT LIKE 'pg_temp_%' AND schema_name NOT LIKE 'pg_toast_temp_%'` - var exists int - err := i.db.QueryRowContext(ctx, query, schemaName).Scan(&exists) + err := i.db.QueryRowContext(ctx, query, schemaName).Scan(quotedName) if err == sql.ErrNoRows { return fmt.Errorf("schema '%s' does not exist in the database", schemaName) } diff --git a/ir/ir.go b/ir/ir.go index 634fc2a6f..6ebbf58c6 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -15,7 +15,8 @@ type IR struct { // Metadata contains information about the schema dump type Metadata struct { - DatabaseVersion string `json:"database_version"` + DatabaseVersion string `json:"database_version"` + QuotedSchemaName string `json:"-"` // spelling used by PostgreSQL's deparsers // ShadowedOperators lists the operator names in the inspected and managed // schemas whose every overload duplicates a pg_catalog operator's name and // operand types. pg_catalog is searched first, so an unqualified reference From a3527a00037e5e36306d8cede4dbe476c22962b1 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:58:06 +0000 Subject: [PATCH 8/9] fix: keep bound routine references qualified in migrations Co-Authored-By: Tianzhou --- cmd/plan/plan.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/cmd/plan/plan.go b/cmd/plan/plan.go index 6fea450ae..35d08c778 100644 --- a/cmd/plan/plan.go +++ b/cmd/plan/plan.go @@ -690,8 +690,14 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema, quotedToSchema st fn.Schema = toSchema fn.IdentityArguments = replaceString(fn.IdentityArguments) fn.ReturnType = replaceString(fn.ReturnType) - fn.Definition = replaceString(fn.Definition) fn.QualifiedDefinition = replaceQualifiedBodySchema(fn.QualifiedDefinition) + // Migrations already know the target schema. Keep bound references + // explicit so they resolve regardless of the apply search path. + if fn.QualifiedDefinition != "" { + fn.Definition = fn.QualifiedDefinition + } else { + fn.Definition = replaceString(fn.Definition) + } for i := range fn.SetConfig { fn.SetConfig[i] = replaceString(fn.SetConfig[i]) } @@ -715,8 +721,12 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema, quotedToSchema st // Procedures for _, proc := range schema.Procedures { proc.Schema = toSchema - proc.Definition = replaceString(proc.Definition) proc.QualifiedDefinition = replaceQualifiedBodySchema(proc.QualifiedDefinition) + if proc.QualifiedDefinition != "" { + proc.Definition = proc.QualifiedDefinition + } else { + proc.Definition = replaceString(proc.Definition) + } for _, param := range proc.Parameters { param.DataType = replaceString(param.DataType) if param.DefaultValue != nil { From 77a22bef8cd7fd4c3983f11c1334cb1c0b741bc2 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:02:38 +0000 Subject: [PATCH 9/9] fix: escape routine object references during schema remapping Co-Authored-By: Tianzhou --- cmd/plan/extension_integration_test.go | 30 ++++++++++++++++++ cmd/plan/plan.go | 44 ++++++++++++++++++++++++-- cmd/plan/plan_test.go | 8 +++++ 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/cmd/plan/extension_integration_test.go b/cmd/plan/extension_integration_test.go index 5ac0d7cc5..cb7b0dc03 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -214,6 +214,36 @@ func TestPlan_SQLStandardRoutineInUnicodeSchema(t *testing.T) { require.False(t, p.HasAnyChanges(), p.HumanColored(false)) } +func TestPlan_SQLStandardRoutineSequenceInApostropheSchema(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + ctx := context.Background() + target := testutil.SetupPostgres(t) + defer target.Stop() + db, host, port, name, user, password := testutil.ConnectToPostgres(t, target) + defer db.Close() + _, err := db.ExecContext(ctx, `CREATE SCHEMA "team's data"; SET search_path TO "team's data";`) + require.NoError(t, err) + + file := filepath.Join(t.TempDir(), "schema.sql") + require.NoError(t, os.WriteFile(file, []byte(` + CREATE SEQUENCE local_seq; + CREATE FUNCTION next_id() RETURNS bigint LANGUAGE sql RETURN nextval('local_seq'); + `), 0644)) + config := &PlanConfig{Host: host, Port: port, DB: name, User: user, Password: password, Schema: "team's data", File: file} + provider, err := CreateDesiredStateProvider(config) + require.NoError(t, err) + defer provider.Stop() + p, err := GeneratePlan(config, provider) + require.NoError(t, err) + _, err = db.ExecContext(ctx, p.ToSQL(internalplan.SQLFormatRaw)) + require.NoError(t, err, p.ToSQL(internalplan.SQLFormatRaw)) + var got int64 + require.NoError(t, db.QueryRowContext(ctx, `SELECT "team's data".next_id()`).Scan(&got)) + require.Equal(t, int64(1), got) +} + // TestEmbeddedPlanDB_InstallsTargetExtensions verifies that the embedded plan // database mirrors the extensions installed on the target database (issue #584). // diff --git a/cmd/plan/plan.go b/cmd/plan/plan.go index 35d08c778..95db6f382 100644 --- a/cmd/plan/plan.go +++ b/cmd/plan/plan.go @@ -515,7 +515,6 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema, quotedToSchema st if quotedFromSchema == "" { quotedFromSchema = ir.QuoteIdentifier(fromSchema) } - replaceQualifiedBodySchema := strings.NewReplacer(quotedFromSchema+".", quotedToSchema+".").Replace // stripQualifiers removes same-schema function/type qualifiers from expressions. // After replaceString converts temp schema references to toSchema, expressions may // contain "toSchema.func_name(" or "::toSchema.type" which are redundant same-schema @@ -690,7 +689,7 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema, quotedToSchema st fn.Schema = toSchema fn.IdentityArguments = replaceString(fn.IdentityArguments) fn.ReturnType = replaceString(fn.ReturnType) - fn.QualifiedDefinition = replaceQualifiedBodySchema(fn.QualifiedDefinition) + fn.QualifiedDefinition = remapParsedRoutineBody(fn.QualifiedDefinition, quotedFromSchema, quotedToSchema) // Migrations already know the target schema. Keep bound references // explicit so they resolve regardless of the apply search path. if fn.QualifiedDefinition != "" { @@ -721,7 +720,7 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema, quotedToSchema st // Procedures for _, proc := range schema.Procedures { proc.Schema = toSchema - proc.QualifiedDefinition = replaceQualifiedBodySchema(proc.QualifiedDefinition) + proc.QualifiedDefinition = remapParsedRoutineBody(proc.QualifiedDefinition, quotedFromSchema, quotedToSchema) if proc.QualifiedDefinition != "" { proc.Definition = proc.QualifiedDefinition } else { @@ -906,6 +905,45 @@ func newSchemaStringReplacer(fromSchema, toSchema string) func(string) string { } } +// PostgreSQL deparses parsed SQL bodies without comments and uses doubled +// quotes for identifiers and string constants. +var parsedRoutineToken = regexp.MustCompile(`'(?:[^']|'')*'|"(?:[^"]|"")*"|[a-z_][a-z_0-9$]*`) +var routineObjectIDCast = regexp.MustCompile(`^::(?:regclass|regcollation|regconfig|regdictionary|regoper|regoperator|regproc|regprocedure|regtype)(?:[^a-z_0-9$]|$)`) + +// remapParsedRoutineBody rewrites qualified identifiers and scalar object +// references such as 'tmp.seq'::regclass. String constants have their own +// quoting rules, and ordinary text literals must keep their original values. +func remapParsedRoutineBody(body, quotedFrom, quotedTo string) string { + if body == "" || quotedFrom == "" || quotedFrom == quotedTo { + return body + } + escapeLiteral := func(s string) string { return strings.ReplaceAll(s, "'", "''") } + literalPrefix := "'" + escapeLiteral(quotedFrom) + "." + if !strings.Contains(body, quotedFrom+".") && !strings.Contains(body, literalPrefix) { + return body + } + literalReplacement := "'" + escapeLiteral(quotedTo) + "." + var result strings.Builder + start := 0 + for _, loc := range parsedRoutineToken.FindAllStringIndex(body, -1) { + token := body[loc[0]:loc[1]] + rest := body[loc[1]:] + switch { + case token == quotedFrom && strings.HasPrefix(rest, "."): + token = quotedTo + case strings.HasPrefix(token, literalPrefix) && routineObjectIDCast.MatchString(rest): + token = literalReplacement + strings.TrimPrefix(token, literalPrefix) + default: + continue + } + result.WriteString(body[start:loc[0]]) + result.WriteString(token) + start = loc[1] + } + result.WriteString(body[start:]) + return result.String() +} + // newSameSchemaQualifierStripper creates a function that strips redundant same-schema // qualifiers from SQL expressions. After normalizeSchemaNames replaces temp schema names // with the target schema, expressions may contain "schema.func_name(" or "::schema.type" diff --git a/cmd/plan/plan_test.go b/cmd/plan/plan_test.go index 587ae5ed5..624aa36a6 100644 --- a/cmd/plan/plan_test.go +++ b/cmd/plan/plan_test.go @@ -203,6 +203,14 @@ func TestPlanCommandFileError(t *testing.T) { } } +func TestRemapParsedRoutineBody(t *testing.T) { + body := `RETURN tmp.f(another_tmp.id, 'tmp.seq'::regclass, 'tmp.seq'::text, "tmp.id")` + want := `RETURN "team's data".f(another_tmp.id, '"team''s data".seq'::regclass, 'tmp.seq'::text, "tmp.id")` + if got := remapParsedRoutineBody(body, "tmp", `"team's data"`); got != want { + t.Errorf("remapParsedRoutineBody() = %q, want %q", got, want) + } +} + func TestNormalizeSchemaNames_StripsSameSchemaQualifiersFromViewDefinitions(t *testing.T) { irData := &ir.IR{ Schemas: map[string]*ir.Schema{