postgresai 0.17.0-rc.5 → 0.18.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,18 +7,116 @@ grant connect on database {{DB_IDENT}} to {{ROLE_IDENT}};
7
7
  grant pg_monitor to {{ROLE_IDENT}};
8
8
  grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
9
9
 
10
- -- Required for cluster-wide pg_stat_statements collection.
11
- -- pg_stat_statements is backed by shared memory and holds entries for every database
12
- -- in the cluster, but a role without pg_read_all_stats sees other users' rows with
13
- -- queryid and query text redacted to NULL -- which collapses the per-queryid grouping
14
- -- in the pg_stat_statements metric. pg_monitor already implies pg_read_all_stats;
15
- -- granting it explicitly documents the dependency and keeps the metric working if the
16
- -- pg_monitor grant above is ever narrowed. Idempotent.
17
- grant pg_read_all_stats to {{ROLE_IDENT}};
10
+ -- Cluster-wide pg_stat_statements collection needs pg_read_all_stats (without it, other
11
+ -- users' rows have queryid and query text redacted to NULL). pg_monitor includes it, so it
12
+ -- is not granted directly: on PostgreSQL 16+ that needs ADMIN OPTION on pg_read_all_stats,
13
+ -- which Supabase's `postgres` role does not have (it has ADMIN OPTION on pg_monitor only).
18
14
 
19
15
  -- Create postgres_ai schema for our objects
20
16
  -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times
21
17
  create schema if not exists postgres_ai;
18
+ -- An existing schema keeps its owner, and CREATE OR REPLACE keeps the owner of
19
+ -- existing functions/views. Refuse a schema that another role can still write:
20
+ -- the monitoring role searches postgres_ai and calls our helper from it.
21
+ do {{DO_QUOTE}}
22
+ declare
23
+ schema_oid oid;
24
+ admin_oid oid;
25
+ schema_owner text;
26
+ create_grantee text;
27
+ schema_extension text;
28
+ foreign_object text;
29
+ begin
30
+ set local search_path = pg_catalog, pg_temp;
31
+ select oid into admin_oid from pg_catalog.pg_roles where rolname = current_user;
32
+ select oid into schema_oid from pg_catalog.pg_namespace where nspname = 'postgres_ai';
33
+
34
+ select pg_catalog.pg_get_userbyid(n.nspowner) into schema_owner
35
+ from pg_catalog.pg_namespace n where n.oid = schema_oid;
36
+ if schema_owner <> current_user then
37
+ raise exception 'postgres_ai schema must be owned by the prepare-db administrator'
38
+ using errcode = '42501',
39
+ detail = pg_catalog.format('Schema owner: %s; prepare-db user: %s', schema_owner, current_user),
40
+ hint = 'Have a DBA inspect postgres_ai, then transfer its ownership to the prepare-db user if safe.';
41
+ end if;
42
+
43
+ select case when a.grantee = 0 then 'PUBLIC' else pg_catalog.pg_get_userbyid(a.grantee) end
44
+ into create_grantee
45
+ from pg_catalog.pg_namespace n,
46
+ pg_catalog.aclexplode(coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner))) a
47
+ where n.oid = schema_oid and a.privilege_type = 'CREATE' and a.grantee <> admin_oid
48
+ limit 1;
49
+ if create_grantee is not null then
50
+ raise exception 'postgres_ai schema grants CREATE to another role'
51
+ using errcode = '42501',
52
+ detail = pg_catalog.format('CREATE grantee: %s', create_grantee),
53
+ hint = 'Have a DBA inspect the grant, then revoke CREATE on postgres_ai from that role or PUBLIC if safe.';
54
+ end if;
55
+
56
+ -- Trusted extensions can install bootstrap-owned members without owner
57
+ -- records in pg_shdepend (bootstrap superuser oid 10). Keep extensions out
58
+ -- of the monitoring search path regardless of their extension owner.
59
+ select e.extname into schema_extension
60
+ from pg_catalog.pg_extension e
61
+ where e.extnamespace = schema_oid
62
+ limit 1;
63
+ if schema_extension is not null then
64
+ raise exception 'postgres_ai schema contains an extension'
65
+ using errcode = '42501',
66
+ detail = pg_catalog.format('Extension: %s', schema_extension),
67
+ hint = 'Have a DBA inspect and move or remove this extension if safe before retrying prepare-db.';
68
+ end if;
69
+
70
+ -- Pinned/predefined roles have no pg_shdepend owner rows. Read catalog
71
+ -- owners directly before the dependency scan so those objects cannot hide.
72
+ with owned as (
73
+ select 'pg_class'::pg_catalog.regclass::oid as classid, c.oid as objid, c.relowner as owner_oid
74
+ from pg_catalog.pg_class c where c.relnamespace = schema_oid
75
+ union all select 'pg_proc'::pg_catalog.regclass::oid, p.oid, p.proowner
76
+ from pg_catalog.pg_proc p where p.pronamespace = schema_oid
77
+ union all select 'pg_type'::pg_catalog.regclass::oid, t.oid, t.typowner
78
+ from pg_catalog.pg_type t where t.typnamespace = schema_oid
79
+ union all select 'pg_operator'::pg_catalog.regclass::oid, o.oid, o.oprowner
80
+ from pg_catalog.pg_operator o where o.oprnamespace = schema_oid
81
+ union all select 'pg_opclass'::pg_catalog.regclass::oid, o.oid, o.opcowner
82
+ from pg_catalog.pg_opclass o where o.opcnamespace = schema_oid
83
+ union all select 'pg_opfamily'::pg_catalog.regclass::oid, o.oid, o.opfowner
84
+ from pg_catalog.pg_opfamily o where o.opfnamespace = schema_oid
85
+ union all select 'pg_collation'::pg_catalog.regclass::oid, c.oid, c.collowner
86
+ from pg_catalog.pg_collation c where c.collnamespace = schema_oid
87
+ union all select 'pg_conversion'::pg_catalog.regclass::oid, c.oid, c.conowner
88
+ from pg_catalog.pg_conversion c where c.connamespace = schema_oid
89
+ union all select 'pg_ts_dict'::pg_catalog.regclass::oid, d.oid, d.dictowner
90
+ from pg_catalog.pg_ts_dict d where d.dictnamespace = schema_oid
91
+ union all select 'pg_ts_config'::pg_catalog.regclass::oid, c.oid, c.cfgowner
92
+ from pg_catalog.pg_ts_config c where c.cfgnamespace = schema_oid
93
+ union all select 'pg_statistic_ext'::pg_catalog.regclass::oid, s.oid, s.stxowner
94
+ from pg_catalog.pg_statistic_ext s where s.stxnamespace = schema_oid
95
+ )
96
+ select pg_catalog.format('%s %s (owner %s)', o.type, o.identity,
97
+ pg_catalog.pg_get_userbyid(owned.owner_oid)) into foreign_object
98
+ from owned
99
+ cross join lateral pg_catalog.pg_identify_object(owned.classid, owned.objid, 0) o
100
+ where owned.owner_oid <> admin_oid
101
+ limit 1;
102
+
103
+ -- Retain a dependency scan for object kinds not represented above.
104
+ if foreign_object is null then
105
+ select o.identity into foreign_object
106
+ from pg_catalog.pg_shdepend s
107
+ cross join lateral pg_catalog.pg_identify_object(s.classid, s.objid, s.objsubid) o
108
+ where s.dbid = (select oid from pg_catalog.pg_database where datname = pg_catalog.current_database())
109
+ and s.deptype = 'o' and s.refobjid <> admin_oid
110
+ and o.schema = 'postgres_ai'
111
+ limit 1;
112
+ end if;
113
+ if foreign_object is not null then
114
+ raise exception 'postgres_ai schema contains objects owned by another role'
115
+ using errcode = '42501',
116
+ detail = pg_catalog.format('Foreign-owned object: %s', foreign_object),
117
+ hint = 'Have a DBA inspect this object, then reassign or remove it if safe before retrying prepare-db.';
118
+ end if;
119
+ end {{DO_QUOTE}};
22
120
  grant usage on schema postgres_ai to {{ROLE_IDENT}};
