postgresai 0.18.0-dev.15 → 0.18.0-dev.16

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.
@@ -13533,7 +13533,7 @@ var {
13533
13533
  // package.json
13534
13534
  var package_default = {
13535
13535
  name: "postgresai",
13536
- version: "0.18.0-dev.15",
13536
+ version: "0.18.0-dev.16",
13537
13537
  description: "postgres_ai CLI",
13538
13538
  license: "Apache-2.0",
13539
13539
  private: false,
@@ -16893,7 +16893,7 @@ var Result = import_lib.default.Result;
16893
16893
  var TypeOverrides = import_lib.default.TypeOverrides;
16894
16894
  var defaults = import_lib.default.defaults;
16895
16895
  // package.json
16896
- var version = "0.18.0-dev.15";
16896
+ var version = "0.18.0-dev.16";
16897
16897
  var package_default2 = {
16898
16898
  name: "postgresai",
16899
16899
  version,
@@ -22045,6 +22045,42 @@ function safeDoDelimiter(...values) {
22045
22045
  function redactPasswordsInSql(sql) {
22046
22046
  return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
22047
22047
  }
22048
+ function renderInitPlanSql(plan) {
22049
+ const lines = [
22050
+ "-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.",
22051
+ "begin;"
22052
+ ];
22053
+ for (const step of plan.steps) {
22054
+ const sql = redactPasswordsInSql(step.sql);
22055
+ lines.push(`
22056
+ -- ${step.name}${step.optional ? " (optional)" : ""}`);
22057
+ if (!step.optional) {
22058
+ lines.push(sql);
22059
+ continue;
22060
+ }
22061
+ const delimiter = (base) => {
22062
+ let i = 0;
22063
+ while (sql.includes(`$${base}_${i}$`))
22064
+ i++;
22065
+ return `$${base}_${i}$`;
22066
+ };
22067
+ const outer = delimiter("pgai_optional_outer");
22068
+ const inner = delimiter("pgai_optional_sql");
22069
+ lines.push(`do ${outer}
22070
+ begin
22071
+ begin
22072
+ execute ${inner}
22073
+ ${sql}
22074
+ ${inner};
22075
+ exception when others then
22076
+ raise warning 'optional SQL step ${step.name} skipped: %', sqlerrm;
22077
+ end;
22078
+ end ${outer};`);
22079
+ }
22080
+ lines.push("commit;");
22081
+ return lines.join(`
22082
+ `);
22083
+ }
22048
22084
  function maskConnectionString(dbUrl) {
22049
22085
  let masked = dbUrl;
22050
22086
  const head = dbUrl.match(/^(\s*[a-z][a-z0-9+.-]*:\/\/)([^:@\/?#]*):([\s\S]*)$/i);
@@ -24117,10 +24153,7 @@ async function prepareDatabase(url, provider, opts = {}) {
24117
24153
  }
24118
24154
  const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
24119
24155
  return {
24120
- sql: plan.steps.map((s) => `-- ${s.name}${s.optional ? " (optional: an error in this part can be ignored)" : ""}
24121
- ${redactPasswordsInSql(s.sql)}`).join(`
24122
-
24123
- `),
24156
+ sql: renderInitPlanSql(plan),
24124
24157
  next: `Run the SQL as an admin, with a password of your choice in place of <redacted> (or re-run with an admin URL), then pgai mon deploy again with the ${role} URL`
24125
24158
  };
24126
24159
  } finally {
@@ -33906,10 +33939,7 @@ async function prepareDatabase2(url, provider, opts = {}) {
33906
33939
  }
33907
33940
  const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
33908
33941
  return {
33909
- sql: plan.steps.map((s) => `-- ${s.name}${s.optional ? " (optional: an error in this part can be ignored)" : ""}
33910
- ${redactPasswordsInSql(s.sql)}`).join(`
33911
-
33912
- `),
33942
+ sql: renderInitPlanSql(plan),
33913
33943
  next: `Run the SQL as an admin, with a password of your choice in place of <redacted> (or re-run with an admin URL), then pgai mon deploy again with the ${role} URL`
33914
33944
  };
33915
33945
  } finally {
@@ -36912,6 +36942,42 @@ function safeDoDelimiter2(...values) {
36912
36942
  function redactPasswordsInSql2(sql) {
36913
36943
  return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
36914
36944
  }
36945
+ function renderInitPlanSql2(plan) {
36946
+ const lines = [
36947
+ "-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.",
36948
+ "begin;"
36949
+ ];
36950
+ for (const step of plan.steps) {
36951
+ const sql = redactPasswordsInSql2(step.sql);
36952
+ lines.push(`
36953
+ -- ${step.name}${step.optional ? " (optional)" : ""}`);
36954
+ if (!step.optional) {
36955
+ lines.push(sql);
36956
+ continue;
36957
+ }
36958
+ const delimiter = (base) => {
36959
+ let i = 0;
36960
+ while (sql.includes(`$${base}_${i}$`))
36961
+ i++;
36962
+ return `$${base}_${i}$`;
36963
+ };
36964
+ const outer = delimiter("pgai_optional_outer");
36965
+ const inner = delimiter("pgai_optional_sql");
36966
+ lines.push(`do ${outer}
36967
+ begin
36968
+ begin
36969
+ execute ${inner}
36970
+ ${sql}
36971
+ ${inner};
36972
+ exception when others then
36973
+ raise warning 'optional SQL step ${step.name} skipped: %', sqlerrm;
36974
+ end;
36975
+ end ${outer};`);
36976
+ }
36977
+ lines.push("commit;");
36978
+ return lines.join(`
36979
+ `);
36980
+ }
36915
36981
  function maskConnectionString2(dbUrl) {
36916
36982
  let masked = dbUrl;
36917
36983
  const head = dbUrl.match(/^(\s*[a-z][a-z0-9+.-]*:\/\/)([^:@\/?#]*):([\s\S]*)$/i);
@@ -38539,6 +38605,32 @@ function raiseConnectAttemptTimeout(execArgv = process.execArgv, nodeOptions = p
38539
38605
  return nodeNet.getDefaultAutoSelectFamilyAttemptTimeout();
38540
38606
  }
38541
38607
 
38608
+ // lib/prepare-error.ts
38609
+ function terminalDiagnosticLine(value) {
38610
+ return terminalText(value).replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/[\u202a-\u202e\u2066-\u2069]/g, "");
38611
+ }
38612
+ function prepareDbPrivilegeAdvice(code, failedStep, message, supabase) {
38613
+ if (code !== "42501")
38614
+ return [];
38615
+ if (failedStep === "03.permissions" && message.includes("postgres_ai schema ")) {
38616
+ return ["Fix: ask a DBA to inspect the named schema ownership, grants, or object before retrying"];
38617
+ }
38618
+ const lines = [];
38619
+ if (failedStep === "01.role") {
38620
+ lines.push("Context: role creation/update requires CREATEROLE or superuser");
38621
+ } else if (failedStep === "03.permissions") {
38622
+ lines.push("Context: grants/view/search_path require sufficient GRANT/DDL privileges");
38623
+ }
38624
+ if (supabase) {
38625
+ lines.push("Fix: ensure your Supabase access token has sufficient permissions");
38626
+ } else {
38627
+ lines.push("Fix: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges)");
38628
+ lines.push("Fix: on managed Postgres, use the provider's admin/master user");
38629
+ }
38630
+ lines.push("Tip: run with --print-sql to review the exact SQL plan");
38631
+ return lines;
38632
+ }
38633
+
38542
38634
  // lib/feedback.ts
38543
38635
  var FEEDBACK_URL = "https://gitlab.com/postgres-ai/postgresai/-/work_items/300";
38544
38636
  var FEEDBACK_SUPPRESS_ENV = "PGAI_NO_FEEDBACK_TIP";
@@ -45964,7 +46056,6 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45964
46056
  conn = process.env.PGAI_DB_URL || undefined;
45965
46057
  }
45966
46058
  const shouldPrintSql = !!opts.printSql;
45967
- const redactPasswords = (sql) => redactPasswordsInSql2(sql);
45968
46059
  const { provider, detected } = resolveProvider(opts.provider, conn ?? opts.dbUrl ?? opts.host ?? process.env.PGHOST);
45969
46060
  const note = opts.json ? console.error : console.log;
45970
46061
  if (detected)
@@ -45996,11 +46087,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45996
46087
  console.log(`-- monitoring user: ${opts.monitoringUser}`);
45997
46088
  console.log(`-- provider: ${provider}`);
45998
46089
  console.log(`-- optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
45999
- for (const step of plan.steps) {
46000
- console.log(`
46001
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
46002
- console.log(redactPasswords(step.sql));
46003
- }
46090
+ console.log(renderInitPlanSql2(plan));
46004
46091
  console.log(`
46005
46092
  --- end SQL plan ---
46006
46093
  `);
@@ -46162,11 +46249,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46162
46249
  if (shouldPrintSql) {
46163
46250
  console.log(`
46164
46251
  --- SQL plan ---`);
46165
- for (const step of effectivePlan.steps) {
46166
- console.log(`
46167
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
46168
- console.log(redactPasswords(step.sql));
46169
- }
46252
+ console.log(renderInitPlanSql2(effectivePlan));
46170
46253
  console.log(`
46171
46254
  --- end SQL plan ---
46172
46255
  `);
@@ -46257,24 +46340,18 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46257
46340
  console.error(` Code: ${errAny.code}`);
46258
46341
  }
46259
46342
  if (typeof errAny.detail === "string" && errAny.detail) {
46260
- console.error(` Detail: ${errAny.detail}`);
46343
+ console.error(` Detail: ${terminalDiagnosticLine(errAny.detail)}`);
46261
46344
  }
46262
46345
  if (typeof errAny.hint === "string" && errAny.hint) {
46263
- console.error(` Hint: ${errAny.hint}`);
46346
+ console.error(` Hint: ${terminalDiagnosticLine(errAny.hint)}`);
46264
46347
  }
46265
46348
  if (typeof errAny.httpStatus === "number") {
46266
46349
  console.error(` HTTP Status: ${errAny.httpStatus}`);
46267
46350
  }
46268
46351
  }
46269
46352
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
46270
- if (errAny.code === "42501") {
46271
- if (failedStep === "01.role") {
46272
- console.error(" Context: role creation/update requires CREATEROLE or superuser");
46273
- } else if (failedStep === "03.permissions") {
46274
- console.error(" Context: grants/view/search_path require sufficient GRANT/DDL privileges");
46275
- }
46276
- console.error(" Fix: ensure your Supabase access token has sufficient permissions");
46277
- console.error(" Tip: run with --print-sql to review the exact SQL plan");
46353
+ for (const line of prepareDbPrivilegeAdvice(errAny.code, failedStep, message, true)) {
46354
+ console.error(` ${line}`);
46278
46355
  }
46279
46356
  if (errAny.code === "42P06" || message.includes("already exists") && failedStep === "03.permissions") {
46280
46357
  console.error(" Hint: postgres_ai schema or objects already exist from a previous setup.");
@@ -46460,11 +46537,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46460
46537
  if (shouldPrintSql) {
46461
46538
  console.log(`
46462
46539
  --- SQL plan ---`);
46463
- for (const step of effectivePlan.steps) {
46464
- console.log(`
46465
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
46466
- console.log(redactPasswords(step.sql));
46467
- }
46540
+ console.log(renderInitPlanSql2(effectivePlan));
46468
46541
  console.log(`
46469
46542
  --- end SQL plan ---
46470
46543
  `);
@@ -46549,24 +46622,17 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46549
46622
  console.error(` Code: ${errAny.code}`);
46550
46623
  }
46551
46624
  if (typeof errAny.detail === "string" && errAny.detail) {
46552
- console.error(` Detail: ${errAny.detail}`);
46625
+ console.error(` Detail: ${terminalDiagnosticLine(errAny.detail)}`);
46553
46626
  }
46554
46627
  if (typeof errAny.hint === "string" && errAny.hint) {
46555
- console.error(` Hint: ${errAny.hint}`);
46628
+ console.error(` Hint: ${terminalDiagnosticLine(errAny.hint)}`);
46556
46629
  }
46557
46630
  }
46558
46631
  for (const w of legacyWarnings)
46559
46632
  console.error(`\u26A0 ${w}`);
46560
46633
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
46561
- if (errAny.code === "42501") {
46562
- if (failedStep === "01.role") {
46563
- console.error(" Context: role creation/update requires CREATEROLE or superuser");
46564
- } else if (failedStep === "03.permissions") {
46565
- console.error(" Context: grants/view/search_path require sufficient GRANT/DDL privileges");
46566
- }
46567
- console.error(" Fix: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges)");
46568
- console.error(" Fix: on managed Postgres, use the provider's admin/master user");
46569
- console.error(" Tip: run with --print-sql to review the exact SQL plan");
46634
+ for (const line of prepareDbPrivilegeAdvice(errAny.code, failedStep, message, false)) {
46635
+ console.error(` ${line}`);
46570
46636
  }
46571
46637
  if (errAny.code === "42P06" || message.includes("already exists") && failedStep === "03.permissions") {
46572
46638
  console.error(" Hint: postgres_ai schema or objects already exist from a previous setup.");
@@ -46663,11 +46729,14 @@ program2.command("unprepare-db [conn]").description("remove monitoring setup: dr
46663
46729
  console.log(`-- monitoring user: ${opts.monitoringUser}`);
46664
46730
  console.log(`-- provider: ${provider}`);
46665
46731
  console.log(`-- drop role: ${dropRole}`);
46732
+ console.log("-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.");
46733
+ console.log("begin;");
46666
46734
  for (const step of plan.steps) {
46667
46735
  console.log(`
46668
46736
  -- ${step.name}`);
46669
46737
  console.log(step.sql);
46670
46738
  }
46739
+ console.log("commit;");
46671
46740
  console.log(`
46672
46741
  --- end SQL plan ---
46673
46742
  `);
@@ -46733,11 +46802,14 @@ program2.command("unprepare-db [conn]").description("remove monitoring setup: dr
46733
46802
  if (shouldPrintSql) {
46734
46803
  console.log(`
46735
46804
  --- SQL plan ---`);
46805
+ console.log("-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.");
46806
+ console.log("begin;");
46736
46807
  for (const step of plan.steps) {
46737
46808
  console.log(`
46738
46809
  -- ${step.name}`);
46739
46810
  console.log(step.sql);
46740
46811
  }
46812
+ console.log("commit;");
46741
46813
  console.log(`
46742
46814
  --- end SQL plan ---
46743
46815
  `);
@@ -1,4 +1,6 @@
1
1
  -- Role creation / password update (template-filled by cli/lib/init.ts)
2
+ -- Pin name resolution before the privileged DO block, including for printed SQL.
3
+ set search_path = pg_catalog, pg_temp;
2
4
  --
3
5
  -- A race-safe pattern: create if missing, then alter to set the password.
4
6
  -- `pgai mon deploy` omits the alter, so an existing role keeps its password:
@@ -1,4 +1,5 @@
1
1
  -- Extensions required for postgres_ai monitoring
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  -- Enable pg_stat_statements for query performance monitoring
4
5
  -- Note: Uses IF NOT EXISTS because extension may already be installed.
@@ -1,4 +1,6 @@
1
1
  -- Required permissions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
+ -- The first DO block also runs as the admin; pin before any name resolution.
3
+ set search_path = pg_catalog, pg_temp;
2
4
 
3
5
  -- Allow connect
4
6
  grant connect on database {{DB_IDENT}} to {{ROLE_IDENT}};
@@ -15,6 +17,108 @@ grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
15
17
  -- Create postgres_ai schema for our objects
16
18
  -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times
17
19
  create schema if not exists postgres_ai;
20
+ -- An existing schema keeps its owner, and CREATE OR REPLACE keeps the owner of
21
+ -- existing functions/views. Refuse a schema that another role can still write:
22
+ -- the monitoring role searches postgres_ai and calls our helper from it.
23
+ do {{DO_QUOTE}}
24
+ declare
25
+ schema_oid oid;
26
+ admin_oid oid;
27
+ schema_owner text;
28
+ create_grantee text;
29
+ schema_extension text;
30
+ foreign_object text;
31
+ begin
32
+ set local search_path = pg_catalog, pg_temp;
33
+ select oid into admin_oid from pg_catalog.pg_roles where rolname = current_user;
34
+ select oid into schema_oid from pg_catalog.pg_namespace where nspname = 'postgres_ai';
35
+
36
+ select pg_catalog.pg_get_userbyid(n.nspowner) into schema_owner
37
+ from pg_catalog.pg_namespace n where n.oid = schema_oid;
38
+ if schema_owner <> current_user then
39
+ raise exception 'postgres_ai schema must be owned by the prepare-db administrator'
40
+ using errcode = '42501',
41
+ detail = pg_catalog.format('Schema owner: %s; prepare-db user: %s', schema_owner, current_user),
42
+ hint = 'Have a DBA inspect postgres_ai, then transfer its ownership to the prepare-db user if safe.';
43
+ end if;
44
+
45
+ select case when a.grantee = 0 then 'PUBLIC' else pg_catalog.pg_get_userbyid(a.grantee) end
46
+ into create_grantee
47
+ from pg_catalog.pg_namespace n,
48
+ pg_catalog.aclexplode(coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner))) a
49
+ where n.oid = schema_oid and a.privilege_type = 'CREATE' and a.grantee <> admin_oid
50
+ limit 1;
51
+ if create_grantee is not null then
52
+ raise exception 'postgres_ai schema grants CREATE to another role'
53
+ using errcode = '42501',
54
+ detail = pg_catalog.format('CREATE grantee: %s', create_grantee),
55
+ hint = 'Have a DBA inspect the grant, then revoke CREATE on postgres_ai from that role or PUBLIC if safe.';
56
+ end if;
57
+
58
+ -- Trusted extensions can install bootstrap-owned members without owner
59
+ -- records in pg_shdepend (bootstrap superuser oid 10). Keep extensions out
60
+ -- of the monitoring search path regardless of their extension owner.
61
+ select e.extname into schema_extension
62
+ from pg_catalog.pg_extension e
63
+ where e.extnamespace = schema_oid
64
+ limit 1;
65
+ if schema_extension is not null then
66
+ raise exception 'postgres_ai schema contains an extension'
67
+ using errcode = '42501',
68
+ detail = pg_catalog.format('Extension: %s', schema_extension),
69
+ hint = 'Have a DBA inspect and move or remove this extension if safe before retrying prepare-db.';
70
+ end if;
71
+
72
+ -- Pinned/predefined roles have no pg_shdepend owner rows. Read catalog
73
+ -- owners directly before the dependency scan so those objects cannot hide.
74
+ with owned as (
75
+ select 'pg_class'::pg_catalog.regclass::oid as classid, c.oid as objid, c.relowner as owner_oid
76
+ from pg_catalog.pg_class c where c.relnamespace = schema_oid
77
+ union all select 'pg_proc'::pg_catalog.regclass::oid, p.oid, p.proowner
78
+ from pg_catalog.pg_proc p where p.pronamespace = schema_oid
79
+ union all select 'pg_type'::pg_catalog.regclass::oid, t.oid, t.typowner
80
+ from pg_catalog.pg_type t where t.typnamespace = schema_oid
81
+ union all select 'pg_operator'::pg_catalog.regclass::oid, o.oid, o.oprowner
82
+ from pg_catalog.pg_operator o where o.oprnamespace = schema_oid
83
+ union all select 'pg_opclass'::pg_catalog.regclass::oid, o.oid, o.opcowner
84
+ from pg_catalog.pg_opclass o where o.opcnamespace = schema_oid
85
+ union all select 'pg_opfamily'::pg_catalog.regclass::oid, o.oid, o.opfowner
86
+ from pg_catalog.pg_opfamily o where o.opfnamespace = schema_oid
87
+ union all select 'pg_collation'::pg_catalog.regclass::oid, c.oid, c.collowner
88
+ from pg_catalog.pg_collation c where c.collnamespace = schema_oid
89
+ union all select 'pg_conversion'::pg_catalog.regclass::oid, c.oid, c.conowner
90
+ from pg_catalog.pg_conversion c where c.connamespace = schema_oid
91
+ union all select 'pg_ts_dict'::pg_catalog.regclass::oid, d.oid, d.dictowner
92
+ from pg_catalog.pg_ts_dict d where d.dictnamespace = schema_oid
93
+ union all select 'pg_ts_config'::pg_catalog.regclass::oid, c.oid, c.cfgowner
94
+ from pg_catalog.pg_ts_config c where c.cfgnamespace = schema_oid
95
+ union all select 'pg_statistic_ext'::pg_catalog.regclass::oid, s.oid, s.stxowner
96
+ from pg_catalog.pg_statistic_ext s where s.stxnamespace = schema_oid
97
+ )
98
+ select pg_catalog.format('%s %s (owner %s)', o.type, o.identity,
99
+ pg_catalog.pg_get_userbyid(owned.owner_oid)) into foreign_object
100
+ from owned
101
+ cross join lateral pg_catalog.pg_identify_object(owned.classid, owned.objid, 0) o
102
+ where owned.owner_oid <> admin_oid
103
+ limit 1;
104
+
105
+ -- Retain a dependency scan for object kinds not represented above.
106
+ if foreign_object is null then
107
+ select o.identity into foreign_object
108
+ from pg_catalog.pg_shdepend s
109
+ cross join lateral pg_catalog.pg_identify_object(s.classid, s.objid, s.objsubid) o
110
+ where s.dbid = (select oid from pg_catalog.pg_database where datname = pg_catalog.current_database())
111
+ and s.deptype = 'o' and s.refobjid <> admin_oid
112
+ and o.schema = 'postgres_ai'
113
+ limit 1;
114
+ end if;
115
+ if foreign_object is not null then
116
+ raise exception 'postgres_ai schema contains objects owned by another role'
117
+ using errcode = '42501',
118
+ detail = pg_catalog.format('Foreign-owned object: %s', foreign_object),
119
+ hint = 'Have a DBA inspect this object, then reassign or remove it if safe before retrying prepare-db.';
120
+ end if;
121
+ end {{DO_QUOTE}};
18
122
  grant usage on schema postgres_ai to {{ROLE_IDENT}};
19
123
 
20
124
  -- For bloat analysis: expose pg_statistic via a view
@@ -45,13 +149,13 @@ declare
45
149
  ext_schema text;
46
150
  begin
47
151
  select n.nspname into ext_schema
48
- from pg_extension e
49
- join pg_namespace n on e.extnamespace = n.oid
152
+ from pg_catalog.pg_extension e
153
+ join pg_catalog.pg_namespace n on e.extnamespace = n.oid
50
154
  where e.extname = 'pg_stat_statements';
51
155
 
52
156
  -- Only grant if extension exists and is in a non-standard schema
53
157
  if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
54
- execute format('grant usage on schema %I to %I', ext_schema, {{ROLE_LITERAL}});
158
+ execute pg_catalog.format('grant usage on schema %I to %I', ext_schema, {{ROLE_LITERAL}});
55
159
  end if;
56
160
  end {{DO_QUOTE}};
57
161
 
@@ -72,12 +176,12 @@ begin
72
176
  set local search_path = pg_catalog, pg_temp;
73
177
  -- Detect pg_stat_statements extension schema
74
178
  select n.nspname into ext_schema
75
- from pg_extension e
76
- join pg_namespace n on e.extnamespace = n.oid
179
+ from pg_catalog.pg_extension e
180
+ join pg_catalog.pg_namespace n on e.extnamespace = n.oid
77
181
  where e.extname = 'pg_stat_statements';
78
182
 
79
183
  if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
80
- db_path := 'pg_catalog, postgres_ai, ' || quote_ident(ext_schema) || ', public, pg_temp';
184
+ db_path := 'pg_catalog, postgres_ai, ' || pg_catalog.quote_ident(ext_schema) || ', public, pg_temp';
81
185
  end if;
82
186
 
83
187
  -- Role-wide value: for databases that prepare-db did not run in. All databases share
@@ -88,9 +192,9 @@ begin
88
192
  and setdatabase = 0
89
193
  and ('search_path=' || role_path) = any (setconfig)
90
194
  ) then
91
- execute format('alter user %I set search_path = %s', {{ROLE_LITERAL}}, role_path);
195
+ execute pg_catalog.format('alter user %I set search_path = %s', {{ROLE_LITERAL}}, role_path);
92
196
  end if;
93
197
  -- This database's value: other databases keep their own pg_stat_statements schema.
94
- execute format('alter user %I in database %I set search_path = %s', {{ROLE_LITERAL}}, pg_catalog.current_database(), db_path);
198
+ execute pg_catalog.format('alter user %I in database %I set search_path = %s', {{ROLE_LITERAL}}, pg_catalog.current_database(), db_path);
95
199
  end {{DO_QUOTE}};
96
200
  -- [SEARCH_PATH_BLOCK_END]
@@ -1,4 +1,5 @@
1
1
  -- Optional permissions for RDS Postgres / Aurora (best effort)
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  create schema if not exists rds_tools;
4
5
  create extension if not exists rds_tools with schema rds_tools;
@@ -1,4 +1,5 @@
1
1
  -- Optional permissions for self-managed Postgres (best effort)
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  grant execute on function pg_catalog.pg_stat_file(text) to {{ROLE_IDENT}};
4
5
  grant execute on function pg_catalog.pg_stat_file(text, boolean) to {{ROLE_IDENT}};
@@ -1,4 +1,5 @@
1
1
  -- Helper functions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  -- Remove the retired helper from databases prepared by older CLI versions.
4
5
  -- Only its owner or a superuser can drop it: anyone else gets a warning here. Releases
@@ -2,7 +2,9 @@
2
2
  -- Run before dropping the postgres_ai schema.
3
3
 
4
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;
5
+ -- Use a session SET because --print-sql plans may be run by psql in autocommit.
6
+ -- SET LOCAL outside an explicit transaction is ignored there.
7
+ set search_path = pg_catalog, pg_temp;
6
8
 
7
9
  drop function if exists postgres_ai.explain_generic(text, text, text);
8
10
  drop function if exists postgres_ai.table_describe(text);
@@ -1,9 +1,10 @@
1
1
  -- Revoke permissions and drop objects created by prepare-db (template-filled by cli/lib/init.ts)
2
2
 
3
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;
4
+ -- Printed plans may run in psql autocommit, where SET LOCAL is ignored.
5
+ set search_path = pg_catalog, pg_temp;
5
6
  -- The CLI reads the "unprepare-db:" WARNINGs. A higher setting would hide them.
6
- set local client_min_messages = warning;
7
+ set client_min_messages = warning;
7
8
 
8
9
  -- Drop the postgres_ai.pg_statistic view
9
10
  drop view if exists postgres_ai.pg_statistic;
@@ -57,6 +58,17 @@ begin
57
58
  select from pg_catalog.aclexplode(n.nspacl) a
58
59
  where a.grantee = role_oid and a.privilege_type = 'USAGE')
59
60
  union
61
+ -- prepare-db grants USAGE when pg_stat_statements lives in a custom
62
+ -- extension schema. Retaining the login role must remove that grant too.
63
+ select pg_catalog.format('revoke usage on schema %I from %I', n.nspname, {{ROLE_LITERAL}})
64
+ from pg_catalog.pg_extension e
65
+ join pg_catalog.pg_namespace n on n.oid = e.extnamespace
66
+ where e.extname = 'pg_stat_statements'
67
+ and n.nspname not in ('pg_catalog', 'public')
68
+ and exists (
69
+ select from pg_catalog.aclexplode(n.nspacl) a
70
+ where a.grantee = role_oid and a.privilege_type = 'USAGE')
71
+ union
60
72
  select pg_catalog.format('revoke execute on function %s from %I', p.oid::regprocedure, {{ROLE_LITERAL}})
61
73
  from pg_catalog.pg_proc p
62
74
  where p.oid in (
@@ -2,28 +2,29 @@
2
2
  -- This must run after revoking all permissions from the role.
3
3
 
4
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;
5
+ -- Printed plans may run in psql autocommit, where SET LOCAL is ignored.
6
+ set search_path = pg_catalog, pg_temp;
6
7
 
7
8
  -- Use a DO block to handle the case where the role doesn't exist
8
9
  do {{DO_QUOTE}} begin
9
10
  -- Reassign owned objects to current user before dropping
10
11
  -- This handles any objects that might have been created by the role
11
12
  begin
12
- execute format('reassign owned by %I to current_user', {{ROLE_LITERAL}});
13
+ execute pg_catalog.format('reassign owned by %I to current_user', {{ROLE_LITERAL}});
13
14
  exception when undefined_object then
14
15
  null; -- Role doesn't exist, nothing to reassign
15
16
  end;
16
17
 
17
18
  -- Drop owned objects (in case reassign didn't work for some objects)
18
19
  begin
19
- execute format('drop owned by %I', {{ROLE_LITERAL}});
20
+ execute pg_catalog.format('drop owned by %I', {{ROLE_LITERAL}});
20
21
  exception when undefined_object then
21
22
  null; -- Role doesn't exist
22
23
  end;
23
24
 
24
25
  -- Drop the role
25
26
  begin
26
- execute format('drop role %I', {{ROLE_LITERAL}});
27
+ execute pg_catalog.format('drop role %I', {{ROLE_LITERAL}});
27
28
  exception when undefined_object then
28
29
  null; -- Role doesn't exist, that's fine
29
30
  end;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postgresai",
3
- "version": "0.18.0-dev.15",
3
+ "version": "0.18.0-dev.16",
4
4
  "description": "postgres_ai CLI",
5
5
  "license": "Apache-2.0",
6
6
  "private": false,
package/sql/01.role.sql CHANGED
@@ -1,4 +1,6 @@
1
1
  -- Role creation / password update (template-filled by cli/lib/init.ts)
2
+ -- Pin name resolution before the privileged DO block, including for printed SQL.
3
+ set search_path = pg_catalog, pg_temp;
2
4
  --
3
5
  -- A race-safe pattern: create if missing, then alter to set the password.
4
6
  -- `pgai mon deploy` omits the alter, so an existing role keeps its password:
@@ -1,4 +1,5 @@
1
1
  -- Extensions required for postgres_ai monitoring
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  -- Enable pg_stat_statements for query performance monitoring
4
5
  -- Note: Uses IF NOT EXISTS because extension may already be installed.
@@ -1,4 +1,6 @@
1
1
  -- Required permissions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
+ -- The first DO block also runs as the admin; pin before any name resolution.
3
+ set search_path = pg_catalog, pg_temp;
2
4
 
3
5
  -- Allow connect
4
6
  grant connect on database {{DB_IDENT}} to {{ROLE_IDENT}};
@@ -15,6 +17,108 @@ grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
15
17
  -- Create postgres_ai schema for our objects
16
18
  -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times
17
19
  create schema if not exists postgres_ai;
20
+ -- An existing schema keeps its owner, and CREATE OR REPLACE keeps the owner of
21
+ -- existing functions/views. Refuse a schema that another role can still write:
22
+ -- the monitoring role searches postgres_ai and calls our helper from it.
23
+ do {{DO_QUOTE}}
24
+ declare
25
+ schema_oid oid;
26
+ admin_oid oid;
27
+ schema_owner text;
28
+ create_grantee text;
29
+ schema_extension text;
30
+ foreign_object text;
31
+ begin
32
+ set local search_path = pg_catalog, pg_temp;
33
+ select oid into admin_oid from pg_catalog.pg_roles where rolname = current_user;
34
+ select oid into schema_oid from pg_catalog.pg_namespace where nspname = 'postgres_ai';
35
+
36
+ select pg_catalog.pg_get_userbyid(n.nspowner) into schema_owner
37
+ from pg_catalog.pg_namespace n where n.oid = schema_oid;
38
+ if schema_owner <> current_user then
39
+ raise exception 'postgres_ai schema must be owned by the prepare-db administrator'
40
+ using errcode = '42501',
41
+ detail = pg_catalog.format('Schema owner: %s; prepare-db user: %s', schema_owner, current_user),
42
+ hint = 'Have a DBA inspect postgres_ai, then transfer its ownership to the prepare-db user if safe.';
43
+ end if;
44
+
45
+ select case when a.grantee = 0 then 'PUBLIC' else pg_catalog.pg_get_userbyid(a.grantee) end
46
+ into create_grantee
47
+ from pg_catalog.pg_namespace n,
48
+ pg_catalog.aclexplode(coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner))) a
49
+ where n.oid = schema_oid and a.privilege_type = 'CREATE' and a.grantee <> admin_oid
50
+ limit 1;
51
+ if create_grantee is not null then
52
+ raise exception 'postgres_ai schema grants CREATE to another role'
53
+ using errcode = '42501',
54
+ detail = pg_catalog.format('CREATE grantee: %s', create_grantee),
55
+ hint = 'Have a DBA inspect the grant, then revoke CREATE on postgres_ai from that role or PUBLIC if safe.';
56
+ end if;
57
+
58
+ -- Trusted extensions can install bootstrap-owned members without owner
59
+ -- records in pg_shdepend (bootstrap superuser oid 10). Keep extensions out
60
+ -- of the monitoring search path regardless of their extension owner.
61
+ select e.extname into schema_extension
62
+ from pg_catalog.pg_extension e
63
+ where e.extnamespace = schema_oid
64
+ limit 1;
65
+ if schema_extension is not null then
66
+ raise exception 'postgres_ai schema contains an extension'
67
+ using errcode = '42501',
68
+ detail = pg_catalog.format('Extension: %s', schema_extension),
69
+ hint = 'Have a DBA inspect and move or remove this extension if safe before retrying prepare-db.';
70
+ end if;
71
+
72
+ -- Pinned/predefined roles have no pg_shdepend owner rows. Read catalog
73
+ -- owners directly before the dependency scan so those objects cannot hide.
74
+ with owned as (
75
+ select 'pg_class'::pg_catalog.regclass::oid as classid, c.oid as objid, c.relowner as owner_oid
76
+ from pg_catalog.pg_class c where c.relnamespace = schema_oid
77
+ union all select 'pg_proc'::pg_catalog.regclass::oid, p.oid, p.proowner
78
+ from pg_catalog.pg_proc p where p.pronamespace = schema_oid
79
+ union all select 'pg_type'::pg_catalog.regclass::oid, t.oid, t.typowner
80
+ from pg_catalog.pg_type t where t.typnamespace = schema_oid
81
+ union all select 'pg_operator'::pg_catalog.regclass::oid, o.oid, o.oprowner
82
+ from pg_catalog.pg_operator o where o.oprnamespace = schema_oid
83
+ union all select 'pg_opclass'::pg_catalog.regclass::oid, o.oid, o.opcowner
84
+ from pg_catalog.pg_opclass o where o.opcnamespace = schema_oid
85
+ union all select 'pg_opfamily'::pg_catalog.regclass::oid, o.oid, o.opfowner
86
+ from pg_catalog.pg_opfamily o where o.opfnamespace = schema_oid
87
+ union all select 'pg_collation'::pg_catalog.regclass::oid, c.oid, c.collowner
88
+ from pg_catalog.pg_collation c where c.collnamespace = schema_oid
89
+ union all select 'pg_conversion'::pg_catalog.regclass::oid, c.oid, c.conowner
90
+ from pg_catalog.pg_conversion c where c.connamespace = schema_oid
91
+ union all select 'pg_ts_dict'::pg_catalog.regclass::oid, d.oid, d.dictowner
92
+ from pg_catalog.pg_ts_dict d where d.dictnamespace = schema_oid
93
+ union all select 'pg_ts_config'::pg_catalog.regclass::oid, c.oid, c.cfgowner
94
+ from pg_catalog.pg_ts_config c where c.cfgnamespace = schema_oid
95
+ union all select 'pg_statistic_ext'::pg_catalog.regclass::oid, s.oid, s.stxowner
96
+ from pg_catalog.pg_statistic_ext s where s.stxnamespace = schema_oid
97
+ )
98
+ select pg_catalog.format('%s %s (owner %s)', o.type, o.identity,
99
+ pg_catalog.pg_get_userbyid(owned.owner_oid)) into foreign_object
100
+ from owned
101
+ cross join lateral pg_catalog.pg_identify_object(owned.classid, owned.objid, 0) o
102
+ where owned.owner_oid <> admin_oid
103
+ limit 1;
104
+
105
+ -- Retain a dependency scan for object kinds not represented above.
106
+ if foreign_object is null then
107
+ select o.identity into foreign_object
108
+ from pg_catalog.pg_shdepend s
109
+ cross join lateral pg_catalog.pg_identify_object(s.classid, s.objid, s.objsubid) o
110
+ where s.dbid = (select oid from pg_catalog.pg_database where datname = pg_catalog.current_database())
111
+ and s.deptype = 'o' and s.refobjid <> admin_oid
112
+ and o.schema = 'postgres_ai'
113
+ limit 1;
114
+ end if;
115
+ if foreign_object is not null then
116
+ raise exception 'postgres_ai schema contains objects owned by another role'
117
+ using errcode = '42501',
118
+ detail = pg_catalog.format('Foreign-owned object: %s', foreign_object),
119
+ hint = 'Have a DBA inspect this object, then reassign or remove it if safe before retrying prepare-db.';
120
+ end if;
121
+ end {{DO_QUOTE}};
18
122
  grant usage on schema postgres_ai to {{ROLE_IDENT}};
19
123
 
20
124
  -- For bloat analysis: expose pg_statistic via a view
@@ -45,13 +149,13 @@ declare
45
149
  ext_schema text;
46
150
  begin
47
151
  select n.nspname into ext_schema
48
- from pg_extension e
49
- join pg_namespace n on e.extnamespace = n.oid
152
+ from pg_catalog.pg_extension e
153
+ join pg_catalog.pg_namespace n on e.extnamespace = n.oid
50
154
  where e.extname = 'pg_stat_statements';
51
155
 
52
156
  -- Only grant if extension exists and is in a non-standard schema
53
157
  if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
54
- execute format('grant usage on schema %I to %I', ext_schema, {{ROLE_LITERAL}});
158
+ execute pg_catalog.format('grant usage on schema %I to %I', ext_schema, {{ROLE_LITERAL}});
55
159
  end if;
56
160
  end {{DO_QUOTE}};
57
161
 
@@ -72,12 +176,12 @@ begin
72
176
  set local search_path = pg_catalog, pg_temp;
73
177
  -- Detect pg_stat_statements extension schema
74
178
  select n.nspname into ext_schema
75
- from pg_extension e
76
- join pg_namespace n on e.extnamespace = n.oid
179
+ from pg_catalog.pg_extension e
180
+ join pg_catalog.pg_namespace n on e.extnamespace = n.oid
77
181
  where e.extname = 'pg_stat_statements';
78
182
 
79
183
  if ext_schema is not null and ext_schema not in ('pg_catalog', 'public') then
80
- db_path := 'pg_catalog, postgres_ai, ' || quote_ident(ext_schema) || ', public, pg_temp';
184
+ db_path := 'pg_catalog, postgres_ai, ' || pg_catalog.quote_ident(ext_schema) || ', public, pg_temp';
81
185
  end if;
82
186
 
83
187
  -- Role-wide value: for databases that prepare-db did not run in. All databases share
@@ -88,9 +192,9 @@ begin
88
192
  and setdatabase = 0
89
193
  and ('search_path=' || role_path) = any (setconfig)
90
194
  ) then
91
- execute format('alter user %I set search_path = %s', {{ROLE_LITERAL}}, role_path);
195
+ execute pg_catalog.format('alter user %I set search_path = %s', {{ROLE_LITERAL}}, role_path);
92
196
  end if;
93
197
  -- This database's value: other databases keep their own pg_stat_statements schema.
94
- execute format('alter user %I in database %I set search_path = %s', {{ROLE_LITERAL}}, pg_catalog.current_database(), db_path);
198
+ execute pg_catalog.format('alter user %I in database %I set search_path = %s', {{ROLE_LITERAL}}, pg_catalog.current_database(), db_path);
95
199
  end {{DO_QUOTE}};
96
200
  -- [SEARCH_PATH_BLOCK_END]
@@ -1,4 +1,5 @@
1
1
  -- Optional permissions for RDS Postgres / Aurora (best effort)
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  create schema if not exists rds_tools;
4
5
  create extension if not exists rds_tools with schema rds_tools;
@@ -1,4 +1,5 @@
1
1
  -- Optional permissions for self-managed Postgres (best effort)
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  grant execute on function pg_catalog.pg_stat_file(text) to {{ROLE_IDENT}};
4
5
  grant execute on function pg_catalog.pg_stat_file(text, boolean) to {{ROLE_IDENT}};
@@ -1,4 +1,5 @@
1
1
  -- Helper functions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
+ set search_path = pg_catalog, pg_temp;
2
3
 
3
4
  -- Remove the retired helper from databases prepared by older CLI versions.
4
5
  -- Only its owner or a superuser can drop it: anyone else gets a warning here. Releases
@@ -2,7 +2,9 @@
2
2
  -- Run before dropping the postgres_ai schema.
3
3
 
4
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;
5
+ -- Use a session SET because --print-sql plans may be run by psql in autocommit.
6
+ -- SET LOCAL outside an explicit transaction is ignored there.
7
+ set search_path = pg_catalog, pg_temp;
6
8
 
7
9
  drop function if exists postgres_ai.explain_generic(text, text, text);
8
10
  drop function if exists postgres_ai.table_describe(text);
@@ -1,9 +1,10 @@
1
1
  -- Revoke permissions and drop objects created by prepare-db (template-filled by cli/lib/init.ts)
2
2
 
3
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;
4
+ -- Printed plans may run in psql autocommit, where SET LOCAL is ignored.
5
+ set search_path = pg_catalog, pg_temp;
5
6
  -- The CLI reads the "unprepare-db:" WARNINGs. A higher setting would hide them.
6
- set local client_min_messages = warning;
7
+ set client_min_messages = warning;
7
8
 
8
9
  -- Drop the postgres_ai.pg_statistic view
9
10
  drop view if exists postgres_ai.pg_statistic;
@@ -57,6 +58,17 @@ begin
57
58
  select from pg_catalog.aclexplode(n.nspacl) a
58
59
  where a.grantee = role_oid and a.privilege_type = 'USAGE')
59
60
  union
61
+ -- prepare-db grants USAGE when pg_stat_statements lives in a custom
62
+ -- extension schema. Retaining the login role must remove that grant too.
63
+ select pg_catalog.format('revoke usage on schema %I from %I', n.nspname, {{ROLE_LITERAL}})
64
+ from pg_catalog.pg_extension e
65
+ join pg_catalog.pg_namespace n on n.oid = e.extnamespace
66
+ where e.extname = 'pg_stat_statements'
67
+ and n.nspname not in ('pg_catalog', 'public')
68
+ and exists (
69
+ select from pg_catalog.aclexplode(n.nspacl) a
70
+ where a.grantee = role_oid and a.privilege_type = 'USAGE')
71
+ union
60
72
  select pg_catalog.format('revoke execute on function %s from %I', p.oid::regprocedure, {{ROLE_LITERAL}})
61
73
  from pg_catalog.pg_proc p
62
74
  where p.oid in (
@@ -2,28 +2,29 @@
2
2
  -- This must run after revoking all permissions from the role.
3
3
 
4
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;
5
+ -- Printed plans may run in psql autocommit, where SET LOCAL is ignored.
6
+ set search_path = pg_catalog, pg_temp;
6
7
 
7
8
  -- Use a DO block to handle the case where the role doesn't exist
8
9
  do {{DO_QUOTE}} begin
9
10
  -- Reassign owned objects to current user before dropping
10
11
  -- This handles any objects that might have been created by the role
11
12
  begin
12
- execute format('reassign owned by %I to current_user', {{ROLE_LITERAL}});
13
+ execute pg_catalog.format('reassign owned by %I to current_user', {{ROLE_LITERAL}});
13
14
  exception when undefined_object then
14
15
  null; -- Role doesn't exist, nothing to reassign
15
16
  end;
16
17
 
17
18
  -- Drop owned objects (in case reassign didn't work for some objects)
18
19
  begin
19
- execute format('drop owned by %I', {{ROLE_LITERAL}});
20
+ execute pg_catalog.format('drop owned by %I', {{ROLE_LITERAL}});
20
21
  exception when undefined_object then
21
22
  null; -- Role doesn't exist
22
23
  end;
23
24
 
24
25
  -- Drop the role
25
26
  begin
26
- execute format('drop role %I', {{ROLE_LITERAL}});
27
+ execute pg_catalog.format('drop role %I', {{ROLE_LITERAL}});
27
28
  exception when undefined_object then
28
29
  null; -- Role doesn't exist, that's fine
29
30
  end;