Fix previous_version function to work with non-public schema (#190)

Fix the `previous_version` function so that it works correctly for
migrations applied in schema other than`public`.

In particular, this meant that the previous version schema would not be
removed on migration completion for migrations applied is schema other
than `public`.

Extend the test that checks the `--schema` flag is respected with the
extra coverage that would have caught this.
This commit is contained in:
Andrew Farries 2023-10-18 09:00:02 +01:00 committed by GitHub
parent bd53d1082c
commit d486aabe6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 3 deletions

View File

@ -141,9 +141,13 @@ func TestSchemaOptionIsRespected(t *testing.T) {
withMigratorInSchemaAndConnectionToContainer(t, "schema1", func(mig *roll.Roll, db *sql.DB) {
ctx := context.Background()
version := "1_create_table"
const version1 = "1_create_table"
const version2 = "2_create_another_table"
if err := mig.Start(ctx, &migrations.Migration{Name: version, Operations: migrations.Operations{createTableOp("table1")}}); err != nil {
if err := mig.Start(ctx, &migrations.Migration{
Name: version1,
Operations: migrations.Operations{createTableOp("table1")},
}); err != nil {
t.Fatalf("Failed to start migration: %v", err)
}
if err := mig.Complete(ctx); err != nil {
@ -168,6 +172,32 @@ func TestSchemaOptionIsRespected(t *testing.T) {
if !exists {
t.Errorf("Expected table %q to exist in schema %q", "table1", "schema1")
}
// Apply another migration to the same schema
if err := mig.Start(ctx, &migrations.Migration{
Name: version2,
Operations: migrations.Operations{createTableOp("table2")},
}); err != nil {
t.Fatalf("Failed to start migration: %v", err)
}
if err := mig.Complete(ctx); err != nil {
t.Fatalf("Failed to complete migration: %v", err)
}
// Ensure that the versioned schema for the first migration has been dropped
err = db.QueryRow(`
SELECT EXISTS(
SELECT 1
FROM pg_catalog.pg_namespace
WHERE nspname = $1
)`, roll.VersionedSchemaName("schema1", version1)).Scan(&exists)
if err != nil {
t.Fatal(err)
}
if exists {
t.Errorf("Expected schema %q to not exist", version1)
}
})
}

View File

@ -63,7 +63,7 @@ STABLE;
-- Get the name of the previous version of the schema, or NULL if there is none.
CREATE OR REPLACE FUNCTION %[1]s.previous_version(schemaname NAME) RETURNS text
AS $$
SELECT parent FROM %[1]s.migrations WHERE name = (SELECT %[1]s.latest_version('public')) AND schema=schemaname;
SELECT parent FROM %[1]s.migrations WHERE name = (SELECT %[1]s.latest_version(schemaname)) AND schema=schemaname;
$$
LANGUAGE SQL
STABLE;