Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions cmd/dump/extension_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
234 changes: 234 additions & 0 deletions cmd/plan/extension_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
//
Expand Down
36 changes: 29 additions & 7 deletions cmd/plan/partition_stubs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Comment on lines +98 to +102

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Unchanged plans remove partition defaults

Cross-schema partitions with inherited defaults still produce changes when planning an unchanged dump. If public.events.x has DEFAULT 42 and archive.child is its partition, the dump correctly omits that matching default. But the planning stub has no defaults, so the replayed child has none either.

Restoring the parent name and copying stub.Columns does not restore the child's inherited default. The comparison then emits ALTER TABLE child ALTER COLUMN x DROP DEFAULT, changing later inserts directly into the partition. Preserve parent defaults when building the planning stub, and add an empty-plan test for this case.

Knowledge Base Used:

}
}
for stubName := range parents {
delete(schema.Tables, stubName)
}
}

// rewritePartitionOfRef rewrites "PARTITION OF schema.table" to
Expand Down
Loading