@rebasepro/server-postgres 0.29.0 → 0.29.2

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 (161) hide show
  1. package/dist/{BranchService-JiYJ_n9E.js → BranchService-X9R505mP.js} +3 -3
  2. package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-X9R505mP.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +90 -12
  4. package/dist/PostgresBootstrapper.d.ts +34 -0
  5. package/dist/auth/ensure-tables.d.ts +2 -2
  6. package/dist/auth/schema-version.d.ts +5 -5
  7. package/dist/auth/services.d.ts +9 -9
  8. package/dist/{backup-cli-D_aKXPyX.js → backup-cli-CwiJEp_J.js} +3 -3
  9. package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
  10. package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-CbZj9ovZ.js} +2 -2
  11. package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
  12. package/dist/{cli-console-DPdZCWTi.js → cli-console-DDkNetCz.js} +6 -6
  13. package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DDkNetCz.js.map} +1 -1
  14. package/dist/{cli-errors-D8s4z_3g.js → cli-errors-C73Qy7WJ.js} +49 -6
  15. package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
  16. package/dist/cli.js +209 -53
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
  19. package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
  20. package/dist/data-transformer.d.ts +2 -2
  21. package/dist/database-health.d.ts +2 -1
  22. package/dist/database-preflight-DIauc8i5.js +184 -0
  23. package/dist/database-preflight-DIauc8i5.js.map +1 -0
  24. package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
  25. package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
  26. package/dist/db-subcommands.d.ts +1 -1
  27. package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-DDdnjaOW.js} +25 -9
  28. package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
  29. package/dist/{doctor-_g2tHRtG.js → doctor-DwMXljiq.js} +11 -11
  30. package/dist/doctor-DwMXljiq.js.map +1 -0
  31. package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
  32. package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
  33. package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-h1mUO7Uu.js} +18 -10
  34. package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
  35. package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-CUqYgMvo.js} +4 -4
  36. package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
  37. package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-z7ustOl_.js} +3 -3
  38. package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
  39. package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
  40. package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
  41. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
  42. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
  43. package/dist/{generate-files-DbwU8Btx.js → generate-files-BkiRFoV1.js} +3 -3
  44. package/dist/{generate-files-DbwU8Btx.js.map → generate-files-BkiRFoV1.js.map} +1 -1
  45. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
  46. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
  47. package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-D2soazQU.js} +18 -7
  48. package/dist/generated-schema-diff-D2soazQU.js.map +1 -0
  49. package/dist/history/HistoryService.d.ts +2 -3
  50. package/dist/history/ensure-history-table.d.ts +8 -3
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.es.js +22 -14
  53. package/dist/index.es.js.map +1 -1
  54. package/dist/interfaces.d.ts +24 -2
  55. package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
  56. package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
  57. package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-CveNQli3.js} +166 -460
  58. package/dist/migrate-baseline-CveNQli3.js.map +1 -0
  59. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
  60. package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
  61. package/dist/{open-rebase-CTNBmmH8.js → open-rebase-Cvid3iwR.js} +1813 -689
  62. package/dist/open-rebase-Cvid3iwR.js.map +1 -0
  63. package/dist/open-rebase.d.ts +7 -2
  64. package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-80uTIHQs.js} +2 -2
  65. package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
  66. package/dist/pipelined-transaction.d.ts +24 -37
  67. package/dist/{plan-schema-CMNWvqIa.js → plan-schema-CMhNYEYF.js} +109 -14
  68. package/dist/plan-schema-CMhNYEYF.js.map +1 -0
  69. package/dist/{policy-drift-IjD2AUD-.js → policy-drift-Bx6663KD.js} +29 -6
  70. package/dist/policy-drift-Bx6663KD.js.map +1 -0
  71. package/dist/push-index-adoption-C-TpM445.js +22 -0
  72. package/dist/push-index-adoption-C-TpM445.js.map +1 -0
  73. package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-xbpgZEJK.js} +4 -4
  74. package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
  75. package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
  76. package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
  77. package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-7UKspspl.js} +4 -4
  78. package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
  79. package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-BOw5PtU8.js} +14 -8
  80. package/dist/push-policy-plan-BOw5PtU8.js.map +1 -0
  81. package/dist/read-routing.d.ts +10 -30
  82. package/dist/{render-ddl-CzVcbbR1.js → render-ddl-Di-fTGti.js} +40 -10
  83. package/dist/render-ddl-Di-fTGti.js.map +1 -0
  84. package/dist/request-role-cli-Bxxskru9.js +260 -0
  85. package/dist/request-role-cli-Bxxskru9.js.map +1 -0
  86. package/dist/request-role-cli.d.ts +86 -0
  87. package/dist/request-role-migration-BCW4v0rq.js +150 -0
  88. package/dist/request-role-migration-BCW4v0rq.js.map +1 -0
  89. package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
  90. package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
  91. package/dist/rls-enforcement-CyUCPDH8.js +1195 -0
  92. package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
  93. package/dist/rls-settings-BCGMIig3.js +231 -0
  94. package/dist/rls-settings-BCGMIig3.js.map +1 -0
  95. package/dist/schema/doctor-cli.js +145 -7
  96. package/dist/schema/doctor-cli.js.map +1 -1
  97. package/dist/schema/doctor-database.d.ts +27 -0
  98. package/dist/schema/drizzle-ddl.d.ts +2 -2
  99. package/dist/schema/ensure-collection-policies.d.ts +15 -3
  100. package/dist/schema/generate-drizzle-schema.js +1 -1
  101. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -1
  102. package/dist/schema/generate-postgres-ddl.js +1 -1
  103. package/dist/schema/index-adoption.d.ts +99 -0
  104. package/dist/schema/introspect-db-logic.d.ts +2 -1
  105. package/dist/schema/introspect-db.js +3 -3
  106. package/dist/schema/migrate-policy-stamps.d.ts +19 -1
  107. package/dist/schema/plan/diff-plan.d.ts +14 -2
  108. package/dist/schema/plan/render-ddl.d.ts +17 -3
  109. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  110. package/dist/schema/plan/types.d.ts +17 -0
  111. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  112. package/dist/schema/plan/view-names.d.ts +6 -0
  113. package/dist/schema/push-index-adoption.d.ts +10 -0
  114. package/dist/schema/push-policy-plan.d.ts +5 -1
  115. package/dist/schema/rls-bootstrap-sql.d.ts +34 -0
  116. package/dist/schema/search-column.d.ts +2 -2
  117. package/dist/search-column-BM-GV6vH.js.map +1 -1
  118. package/dist/security/caller-sql-columns.d.ts +60 -0
  119. package/dist/security/caller-sql.d.ts +8 -0
  120. package/dist/security/database-preflight.d.ts +24 -0
  121. package/dist/security/policy-drift.d.ts +19 -1
  122. package/dist/security/request-role-migration.d.ts +36 -0
  123. package/dist/security/rls-enforcement.d.ts +277 -21
  124. package/dist/security/rls-settings.d.ts +210 -0
  125. package/dist/services/FetchService.d.ts +33 -8
  126. package/dist/services/PersistService.d.ts +75 -4
  127. package/dist/services/RelationService.d.ts +1 -1
  128. package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
  129. package/dist/services/channel-bus/index.d.ts +2 -2
  130. package/dist/services/channel-history.d.ts +2 -2
  131. package/dist/services/channel-presence.d.ts +3 -3
  132. package/dist/services/dataService.d.ts +8 -2
  133. package/dist/services/realtimeService.d.ts +21 -5
  134. package/dist/services/socket-liveness.d.ts +6 -1
  135. package/dist/services/view-access.d.ts +2 -2
  136. package/dist/types.d.ts +1 -1
  137. package/dist/utils/drizzle-conditions.d.ts +12 -0
  138. package/dist/utils/positional-params.d.ts +40 -0
  139. package/dist/view-names-Dscp6--B.js +24 -0
  140. package/dist/view-names-Dscp6--B.js.map +1 -0
  141. package/dist/{websocket-D2y88dOa.js → websocket-BSYV_KSw.js} +3 -3
  142. package/dist/websocket-BSYV_KSw.js.map +1 -0
  143. package/dist/websocket.d.ts +14 -3
  144. package/package.json +7 -7
  145. package/dist/deferred-index-build-F2GWu009.js.map +0 -1
  146. package/dist/doctor-_g2tHRtG.js.map +0 -1
  147. package/dist/ensure-collection-policies-DUpWJb5D.js.map +0 -1
  148. package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
  149. package/dist/ensure-tables-Bx1DYarz.js.map +0 -1
  150. package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
  151. package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
  152. package/dist/migrate-baseline-BeepEphh.js.map +0 -1
  153. package/dist/migrate-policy-stamps-cYMJ_9Ha.js.map +0 -1
  154. package/dist/open-rebase-CTNBmmH8.js.map +0 -1
  155. package/dist/plan-schema-CMNWvqIa.js.map +0 -1
  156. package/dist/policy-drift-IjD2AUD-.js.map +0 -1
  157. package/dist/push-policy-plan--oRXOj4X.js.map +0 -1
  158. package/dist/render-ddl-CzVcbbR1.js.map +0 -1
  159. package/dist/rls-enforcement-jZTv1yci.js +0 -534
  160. package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
  161. package/dist/websocket-D2y88dOa.js.map +0 -1