23
121
 
24
122
  -- For bloat analysis: expose pg_statistic via a view
@@ -44,43 +142,57 @@ grant usage on schema public to {{ROLE_IDENT}};
44
142
  -- Grant access to the schema where pg_stat_statements is installed.
45
143
  -- Some providers (e.g., Supabase) install extensions in a separate 'extensions' schema
46
144
  -- rather than pg_catalog. This DO block detects the schema and grants USAGE if needed.
47
- do $$
145
+ do {{DO_QUOTE}}
48
146
  declare
49
147
  ext_schema text;
50
148
  begin
51
149
  select n.nspname into ext_schema
52
- from pg_extension e
53
- join pg_namespace n on e.extnamespace = n.oid
150
+ from pg_catalog.pg_extension e
151
+ join pg_catalog.pg_namespace n on e.extnamespace = n.oid
54
152
  where e.extname = 'pg_stat_statements';
55
153
 
56
154
  -- Only grant if extension exists and is in a non-standard schema
57
155
  if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
58
- execute format('grant usage on schema %I to {{ROLE_IDENT}}', ext_schema);
156
+ execute pg_catalog.format('grant usage on schema %I to %I', ext_schema, {{ROLE_LITERAL}});
59
157
  end if;
60
- end $$;
158
+ end {{DO_QUOTE}};
61
159
 
