diff --git a/cmd/dump/extension_integration_test.go b/cmd/dump/extension_integration_test.go index d8eddc88..94eee78a 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 e6490425..cb7b0dc0 100644 --- a/cmd/plan/extension_integration_test.go +++ b/cmd/plan/extension_integration_test.go @@ -2,14 +2,248 @@ package plan import ( "context" + "fmt" "os" "path/filepath" "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" ) +// 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 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); + `) + 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)) + }) + } + } + } + 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) { + 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) + } + } +} + +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) +} + +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)) +} + +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/partition_stubs.go b/cmd/plan/partition_stubs.go index f027b51e..25357c95 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 10677920..95db6f38 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) } @@ -379,7 +379,10 @@ 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) } // Extract the target database's major version (e.g. "PostgreSQL 18.1" -> 18) @@ -506,8 +509,12 @@ 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) + quotedFromSchema := irData.Metadata.QuotedSchemaName + if quotedFromSchema == "" { + quotedFromSchema = ir.QuoteIdentifier(fromSchema) + } // 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 @@ -621,8 +628,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 +666,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)) } } @@ -680,7 +689,14 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { fn.Schema = toSchema fn.IdentityArguments = replaceString(fn.IdentityArguments) fn.ReturnType = replaceString(fn.ReturnType) - fn.Definition = replaceString(fn.Definition) + 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 != "" { + fn.Definition = fn.QualifiedDefinition + } else { + fn.Definition = replaceString(fn.Definition) + } for i := range fn.SetConfig { fn.SetConfig[i] = replaceString(fn.SetConfig[i]) } @@ -704,7 +720,12 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) { // Procedures for _, proc := range schema.Procedures { proc.Schema = toSchema - proc.Definition = replaceString(proc.Definition) + proc.QualifiedDefinition = remapParsedRoutineBody(proc.QualifiedDefinition, quotedFromSchema, quotedToSchema) + 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 { @@ -884,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 814f24e4..624aa36a 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{ @@ -221,7 +229,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 +275,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 +302,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 +332,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 +357,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 +411,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 +450,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 +479,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/internal/diff/function.go b/internal/diff/function.go index 7a9c5876..9927a009 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 6ad2b964..39208cfa 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 0ed1714f..9339c5bd 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 } @@ -1380,21 +1382,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 @@ -1960,12 +1963,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 @@ -2770,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) } @@ -2946,6 +2949,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/ir.go b/ir/ir.go index b8f39a07..6ebbf58c 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 @@ -237,23 +238,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 +600,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/normalize.go b/ir/normalize.go index 960db44e..b40e6ac9 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 diff --git a/ir/queries/queries.sql b/ir/queries/queries.sql index 3bb4d9d2..ac8588c0 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) @@ -1752,17 +1754,18 @@ 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, + deparse.qualified_body::text AS qualified_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' @@ -1782,6 +1785,21 @@ 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 ( + -- 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 +) qualified ON true +JOIN LATERAL ( + -- 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 = $1 AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( @@ -1811,19 +1829,35 @@ 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, + deparse.qualified_body::text AS qualified_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 ( + -- 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 +) qualified ON true +JOIN LATERAL ( + -- 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 = $1 AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( @@ -2424,7 +2458,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 @@ -2456,7 +2492,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 @@ -2546,7 +2584,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 @@ -2575,7 +2615,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 @@ -2703,7 +2745,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 @@ -2724,10 +2768,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 0232a7c5..1253fd27 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) @@ -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 @@ -2156,17 +2162,18 @@ 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, + deparse.qualified_body::text AS qualified_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 +2193,21 @@ 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 ( + -- 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 +) qualified ON true +JOIN LATERAL ( + -- 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 = $1 AND r.routine_type = 'FUNCTION' AND NOT EXISTS ( @@ -2209,24 +2231,25 @@ ORDER BY r.routine_schema, r.routine_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 @@ -2243,6 +2266,7 @@ func (q *Queries) GetFunctionsForSchema(ctx context.Context, dollar_1 sql.NullSt &i.RoutineSchema, &i.RoutineName, &i.RoutineDefinition, + &i.QualifiedRoutineDefinition, &i.RoutineType, &i.DataType, &i.ExternalLanguage, @@ -2452,10 +2476,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) @@ -3158,7 +3184,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 @@ -3190,7 +3218,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 @@ -3409,19 +3439,35 @@ 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, + deparse.qualified_body::text AS qualified_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 ( + -- 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 +) qualified ON true +JOIN LATERAL ( + -- 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 = $1 AND r.routine_type = 'PROCEDURE' AND NOT EXISTS ( @@ -3445,14 +3491,15 @@ ORDER BY r.routine_schema, r.routine_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 @@ -3469,6 +3516,7 @@ func (q *Queries) GetProceduresForSchema(ctx context.Context, dollar_1 sql.NullS &i.RoutineSchema, &i.RoutineName, &i.RoutineDefinition, + &i.QualifiedRoutineDefinition, &i.RoutineType, &i.ExternalLanguage, &i.ProcedureComment, @@ -3933,7 +3981,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 @@ -3962,7 +4012,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/stub.go b/ir/stub.go index d10a60e1..02683e54 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) }