@@ -2,13 +2,13 @@
2
2
  import { createRequire as __createRequire } from "module";
3
3
  __createRequire(import.meta.url);
4
4
  import { a as buildSearchColumnSpec } from "../search-column-BM-GV6vH.js";
5
- import { a as diagnoseDbError } from "../cli-errors-D8s4z_3g.js";
6
- import { d as validatePolicyPgRoles, f as warnOnAnonymousGrants } from "../rls-enforcement-jZTv1yci.js";
5
+ import { a as diagnoseDbError } from "../cli-errors-C73Qy7WJ.js";
6
+ import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles } from "../rls-enforcement-CyUCPDH8.js";
7
7
  import { n as describeFailure, t as chalk } from "../source-fZb92pN8.js";
8
- import { n as formatPolicyDrift, r as hasDrift, t as checkPolicyDrift } from "../policy-drift-IjD2AUD-.js";
9
- import { n as loadCollections, r as runDoctor } from "../doctor-_g2tHRtG.js";
8
+ import { i as hasDrift, r as formatPolicyDrift, t as checkPolicyDrift } from "../policy-drift-Bx6663KD.js";
9
+ import { n as loadCollections, r as runDoctor } from "../doctor-DwMXljiq.js";
10
10
  import { isPostgresCollectionConfig } from "@rebasepro/types";
11
- import { getTableName, relationalCollections } from "@rebasepro/common";
11
+ import { getTableName, relationalCollections, resolveJunctionSpecs } from "@rebasepro/common";
12
12
  import path from "path";
13
13
  //#region src/schema/doctor-policy-checks.ts
