@@ -88,7 +88,17 @@ CI_start_postgres() {
88
88
89
89
swap_postgres_and_supabase_admin () {
90
90
run_sql << 'EOSQL '
91
- alter database postgres connection limit 0;
91
+ do $$
92
+ declare
93
+ rec record;
94
+ begin
95
+ for rec in
96
+ select * from pg_database
97
+ loop
98
+ execute(format('alter database %I connection limit 0', datname));
99
+ end loop;
100
+ end
101
+ $$;
92
102
select pg_terminate_backend(pid) from pg_stat_activity where backend_type = 'client backend' and pid != pg_backend_pid();
93
103
EOSQL
94
104
206
216
$$;
207
217
208
218
-- Swap postgres & supabase_admin on in-database objects (schemas, tables, functions, etc.).
219
+ -- We execute the script directly on the `postgres` database, and we use dblink for user-defined dbs.
209
220
do $$
221
+ declare
222
+ swap_postgres_supabase_admin_on_in_database_objects_script text := $script$
223
+ do $script_do$
210
224
declare
211
225
event_triggers jsonb[] := (select coalesce(array_agg(jsonb_build_object('name', evtname)), '{}') from pg_event_trigger where evtowner = 'supabase_admin'::regrole);
212
226
user_mappings jsonb[] := (
@@ -561,9 +575,48 @@ begin
561
575
alter event trigger pgsodium_trg_mask_update enable;
562
576
end if;
563
577
end
578
+ $script_do$;
579
+ $script$;
580
+ dblink_schema text := (select extnamespace::regnamespace from pg_extension where extname = 'dblink');
581
+ rec record;
582
+ begin
583
+ -- Run script on database `postgres`
584
+ execute swap_postgres_supabase_admin_on_in_database_objects_script;
585
+
586
+ create schema _supabase_dblink;
587
+ if dblink_schema is null then
588
+ create extension dblink schema _supabase_dblink;
589
+ else
590
+ alter extension dblink set schema _supabase_dblink;
591
+ end if;
592
+
593
+ -- Run script on the rest of the dbs except template0.
594
+ -- Note that transaction across databases is not possible, so if a failure
595
+ -- occurs the script may not get rolled back on the other dbs.
596
+ for rec in
597
+ select * from pg_database where datname not in ('postgres', 'template0')
598
+ loop
599
+ perform _supabase_dblink.dblink_exec('dbname=' || quote_ident(rec.datname), swap_postgres_supabase_admin_on_in_database_objects_script);
600
+ end loop;
601
+
602
+ if dblink_schema is not null then
603
+ execute(format('alter extension dblink set schema %s', dblink_schema));
604
+ end if;
605
+ drop schema _supabase_dblink cascade;
606
+ end
564
607
$$;
565
608
566
- alter database postgres connection limit -1;
609
+ do $$
610
+ declare
611
+ rec record;
612
+ begin
613
+ for rec in
614
+ select * from pg_database
615
+ loop
616
+ execute(format('alter database %I connection limit -1', rec.datname));
617
+ end loop;
618
+ end
619
+ $$;
567
620
568
621
set session authorization supabase_admin;
569
622
drop role supabase_tmp;
0 commit comments