@akal/supaforge 0.0.34 → 0.0.36

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.
Files changed (54) hide show
  1. package/README.md +32 -13
  2. package/dist/base-command.d.ts +1 -1
  3. package/dist/base-command.js +4 -4
  4. package/dist/{branch-C4ndfoj5.d.ts → branch-BppjQBv_.d.ts} +1 -1
  5. package/dist/{chunk-ICSCHS72.js → chunk-5UHIWFQG.js} +76 -186
  6. package/dist/{chunk-S5L4A3UR.js → chunk-AL6INEFX.js} +3 -3
  7. package/dist/{chunk-OB5GP7UB.js → chunk-CAQ3QQFP.js} +437 -45
  8. package/dist/{chunk-TPX2MAO4.js → chunk-CCB7ARZU.js} +54 -5
  9. package/dist/{chunk-V2SBZERO.js → chunk-EWNZIRCD.js} +4 -4
  10. package/dist/{chunk-EFKQOQGG.js → chunk-FD2JKEJA.js} +7 -5
  11. package/dist/{chunk-3WKWPSFN.js → chunk-GGZ7YWBZ.js} +191 -32
  12. package/dist/{chunk-F46FFUKC.js → chunk-JX5L253P.js} +56 -18
  13. package/dist/{chunk-GQPGH6YR.js → chunk-KHXEES2M.js} +2 -2
  14. package/dist/{chunk-MG3SFV5J.js → chunk-KT7NMELZ.js} +77 -7
  15. package/dist/{chunk-PYAGSMFB.js → chunk-M2564IGT.js} +159 -19
  16. package/dist/{chunk-7DL63NWP.js → chunk-MRXIE55Y.js} +7 -3
  17. package/dist/{chunk-6ERVCWLY.js → chunk-MZPWRWBL.js} +7 -7
  18. package/dist/{chunk-5STH2A6K.js → chunk-OXS42LJH.js} +4 -4
  19. package/dist/{chunk-HNJ6BNNZ.js → chunk-Q43MN6NE.js} +2 -2
  20. package/dist/{chunk-ZI435CAU.js → chunk-RQCXGO37.js} +2 -2
  21. package/dist/{chunk-KNXHLVF7.js → chunk-SQ52YBKK.js} +3 -2
  22. package/dist/{chunk-N5VNNOA2.js → chunk-YUJ2MHLM.js} +1236 -22
  23. package/dist/chunk-Z2YUOA4W.js +242 -0
  24. package/dist/commands/clone.d.ts +2 -2
  25. package/dist/commands/clone.js +10 -9
  26. package/dist/commands/diff.d.ts +25 -22
  27. package/dist/commands/diff.js +14 -15
  28. package/dist/commands/hukam.d.ts +2 -3
  29. package/dist/commands/hukam.js +14 -15
  30. package/dist/commands/init.d.ts +1 -1
  31. package/dist/commands/init.js +2 -2
  32. package/dist/commands/mcp.js +9 -10
  33. package/dist/commands/migrate/baseline.d.ts +1 -1
  34. package/dist/commands/migrate/baseline.js +5 -5
  35. package/dist/commands/migrate/create.d.ts +1 -1
  36. package/dist/commands/migrate/create.js +27 -13
  37. package/dist/commands/migrate/list.d.ts +1 -1
  38. package/dist/commands/migrate/list.js +5 -5
  39. package/dist/commands/migrate/run.d.ts +4 -1
  40. package/dist/commands/migrate/run.js +9 -8
  41. package/dist/commands/report.d.ts +1 -1
  42. package/dist/commands/report.js +5 -5
  43. package/dist/commands/restore.d.ts +1 -1
  44. package/dist/commands/restore.js +14 -13
  45. package/dist/commands/snapshot.d.ts +1 -1
  46. package/dist/commands/snapshot.js +8 -8
  47. package/dist/commands/sync.d.ts +2 -3
  48. package/dist/commands/sync.js +14 -15
  49. package/dist/{config-CTbeRlJk.d.ts → config-l3ggjw9r.d.ts} +2 -0
  50. package/dist/index.d.ts +38 -4
  51. package/dist/index.js +13 -14
  52. package/package.json +2 -2
  53. package/dist/chunk-DQJSSTIJ.js +0 -940
  54. package/dist/chunk-DQQ5E563.js +0 -64
@@ -2,15 +2,18 @@ import {
2
2
  CHECK_NAMES,
3
3
  RolesCheck,
4
4
  applyTableFilter,
5
+ destructiveReason,
5
6
  isComparisonCheck,
6
- resolveTableFilter
7
- } from "./chunk-DQJSSTIJ.js";
8
- import {
7
+ parseStatements,
9
8
  policyOnlyKeys,
9
+ relationName,
10
+ resolveTableFilter,
10
11
  runDbDiff,
12
+ schemaNotices,
11
13
  sqlSkeleton,
12
- sqlToIssues
13
- } from "./chunk-N5VNNOA2.js";
14
+ sqlToIssues,
15
+ withoutAbsentRoles
16
+ } from "./chunk-YUJ2MHLM.js";
14
17
  import {
15
18
  splitSqlStatements
16
19
  } from "./chunk-WK5YTINL.js";