14
14
  /**
@@ -67,7 +67,7 @@ async function runPolicyChecks(collectionsPath, databaseUrl) {
67
67
  console.error(chalk.red(err instanceof Error ? err.message : String(err)));
68
68
  }
69
69
  warnOnAnonymousGrants(collections);
70
- const drift = await checkPolicyDrift(pool, collections);
70
+ const drift = await checkPolicyDrift(pool, collections, { adminRoleAvailable: "detect" });
71
71
  console.log("");
72
72
  if (hasDrift(drift)) {
73
73
  problems = true;
@@ -183,6 +183,140 @@ async function runSearchScaleCheck(collectionsPath, databaseUrl) {
183
183
  }
184
184
  }
185
185
  //#endregion
186
+ //#region src/schema/doctor-database.ts
187
+ /**
188
+ * `rebase doctor --database`: whether this database can host Rebase's request
189
+ * role(s) under the project's `rls` settings, read from the catalogue without
190
+ * changing anything.
191
+ *
192
+ * Lives beside `doctor-cli.ts` rather than inside it because that file runs
193
+ * `main()` on import; the rendering and the table list are tested here.
194
+ */
195
+ /**
196
+ * The tables Rebase serves, as the server would list them: every relational
197
+ * collection's table in its schema (`public` by default), and every junction
198
+ * table a many-to-many declares.
199
+ */
200
+ function managedTablesOf(collections) {
201
+ const relational = relationalCollections(collections);
202
+ const tables = /* @__PURE__ */ new Map();
203
+ const add = (schema, table) => tables.set(`${schema}.${table}`, {
204
+ schema,
205
+ table
206
+ });
207
+ for (const collection of relational) add(isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public", getTableName(collection));
208
+ for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);
209
+ return [...tables.values()];
210
+ }
211
+ /** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */
212
+ function preflightSchemasOf(collections) {
213
+ return Array.from(/* @__PURE__ */ new Set([
214
+ "public",
215
+ "rebase",
216
+ ...relationalCollections(collections).filter(isPostgresCollectionConfig).map((c) => c.schema).filter((s) => !!s)
217
+ ]));
218
+ }
219
+ var LEVEL_ORDER = [
220
+ "fail",
221
+ "warn",
222
+ "ok"
223
+ ];
224
+ var LEVEL_TITLE = {
225
+ fail: "Needs fixing before Rebase can serve requests here",
226
+ warn: "Worth a look",
227
+ ok: "Fine"
228
+ };
229
+ var LEVEL_MARK = {
230
+ fail: chalk.red("✗"),
231
+ warn: chalk.yellow("⚠"),
232
+ ok: chalk.green("✓")
233
+ };
234
+ /**
235
+ * The report, grouped by level, failures first. Each finding that is not fine
236
+ * shows the SQL to run as an administrator in gray, and the `rls` setting that
237
+ * would fit Rebase to the database instead.
238
+ */
239
+ function renderPreflightFindings(findings, settings) {
240
+ const lines = [];
241
+ lines.push(chalk.bold(" Database preflight"));
242
+ lines.push(chalk.gray(` Request role(s): ${settings.roles.join(", ")}. ` + (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(", ")}.` : "The other rls settings are at their defaults.")));
243
+ for (const level of LEVEL_ORDER) {
244
+ const group = findings.filter((f) => f.level === level);
245
+ if (group.length === 0) continue;
246
+ lines.push("");
247
+ lines.push(` ${LEVEL_TITLE[level]}`);
248
+ for (const finding of group) {
249
+ lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);
250
+ if (finding.sql) for (const sqlLine of finding.sql.split("\n")) lines.push(chalk.gray(` ${sqlLine}`));
251
+ if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? "or set" : "set"}: ${finding.setting}`));
252
+ }
253
+ }
254
+ return lines;
255
+ }
256
+ /** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */
257
+ function preflightStatus(findings) {
258
+ return findings.some((f) => f.level === "fail") ? "problems" : "ok";
259
+ }
260
+ /**
261
+ * Every table in `schemas` but `rebase`: what a project with no declared
262
+ * collections serves, since its API is introspected from the database.
263
+ */
264
+ async function everyTableIn(run, schemas) {
265
+ const names = schemas.filter((s) => s !== "rebase").map((s) => `'${s.replace(/'/g, "''")}'`);
266
+ if (names.length === 0) return [];
267
+ return (await run(`
268
+ SELECT n.nspname AS schema, c.relname AS name
269
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
270
+ WHERE n.nspname IN (${names.join(", ")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
271
+ ORDER BY 1, 2
272
+ `)).map((r) => ({
273
+ schema: String(r.schema),
274
+ table: String(r.name)
275
+ }));
276
+ }
277
+ /**
278
+ * Run the preflight against `databaseUrl` with the settings a command outside
279
+ * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
280
+ * and print it. Never reports `ok` for a check it could not run.
281
+ */
282
+ async function runDatabasePreflight(collectionsPath, databaseUrl) {
283
+ if (!databaseUrl) {
284
+ console.error(chalk.yellow(" ⚠ No DATABASE_URL — the database preflight did NOT run"));
285
+ return "unchecked";
286
+ }
287
+ const { loadCollections } = await import("../doctor-DwMXljiq.js").then((n) => n.t);
288
+ const { preflightDatabase } = await import("../database-preflight-DIauc8i5.js");
289
+ const { readRecordedRequestRoles } = await import("../rls-enforcement-CyUCPDH8.js").then((n) => n.y);
290
+ const { cliRlsSettings } = await import("../rls-settings-BCGMIig3.js").then((n) => n.a);
291
+ const { Pool } = await import("pg");
292
+ const pool = new Pool({ connectionString: databaseUrl });
293
+ try {
294
+ const run = async (text) => (await pool.query(text)).rows;
295
+ const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
296
+ const existing = new Set((await run("SELECT nspname FROM pg_namespace")).map((row) => String(row.nspname)));
297
+ const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));
298
+ const settings = cliRlsSettings(await readRecordedRequestRoles(run));
299
+ let managedTables = managedTablesOf(collections);
300
+ console.log("");
301
+ if (managedTables.length === 0) {
302
+ managedTables = await everyTableIn(run, schemas);
303
+ console.log(chalk.gray(" No declared collections: every table in public is treated as served, as an introspected project serves them."));
304
+ }
305
+ const findings = await preflightDatabase(run, settings, {
306
+ schemas,
307
+ managedTables
308
+ });
309
+ for (const line of renderPreflightFindings(findings, settings)) console.log(line);
310
+ console.log("");
311
+ return preflightStatus(findings);
312
+ } catch (err) {
313
+ console.error(chalk.red(" ✗ Could not run the database preflight:"), err instanceof Error ? err.message : String(err));
314
+ return "unchecked";
315
+ } finally {
316
+ await pool.end();
317
+ }
318
+ }
319
+ //#endregion
186
320
  //#region src/schema/doctor-cli.ts
