Skip to content

Commit 84ef318

Browse files
Infer CREATE/DROP SCHEMA migrations (#359)
Update the `raw_migation` event trigger function to capture `CREATE SCHEMA` and `DROP SCHEMA` statements.
1 parent 8234b9e commit 84ef318

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

pkg/state/state.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,11 @@ BEGIN
276276
RETURN;
277277
END IF;
278278
279-
IF tg_event = 'sql_drop' and tg_tag != 'ALTER TABLE' THEN
279+
IF tg_event = 'sql_drop' AND tg_tag = 'DROP SCHEMA' THEN
280+
-- Take the schema name from the drop schema command
281+
SELECT object_identity INTO schemaname FROM pg_event_trigger_dropped_objects();
282+
283+
ELSIF tg_event = 'sql_drop' and tg_tag != 'ALTER TABLE' THEN
280284
-- Guess the schema from drop commands
281285
SELECT schema_name INTO schemaname FROM pg_catalog.pg_event_trigger_dropped_objects() WHERE schema_name IS NOT NULL;
282286
@@ -286,7 +290,11 @@ BEGIN
286290
RETURN;
287291
END IF;
288292
289-
SELECT schema_name INTO schemaname FROM pg_catalog.pg_event_trigger_ddl_commands() WHERE schema_name IS NOT NULL;
293+
IF tg_tag = 'CREATE SCHEMA' THEN
294+
SELECT object_identity INTO schemaname FROM pg_event_trigger_ddl_commands();
295+
ELSE
296+
SELECT schema_name INTO schemaname FROM pg_catalog.pg_event_trigger_ddl_commands() WHERE schema_name IS NOT NULL;
297+
END IF;
290298
END IF;
291299
292300
IF schemaname IS NULL THEN

pkg/state/state_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,25 @@ func TestInferredMigration(t *testing.T) {
197197
},
198198
},
199199
},
200+
{
201+
name: "create/drop schema",
202+
sqlStmts: []string{
203+
"CREATE SCHEMA foo",
204+
"DROP SCHEMA foo",
205+
},
206+
wantMigrations: []migrations.Migration{
207+
{
208+
Operations: migrations.Operations{
209+
&migrations.OpRawSQL{Up: "CREATE SCHEMA foo"},
210+
},
211+
},
212+
{
213+
Operations: migrations.Operations{
214+
&migrations.OpRawSQL{Up: "DROP SCHEMA foo"},
215+
},
216+
},
217+
},
218+
},
200219
}
201220

202221
for _, tt := range tests {

0 commit comments

Comments
 (0)