62
- -- [SEARCH_PATH_BLOCK_START] Keep search_path predictable; postgres_ai first so our objects are found.
63
- -- Dynamically include the pg_stat_statements extension schema if it's in a non-standard location.
64
- do $$
160
+ -- [SEARCH_PATH_BLOCK_START] Resolve built-ins from pg_catalog first; keep pg_temp last.
161
+ -- Do not include the role-named schema: it may be writable by that role.
162
+ -- public stays for pg_stat_statements. Residual risk: a function in public with
163
+ -- an exact-type match (e.g. public.quote_ident(name)) still beats pg_catalog.
164
+ -- The path for this database includes its pg_stat_statements schema if it is in a non-standard location.
165
+ do {{DO_QUOTE}}
65
166
  declare
66
167
  ext_schema text;
67
- sp text;
168
+ role_path constant text := 'pg_catalog, postgres_ai, public, pg_temp';
169
+ db_path text := role_path;
68
170
  begin
171
+ -- This block runs as the admin: resolve its operators and functions from pg_catalog only
172
+ -- (CVE-2018-1058). The pin is inside the block: a DO block always runs in a transaction,
173
+ -- also in psql autocommit.
174
+ set local search_path = pg_catalog, pg_temp;
69
175
  -- Detect pg_stat_statements extension schema
70
176
  select n.nspname into ext_schema
71
- from pg_extension e
72
- join pg_namespace n on e.extnamespace = n.oid
177
+ from pg_catalog.pg_extension e
178
+ join pg_catalog.pg_namespace n on e.extnamespace = n.oid
73
179
  where e.extname = 'pg_stat_statements';
74
180
 
75
- -- Build search_path: include extension schema if in non-standard location
76
181
  if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
77
- sp := 'postgres_ai, ' || quote_ident(ext_schema) || ', "$user", public, pg_catalog';
78
- else
79
- sp := 'postgres_ai, "$user", public, pg_catalog';
182
+ db_path := 'pg_catalog, postgres_ai, ' || pg_catalog.quote_ident(ext_schema) || ', public, pg_temp';
80
183
  end if;
81
184
 