187
321
  /**
188
322
  * CLI entry point for `rebase doctor`.
@@ -193,6 +327,7 @@ async function main() {
193
327
  const schemaArg = process.argv.find((a) => a.startsWith("--schema="));
194
328
  const sdkArg = process.argv.find((a) => a.startsWith("--sdk="));
195
329
  const policiesOnly = process.argv.includes("--policies");
330
+ const databaseOnly = process.argv.includes("--database");
196
331
  const collectionsPath = collectionsArg?.split("=")[1] ?? path.join("..", "config", "collections");
197
332
  const schemaPath = schemaArg?.split("=")[1] ?? path.join("src", "schema.generated.ts");
198
333
  const sdkPath = sdkArg?.split("=")[1] ?? path.join("..", "generated", "sdk", "database.types.ts");
@@ -206,7 +341,10 @@ async function main() {
206
341
  else dotenv.config({ quiet: true });
207
342
  } catch {}
208
343
  const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
209
- if (policiesOnly) process.exit(exitCodeForPolicyGate(await runPolicyChecks(collectionsPath, databaseUrl)));
344
+ if (policiesOnly || databaseOnly) {
345
+ const statuses = [...databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : [], ...policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : []];
346
+ process.exit(statuses.some((status) => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);
347
+ }
210
348
  const report = await runDoctor({
211
349
  collectionsPath: path.resolve(process.cwd(), collectionsPath),
212
350
  schemaPath: path.resolve(process.cwd(), schemaPath),
@@ -1 +1 @@
1
- {"version":3,"file":"doctor-cli.js","names":[],"sources":["../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a collections path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero collections. Any exception at all — a collection file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the collections describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsPath);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const collections: CollectionConfig[] = await loadCollections(resolvedPath);\n\n // Zero collections is not \"no drift\", it is nothing to compare. The\n // loader returns `[]` for a path that does not exist, so the commonest\n // way to get here is a `--collections` path resolved against the wrong\n // directory — which used to render as a green tick.\n if (collections.length === 0) {\n console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no collection\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the collection reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, collections as never);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(collections as never);\n\n const drift = await checkPolicyDrift(pool as never, collections);\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your collections\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every collection import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: collections searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the collections\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { isPostgresCollectionConfig, type CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { buildSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A collection whose search would be `ILIKE` over these fields. */\nexport interface IlikeSearchedCollection {\n slug: string;\n schema: string;\n table: string;\n /** The string properties the search reads. */\n fields: string[];\n}\n\n/**\n * The collections a search reaches without an index: no `search` block (or\n * one that does not build), and at least one property the default search\n * reads — a `string`, not an enum, not a uuid key (the rule in\n * `DrizzleConditionBuilder.buildSearchConditions`).\n */\nexport function ilikeSearchedCollections(collections: CollectionConfig[]): IlikeSearchedCollection[] {\n const found: IlikeSearchedCollection[] = [];\n for (const collection of relationalCollections(collections)) {\n if (!isPostgresCollectionConfig(collection)) continue;\n let indexed: boolean;\n try {\n indexed = buildSearchColumnSpec(collection) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = Object.entries(collection.properties ?? {})\n .filter(([, property]) => property.type === \"string\" && !property.enum && property.isId !== \"uuid\")\n .map(([key]) => key);\n const table = getTableName(collection);\n if (fields.length === 0 || !table) continue;\n found.push({ slug: collection.slug, schema: collection.schema ?? \"public\", table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedCollection[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedCollection & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per collection. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedCollection & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `collectionsPath`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(collectionsPath: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n const candidates = ilikeSearchedCollections(collections);\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\n\nasync function main() {\n const collectionsArg = process.argv.find((a) => a.startsWith(\"--collections=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n\n const collectionsPath = collectionsArg?.split(\"=\")[1] ?? path.join(\"..\", \"config\", \"collections\");\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly) {\n // Non-zero so this can gate CI — the whole point of the flag, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n process.exit(exitCodeForPolicyGate(await runPolicyChecks(collectionsPath, databaseUrl)));\n }\n\n const report = await runDoctor({\n collectionsPath: path.resolve(process.cwd(), collectionsPath),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(collectionsPath, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING);\n if (banner) {\n console.error(banner);\n } else {\n console.error(chalk.red(` ✗ Doctor failed: ${describeFailure(err)}`));\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAAsB,QAAkC;CACpE,OAAO,WAAW,OAAO,IAAI;AACjC;;;;;;;AAQA,eAAsB,gBAAgB,iBAAyB,aAAkD;CAC7G,IAAI,CAAC,aAAa;EACd,QAAQ,MAAM,MAAM,OAAO,qDAAqD,CAAC;EACjF,OAAO;CACX;CAEA,MAAM,eAAe,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe;CAChE,IAAI,WAAW;CACf,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,OAAO,IAAI,KAAK,EAAE,kBAAkB,YAAY,CAAC;CACvD,IAAI;EACA,MAAM,cAAkC,MAAM,gBAAgB,YAAY;EAM1E,IAAI,YAAY,WAAW,GAAG;GAC1B,QAAQ,MAAM,MAAM,IAAI,+BAA+B,cAAc,CAAC;GACtE,QAAQ,MAAM,MAAM,KAAK,iGAAiG,CAAC;GAC3H,OAAO;EACX;EAEA,MA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.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a collections path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero collections. Any exception at all — a collection file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the collections describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsPath);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const collections: CollectionConfig[] = await loadCollections(resolvedPath);\n\n // Zero collections is not \"no drift\", it is nothing to compare. The\n // loader returns `[]` for a path that does not exist, so the commonest\n // way to get here is a `--collections` path resolved against the wrong\n // directory — which used to render as a green tick.\n if (collections.length === 0) {\n console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no collection\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the collection reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, collections);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(collections);\n\n // Where a boot on this database writes the server-or-admin policies:\n // `TO public` where its admin switch is not live, and that is no drift.\n const drift = await checkPolicyDrift(pool, collections, { adminRoleAvailable: \"detect\" });\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your collections\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every collection import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: collections searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the collections\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { isPostgresCollectionConfig, type CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { buildSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A collection whose search would be `ILIKE` over these fields. */\nexport interface IlikeSearchedCollection {\n slug: string;\n schema: string;\n table: string;\n /** The string properties the search reads. */\n fields: string[];\n}\n\n/**\n * The collections a search reaches without an index: no `search` block (or\n * one that does not build), and at least one property the default search\n * reads — a `string`, not an enum, not a uuid key (the rule in\n * `DrizzleConditionBuilder.buildSearchConditions`).\n */\nexport function ilikeSearchedCollections(collections: CollectionConfig[]): IlikeSearchedCollection[] {\n const found: IlikeSearchedCollection[] = [];\n for (const collection of relationalCollections(collections)) {\n if (!isPostgresCollectionConfig(collection)) continue;\n let indexed: boolean;\n try {\n indexed = buildSearchColumnSpec(collection) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = Object.entries(collection.properties ?? {})\n .filter(([, property]) => property.type === \"string\" && !property.enum && property.isId !== \"uuid\")\n .map(([key]) => key);\n const table = getTableName(collection);\n if (fields.length === 0 || !table) continue;\n found.push({ slug: collection.slug, schema: collection.schema ?? \"public\", table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedCollection[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedCollection & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per collection. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedCollection & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `collectionsPath`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(collectionsPath: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n const candidates = ilikeSearchedCollections(collections);\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","/**\n * `rebase doctor --database`: whether this database can host Rebase's request\n * role(s) under the project's `rls` settings, read from the catalogue without\n * changing anything.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import; the rendering and the table list are tested here.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName, relationalCollections, resolveJunctionSpecs } from \"@rebasepro/common\";\nimport type { PreflightFinding } from \"../security/database-preflight\";\nimport type { ManagedTable, RawSqlRunner } from \"../security/rls-enforcement\";\nimport type { RlsSettings } from \"../security/rls-settings\";\nimport type { PolicyCheckStatus } from \"./doctor-policy-checks\";\n\n/**\n * The tables Rebase serves, as the server would list them: every relational\n * collection's table in its schema (`public` by default), and every junction\n * table a many-to-many declares.\n */\nexport function managedTablesOf(collections: CollectionConfig[]): ManagedTable[] {\n const relational = relationalCollections(collections);\n const tables = new Map<string, ManagedTable>();\n const add = (schema: string, table: string) => tables.set(`${schema}.${table}`, { schema, table });\n for (const collection of relational) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n add(schema, getTableName(collection));\n }\n for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);\n return [...tables.values()];\n}\n\n/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */\nexport function preflightSchemasOf(collections: CollectionConfig[]): string[] {\n return Array.from(new Set([\n \"public\",\n \"rebase\",\n ...relationalCollections(collections)\n .filter(isPostgresCollectionConfig)\n .map((c) => c.schema)\n .filter((s): s is string => !!s)\n ]));\n}\n\nconst LEVEL_ORDER: PreflightFinding[\"level\"][] = [\"fail\", \"warn\", \"ok\"];\nconst LEVEL_TITLE: Record<PreflightFinding[\"level\"], string> = {\n fail: \"Needs fixing before Rebase can serve requests here\",\n warn: \"Worth a look\",\n ok: \"Fine\"\n};\nconst LEVEL_MARK: Record<PreflightFinding[\"level\"], string> = {\n fail: chalk.red(\"✗\"),\n warn: chalk.yellow(\"⚠\"),\n ok: chalk.green(\"✓\")\n};\n\n/**\n * The report, grouped by level, failures first. Each finding that is not fine\n * shows the SQL to run as an administrator in gray, and the `rls` setting that\n * would fit Rebase to the database instead.\n */\nexport function renderPreflightFindings(\n findings: readonly PreflightFinding[],\n settings: Pick<RlsSettings, \"roles\" | \"nonDefaults\">\n): string[] {\n const lines: string[] = [];\n lines.push(chalk.bold(\" Database preflight\"));\n lines.push(chalk.gray(\n ` Request role(s): ${settings.roles.join(\", \")}. ` +\n (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(\", \")}.` : \"The other rls settings are at their defaults.\")\n ));\n for (const level of LEVEL_ORDER) {\n const group = findings.filter((f) => f.level === level);\n if (group.length === 0) continue;\n lines.push(\"\");\n lines.push(` ${LEVEL_TITLE[level]}`);\n for (const finding of group) {\n lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);\n if (finding.sql) {\n for (const sqlLine of finding.sql.split(\"\\n\")) lines.push(chalk.gray(` ${sqlLine}`));\n }\n if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? \"or set\" : \"set\"}: ${finding.setting}`));\n }\n }\n return lines;\n}\n\n/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */\nexport function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus {\n return findings.some((f) => f.level === \"fail\") ? \"problems\" : \"ok\";\n}\n\n/**\n * Every table in `schemas` but `rebase`: what a project with no declared\n * collections serves, since its API is introspected from the database.\n */\nasync function everyTableIn(run: RawSqlRunner, schemas: readonly string[]): Promise<ManagedTable[]> {\n const names = schemas.filter((s) => s !== \"rebase\").map((s) => `'${s.replace(/'/g, \"''\")}'`);\n if (names.length === 0) return [];\n const rows = await run(`\n SELECT n.nspname AS schema, c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname IN (${names.join(\", \")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n ORDER BY 1, 2\n `);\n return rows.map((r) => ({ schema: String(r.schema), table: String(r.name) }));\n}\n\n/**\n * Run the preflight against `databaseUrl` with the settings a command outside\n * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),\n * and print it. Never reports `ok` for a check it could not run.\n */\nexport async function runDatabasePreflight(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — the database preflight did NOT run\"));\n return \"unchecked\";\n }\n\n const { loadCollections } = await import(\"./doctor\");\n const { preflightDatabase } = await import(\"../security/database-preflight\");\n const { readRecordedRequestRoles } = await import(\"../security/rls-enforcement\");\n const { cliRlsSettings } = await import(\"../security/rls-settings\");\n const { Pool } = await import(\"pg\");\n\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const run: RawSqlRunner = async (text) => (await pool.query(text)).rows as Record<string, unknown>[];\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n // Only the schemas that exist: the SQL a finding carries grants on each\n // one, and a GRANT on a missing schema fails the whole script. A boot\n // grants on the ones it creates itself.\n const existing = new Set((await run(\"SELECT nspname FROM pg_namespace\")).map((row) => String(row.nspname)));\n const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n\n let managedTables = managedTablesOf(collections);\n console.log(\"\");\n if (managedTables.length === 0) {\n managedTables = await everyTableIn(run, schemas);\n console.log(chalk.gray(\" No declared collections: every table in public is treated as served, as an introspected project serves them.\"));\n }\n\n const findings = await preflightDatabase(run, settings, { schemas, managedTables });\n for (const line of renderPreflightFindings(findings, settings)) console.log(line);\n console.log(\"\");\n return preflightStatus(findings);\n } catch (err) {\n console.error(chalk.red(\" ✗ Could not run the database preflight:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { runDatabasePreflight } from \"./doctor-database\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\n\nasync function main() {\n const collectionsArg = process.argv.find((a) => a.startsWith(\"--collections=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n // --database runs only the preflight of the database itself: whether the\n // request role(s) can be set up and used here under the project's `rls`\n // settings. Read-only, and a gate like --policies.\n const databaseOnly = process.argv.includes(\"--database\");\n\n const collectionsPath = collectionsArg?.split(\"=\")[1] ?? path.join(\"..\", \"config\", \"collections\");\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly || databaseOnly) {\n // Non-zero so this can gate CI — the whole point of the flags, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n const statuses = [\n ...(databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : []),\n ...(policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : [])\n ];\n process.exit(statuses.some(status => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);\n }\n\n const report = await runDoctor({\n collectionsPath: path.resolve(process.cwd(), collectionsPath),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(collectionsPath, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING);\n if (banner) {\n console.error(banner);\n } else {\n console.error(chalk.red(` ✗ Doctor failed: ${describeFailure(err)}`));\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAAsB,QAAkC;CACpE,OAAO,WAAW,OAAO,IAAI;AACjC;;;;;;;AAQA,eAAsB,gBAAgB,iBAAyB,aAAkD;CAC7G,IAAI,CAAC,aAAa;EACd,QAAQ,MAAM,MAAM,OAAO,qDAAqD,CAAC;EACjF,OAAO;CACX;CAEA,MAAM,eAAe,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe;CAChE,IAAI,WAAW;CACf,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,OAAO,IAAI,KAAK,EAAE,kBAAkB,YAAY,CAAC;CACvD,IAAI;EACA,MAAM,cAAkC,MAAM,gBAAgB,YAAY;EAM1E,IAAI,YAAY,WAAW,GAAG;GAC1B,QAAQ,MAAM,MAAM,IAAI,+BAA+B,cAAc,CAAC;GACtE,QAAQ,MAAM,MAAM,KAAK,iGAAiG,CAAC;GAC3H,OAAO;EACX;EAEA,MAAM,SAAS,OAAO,UAAkB,MAAM,KAAK,MAAM,IAAI,EAAA,CAAG;EAUhE,IA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
@@ -0,0 +1,27 @@
1
+ import type { CollectionConfig } from "@rebasepro/types";
2
+ import type { PreflightFinding } from "../security/database-preflight.js";
3
+ import type { ManagedTable } from "../security/rls-enforcement.js";
4
+ import type { RlsSettings } from "../security/rls-settings.js";
5
+ import type { PolicyCheckStatus } from "./doctor-policy-checks.js";
6
+ /**
7
+ * The tables Rebase serves, as the server would list them: every relational
8
+ * collection's table in its schema (`public` by default), and every junction
9
+ * table a many-to-many declares.
10
+ */
11
+ export declare function managedTablesOf(collections: CollectionConfig[]): ManagedTable[];
12
+ /** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */
13
+ export declare function preflightSchemasOf(collections: CollectionConfig[]): string[];
14
+ /**
15
+ * The report, grouped by level, failures first. Each finding that is not fine
16
+ * shows the SQL to run as an administrator in gray, and the `rls` setting that
17
+ * would fit Rebase to the database instead.
18
+ */
19
+ export declare function renderPreflightFindings(findings: readonly PreflightFinding[], settings: Pick<RlsSettings, "roles" | "nonDefaults">): string[];
20
+ /** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */
21
+ export declare function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus;
22
+ /**
23
+ * Run the preflight against `databaseUrl` with the settings a command outside
24
+ * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
25
+ * and print it. Never reports `ok` for a check it could not run.
26
+ */
27
+ export declare function runDatabasePreflight(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus>;
@@ -1,9 +1,9 @@
1
- import type { NodePgDatabase } from "drizzle-orm/node-postgres";
2
1
  import { type DdlBootstrapper } from "@rebasepro/server";
2
+ import type { PgSqlDatabase } from "../interfaces.js";
3
3
  /**
4
4
  * A {@link DdlBootstrapper} that runs its statements through `db.execute`.
5
5
  *
6
6
  * @param db the Drizzle handle the calling store already holds
7
7
  * @param scope log prefix identifying the caller, e.g. `"channel-presence"`
8
8
  */
9
- export declare function drizzleDdlBootstrapper(db: NodePgDatabase<Record<string, unknown>>, scope: string): DdlBootstrapper;
9
+ export declare function drizzleDdlBootstrapper(db: PgSqlDatabase<Record<string, unknown>>, scope: string): DdlBootstrapper;
@@ -120,7 +120,9 @@ export type PolicyStampState = "current" | "stale" | "unstamped";
120
120
  * `search_path`: call it under the path the stamps were written under (a
121
121
  * boot's, `public` unless the URL pins one), or a current stamp reads stale.
122
122
  */
123
- export declare function readPolicyStamps(client: Queryable, collections: CollectionConfig[]): Promise<Map<string, Map<string, PolicyStampState>>>;
123
+ export declare function readPolicyStamps(client: Queryable, collections: CollectionConfig[], options?: {
124
+ adminRoleAvailable?: boolean;
125
+ }): Promise<Map<string, Map<string, PolicyStampState>>>;
124
126
  /**
125
127
  * For each of `policies`, whether the `CREATE POLICY` the plan renders for it
126
128
  * stores the definition the database holds now: made under a probe name on
@@ -144,6 +146,7 @@ export declare function probeRenderedPolicies(client: Queryable, collections: Co
144
146
  name: string;
145
147
  }[], options?: {
146
148
  searchPath?: string;
149
+ adminRoleAvailable?: boolean;
147
150
  }): Promise<Map<string, boolean>>;
148
151
  export interface TableLockResult {
149
152
  /** Tables RLS is now on for. */
@@ -210,9 +213,18 @@ export declare function tablesRlsWouldEnable(client: Queryable, collections: Col
210
213
  * others, with backoff, within a retry budget for the whole step; one still
211
214
  * held after that is reported in `deferred` — its transaction rolled back, so
212
215
  * it is exactly as it was before this boot — or, if RLS was off on it, closed
213
- * by revoking the user role's grant, as any table RLS cannot be enabled on is.
216
+ * by revoking the user role's grant, like every table RLS cannot be enabled on.
214
217
  */
215
- export declare function ensureCollectionPolicies(client: Queryable, collections: CollectionConfig[], log?: (message: string) => void, options?: BootLockOptions): Promise<PolicyEnsureResult>;
218
+ export declare function ensureCollectionPolicies(client: Queryable, collections: CollectionConfig[], log?: (message: string) => void, options?: BootLockOptions & {
219
+ /**
220
+ * Whether this server's admin switch is live (`settleAdminSwitch`).
221
+ * `false` writes the server-or-admin policies `TO public` and creates
222
+ * no role: written `TO rebase_admin` while admin requests run as the
223
+ * request role, they would refuse every admin caller. Left out, they
224
+ * go `TO rebase_admin` wherever that role exists or can be made.
225
+ */
226
+ adminRoleAvailable?: boolean;
227
+ }): Promise<PolicyEnsureResult>;
216
228
  /**
217
229
  * The warning a boot gives for one entry of {@link PolicyEnsureResult.rulesDropped}:
218
230
  * each policy, what it means for the table, and the likely cause.
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { t as main } from "../generate-drizzle-schema-taNTu3xv.js";
3
+ import { t as main } from "../generate-drizzle-schema-BIUqhSzh.js";
4
4
  //#region src/schema/bin/generate-drizzle-schema.ts
5
5
  /**
6
6
  * The built entry point for `generate-drizzle-schema`.
@@ -180,6 +180,8 @@ export interface CollectionPolicyPlan {
180
180
  /** One policy of a {@link CollectionPolicyPlan}, as the statements that make it. */
181
181
  export interface PolicyApplyPlan {
182
182
  name: string;
183
+ /** Written `TO rebase_admin` by the compiler's choice (`rls.adminPolicies`). */
184
+ adminTarget: boolean;
183
185
  restrictive: boolean;
184
186
  /** Its `DROP POLICY IF EXISTS` / `CREATE POLICY` statements — a slice of `policyStatements`. */
185
187
  statements: string[];
@@ -194,7 +196,9 @@ export interface PolicyApplyPlan {
194
196
  * The same policies `policies.sql` carries, from the same plan, so boot and
195
197
  * `db push` produce identical RLS from identical collections.
196
198
  */
197
- export declare const planCollectionPolicies: (allCollections: CollectionConfig[]) => CollectionPolicyPlan[];
199
+ export declare const planCollectionPolicies: (allCollections: CollectionConfig[], options?: {
200
+ adminRoleAvailable?: boolean;
201
+ }) => CollectionPolicyPlan[];
198
202
  /**
199
203
  * The `generated column → column it reads` edges a project's `search` blocks
200
204
  * imply, derived from the collections alone.
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { r as out } from "../source-fZb92pN8.js";
4
- import { r as writePostgresDdl } from "../generate-files-DbwU8Btx.js";
4
+ import { r as writePostgresDdl } from "../generate-files-BkiRFoV1.js";
5
5
  import path from "path";
6
6
  //#region src/schema/generate-postgres-ddl.ts
7
7
  /**
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Adopting an index the database already has, instead of building a twin.
3
+ *
4
+ * A declared index is found by its derived name (`collection-index.ts`), so an
5
+ * index someone made by hand — or one an introspected database arrived with —
6
+ * is invisible to it however exactly it matches the declaration: boot and
7
+ * `db push` built the same index again under the derived name, and every write
8
+ * to the table then maintained two. Declaring the indexes an application
9
+ * already has is the first thing anyone does when they bring a database to
10
+ * Rebase, so that was the common case, not an edge.
11
+ *
12
+ * So before an index is built, an existing one with the same definition on the
13
+ * same table takes the derived name (`ALTER INDEX … RENAME TO …`: a catalogue
14
+ * update, no rebuild, a brief lock). From then on it is the declared index:
15
+ * found by name, kept by push, dropped when the declaration is removed.
16
+ *
17
+ * "The same definition" is read from the catalogue part by part, not by
18
+ * comparing SQL text: the access method, uniqueness, the key columns in order
19
+ * with their direction and NULLS placement, the INCLUDE columns, the predicate,
20
+ * and — because two indexes over the same columns can still answer different
21
+ * queries — that every key uses its type's default operator class and the
22
+ * column's own collation. An index that differs in any of those, is over an
23
+ * expression, backs a constraint, is INVALID, or already carries a Rebase name
24
+ * is left alone, and the declared one is built beside it as before.
25
+ *
26
+ * A partial index is adopted only when the two predicates read the same once
27
+ * Postgres's own spelling is normalised away (identifier quotes, casts on
28
+ * literals, parentheses, case). A wrong adoption would leave a declared index
29
+ * answering a narrower question than the one declared, so a predicate this
30
+ * cannot read as the same is not adopted.
31
+ */
32
+ import { type CollectionIndexSpec } from "./collection-index.js";
33
+ /** What the catalogue says about one existing index. */
34
+ export interface ExistingIndexShape {
35
+ schema: string;
36
+ table: string;
37
+ index: string;
38
+ method: string;
39
+ unique: boolean;
40
+ /** Key columns in order; `null` where a key is an expression. */
41
+ keys: (string | null)[];
42
+ /** `pg_index.indoption` per key: bit 1 is DESC, bit 2 is NULLS FIRST. */
43
+ options: number[];
44
+ include: string[];
45
+ /** `pg_get_expr` of the predicate, or `null` for a whole-table index. */
46
+ predicate: string | null;
47
+ /** Every key uses its type's default operator class and the column's collation. */
48
+ defaultOpclassAndCollation: boolean;
49
+ /** Backs a primary key, unique or exclusion constraint. */
50
+ constraint: boolean;
51
+ /** False when a cancelled concurrent build left it unusable. */
52
+ valid: boolean;
53
+ }
54
+ /** An existing index taking a declared index's name. */
55
+ export interface IndexAdoption {
56
+ schema: string;
57
+ table: string;
58
+ /** Its name now. */
59
+ from: string;
60
+ /** The declared index's derived name. */
61
+ to: string;
62
+ }
63
+ /**
64
+ * Every index on an ordinary or partitioned table in `schemas`, as
65
+ * {@link ExistingIndexShape} rows. The schema names are written in as quoted
66
+ * literals: the boot's catalogue reader runs its queries without parameters.
67
+ */
68
+ export declare const indexShapesSql: (schemas: readonly string[]) => string;
69
+ /** Something that runs a query: a pg client or pool, the boot's catalogue reader, a test double. */
70
+ export interface ShapeQueryable {
71
+ query<R>(text: string): Promise<{
72
+ rows: R[];
73
+ }>;
74
+ }
75
+ /** Read the {@link ExistingIndexShape}s of the given schemas. */
76
+ export declare function readIndexShapes(client: ShapeQueryable, schemas: readonly string[]): Promise<ExistingIndexShape[]>;
77
+ /** Whether `shape` is `spec` under another name. */
78
+ export declare function indexMatchesSpec(spec: CollectionIndexSpec, shape: ExistingIndexShape): boolean;
79
+ /**
80
+ * The renames that make existing indexes the declared ones: for each spec
81
+ * whose derived name the catalogue does not hold, the first existing index on
82
+ * its table with the same definition — never one carrying a Rebase name (it is
83
+ * some declaration's, or one a removed declaration left for push to drop), and
84
+ * never the same one twice.
85
+ */
86
+ export declare function planIndexAdoptions(specs: readonly CollectionIndexSpec[], shapes: readonly ExistingIndexShape[]): IndexAdoption[];
87
+ /** The `ALTER INDEX … RENAME TO …` for one adoption. */
88
+ export declare function indexAdoptionStatement(adoption: IndexAdoption): string;
89
+ /**
90
+ * A migration's `CREATE INDEX` of a declared (Rebase-named) index, written
91
+ * `CREATE INDEX IF NOT EXISTS`. `rebase db migrate` adopts an identical
92
+ * existing index before it applies — renaming it to the declared name — and
93
+ * the migration's own statement then finds it there instead of failing on the
94
+ * name. An index named any other way is left as Atlas wrote it.
95
+ */
96
+ export declare function declaredIndexesIfNotExists(migrationSql: string): {
97
+ sql: string;
98
+ rewritten: number;
99
+ };
@@ -138,7 +138,8 @@ export interface SchemaMetadata {
138
138
  * two things hold:
139
139
  *
140
140
  * - **Every key column can carry `isId`,** which exists on string and number
141
- * properties only. Read from the column's SQL type, not a data sample: a
141
+ * properties, and on a date property over a `date` column (a calendar day).
142
+ * Read from the column's SQL type, not a data sample: a
142
143
  * `line_no` holding only 1s is not a boolean. A key with a column of another
143
144
  * type — pagila's `payment` is keyed on a timestamp too — can be marked on
144
145
  * some of its columns only, and those would be read as the whole key.
@@ -1,11 +1,11 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { n as require_arg, o as __toESM, t as promptConfirm } from "../cli-prompt-DXG0yk-h.js";
4
- import { u as pinSearchPath } from "../connection-COuS5Fm-.js";
5
- import { a as diagnoseDbError } from "../cli-errors-D8s4z_3g.js";
4
+ import { u as pinSearchPath } from "../connection-C1zXTPJq.js";
5
+ import { a as diagnoseDbError } from "../cli-errors-C73Qy7WJ.js";
6
6
  import { a as outWarn, i as outError, r as out, t as chalk } from "../source-fZb92pN8.js";
7
7
  import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-DevUrzll.js";
8
- import { a as compositeKeySkipReason, c as generateIndexContent, d as mergeIndexContent, f as safeHostFromUrl, h as lookupCandidates, i as buildTablesMap, m as classifyTables, o as describeRlsOffTables, r as buildEnumMap, s as generateCollectionFile } from "../introspect-db-logic-DgQVzccW.js";
8
+ import { a as compositeKeySkipReason, c as generateIndexContent, d as mergeIndexContent, f as safeHostFromUrl, h as lookupCandidates, i as buildTablesMap, m as classifyTables, o as describeRlsOffTables, r as buildEnumMap, s as generateCollectionFile } from "../introspect-db-logic-DWqAEURB.js";
9
9
  import pg from "pg";
10
10
  import path from "path";
11
11
  import fs from "fs";
@@ -6,7 +6,7 @@ import type { Queryable } from "../security/policy-drift.js";
6
6
  * unstamped costs the next boot a re-apply of its table, which is what every
7
7
  * boot after a migrate did before this.
8
8
  */
9
- export declare function stampMigratedPolicies(databaseUrl: string, collectionsPath: string): Promise<void>;
9
+ export declare function stampMigratedPolicies(databaseUrl: string, collectionsPath: string, adminRoleAvailable?: boolean): Promise<void>;
10
10
  /**
11
11
  * Stamp every declared policy whose stored definition its rule would store
12
12
  * as it is, and none other.
@@ -18,6 +18,24 @@ export declare function stampMigratedPolicies(databaseUrl: string, collectionsPa
18
18
  */
19
19
  export declare function stampPoliciesStoredAsRendered(client: Queryable, collections: CollectionConfig[], options?: {
20
20
  searchPath?: string;
21
+ adminRoleAvailable?: boolean;
21
22
  }): Promise<{
22
23
  stamped: number;
23
24
  }>;
25
+ /**
26
+ * Where the admin switch is not live, move the server-or-admin policies a
27
+ * migration just wrote `TO rebase_admin` back `TO public`, as `db push` and a
28
+ * provisioning boot write them.
29
+ *
30
+ * A migration replays `policies.sql` as `db generate` wrote it, and that cannot
31
+ * know the database it will run on. Left `TO rebase_admin` while admin requests
32
+ * still run as the request role, those policies refuse every admin caller —
33
+ * `dataAsAdmin` in crons, jobs and functions included — and a boot with
34
+ * `REBASE_PROVISION=false` never puts them right.
35
+ *
36
+ * This is the boot's own ensure under the fallback plan, so a table whose
37
+ * policies are already what that plan makes is left alone.
38
+ *
39
+ * @returns how many policies were written again.
40
+ */
41
+ export declare function moveMigratedAdminPoliciesToPublic(client: Queryable, collections: CollectionConfig[], log?: (message: string) => void): Promise<number>;