@@ -25,19 +28,22 @@ import {
25
28
  readJsonArray,
26
29
  readJsonObject,
27
30
  schemaPolicySql
28
- } from "./chunk-ICSCHS72.js";
31
+ } from "./chunk-5UHIWFQG.js";
29
32
  import {
30
33
  Check,
31
34
  CheckSkipped,
32
35
  MigrationsCheck,
36
+ holdSnapshot,
33
37
  isCheckSkipped,
34
38
  pgQuery,
35
39
  quoteIdent,
36
40
  quoteLiteral,
37
41
  quoteName,
38
42
  readOrAbsent,
43
+ releaseSnapshots,
44
+ setSnapshotsOff,
39
45
  sqlLiteral
40
- } from "./chunk-MG3SFV5J.js";
46
+ } from "./chunk-KT7NMELZ.js";
41
47
  import {
42
48
  DEFAULT_IGNORE_SCHEMAS,
43
49
  SCORE_MAX,
@@ -48,7 +54,7 @@ import {
48
54
  STORAGE_LIST_LIMIT,
49
55
  SUPABASE_MGMT_API,
50
56
  friendlyDbError
51
- } from "./chunk-KNXHLVF7.js";
57
+ } from "./chunk-SQ52YBKK.js";
52
58
 
53
59
  // src/scoring.ts