82
- execute format('alter user {{ROLE_IDENT}} set search_path = %s', sp);
83
- end $$;
185
+ -- Role-wide value: for databases that prepare-db did not run in. All databases share
186
+ -- this one row, so write it only when it holds another value.
187
+ if not exists (
188
+ select from pg_catalog.pg_db_role_setting
189
+ where setrole = (select oid from pg_catalog.pg_roles where rolname = {{ROLE_LITERAL}})
190
+ and setdatabase = 0
191
+ and ('search_path=' || role_path) = any (setconfig)
192
+ ) then
193
+ execute pg_catalog.format('alter user %I set search_path = %s', {{ROLE_LITERAL}}, role_path);
194
+ end if;
195
+ -- This database's value: other databases keep their own pg_stat_statements schema.
196
+ execute pg_catalog.format('alter user %I in database %I set search_path = %s', {{ROLE_LITERAL}}, pg_catalog.current_database(), db_path);
197
+ end {{DO_QUOTE}};
84
198
  -- [SEARCH_PATH_BLOCK_END]
85
-
86
-
@@ -1,6 +1,7 @@
1
1
  -- Optional permissions for RDS Postgres / Aurora (best effort)
2
2
 
3
- create extension if not exists rds_tools;
3
+ create schema if not exists rds_tools;
4
+ create extension if not exists rds_tools with schema rds_tools;
4
5
  grant execute on function rds_tools.pg_ls_multixactdir() to {{ROLE_IDENT}};
5
6
 
6
7
 
@@ -1,6 +1,17 @@
1
1
  -- Helper functions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
- -- These functions use SECURITY DEFINER to allow the monitoring user to perform
3
- -- operations they don't have direct permissions for.
2
+
3
+ -- Remove the retired helper from databases prepared by older CLI versions.
4
+ -- Only its owner or a superuser can drop it: anyone else gets a warning here. Releases
5
+ -- installed table_describe with the same owner, so replacing it below then fails.
6
+ do {{DO_QUOTE}}
7
+ begin
8
+ -- Runs as the admin: resolve names from pg_catalog only (CVE-2018-1058).
9
+ set local search_path = pg_catalog, pg_temp;
10
+ drop function if exists postgres_ai.explain_generic(text, text, text);
11
+ exception when insufficient_privilege then
12
+ raise warning 'postgres_ai: legacy SECURITY DEFINER helper was NOT removed: %', sqlerrm
13
+ using hint = 'Its owner or a superuser must drop it, then re-run prepare-db.';
14
+ end {{DO_QUOTE}};
4
15
 
5
16
  /*
6
17
  * table_describe
@@ -15,18 +26,25 @@
15
26
  *
16
27
  * Usage:
17
28
  * select postgres_ai.table_describe('public.users');
18
- * select postgres_ai.table_describe('my_table'); -- uses search_path
29
+ * select postgres_ai.table_describe('my_table'); -- pg_catalog, then public
30
+ *
31
+ * SECURITY INVOKER: it reads only the world-readable catalog, so it needs no
32
+ * privilege the caller lacks. Names are resolved by catalog query, not regclass
33
+ * (which demands USAGE on the schema): unqualified in pg_catalog, then public.
34
+ * search_path is pg_catalog, pg_temp so objects in a writable schema cannot
35
+ * shadow a built-in the function calls.
19
36
  */
20
37
  create or replace function postgres_ai.table_describe(
21
38
  in table_name text,
22
39
  out result text
23
40
  )
24
41
  language plpgsql
25
- security definer
26
- set search_path = pg_catalog, public
42
+ security invoker
43
+ set search_path = pg_catalog, pg_temp
27
44
  as $$
28
45
  declare
29
46
  v_oid oid;
47
+ v_ident text[];
30
48
  v_schema text;
31
49
  v_table text;
32
50
  v_relkind char;
@@ -37,8 +55,24 @@ declare
37
55
  v_rec record;
38
56
  v_constraint_count int := 0;
39
57
  begin
