postgresai 0.18.0-beta.1 → 0.18.0-beta.3

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-beta.1",
13536
+ version: "0.18.0-beta.3",
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-beta.1";
16896
+ var version = "0.18.0-beta.3";
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 {
@@ -35728,13 +35758,13 @@ function registerDblabAccessCommands(dblab, deps) {
35728
35758
  var MONITORING_STEPS = [
35729
35759
  { key: "preparing", label: "Prepare the database" },
35730
35760
  { key: "provisioning", label: "Create the monitoring box" },
35731
- { key: "box", label: "Install monitoring (about 5 min)" },
35761
+ { key: "box", label: "Install monitoring (1-5 min)" },
35732
35762
  { key: "ready", label: "Ready" }
35733
35763
  ];
35734
35764
  var SUPABASE_STEPS = [
35735
35765
  { key: "preparing", label: "Connect Supabase" },
35736
35766
  { key: "provisioning", label: "Create the monitoring box" },
35737
- { key: "box", label: "Prepare the database and install monitoring (about 5 min)" },
35767
+ { key: "box", label: "Prepare the database and install monitoring (1-5 min)" },
35738
35768
  { key: "ready", label: "Ready" }
35739
35769
  ];
35740
35770
  var monitoringSteps = (provider) => provider === "supabase" ? SUPABASE_STEPS : MONITORING_STEPS;
@@ -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);
@@ -45200,6 +45266,7 @@ var LOCAL_INSTALL_MANAGED_ENV_KEYS = [
45200
45266
  var INSTANCE_JOBS_PROFILE = "instance-jobs";
45201
45267
  var DEMO_PROFILE = "demo";
45202
45268
  var PRESTARTED_MARKER = ".prestarted";
45269
+ var PRESTARTED_DONE_MARKER = ".prestarted.done";
45203
45270
  var PRESTART_SERVICES = [
45204
45271
  "sink-postgres",
45205
45272
  "sink-prometheus",
@@ -45224,9 +45291,12 @@ function composeProfilesValue(existing, want, profile = INSTANCE_JOBS_PROFILE) {
45224
45291
  profiles.splice(at, 1);
45225
45292
  return profiles.length > 0 ? profiles.join(",") : null;
45226
45293
  }
45227
- function instanceJobsProfileEnabled(composeProfiles, profile = INSTANCE_JOBS_PROFILE) {
45294
+ function profileEnabled(composeProfiles, profile) {
45228
45295
  return (composeProfiles ?? "").split(",").map((p) => p.trim()).includes(profile);
45229
45296
  }
45297
+ function instanceJobsProfileEnabled(composeProfiles, profile = INSTANCE_JOBS_PROFILE) {
45298
+ return profileEnabled(composeProfiles, profile);
45299
+ }
45230
45300
  function resolveInstanceJobsRequest(flag, envValue) {
45231
45301
  if (flag !== undefined)
45232
45302
  return { enabled: flag };
@@ -46002,7 +46072,6 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46002
46072
  conn = process.env.PGAI_DB_URL || undefined;
46003
46073
  }
46004
46074
  const shouldPrintSql = !!opts.printSql;
46005
- const redactPasswords = (sql) => redactPasswordsInSql2(sql);
46006
46075
  const { provider, detected } = resolveProvider(opts.provider, conn ?? opts.dbUrl ?? opts.host ?? process.env.PGHOST);
46007
46076
  const note = opts.json ? console.error : console.log;
46008
46077
  if (detected)
@@ -46034,11 +46103,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46034
46103
  console.log(`-- monitoring user: ${opts.monitoringUser}`);
46035
46104
  console.log(`-- provider: ${provider}`);
46036
46105
  console.log(`-- optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
46037
- for (const step of plan.steps) {
46038
- console.log(`
46039
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
46040
- console.log(redactPasswords(step.sql));
46041
- }
46106
+ console.log(renderInitPlanSql2(plan));
46042
46107
  console.log(`
46043
46108
  --- end SQL plan ---
46044
46109
  `);
@@ -46200,11 +46265,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46200
46265
  if (shouldPrintSql) {
46201
46266
  console.log(`
46202
46267
  --- SQL plan ---`);
46203
- for (const step of effectivePlan.steps) {
46204
- console.log(`
46205
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
46206
- console.log(redactPasswords(step.sql));
46207
- }
46268
+ console.log(renderInitPlanSql2(effectivePlan));
46208
46269
  console.log(`
46209
46270
  --- end SQL plan ---
46210
46271
  `);
@@ -46492,11 +46553,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46492
46553
  if (shouldPrintSql) {
46493
46554
  console.log(`
46494
46555
  --- SQL plan ---`);
46495
- for (const step of effectivePlan.steps) {
46496
- console.log(`
46497
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
46498
- console.log(redactPasswords(step.sql));
46499
- }
46556
+ console.log(renderInitPlanSql2(effectivePlan));
46500
46557
  console.log(`
46501
46558
  --- end SQL plan ---
46502
46559
  `);
@@ -46688,11 +46745,14 @@ program2.command("unprepare-db [conn]").description("remove monitoring setup: dr
46688
46745
  console.log(`-- monitoring user: ${opts.monitoringUser}`);
46689
46746
  console.log(`-- provider: ${provider}`);
46690
46747
  console.log(`-- drop role: ${dropRole}`);
46748
+ console.log("-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.");
46749
+ console.log("begin;");
46691
46750
  for (const step of plan.steps) {
46692
46751
  console.log(`
46693
46752
  -- ${step.name}`);
46694
46753
  console.log(step.sql);
46695
46754
  }
46755
+ console.log("commit;");
46696
46756
  console.log(`
46697
46757
  --- end SQL plan ---
46698
46758
  `);
@@ -46758,11 +46818,14 @@ program2.command("unprepare-db [conn]").description("remove monitoring setup: dr
46758
46818
  if (shouldPrintSql) {
46759
46819
  console.log(`
46760
46820
  --- SQL plan ---`);
46821
+ console.log("-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.");
46822
+ console.log("begin;");
46761
46823
  for (const step of plan.steps) {
46762
46824
  console.log(`
46763
46825
  -- ${step.name}`);
46764
46826
  console.log(step.sql);
46765
46827
  }
46828
+ console.log("commit;");
46766
46829
  console.log(`
46767
46830
  --- end SQL plan ---
46768
46831
  `);
@@ -47690,30 +47753,38 @@ function instancesUseDemoTarget(instancesPath) {
47690
47753
  try {
47691
47754
  if (!fs10.statSync(instancesPath).isFile())
47692
47755
  return false;
47693
- return /@target-db[:/]/.test(fs10.readFileSync(instancesPath, "utf8"));
47756
+ return loadInstances2(instancesPath).some((instance) => {
47757
+ try {
47758
+ return new URL(String(instance.conn_str ?? "")).hostname === "target-db";
47759
+ } catch {
47760
+ return false;
47761
+ }
47762
+ });
47694
47763
  } catch {
47695
47764
  return false;
47696
47765
  }
47697
47766
  }
47698
- function removeDemoContainers() {
47699
- for (const service of ["target-standby", "target-db"]) {
47700
- const ps = spawnSync3("docker", ["ps", "-aq", "--filter", `name=^${service}$`, "--filter", `label=com.docker.compose.service=${service}`], { stdio: "pipe", encoding: "utf8", timeout: 1e4 });
47701
- if (ps.status !== 0 || !String(ps.stdout).trim())
47702
- continue;
47703
- console.log(`Removing the ${service} container: the demo database is not part of this install (its volume is kept)`);
47704
- spawnSync3("docker", ["rm", "-f", service], { stdio: "ignore", timeout: 30000 });
47705
- }
47767
+ async function removeDemoContainers(projectDir) {
47768
+ const cmd = getComposeCmd();
47769
+ if (!cmd)
47770
+ return;
47771
+ const ps = spawnSync3(cmd[0], [...cmd.slice(1), "-f", path8.resolve(projectDir, "docker-compose.yml"), "ps", "-a", "--format", "{{.Service}}"], { cwd: projectDir, env: { ...process.env, COMPOSE_PROFILES: DEMO_PROFILE }, stdio: "pipe", encoding: "utf8", timeout: 15000 });
47772
+ const present = String(ps.stdout ?? "").split(/\s+/).filter((s) => s === "target-db" || s === "target-standby");
47773
+ if (ps.status !== 0 || present.length === 0)
47774
+ return;
47775
+ console.log(`Removing the demo database (containers ${present.join(", ")}): this install monitors your own database. Its data volumes are kept.`);
47776
+ await runCompose(["rm", "-f", "-s", ...present], undefined, { COMPOSE_PROFILES: DEMO_PROFILE });
47706
47777
  }
47707
- function syncDemoProfile(projectDir, instancesPath) {
47778
+ async function syncDemoProfile(projectDir, instancesPath) {
47708
47779
  const current = readEnvValue(projectDir, "COMPOSE_PROFILES") ?? null;
47709
- if (instanceJobsProfileEnabled(current, DEMO_PROFILE))
47780
+ if (profileEnabled(current, DEMO_PROFILE))
47710
47781
  return;
47711
47782
  if (instancesUseDemoTarget(instancesPath)) {
47712
47783
  setEnvValues(projectDir, { COMPOSE_PROFILES: composeProfilesValue(current, true, DEMO_PROFILE) });
47713
- console.log(`Enabled the '${DEMO_PROFILE}' compose profile: instances.yml monitors the demo database`);
47784
+ console.log(`Kept the demo database running: instances.yml monitors it (added '${DEMO_PROFILE}' to COMPOSE_PROFILES in .env)`);
47714
47785
  return;
47715
47786
  }
47716
- removeDemoContainers();
47787
+ await removeDemoContainers(projectDir);
47717
47788
  }
47718
47789
  async function ensureGrafanaPassword(cfgPath) {
47719
47790
  let grafanaPassword = "";
@@ -47761,16 +47832,29 @@ async function ensureGrafanaPassword(cfgPath) {
47761
47832
  }
47762
47833
  return grafanaPassword;
47763
47834
  }
47835
+ function prestartRefusal(projectDir) {
47836
+ for (const marker of [PRESTARTED_MARKER, PRESTARTED_DONE_MARKER]) {
47837
+ if (fs10.existsSync(path8.join(projectDir, marker))) {
47838
+ return "This stack was already started with --prestart";
47839
+ }
47840
+ }
47841
+ const { containers } = checkRunningContainers();
47842
+ const pgwatch = containers.filter((c) => c.startsWith("pgwatch"));
47843
+ if (pgwatch.length > 0) {
47844
+ return `A configured monitoring stack is already running (${pgwatch.join(", ")}); --prestart is only for a fresh box`;
47845
+ }
47846
+ return null;
47847
+ }
47848
+ function runningComposeServices(projectDir) {
47849
+ const cmd = getComposeCmd();
47850
+ if (!cmd)
47851
+ return [];
47852
+ const ps = spawnSync3(cmd[0], [...cmd.slice(1), "-f", path8.resolve(projectDir, "docker-compose.yml"), "ps", "--status", "running", "--services"], { cwd: projectDir, stdio: "pipe", encoding: "utf8", timeout: 15000 });
47853
+ return ps.status === 0 ? String(ps.stdout ?? "").split(/\s+/).filter(Boolean) : [];
47854
+ }
47764
47855
  async function runPrestart(projectDir, instancesPath, imageTag) {
47765
47856
  console.log(`Prestart: starting the monitoring infrastructure without a target
47766
47857
  `);
47767
- const { running, containers } = checkRunningContainers();
47768
- if (running) {
47769
- console.error(`\u2717 Monitoring services are already running: ${containers.join(", ")}`);
47770
- console.error(" --prestart is for a stack that has never started; nothing was changed");
47771
- process.exitCode = 1;
47772
- return;
47773
- }
47774
47858
  if (!fs10.existsSync(instancesPath)) {
47775
47859
  fs10.writeFileSync(instancesPath, `# PostgreSQL instances to monitor
47776
47860
  # Add your instances using: postgres-ai mon targets add
@@ -47808,7 +47892,7 @@ async function runPrestart(projectDir, instancesPath, imageTag) {
47808
47892
  encoding: "utf8",
47809
47893
  mode: 384
47810
47894
  });
47811
- console.log(`\u2713 Monitoring infrastructure started; finish with: postgresai mon local-install --continue-prestarted --db-url <url> --api-key <key>
47895
+ console.log(`\u2713 Monitoring infrastructure started; finish with 'postgresai mon local-install --continue-prestarted --db-url <url> --api-key <key>'
47812
47896
  `);
47813
47897
  }
47814
47898
  async function reloadHostMetricsFiles(projectDir) {
@@ -47821,7 +47905,7 @@ async function reloadHostMetricsFiles(projectDir) {
47821
47905
  if (files.length === 0)
47822
47906
  return;
47823
47907
  if (await runCompose(["kill", "-s", "SIGHUP", "sink-prometheus"]) !== 0) {
47824
- console.error("\u26A0 Could not reload sink-prometheus; host metrics start with its next restart ('postgresai mon restart')");
47908
+ console.error("\u26A0 Could not reload the metrics store; host metrics start after 'postgresai mon restart'");
47825
47909
  }
47826
47910
  }
47827
47911
  async function applyInstanceJobsProfile(projectDir, enabled) {
@@ -48384,7 +48468,7 @@ mon.command("local-install").description("install local monitoring stack (genera
48384
48468
  " PGAI_ENABLE_IPV6=false (accepted: true|false|yes|no, lowercase)",
48385
48469
  ""
48386
48470
  ].join(`
48387
- `)).option("--demo", "demo mode with sample database", false).option("--api-key <key>", "Postgres AI API key for automated report uploads").option("--org <alias>", `organization alias (or ${ORG_ENV}); required to register with a global token`).option("--org-id <id>", `organization id (or ${ORG_ID_ENV}); alternative to --org`).option("--db-url <url>", "PostgreSQL connection URL to monitor (or PGAI_DB_URL)").option("--tag <tag>", "Docker image tag to use (e.g., 0.14.0, 0.14.0-dev.33)").option("--project <name>", "Docker Compose project name (default: postgres_ai)").option("--instance-id <uuid>", "adopt a console-provisioned monitoring instance instead of self-registering a new one (set automatically by the provisioning flow; PGAI_INSTANCE_ID env also works)").option("--vcpus <n>", "source DB vCPU count used for AAS zone thresholds (PGAI_VCPUS env also works). Omit or 0 = unknown: the platform keeps the value it stamped at provision time. An explicit non-zero value overwrites the stored one; changing it re-arms the AAS backfill.").option("--instance-jobs", "enable the instance-jobs compose profile (outbound collection channel; PGAI_INSTANCE_JOBS env also works). Writes COMPOSE_PROFILES into the stack .env, so every later mon command covers the container").option("--no-instance-jobs", "disable the instance-jobs compose profile and remove its container").option("--prestart", "pre-baked images, at first boot: start storage, Grafana and self-monitoring with fresh secrets, ports on 127.0.0.1, no target, no API calls", false).option("--continue-prestarted", "finish an install on a stack started by --prestart: add the target, key and registration, and recreate only what changed", false).option("-y, --yes", "accept all defaults and skip interactive prompts", false).action(async (opts) => {
48471
+ `)).option("--demo", "demo mode with sample database", false).option("--api-key <key>", "Postgres AI API key for automated report uploads").option("--org <alias>", `organization alias (or ${ORG_ENV}); required to register with a global token`).option("--org-id <id>", `organization id (or ${ORG_ID_ENV}); alternative to --org`).option("--db-url <url>", "PostgreSQL connection URL to monitor (or PGAI_DB_URL)").option("--tag <tag>", "Docker image tag to use (e.g., 0.14.0, 0.14.0-dev.33)").option("--project <name>", "Docker Compose project name (default: postgres_ai)").option("--instance-id <uuid>", "adopt a console-provisioned monitoring instance instead of self-registering a new one (set automatically by the provisioning flow; PGAI_INSTANCE_ID env also works)").option("--vcpus <n>", "source DB vCPU count used for AAS zone thresholds (PGAI_VCPUS env also works). Omit or 0 = unknown: the platform keeps the value it stamped at provision time. An explicit non-zero value overwrites the stored one; changing it re-arms the AAS backfill.").option("--instance-jobs", "enable the instance-jobs compose profile (outbound collection channel; PGAI_INSTANCE_JOBS env also works). Writes COMPOSE_PROFILES into the stack .env, so every later mon command covers the container").option("--no-instance-jobs", "disable the instance-jobs compose profile and remove its container").addOption(new Option2("--prestart", "managed images, at first boot: start storage, Grafana and self-monitoring with fresh secrets, ports on 127.0.0.1, no target, no API calls").default(false).hideHelp()).addOption(new Option2("--continue-prestarted", "managed images: finish an install on a stack started by --prestart, recreating only what changed").default(false).hideHelp()).option("-y, --yes", "accept all defaults and skip interactive prompts", false).action(async (opts) => {
48388
48472
  const globalOpts = program2.opts();
48389
48473
  let apiKey = opts.apiKey || globalOpts.apiKey || (process.env.PGAI_DB_URL ? process.env.PGAI_API_KEY : undefined);
48390
48474
  opts.dbUrl ??= process.env.PGAI_DB_URL;
@@ -48398,6 +48482,20 @@ mon.command("local-install").description("install local monitoring stack (genera
48398
48482
  const { projectDir, instancesFile: instancesPath } = await resolveOrInitPaths();
48399
48483
  console.log(`Project directory: ${projectDir}
48400
48484
  `);
48485
+ if (opts.prestart) {
48486
+ const identity = opts.instanceId || process.env.PGAI_INSTANCE_ID || opts.instanceJobs !== undefined || (process.env.PGAI_INSTANCE_JOBS ?? "").trim() !== "" || opts.project;
48487
+ if (opts.demo || opts.dbUrl || apiKey || opts.continuePrestarted || identity) {
48488
+ console.error("\u2717 --prestart starts the stack without a target or an identity: it cannot be combined with --demo, --db-url, --api-key, --instance-id, --project, --instance-jobs or --continue-prestarted (or PGAI_INSTANCE_ID / PGAI_INSTANCE_JOBS)");
48489
+ process.exitCode = 1;
48490
+ return;
48491
+ }
48492
+ const refusal = prestartRefusal(projectDir);
48493
+ if (refusal) {
48494
+ console.error(`\u2717 ${refusal}. Nothing was changed.`);
48495
+ process.exitCode = 1;
48496
+ return;
48497
+ }
48498
+ }
48401
48499
  if (opts.project && !applyProjectName(projectDir, opts.project)) {
48402
48500
  process.exitCode = 1;
48403
48501
  return;
@@ -48414,12 +48512,7 @@ mon.command("local-install").description("install local monitoring stack (genera
48414
48512
  return;
48415
48513
  }
48416
48514
  const instanceJobs = instanceJobsRequest.enabled;
48417
- if (opts.prestart && (opts.demo || opts.dbUrl || apiKey || opts.continuePrestarted || opts.instanceId)) {
48418
- console.error("\u2717 --prestart starts the stack without a target: it cannot be combined with --demo, --db-url, --api-key, --instance-id or --continue-prestarted");
48419
- process.exitCode = 1;
48420
- return;
48421
- }
48422
- const { content: envContent, preservedKeys } = buildLocalInstallEnv(existingEnv, imageTag, opts.instanceId || process.env.PGAI_INSTANCE_ID || null, path8.resolve(projectDir, ".pgwatch-config"), instanceJobs, opts.demo);
48515
+ const { content: envContent, preservedKeys } = buildLocalInstallEnv(existingEnv, imageTag, opts.instanceId || process.env.PGAI_INSTANCE_ID || null, path8.resolve(projectDir, ".pgwatch-config"), instanceJobs, opts.demo ? true : undefined);
48423
48516
  writeEnvFile(envFile, envContent);
48424
48517
  if (preservedKeys.length > 0) {
48425
48518
  console.log(`Preserved existing .env settings: ${preservedKeys.join(", ")}
@@ -48451,7 +48544,7 @@ Use demo mode without API key: postgres-ai mon local-install --demo`);
48451
48544
  }
48452
48545
  const onPrestarted = opts.continuePrestarted && fs10.existsSync(path8.join(projectDir, PRESTARTED_MARKER));
48453
48546
  if (opts.continuePrestarted && !onPrestarted) {
48454
- console.log(`(no ${PRESTARTED_MARKER} marker in ${projectDir}: installing as usual)
48547
+ console.log(`(this stack was not started with --prestart: installing as usual)
48455
48548
  `);
48456
48549
  }
48457
48550
  const { running, containers } = checkRunningContainers();
@@ -48684,23 +48777,26 @@ Searched: ${demoCandidates.join(", ")}
48684
48777
  console.warn(` ${error instanceof Error ? error.message : String(error)}`);
48685
48778
  }
48686
48779
  }
48687
- if (!opts.demo)
48688
- removeDemoContainers();
48780
+ if (!opts.demo) {
48781
+ const profiles = readEnvValue(projectDir, "COMPOSE_PROFILES") ?? null;
48782
+ if (profileEnabled(profiles, DEMO_PROFILE)) {
48783
+ setEnvValues(projectDir, { COMPOSE_PROFILES: composeProfilesValue(profiles, false, DEMO_PROFILE) });
48784
+ }
48785
+ await removeDemoContainers(projectDir);
48786
+ }
48689
48787
  await runCompose(["rm", "-f", "-s", "config-init"]);
48690
48788
  let code2;
48691
48789
  if (onPrestarted) {
48692
48790
  console.log("Step 5: Applying the configuration to the prestarted stack...");
48693
- const readersRunning = [];
48694
- for (const service of TARGET_READER_SERVICES) {
48695
- if (await composeServiceRunning(projectDir, service))
48696
- readersRunning.push(service);
48697
- }
48698
- code2 = await runCompose(["up", "-d"], grafanaPassword);
48699
- if (code2 === 0 && readersRunning.length > 0) {
48700
- code2 = await runCompose(["up", "-d", "--force-recreate", "--no-deps", ...readersRunning], grafanaPassword);
48701
- }
48791
+ const readersRunning = runningComposeServices(projectDir).filter((s) => TARGET_READER_SERVICES.includes(s));
48792
+ code2 = readersRunning.length > 0 ? await runCompose(["up", "-d", "--force-recreate", "--no-deps", ...readersRunning], grafanaPassword) : 0;
48793
+ if (code2 === 0)
48794
+ code2 = await runCompose(["up", "-d"], grafanaPassword);
48702
48795
  if (code2 === 0)
48703
48796
  await reloadHostMetricsFiles(projectDir);
48797
+ if (code2 === 0) {
48798
+ fs10.renameSync(path8.join(projectDir, PRESTARTED_MARKER), path8.join(projectDir, PRESTARTED_DONE_MARKER));
48799
+ }
48704
48800
  } else {
48705
48801
  console.log("Step 5: Starting monitoring services...");
48706
48802
  code2 = await runCompose(["up", "-d", "--force-recreate"], grafanaPassword);
@@ -48825,7 +48921,7 @@ mon.command("start").description("start monitoring services").action(async () =>
48825
48921
  return;
48826
48922
  }
48827
48923
  const { projectDir, instancesFile } = await resolveOrInitPaths();
48828
- syncDemoProfile(projectDir, instancesFile);
48924
+ await syncDemoProfile(projectDir, instancesFile);
48829
48925
  const code = await runCompose(["up", "-d"]);
48830
48926
  if (code !== 0)
48831
48927
  process.exitCode = code;
@@ -48918,7 +49014,7 @@ function monitoringHealthServices(instanceJobsEnabled = false, demoEnabled = fal
48918
49014
  { name: "Prometheus", container: "sink-prometheus" },
48919
49015
  { name: "PGWatch (Postgres)", container: "pgwatch-postgres" },
48920
49016
  { name: "PGWatch (Prometheus)", container: "pgwatch-prometheus" },
48921
- { name: "Target DB", container: "target-db", ...demoEnabled ? {} : { optional: true } },
49017
+ { name: "Demo DB", container: "target-db", ...demoEnabled ? {} : { optional: true } },
48922
49018
  { name: "Sink Postgres", container: "sink-postgres" },
48923
49019
  {
48924
49020
  name: "Instance jobs",
@@ -48931,7 +49027,7 @@ function monitoringHealthServices(instanceJobsEnabled = false, demoEnabled = fal
48931
49027
  }
48932
49028
  mon.command("health").description("health check for monitoring services").option("--wait <seconds>", "wait time in seconds for services to become healthy", parseInt, 0).action(async (opts) => {
48933
49029
  const profiles = readComposeProfiles();
48934
- const services = monitoringHealthServices(instanceJobsProfileEnabled(profiles), instanceJobsProfileEnabled(profiles, DEMO_PROFILE));
49030
+ const services = monitoringHealthServices(instanceJobsProfileEnabled(profiles), profileEnabled(profiles, DEMO_PROFILE));
48935
49031
  const waitTime = opts.wait || 0;
48936
49032
  const maxAttempts = waitTime > 0 ? Math.ceil(waitTime / 5) : 1;
48937
49033
  console.log(`Checking service health...
@@ -49035,7 +49131,7 @@ mon.command("update").description("update monitoring stack (migrate .env, pull i
49035
49131
  process.exitCode = 1;
49036
49132
  return;
49037
49133
  }
49038
- syncDemoProfile(projectDir, instancesFile);
49134
+ await syncDemoProfile(projectDir, instancesFile);
49039
49135
  console.log("Checking .env for newly-required keys...");
49040
49136
  const added = ensureRequiredEnvVars(projectDir);
49041
49137
  if (added.length > 0) {
@@ -51513,6 +51609,7 @@ export {
51513
51609
  monitoringHealthServices,
51514
51610
  persistInstanceId,
51515
51611
  planMonitoringRegistration,
51612
+ profileEnabled,
51516
51613
  program2 as program,
51517
51614
  readComposeProfiles,
51518
51615
  readDeployedTag,
@@ -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}};
@@ -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;
@@ -2,7 +2,8 @@
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postgresai",
3
- "version": "0.18.0-beta.1",
3
+ "version": "0.18.0-beta.3",
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}};
@@ -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;
@@ -2,7 +2,8 @@
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