54
60
  function summarize(results) {
@@ -88,6 +94,111 @@ function computePostureScore(results) {
88
94
  return scoreOf(posture);
89
95
  }
90
96
 
97
+ // src/hazards.ts
98
+ var VOLATILE = /* @__PURE__ */ new Set(["random", "gen_random_uuid", "uuid_generate_v4", "uuid_generate_v1", "clock_timestamp", "nextval", "timeofday"]);
99
+ var table = (rv) => rv ? rv.schemaname ? `${rv.schemaname}.${relationName(rv)}` : relationName(rv) : "";
100
+ function hazardsOf(sql) {
101
+ const out = [];
102
+ const add = (h) => {
103
+ if (!out.some((o) => o.kind === h.kind && o.on === h.on)) out.push(h);
104
+ };
105
+ const loss = destructiveReason(sql);
106
+ if (loss) add({ kind: "data-loss", detail: loss });
107
+ const statements = parseStatements(sql);
108
+ if (!statements) return out;
109
+ const created = new Set(statements.filter((s) => s.kind === "CreateStmt").map((s) => table(s.node.relation)));
110
+ const existing = (name) => name !== "" && !created.has(name);
111
+ for (const s of statements) {
112
+ for (const h of statementHazards(s)) {
113
+ if (h.on === void 0 || existing(h.on)) add(h);
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+ function statementHazards(s) {
119
+ const n = s.node;
120
+ switch (s.kind) {
121
+ case "AlterTableStmt":
122
+ return alterTableHazards(table(n.relation), n.cmds ?? []);
123
+ case "IndexStmt":
124
+ return n.concurrent ? [{ kind: "not-transactional", on: table(n.relation), detail: `builds an index concurrently, which cannot run inside a transaction` }] : [{ kind: "blocks-writes", on: table(n.relation), detail: `blocks writes to ${table(n.relation)} while the index builds` }];
125
+ case "CreateTrigStmt":
126
+ return [{ kind: "blocks-writes", on: table(n.relation), detail: `blocks writes to ${table(n.relation)} briefly` }];
127
+ case "CreatePolicyStmt":
128
+ case "AlterPolicyStmt":
129
+ case "RuleStmt":
130
+ return [{ kind: "blocks-reads-and-writes", on: table(n.table ?? n.relation), detail: `blocks reads and writes on ${table(n.table ?? n.relation)} briefly` }];
131
+ case "RenameStmt":
132
+ return n.relation ? [{ kind: "blocks-reads-and-writes", on: table(n.relation), detail: `blocks reads and writes on ${table(n.relation)} briefly` }] : [];
133
+ case "RefreshMatViewStmt":
134
+ return n.concurrent ? [] : [{ kind: "blocks-reads-and-writes", on: table(n.relation), detail: `blocks reads of ${table(n.relation)} while it refreshes` }];
135
+ case "VacuumStmt":
136
+ return [{ kind: "not-transactional", detail: "VACUUM cannot run inside a transaction" }];
137
+ case "ReindexStmt":
138
+ return (n.params ?? []).some((p) => p.DefElem?.defname === "concurrently") ? [{ kind: "not-transactional", detail: "REINDEX CONCURRENTLY cannot run inside a transaction" }] : [];
139
+ default:
140
+ return [];
141
+ }
142
+ }
143
+ function alterTableHazards(name, cmds) {
144
+ const out = [];
145
+ let exclusive = false;
146
+ let writesOnly = false;
147
+ for (const { AlterTableCmd: cmd } of cmds) {
148
+ if (!cmd) continue;
149
+ switch (cmd.subtype) {
150
+ // Lighter locks: other DDL waits, reads and writes go on.
151
+ case "AT_SetStatistics":
152
+ case "AT_SetOptions":
153
+ case "AT_ResetOptions":
154
+ case "AT_SetRelOptions":
155
+ case "AT_ResetRelOptions":
156
+ case "AT_ValidateConstraint":
157
+ case "AT_ClusterOn":
158
+ case "AT_DropCluster":
159
+ continue;
160
+ case "AT_AlterColumnType":
161
+ out.push({ kind: "rewrite", on: name, detail: `may rewrite ${name}: a column's type changes, unless the new type is binary-compatible` });
162
+ break;
163
+ case "AT_SetLogged":
164
+ case "AT_SetUnLogged":
165
+ out.push({ kind: "rewrite", on: name, detail: `rewrites ${name}: LOGGED and UNLOGGED tables are stored differently` });
166
+ break;
167
+ case "AT_AddColumn": {
168
+ const def = cmd.def?.ColumnDef;
169
+ const constraints = def?.constraints ?? [];
170
+ const generated = constraints.some((c) => c.Constraint?.contype === "CONSTR_GENERATED");
171
+ const volatile = constraints.some((c) => c.Constraint?.contype === "CONSTR_DEFAULT" && VOLATILE.has(String(c.Constraint.raw_expr?.FuncCall?.funcname?.at(-1)?.String?.sval ?? "")));
172
+ if (generated || volatile) {
173
+ out.push({ kind: "rewrite", on: name, detail: `rewrites ${name}: the new column's ${generated ? "generated value" : "default"} is computed for every row` });
174
+ }
175
+ break;
176
+ }
177
+ case "AT_AddConstraint": {
178
+ const c = cmd.def?.Constraint;
179
+ if (c && !c.skip_validation && (c.contype === "CONSTR_CHECK" || c.contype === "CONSTR_FOREIGN")) {
180
+ out.push({ kind: "full-scan", on: name, detail: `scans every row of ${name} to check the new constraint (NOT VALID, then VALIDATE, avoids holding the lock)` });
181
+ }
182
+ if (c?.contype === "CONSTR_FOREIGN") {
183
+ writesOnly = true;
184
+ continue;
185
+ }
186
+ break;
187
+ }
188
+ case "AT_SetNotNull":
189
+ out.push({ kind: "full-scan", on: name, detail: `scans every row of ${name} to check for NULLs` });
190
+ break;
191
+ }
192
+ exclusive = true;
193
+ }
194
+ if (exclusive) {
195
+ out.unshift({ kind: "blocks-reads-and-writes", on: name, detail: `blocks reads and writes on ${name} while it runs` });
196
+ } else if (writesOnly) {
197
+ out.unshift({ kind: "blocks-writes", on: name, detail: `blocks writes to ${name} while the key is checked` });
198
+ }
199
+ return out;
200
+ }
201
+
91
202
  // src/scanner.ts
92
203
  function resolveExcludedChecks(config) {
93
204
  const lists = [config?.checks?.exclude, config?.environments?.[config?.target ?? ""]?.checks?.exclude];
@@ -110,14 +221,23 @@ function checkConcurrency() {
110
221
  }
111
222
  return 4;
112
223
  }
224
+ function withHazards(issues) {
225
+ return issues.map((issue) => {
226
+ if (!issue.sql?.up) return issue;
227
+ const hazards = hazardsOf(issue.sql.up);
228
+ return hazards.length > 0 ? { ...issue, hazards } : issue;
229
+ });
230
+ }
113
231
  async function runCheck(check, ctx, name, sourceDbUrl) {
114
232
  const start = performance.now();
233
+ const notices = [];
115
234
  try {
116
- const issues = await check.scan(ctx);
235
+ const issues = withHazards(await check.scan({ ...ctx, onNotice: (n) => notices.push(n) }));
117
236
  return {
118
237
  check: name,
119
238
  status: issues.length > 0 ? "drifted" : "clean",
120
239
  issues,
240
+ ...notices.length > 0 ? { notices } : {},
121
241
  durationMs: Math.round(performance.now() - start)
122
242
  };
123
243
  } catch (err) {
@@ -179,9 +299,17 @@ async function scan(registry, options, bus) {
179
299
  await bus?.emit("supaforge.check.after", { check: name, result });
180
300
  }
181
301
  };
182
- await Promise.all(
183
- Array.from({ length: Math.min(checkConcurrency(), total) }, () => worker())
184
- );
302
+ setSnapshotsOff(options.snapshot === false);
303
+ if (options.snapshot !== false) {
304
+ await Promise.all([source?.dbUrl, target?.dbUrl].filter(Boolean).map((url) => holdSnapshot(url)));
305
+ }
306
+ try {
307
+ await Promise.all(
308
+ Array.from({ length: Math.min(checkConcurrency(), total) }, () => worker())
309
+ );
310
+ } finally {
311
+ if (options.snapshot !== false) await releaseSnapshots();
312
+ }
185
313
  foldDuplicatePolicyFindings(results);
186
314
  foldDuplicateExtensionFindings(results);
187
315
  const summary = summarize(results);
@@ -265,7 +393,7 @@ var SchemaCheck = class extends Check {
265
393
  type: "schema",
266
394
  include: "both",
267
395
  timeoutSeconds: ctx.target?.checks?.schema?.timeout,
268
- onProgress: ctx.onDetail ? ({ table, tablesSeen }) => ctx.onDetail?.(`${tablesSeen} tables \xB7 ${table}`) : void 0,
396
+ onProgress: ctx.onDetail ? ({ table: table2, tablesSeen }) => ctx.onDetail?.(`${tablesSeen} tables \xB7 ${table2}`) : void 0,
269
397
  ignoreSchemas,
270
398
  // dbdiff takes the include/exclude lists natively, globs and all, so
271
399
  // the scope is enforced in the diff itself rather than by discarding
@@ -275,7 +403,10 @@ var SchemaCheck = class extends Check {
275
403
  }),
276
404
  this.fetchIgnoredSchemaTables(ctx.target.dbUrl, ignoreSchemas)
277
405
  ]);
278
- return sqlToIssues(result, "schema", ignoreSchemas, ignoredSchemaTables);
406
+ for (const notice of schemaNotices(result.notices ?? [])) ctx.onNotice?.(notice);
407
+ const issues = sqlToIssues(result, "schema", ignoreSchemas, ignoredSchemaTables);
408
+ const roles = await this.targetRoles(ctx.target.dbUrl);
409
+ return roles?.size ? withoutAbsentRoles(issues, roles) : issues;
279
410
  } catch (err) {
280
411
  if (err instanceof Error && err.message.includes("@dbdiff/cli is not installed")) {
281
412
  throw new CheckSkipped("@dbdiff/cli is not installed");
@@ -293,6 +424,15 @@ var SchemaCheck = class extends Check {
293
424
  * Returns a Set of lowercase table names, bare and schema-qualified. Fails silently so that a transient
294
425
  * DB error here never blocks the main schema diff.
295
426
  */
427
+ /** The target's roles, or undefined when they cannot be read. */
428
+ async targetRoles(dbUrl) {
429
+ try {
430
+ const rows = await this.queryFn(dbUrl, "SELECT rolname FROM pg_roles");
431
+ return new Set(rows.map((r) => r.rolname));
432
+ } catch {
433
+ return void 0;
434
+ }
435
+ }
296
436
  async fetchIgnoredSchemaTables(dbUrl, ignoreSchemas) {
297
437
  if (ignoreSchemas.length === 0) return /* @__PURE__ */ new Set();
298
438
  try {
@@ -1031,8 +1171,8 @@ var StorageCheck = class extends Check {
1031
1171
  }
1032
1172
  return issues;
1033
1173
  }
1034
- async hasTable(dbUrl, table) {
1035
- const rows = await this.queryFn(dbUrl, tableExistsSql(table));
1174
+ async hasTable(dbUrl, table2) {
1175
+ const rows = await this.queryFn(dbUrl, tableExistsSql(table2));
1036
1176
  return rows[0]?.present === true;
1037
1177
  }
1038
1178
  async listTypedBuckets(dbUrl, spec) {
@@ -1137,11 +1277,11 @@ var TYPED_BUCKET_TABLES = [
1137
1277
  sql: `SELECT id AS key FROM storage.buckets_vectors ORDER BY id`
1138
1278
  }
1139
1279
  ];
1140
- function tableExistsSql(table) {
1280
+ function tableExistsSql(table2) {
1141
1281
  return `
1142
1282
  SELECT EXISTS (
1143
1283
  SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1144
- WHERE n.nspname = 'storage' AND c.relname = '${table}'
1284
+ WHERE n.nspname = 'storage' AND c.relname = '${table2}'
1145
1285
  ) AS present
1146
1286
  `;
1147
1287
  }
@@ -1499,14 +1639,14 @@ function diffAuthConfig(source, target, targetSrc) {
1499
1639
  const sv = source[key];
1500
1640
  const tv = target[key];
1501
1641
  if (JSON.stringify(sv) === JSON.stringify(tv)) continue;
1502
- const kind = classifyAuthKey(key);
1642
+ const kind2 = classifyAuthKey(key);
1503
1643
  const base2 = {
1504
1644
  id: `auth-${key.toLowerCase()}`,
1505
1645
  check: "auth",
1506
1646
  severity: isCriticalAuthKey(key) ? "critical" : "info",
1507
1647
  title: `Auth config mismatch: ${key}`
1508
1648
  };
1509
- if (kind === "secret") {
1649
+ if (kind2 === "secret") {
1510
1650
  issues.push({
1511
1651
  ...base2,
1512
1652
  description: `"${key}" differs between source and target. It is a secret: set it on the target directly.`,
@@ -1514,14 +1654,14 @@ function diffAuthConfig(source, target, targetSrc) {
1514
1654
  });
1515
1655
  continue;
1516
1656
  }
1517
- const action = targetSrc.kind === "hosted" && kind === "shared" ? {
1657
+ const action = targetSrc.kind === "hosted" && kind2 === "shared" ? {
1518
1658
  method: "PATCH",
1519
1659
  url: `${SUPABASE_MGMT_API}/${encodeURIComponent(targetSrc.ref)}/config/auth`,
1520
1660
  headers: { Authorization: `Bearer ${targetSrc.token}` },
1521
1661
  body: { [key]: sv },
1522
1662
  label: `Set auth config "${key}" to ${JSON.stringify(sv)} in target`
1523
1663
  } : void 0;
1524
- const manualOnly = kind === "environment" ? `"${key}" belongs to each environment and is not copied. Change it on the target if it is wrong there.` : action ? void 0 : "Self-hosted GoTrue is configured through its environment \u2014 update the target deployment and restart it.";
1664
+ const manualOnly = kind2 === "environment" ? `"${key}" belongs to each environment and is not copied. Change it on the target if it is wrong there.` : action ? void 0 : "Self-hosted GoTrue is configured through its environment \u2014 update the target deployment and restart it.";
1525
1665
  issues.push({
1526
1666
  ...base2,
1527
1667
  description: `"${key}" differs between source (${JSON.stringify(sv)}) and target (${JSON.stringify(tv)}).` + (manualOnly ? ` ${manualOnly}` : ""),
@@ -1638,25 +1778,25 @@ SELECT cron.schedule('${key}', '${tj.schedule}', $$${tj.command.trim()}$$);`
1638
1778
  }
1639
1779
 
1640
1780
  // src/checksum.ts
1641
- async function getTableFingerprint(dbUrl, table, queryFn = pgQuery) {
1781
+ async function getTableFingerprint(dbUrl, table2, queryFn = pgQuery) {
1642
1782
  const sql = `
1643
1783
  SELECT count(*)::int AS row_count,
1644
1784
  coalesce(sum(('x' || substr(d, 1, 16))::bit(64)::bigint::numeric), 0)::text
1645
1785
  || ':' ||
1646
1786
  coalesce(sum(('x' || substr(d, 17, 16))::bit(64)::bigint::numeric), 0)::text AS content
1647
- FROM (SELECT md5(t::text) AS d FROM ${quoteIdent(table)} t) s
1787
+ FROM (SELECT md5(t::text) AS d FROM ${quoteIdent(table2)} t) s
1648
1788
  `;
1649
1789
  const [row] = await queryFn(dbUrl, sql);
1650
1790
  return {
1651
- table,
1791
+ table: table2,
1652
1792
  rowCount: row.row_count,
1653
1793
  content: row.content
1654
1794
  };
1655
1795
  }
1656
- async function tablesMatch(sourceUrl, targetUrl, table, queryFn = pgQuery) {
1796
+ async function tablesMatch(sourceUrl, targetUrl, table2, queryFn = pgQuery) {
1657
1797
  const [source, target] = await Promise.all([
1658
- getTableFingerprint(sourceUrl, table, queryFn),
1659
- getTableFingerprint(targetUrl, table, queryFn)
1798
+ getTableFingerprint(sourceUrl, table2, queryFn),
1799
+ getTableFingerprint(targetUrl, table2, queryFn)
1660
1800
  ]);
1661
1801
  return source.rowCount === target.rowCount && source.content === target.content;
1662
1802
  }
@@ -1664,20 +1804,20 @@ async function filterChangedTables(sourceUrl, targetUrl, tables, queryFn = pgQue
1664
1804
  const changed = [];
1665
1805
  const skipped = [];
1666
1806
  const results = await Promise.all(
1667
- tables.map(async (table) => {
1807
+ tables.map(async (table2) => {
1668
1808
  try {
1669
- const match = await tablesMatch(sourceUrl, targetUrl, table, queryFn);
1670
- return { table, match };
1809
+ const match = await tablesMatch(sourceUrl, targetUrl, table2, queryFn);
1810
+ return { table: table2, match };
1671
1811
  } catch {
1672
- return { table, match: false };
1812
+ return { table: table2, match: false };
1673
1813
  }
1674
1814
  })
1675
1815
  );
1676
- for (const { table, match } of results) {
1816
+ for (const { table: table2, match } of results) {
1677
1817
  if (match) {
1678
- skipped.push(table);
1818
+ skipped.push(table2);
1679
1819
  } else {
1680
- changed.push(table);
1820
+ changed.push(table2);
1681
1821
  }
1682
1822
  }
1683
1823
  return { changed, skipped };
@@ -1973,11 +2113,24 @@ var ExtensionsCheck = class extends Check {
1973
2113
  }
1974
2114
  name = "extensions";
1975
2115
  async scan(ctx) {
1976
- const [source, target] = await Promise.all([
2116
+ const [source, target, reachable] = await Promise.all([
1977
2117
  this.fetchExtensions(ctx.source.dbUrl),
1978
- this.fetchExtensions(ctx.target.dbUrl)
2118
+ this.fetchExtensions(ctx.target.dbUrl),
2119
+ this.fetchUpdates(ctx.target.dbUrl)
1979
2120
  ]);
1980
- return diffExtensions(source, target);
2121
+ const ignored = new Set(ctx.config.ignoreExtensions ?? []);
2122
+ return diffExtensions(source, target.filter((e) => !ignored.has(e.name) || source.some((s) => s.name === e.name)), reachable);
2123
+ }
2124
+ /** The versions each installed extension can be updated to on this server. */
2125
+ async fetchUpdates(dbUrl) {
2126
+ try {
2127
+ const rows = await this.queryFn(dbUrl, UPDATES_SQL);
2128
+ const out = /* @__PURE__ */ new Map();
2129
+ for (const r of rows) out.set(r.name, (out.get(r.name) ?? /* @__PURE__ */ new Set()).add(r.version));
2130
+ return out;
2131
+ } catch {
2132
+ return void 0;
2133
+ }
1981
2134
  }
1982
2135
  async fetchExtensions(dbUrl) {
1983
2136
  return await this.queryFn(dbUrl, EXTENSIONS_SQL);
@@ -1991,7 +2144,13 @@ var EXTENSIONS_SQL = `
1991
2144
  JOIN pg_namespace n ON n.oid = e.extnamespace
1992
2145
  ORDER BY e.extname
1993
2146
  `;
1994
- function diffExtensions(source, target) {
2147
+ var UPDATES_SQL = `
2148
+ SELECT e.extname AS name, p.target AS version
2149
+ FROM pg_extension e
2150
+ CROSS JOIN LATERAL pg_extension_update_paths(e.extname) p
2151
+ WHERE p.source = e.extversion AND p.path IS NOT NULL
2152
+ `;
2153
+ function diffExtensions(source, target, reachable) {
1995
2154
  const issues = [];
1996
2155
  const sourceMap = new Map(source.map((e) => [e.name, e]));
1997
2156
  const targetMap = new Map(target.map((e) => [e.name, e]));
@@ -2005,7 +2164,13 @@ function diffExtensions(source, target) {
2005
2164
  description: `Extension "${name}" (v${ext.version}) is enabled in source (schema: ${ext.schema}) but not in target.`,
2006
2165
  sourceValue: ext,
2007
2166
  sql: {
2008
- up: `CREATE EXTENSION IF NOT EXISTS ${quoteName(name)}${ext.schema !== "public" ? ` SCHEMA ${quoteName(ext.schema)}` : ""};`,
2167
+ // Into the schema it is in on the source, which plain PostgreSQL
2168
+ // may not have — Supabase's `extensions`. Made first; if the server
2169
+ // does not ship the extension, the fix is left out with it. A
2170
+ // system schema (pg_cron's pg_catalog) is always there, and cannot
2171
+ // be made.
2172
+ up: ext.schema === "public" ? `CREATE EXTENSION IF NOT EXISTS ${quoteName(name)};` : `${ext.schema.startsWith("pg_") ? "" : `CREATE SCHEMA IF NOT EXISTS ${quoteName(ext.schema)};
2173
+ `}CREATE EXTENSION IF NOT EXISTS ${quoteName(name)} SCHEMA ${quoteName(ext.schema)};`,
2009
2174
  down: `DROP EXTENSION IF EXISTS ${quoteName(name)};`
2010
2175
  }
2011
2176
  });
@@ -2027,6 +2192,7 @@ function diffExtensions(source, target) {
2027
2192
  const tgtExt = targetMap.get(name);
2028
2193
  if (!tgtExt) continue;
2029
2194
  if (srcExt.version !== tgtExt.version) {
2195
+ const updatable = !reachable || reachable.get(name)?.has(srcExt.version);
2030
2196
  issues.push({
2031
2197
  id: `ext-version-${name}`,
2032
2198
  check: "extensions",
@@ -2035,12 +2201,236 @@ function diffExtensions(source, target) {
2035
2201
  description: `Extension "${name}" is v${srcExt.version} in source but v${tgtExt.version} in target.`,
2036
2202
  sourceValue: srcExt,
2037
2203
  targetValue: tgtExt,
2038
- sql: {
2039
- up: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(srcExt.version)};`,
2040
- down: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(tgtExt.version)};`
2041
- }
2204
+ ...updatable ? {
2205
+ sql: {
2206
+ up: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(srcExt.version)};`,
2207
+ down: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(tgtExt.version)};`
2208
+ }
2209
+ } : { manualOnly: `the target cannot go from v${tgtExt.version} to v${srcExt.version}: its server has no update path there (an extension cannot be moved down a version)` }
2210
+ });
2211
+ }
2212
+ }
2213
+ return issues;
2214
+ }
2215
+
2216
+ // src/checks/queues.ts
2217
+ var QueuesCheck = class extends Check {
2218
+ constructor(queryFn = pgQuery) {
2219
+ super();
2220
+ this.queryFn = queryFn;
2221
+ }
2222
+ name = "queues";
2223
+ async scan(ctx) {
2224
+ const [source, target] = await Promise.all([
2225
+ this.fetchQueues(ctx.source.dbUrl),
2226
+ this.fetchQueues(ctx.target.dbUrl)
2227
+ ]);
2228
+ if (!source.available && !target.available) {
2229
+ throw new CheckSkipped("pgmq extension not installed");
2230
+ }
2231
+ return diffQueues(source.queues, target.queues, target.available);
2232
+ }
2233
+ async fetchQueues(dbUrl) {
2234
+ return readOrAbsent(
2235
+ async () => ({ queues: await this.queryFn(dbUrl, QUEUES_SQL), available: true }),
2236
+ { queues: [], available: false }
2237
+ );
2238
+ }
2239
+ };
2240
+ var QUEUES_SQL = `
2241
+ SELECT queue_name, is_partitioned, is_unlogged
2242
+ FROM pgmq.meta
2243
+ ORDER BY queue_name
2244
+ `;
2245
+ function createSql(q) {
2246
+ if (q.is_partitioned) return void 0;
2247
+ return `SELECT pgmq.${q.is_unlogged ? "create_unlogged" : "create"}(${quoteLiteral(q.queue_name)});`;
2248
+ }
2249
+ var dropSql = (q) => `SELECT pgmq.drop_queue(${quoteLiteral(q.queue_name)});`;
2250
+ var kind = (q) => q.is_partitioned ? "partitioned" : q.is_unlogged ? "unlogged" : "standard";
2251
+ function diffQueues(source, target, targetHasPgmq = true) {
2252
+ const issues = [];
2253
+ const sourceMap = new Map(source.map((q) => [q.queue_name, q]));
2254
+ const targetMap = new Map(target.map((q) => [q.queue_name, q]));
2255
+ const needsExtension = targetHasPgmq ? "" : "CREATE EXTENSION IF NOT EXISTS pgmq;\n";
2256
+ for (const [name, q] of sourceMap) {
2257
+ const t = targetMap.get(name);
2258
+ if (!t) {
2259
+ const up = createSql(q);
2260
+ issues.push({
2261
+ id: `queues-missing-${name}`,
2262
+ check: "queues",
2263
+ severity: "warning",
2264
+ title: `Missing queue: ${name}`,
2265
+ description: `Queue "${name}" (${kind(q)}) exists in source but not in target.`,
2266
+ sourceValue: q,
2267
+ ...up ? { sql: { up: needsExtension + up, down: dropSql(q) } } : { manualOnly: "a partitioned queue is created with pg_partman settings pgmq.meta does not record \u2014 create it with pgmq.create_partitioned on the target" }
2268
+ });
2269
+ } else if (kind(q) !== kind(t)) {
2270
+ issues.push({
2271
+ id: `queues-kind-${name}`,
2272
+ check: "queues",
2273
+ severity: "warning",
2274
+ title: `Queue kind differs: ${name}`,
2275
+ description: `Queue "${name}" is ${kind(q)} in source and ${kind(t)} in target. Changing it means dropping the queue and its messages, so it is left to you.`,
2276
+ sourceValue: q,
2277
+ targetValue: t,
2278
+ manualOnly: "changing a queue's kind drops it and its messages; recreate it by hand when it is empty"
2279
+ });
2280
+ }
2281
+ }
2282
+ for (const [name, t] of targetMap) {
2283
+ if (sourceMap.has(name)) continue;
2284
+ const down = createSql(t);
2285
+ issues.push({
2286
+ id: `queues-extra-${name}`,
2287
+ check: "queues",
2288
+ severity: "critical",
2289
+ title: `Extra queue: ${name}`,
2290
+ description: `Queue "${name}" exists in target but not in source. Dropping it drops its messages.`,
2291
+ targetValue: t,
2292
+ sql: { up: dropSql(t), down: down ?? "" }
2293
+ });
2294
+ }
2295
+ return issues;
2296
+ }
2297
+
2298
+ // src/checks/partitions.ts
2299
+ var SHAPE = ["control", "partition_interval", "partition_type", "epoch", "time_encoder", "time_decoder"];
2300
+ var SETTINGS = [
2301
+ "premake",
2302
+ "automatic_maintenance",
2303
+ "retention",
2304
+ "retention_schema",
2305
+ "retention_keep_index",
2306
+ "retention_keep_table",
2307
+ "optimize_constraint",
2308
+ "infinite_time_partitions",
2309
+ "inherit_privileges",
2310
+ "constraint_valid",
2311
+ "ignore_default_data",
2312
+ "maintenance_order",
2313
+ "retention_keep_publication",
2314
+ "detach_before_drop",
2315
+ "jobmon",
2316
+ "date_trunc_interval"
2317
+ ];
2318
+ var PartitionsCheck = class extends Check {
2319
+ constructor(queryFn = pgQuery) {
2320
+ super();
2321
+ this.queryFn = queryFn;
2322
+ }
2323
+ name = "partitions";
2324
+ async scan(ctx) {
2325
+ const [source, target] = await Promise.all([this.fetch(ctx.source.dbUrl), this.fetch(ctx.target.dbUrl)]);
2326
+ if (source.schema === null && target.schema === null) {
2327
+ throw new CheckSkipped("pg_partman extension not installed");
2328
+ }
2329
+ return diffPartitionSets(source.sets, target.sets, target.schema);
2330
+ }
2331
+ async fetch(dbUrl) {
2332
+ const rows = await this.queryFn(dbUrl, `SELECT n.nspname AS schema FROM pg_extension e
2333
+ JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'pg_partman'`);
2334
+ const schema = rows[0]?.schema ?? null;
2335
+ if (schema === null) return { schema, sets: [] };
2336
+ const sets = await this.queryFn(dbUrl, `
2337
+ SELECT (SELECT n.nspname || '.' || c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
2338
+ WHERE c.oid = to_regclass(pc.parent_table)) AS parent_table, pc.control, pc.partition_interval, pc.partition_type,
2339
+ pc.epoch, pc.premake, pc.automatic_maintenance, pc.constraint_cols, pc.jobmon, pc.date_trunc_interval,
2340
+ pc.time_encoder, pc.time_decoder,
2341
+ to_regclass(pc.parent_table || '_default') IS NOT NULL AS has_default,
2342
+ (to_jsonb(pc) - ARRAY(SELECT k FROM jsonb_object_keys(to_jsonb(pc)) k WHERE k <> ALL($1::text[]))) AS settings
2343
+ FROM ${quoteIdent(schema)}.part_config pc
2344
+ WHERE to_regclass(pc.parent_table) IS NOT NULL
2345
+ ORDER BY 1`, [SETTINGS]);
2346
+ return { schema, sets };
2347
+ }
2348
+ };
2349
+ var literal = (v) => v === null || v === void 0 ? "NULL" : typeof v === "boolean" || typeof v === "number" ? String(v) : Array.isArray(v) ? `ARRAY[${v.map((x) => quoteLiteral(String(x))).join(", ")}]::text[]` : quoteLiteral(String(v));
2350
+ function registerSql(set, schema) {
2351
+ const args = [
2352
+ `p_parent_table => ${quoteLiteral(set.parent_table)}`,
2353
+ `p_control => ${quoteLiteral(set.control)}`,
2354
+ `p_interval => ${quoteLiteral(set.partition_interval)}`,
2355
+ `p_type => ${quoteLiteral(set.partition_type)}`,
2356
+ `p_epoch => ${quoteLiteral(set.epoch)}`,
2357
+ `p_premake => ${set.premake}`,
2358
+ `p_default_table => ${set.has_default}`,
2359
+ `p_automatic_maintenance => ${quoteLiteral(set.automatic_maintenance)}`,
2360
+ `p_jobmon => ${set.jobmon}`,
2361
+ ...set.constraint_cols?.length ? [`p_constraint_cols => ${literal(set.constraint_cols)}`] : [],
2362
+ ...set.date_trunc_interval ? [`p_date_trunc_interval => ${quoteLiteral(set.date_trunc_interval)}`] : [],
2363
+ ...set.time_encoder ? [`p_time_encoder => ${quoteLiteral(set.time_encoder)}`] : [],
2364
+ ...set.time_decoder ? [`p_time_decoder => ${quoteLiteral(set.time_decoder)}`] : []
2365
+ ];
2366
+ return `SELECT ${quoteIdent(schema)}.create_parent(${args.join(", ")});`;
2367
+ }
2368
+ function updateSql(schema, parent, settings) {
2369
+ const sets = Object.entries(settings).map(([k, v]) => `${quoteIdent(k)} = ${literal(v)}`);
2370
+ return `UPDATE ${quoteIdent(schema)}.part_config SET ${sets.join(", ")} WHERE parent_table = ${quoteLiteral(parent)};`;
2371
+ }
2372
+ function undoSql(schema, parent) {
2373
+ return `DELETE FROM ${quoteIdent(schema)}.part_config WHERE parent_table = ${quoteLiteral(parent)};`;
2374
+ }
2375
+ function diffPartitionSets(source, target, targetSchema) {
2376
+ const issues = [];
2377
+ const targetMap = new Map(target.map((s) => [s.parent_table, s]));
2378
+ const sourceNames = new Set(source.map((s) => s.parent_table));
2379
+ for (const s of source) {
2380
+ const t = targetMap.get(s.parent_table);
2381
+ if (!t) {
2382
+ issues.push({
2383
+ id: `partitions-missing-${s.parent_table}`,
2384
+ check: "partitions",
2385
+ severity: "warning",
2386
+ title: `Partition set not registered: ${s.parent_table}`,
2387
+ description: `pg_partman manages ${s.parent_table} in source (${s.partition_type} by ${s.control}, every ${s.partition_interval}) but not in target.`,
2388
+ sourceValue: s,
2389
+ ...targetSchema ? { sql: { up: `${registerSql(s, targetSchema)}
2390
+ ${updateSql(targetSchema, s.parent_table, s.settings)}`, down: undoSql(targetSchema, s.parent_table) } } : { manualOnly: "the target does not have pg_partman; install it, then re-run to register the partition set" }
2042
2391
  });
2392
+ continue;
2043
2393
  }
2394
+ const reshaped = SHAPE.filter((k) => String(s[k] ?? "") !== String(t[k] ?? ""));
2395
+ if (reshaped.length > 0) {
2396
+ issues.push({
2397
+ id: `partitions-shape-${s.parent_table}`,
2398
+ check: "partitions",
2399
+ severity: "warning",
2400
+ title: `Partition set differs: ${s.parent_table}`,
2401
+ description: `${reshaped.join(", ")} differ${reshaped.length === 1 ? "s" : ""} for ${s.parent_table}. pg_partman cannot change that in place.`,
2402
+ sourceValue: s,
2403
+ targetValue: t,
2404
+ manualOnly: "changing how a set is partitioned means undoing and recreating it with pg_partman (undo_partition, then create_parent)"
2405
+ });
2406
+ continue;
2407
+ }
2408
+ const changed = Object.fromEntries(Object.entries(s.settings).filter(([k, v]) => JSON.stringify(v) !== JSON.stringify(t.settings[k])));
2409
+ if (Object.keys(changed).length > 0 && targetSchema) {
2410
+ const previous = Object.fromEntries(Object.keys(changed).map((k) => [k, t.settings[k]]));
2411
+ issues.push({
2412
+ id: `partitions-settings-${s.parent_table}`,
2413
+ check: "partitions",
2414
+ severity: "warning",
2415
+ title: `Partition set settings differ: ${s.parent_table}`,
2416
+ description: `${Object.keys(changed).join(", ")} differ for ${s.parent_table}.`,
2417
+ sourceValue: s.settings,
2418
+ targetValue: t.settings,
2419
+ sql: { up: updateSql(targetSchema, s.parent_table, changed), down: updateSql(targetSchema, s.parent_table, previous) }
2420
+ });
2421
+ }
2422
+ }
2423
+ for (const t of target) {
2424
+ if (sourceNames.has(t.parent_table)) continue;
2425
+ issues.push({
2426
+ id: `partitions-extra-${t.parent_table}`,
2427
+ check: "partitions",
2428
+ severity: "info",
2429
+ title: `Extra partition set: ${t.parent_table}`,
2430
+ description: `pg_partman manages ${t.parent_table} in target but not in source.`,
2431
+ targetValue: t,
2432
+ manualOnly: "unregistering a set leaves its partitions as ordinary tables; use pg_partman's undo_partition if that is what you want"
2433
+ });
2044
2434
  }
2045
2435
  return issues;
2046
2436
  }
@@ -2062,6 +2452,8 @@ function createDefaultRegistry(options = {}) {
2062
2452
  registry.register(new ExtensionsCheck());
2063
2453
  registry.register(new MigrationsCheck());
2064
2454
  registry.register(new RolesCheck());
2455
+ registry.register(new QueuesCheck());
2456
+ registry.register(new PartitionsCheck());
2065
2457
  return registry;
2066
2458
  }
2067
2459
 
@@ -2073,4 +2465,4 @@ export {
2073
2465
  CheckRegistry,
2074
2466
  createDefaultRegistry
2075
2467
  };
2076
- //# sourceMappingURL=chunk-OB5GP7UB.js.map
2468
+ //# sourceMappingURL=chunk-CAQ3QQFP.js.map