40
- -- Resolve table name to OID (handles schema-qualified and search_path)
41
- v_oid := table_name::regclass::oid;
58
+ -- Resolve table name to OID: [current database.]schema.table (pg_temp is the
59
+ -- caller's temp schema), or an unqualified name in pg_catalog, then public
60
+ v_ident := parse_ident(table_name);
61
+ select c.oid into v_oid
62
+ from pg_class c
63
+ join pg_namespace n on n.oid = c.relnamespace
64
+ where (cardinality(v_ident) <= 2 or (cardinality(v_ident) = 3 and v_ident[1] = current_database()))
65
+ and c.relname = v_ident[cardinality(v_ident)]::name
66
+ and case
67
+ when cardinality(v_ident) = 1 then n.nspname in ('pg_catalog', 'public')
68
+ when v_ident[cardinality(v_ident) - 1] = 'pg_temp' then n.oid = pg_my_temp_schema()
69
+ else n.nspname = v_ident[cardinality(v_ident) - 1]::name
70
+ end
71
+ order by n.nspname = 'public'
72
+ limit 1;
73
+ if v_oid is null then
74
+ raise exception 'relation "%" does not exist', table_name using errcode = '42P01';
75
+ end if;
42
76
 
43
77
  -- Get basic table info
44
78
  select
@@ -207,7 +241,7 @@ begin
207
241
  when 'f' then v_line := v_line || 'FK: ';
208
242
  when 'u' then v_line := v_line || 'UNIQUE: ';
209
243
  when 'c' then v_line := v_line || 'CHECK: ';
210
- else v_line := v_line || v_rec.contype || ': ';
244
+ else v_line := v_line || v_rec.contype::text || ': ';
211
245
  end case;
212
246
  v_line := v_line || v_rec.conname || ' ' || v_rec.condef;
213
247
  v_lines := array_append(v_lines, v_line);
@@ -1,5 +1,8 @@
1
1
  -- Drop helper functions created by prepare-db (template-filled by cli/lib/init.ts)
2
2
  -- Run before dropping the postgres_ai schema.
3
3
 
4
+ -- Objects in other schemas (for example, a planted public.format) must not run as the admin.
5
+ set local search_path = pg_catalog, pg_temp;
6
+
4
7
  drop function if exists postgres_ai.explain_generic(text, text, text);
5
8
  drop function if exists postgres_ai.table_describe(text);
@@ -1,30 +1,97 @@
1
1
  -- Revoke permissions and drop objects created by prepare-db (template-filled by cli/lib/init.ts)
2
2
 
3
+ -- Objects in other schemas (for example, a planted public.=) must not run as the admin.
4
+ set local search_path = pg_catalog, pg_temp;
5
+ -- The CLI reads the "unprepare-db:" WARNINGs. A higher setting would hide them.
6
+ set local client_min_messages = warning;
7
+
3
8
  -- Drop the postgres_ai.pg_statistic view
4
9
  drop view if exists postgres_ai.pg_statistic;
5
10
 
6
- -- Drop the postgres_ai schema (CASCADE to handle any remaining objects)
7
- drop schema if exists postgres_ai cascade;
8
-
9
- -- Revoke permissions from the monitoring role
10
- -- Use a DO block to handle the case where the role doesn't exist
11
- do $$ begin
12
- revoke pg_monitor from {{ROLE_IDENT}};
13
- exception when undefined_object then
14
- null; -- Role doesn't exist, nothing to revoke
15
- end $$;
16
-
17
- do $$ begin
18
- revoke select on pg_catalog.pg_index from {{ROLE_IDENT}};
19
- exception when undefined_object then
20
- null; -- Role doesn't exist
21
- end $$;
11
+ -- Revoke only the grants that the role holds. The postgres_ai schema stays
12
+ -- because it may contain customer objects. The pg_read_all_stats membership
13
+ -- comes from older prepare-db versions. The functions come from optional
14
+ -- permissions (04, 05). A non-superuser admin cannot revoke a grant that a
15
+ -- superuser made. Pass 1 revokes. Pass 2 sends one "grant left" WARNING for
16
+ -- each grant that stays. The CLI shows these WARNINGs and exits 1.
17
+ do {{DO_QUOTE}}
18
+ declare
19
+ role_oid oid;
20
+ stmt text;
21
+ begin
22
+ select oid into role_oid from pg_catalog.pg_roles where rolname = {{ROLE_LITERAL}};
23
+ if role_oid is null then
24
+ return; -- The monitoring role was already removed.
25
+ end if;
22
26
 
23
- do $$ begin
24
- revoke connect on database {{DB_IDENT}} from {{ROLE_IDENT}};
25
- exception when undefined_object then
26
- null; -- Role doesn't exist
27
- end $$;
27
+ for pass in 1..2 loop
28
+ for stmt in
29
+ -- PG 16+ keeps one row for each grantor. A revoke without GRANTED BY
30
+ -- removes only the row of the current user. PG < 16 can keep the oid of
31
+ -- a dropped grantor; then the statement has no GRANTED BY.
32
+ select pg_catalog.format('revoke %s from %I', m.roleid::regrole, {{ROLE_LITERAL}})
33
+ || coalesce(' granted by ' || pg_catalog.quote_ident(g.rolname), '')
34
+ from pg_catalog.pg_auth_members m
35
+ left join pg_catalog.pg_roles g on g.oid = m.grantor
36
+ where m.member = role_oid
37
+ and m.roleid in ('pg_monitor'::regrole, 'pg_read_all_stats'::regrole)
38
+ union
39
+ select pg_catalog.format('revoke select on pg_catalog.pg_index from %I', {{ROLE_LITERAL}})
40
+ from pg_catalog.pg_class c
41
+ where c.oid operator(pg_catalog.=) pg_catalog.to_regclass('pg_catalog.pg_index')::oid
42
+ and exists (
43
+ select from pg_catalog.aclexplode(c.relacl) a
44
+ where a.grantee = role_oid and a.privilege_type = 'SELECT')
45
+ union
46
+ select pg_catalog.format('revoke connect on database %I from %I', d.datname, {{ROLE_LITERAL}})
47
+ from pg_catalog.pg_database d
48
+ where d.datname = pg_catalog.current_database()
49
+ and exists (
50
+ select from pg_catalog.aclexplode(d.datacl) a
51
+ where a.grantee = role_oid and a.privilege_type = 'CONNECT')
52
+ union
53
+ select pg_catalog.format('revoke usage on schema postgres_ai from %I', {{ROLE_LITERAL}})
54
+ from pg_catalog.pg_namespace n
55
+ where n.nspname = 'postgres_ai'
56
+ and exists (
57
+ select from pg_catalog.aclexplode(n.nspacl) a
58
+ where a.grantee = role_oid and a.privilege_type = 'USAGE')
59
+ union
60
+ -- prepare-db grants USAGE when pg_stat_statements lives in a custom
61
+ -- extension schema. Retaining the login role must remove that grant too.
62
+ select pg_catalog.format('revoke usage on schema %I from %I', n.nspname, {{ROLE_LITERAL}})
63
+ from pg_catalog.pg_extension e
64
+ join pg_catalog.pg_namespace n on n.oid = e.extnamespace
65
+ where e.extname = 'pg_stat_statements'
66
+ and n.nspname not in ('pg_catalog', 'public')
67
+ and exists (
68
+ select from pg_catalog.aclexplode(n.nspacl) a
69
+ where a.grantee = role_oid and a.privilege_type = 'USAGE')
70
+ union
71
+ select pg_catalog.format('revoke execute on function %s from %I', p.oid::regprocedure, {{ROLE_LITERAL}})
72
+ from pg_catalog.pg_proc p
73
+ where p.oid in (
74
+ pg_catalog.to_regprocedure('rds_tools.pg_ls_multixactdir()'),
75
+ pg_catalog.to_regprocedure('pg_catalog.pg_stat_file(text)'),
76
+ pg_catalog.to_regprocedure('pg_catalog.pg_stat_file(text, boolean)'),
77
+ pg_catalog.to_regprocedure('pg_catalog.pg_ls_dir(text)'),
78
+ pg_catalog.to_regprocedure('pg_catalog.pg_ls_dir(text, boolean, boolean)'))
79
+ and exists (
80
+ select from pg_catalog.aclexplode(p.proacl) a
81
+ where a.grantee = role_oid and a.privilege_type = 'EXECUTE')
82
+ loop
83
+ if pass = 2 then
84
+ raise warning 'unprepare-db: grant left; a superuser can run: %', stmt;
85
+ else
86
+ begin
87
+ execute stmt;
88
+ exception when insufficient_privilege then
89
+ raise warning 'unprepare-db: % failed: %', stmt, sqlerrm;
90
+ end;
91
+ end if;
92
+ end loop;
93
+ end loop;
94
+ end {{DO_QUOTE}};
28
95
 
29
96
  -- Note: USAGE on public is typically granted by default; we don't revoke it
30
97
  -- to avoid breaking other applications that may rely on it.
@@ -1,27 +1,30 @@
1
1
  -- Drop the monitoring role created by prepare-db (template-filled by cli/lib/init.ts)
2
2
  -- This must run after revoking all permissions from the role.
3
3
 
4
+ -- Objects in other schemas (for example, a planted public.format) must not run as the admin.
5
+ set local search_path = pg_catalog, pg_temp;
6
+
4
7
  -- Use a DO block to handle the case where the role doesn't exist
5
- do $$ begin
8
+ do {{DO_QUOTE}} begin
6
9
  -- Reassign owned objects to current user before dropping
7
10
  -- This handles any objects that might have been created by the role
8
11
  begin
9
- execute format('reassign owned by %I to current_user', {{ROLE_LITERAL}});
12
+ execute pg_catalog.format('reassign owned by %I to current_user', {{ROLE_LITERAL}});
10
13
  exception when undefined_object then
11
14
  null; -- Role doesn't exist, nothing to reassign
12
15
  end;
13
16
 
14
17
  -- Drop owned objects (in case reassign didn't work for some objects)
15
18
  begin
16
- execute format('drop owned by %I', {{ROLE_LITERAL}});
19
+ execute pg_catalog.format('drop owned by %I', {{ROLE_LITERAL}});
17
20
  exception when undefined_object then
18
21
  null; -- Role doesn't exist
19
22
  end;
20
23
 
21
24
  -- Drop the role
22
25
  begin
23
- execute format('drop role %I', {{ROLE_LITERAL}});
26
+ execute pg_catalog.format('drop role %I', {{ROLE_LITERAL}});
24
27
  exception when undefined_object then
25
28
  null; -- Role doesn't exist, that's fine
26
29
  end;
27
- end $$;
30
+ end {{DO_QUOTE}};
@@ -1,16 +0,0 @@
1
- -- Role creation / password update (template-filled by cli/lib/init.ts)
2
- --
3
- -- Always uses a race-safe pattern (create if missing, then always alter to set the password):
4
- -- do $$ begin
5
- -- if not exists (select 1 from pg_catalog.pg_roles where rolname = '...') then
6
- -- begin
7
- -- create user "..." with password '...';
8
- -- exception when duplicate_object then
9
- -- null;
10
- -- end;
11
- -- end if;
12
- -- alter user "..." with password '...';
13
- -- end $$;
14
- {{ROLE_STMT}}
15
-
16
-
@@ -1,8 +0,0 @@
1
- -- Extensions required for postgres_ai monitoring
2
-
3
- -- Enable pg_stat_statements for query performance monitoring
4
- -- Note: Uses IF NOT EXISTS because extension may already be installed.
5
- -- We do NOT drop this extension in unprepare-db since it may have been pre-existing.
6
- create extension if not exists pg_stat_statements;
7
-
8
-
@@ -1,86 +0,0 @@
1
- -- Required permissions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
-
3
- -- Allow connect
4
- grant connect on database {{DB_IDENT}} to {{ROLE_IDENT}};
5
-
6
- -- Standard monitoring privileges
7
- grant pg_monitor to {{ROLE_IDENT}};
8
- grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
9
-
10
- -- Required for cluster-wide pg_stat_statements collection.
11
- -- pg_stat_statements is backed by shared memory and holds entries for every database
12
- -- in the cluster, but a role without pg_read_all_stats sees other users' rows with
13
- -- queryid and query text redacted to NULL -- which collapses the per-queryid grouping
14
- -- in the pg_stat_statements metric. pg_monitor already implies pg_read_all_stats;
15
- -- granting it explicitly documents the dependency and keeps the metric working if the
16
- -- pg_monitor grant above is ever narrowed. Idempotent.
17
- grant pg_read_all_stats to {{ROLE_IDENT}};
18
-
19
- -- Create postgres_ai schema for our objects
20
- -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times
21
- create schema if not exists postgres_ai;
22
- grant usage on schema postgres_ai to {{ROLE_IDENT}};
23
-
24
- -- For bloat analysis: expose pg_statistic via a view
25
- create or replace view postgres_ai.pg_statistic as
26
- select
27
- n.nspname as schemaname,
28
- c.relname as tablename,
29
- a.attname,
30
- s.stanullfrac as null_frac,
31
- s.stawidth as avg_width,
32
- false as inherited
33
- from pg_catalog.pg_statistic s
34
- join pg_catalog.pg_class c on c.oid = s.starelid
35
- join pg_catalog.pg_namespace n on n.oid = c.relnamespace
36
- join pg_catalog.pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
37
- where a.attnum > 0 and not a.attisdropped;
38
-
39
- grant select on postgres_ai.pg_statistic to {{ROLE_IDENT}};
40
-
41
- -- Hardened clusters sometimes revoke PUBLIC on schema public
42
- grant usage on schema public to {{ROLE_IDENT}};
43
-
44
- -- Grant access to the schema where pg_stat_statements is installed.
45
- -- Some providers (e.g., Supabase) install extensions in a separate 'extensions' schema
46
- -- rather than pg_catalog. This DO block detects the schema and grants USAGE if needed.
47
- do $$
48
- declare
49
- ext_schema text;
50
- begin
51
- select n.nspname into ext_schema
52
- from pg_extension e
53
- join pg_namespace n on e.extnamespace = n.oid
54
- where e.extname = 'pg_stat_statements';
55
-
56
- -- Only grant if extension exists and is in a non-standard schema
57
- if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
58
- execute format('grant usage on schema %I to {{ROLE_IDENT}}', ext_schema);
59
- end if;
60
- end $$;
61
-
62
- -- [SEARCH_PATH_BLOCK_START] Keep search_path predictable; postgres_ai first so our objects are found.
63
- -- Dynamically include the pg_stat_statements extension schema if it's in a non-standard location.
64
- do $$
65
- declare
66
- ext_schema text;
67
- sp text;
68
- begin
69
- -- Detect pg_stat_statements extension schema
70
- select n.nspname into ext_schema
71
- from pg_extension e
72
- join pg_namespace n on e.extnamespace = n.oid
73
- where e.extname = 'pg_stat_statements';
74
-
75
- -- Build search_path: include extension schema if in non-standard location
76
- if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
77
- sp := 'postgres_ai, ' || quote_ident(ext_schema) || ', "$user", public, pg_catalog';
78
- else
79
- sp := 'postgres_ai, "$user", public, pg_catalog';
80
- end if;
81
-
82
- execute format('alter user {{ROLE_IDENT}} set search_path = %s', sp);
83
- end $$;
84
- -- [SEARCH_PATH_BLOCK_END]
85
-
86
-
@@ -1,6 +0,0 @@
1
- -- Optional permissions for RDS Postgres / Aurora (best effort)
2
-
3
- create extension if not exists rds_tools;
4
- grant execute on function rds_tools.pg_ls_multixactdir() to {{ROLE_IDENT}};
5
-
6
-
@@ -1,8 +0,0 @@
1
- -- Optional permissions for self-managed Postgres (best effort)
2
-
3
- grant execute on function pg_catalog.pg_stat_file(text) to {{ROLE_IDENT}};
4
- grant execute on function pg_catalog.pg_stat_file(text, boolean) to {{ROLE_IDENT}};
5
- grant execute on function pg_catalog.pg_ls_dir(text) to {{ROLE_IDENT}};
6
- grant execute on function pg_catalog.pg_ls_dir(text, boolean, boolean) to {{ROLE_IDENT}};
7
-
8
-