@rebasepro/server-postgres 0.29.1 → 0.29.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/{BranchService-BIIBF5ZL.js → BranchService-CrXvcES2.js} +3 -3
  2. package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-CrXvcES2.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +64 -4
  4. package/dist/PostgresBootstrapper.d.ts +27 -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-QcOpmRpQ.js → backup-cli-CTKCOLpX.js} +3 -3
  9. package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
  10. package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CqGIwSYx.js} +2 -2
  11. package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
  12. package/dist/{cli-console-DTsm96lW.js → cli-console-DBPw-oAz.js} +6 -6
  13. package/dist/{cli-console-DTsm96lW.js.map → cli-console-DBPw-oAz.js.map} +1 -1
  14. package/dist/{cli-errors-DwqFRIWz.js → cli-errors-DYTxnLbW.js} +5 -5
  15. package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
  16. package/dist/cli.js +185 -49
  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-D5JtPt8i.js → database-preflight-iBpT7-vv.js} +36 -3
  23. package/dist/database-preflight-iBpT7-vv.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/{deferred-index-build-B8feKnUj.js → deferred-index-build-BCU9RoHK.js} +18 -6
  27. package/dist/deferred-index-build-BCU9RoHK.js.map +1 -0
  28. package/dist/{doctor-BaR11xUe.js → doctor-Kg1oUK0Q.js} +11 -11
  29. package/dist/doctor-Kg1oUK0Q.js.map +1 -0
  30. package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-Bo-_fDAy.js} +25 -15
  31. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-DCJINkT_.js} +11 -8
  33. package/dist/ensure-collection-tables-DCJINkT_.js.map +1 -0
  34. package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-BPGaGh0y.js} +4 -4
  35. package/dist/ensure-tables-BPGaGh0y.js.map +1 -0
  36. package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-YAgOZS4I.js} +3 -3
  37. package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
  38. package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
  39. package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
  40. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-LTLZvt6r.js} +3 -3
  41. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
  42. package/dist/{generate-files-Bl3_D_oP.js → generate-files-CsaVzatS.js} +3 -3
  43. package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-CsaVzatS.js.map} +1 -1
  44. package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +45 -7
  45. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
  46. package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-By4dxyTH.js} +8 -5
  47. package/dist/generated-schema-diff-By4dxyTH.js.map +1 -0
  48. package/dist/history/HistoryService.d.ts +2 -3
  49. package/dist/history/ensure-history-table.d.ts +8 -3
  50. package/dist/index.es.js +15 -15
  51. package/dist/interfaces.d.ts +24 -2
  52. package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
  53. package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
  54. package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CmWXL7qx.js} +163 -502
  55. package/dist/migrate-baseline-CmWXL7qx.js.map +1 -0
  56. package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-BN_Qad6c.js} +42 -13
  57. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +1 -0
  58. package/dist/{open-rebase-CiO_sjMT.js → open-rebase-40paQfVW.js} +1401 -655
  59. package/dist/open-rebase-40paQfVW.js.map +1 -0
  60. package/dist/open-rebase.d.ts +1 -1
  61. package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-DJHjCF7-.js} +2 -2
  62. package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
  63. package/dist/pipelined-transaction.d.ts +24 -37
  64. package/dist/{plan-schema-BYxOzflz.js → plan-schema-vJd3UEmT.js} +41 -11
  65. package/dist/plan-schema-vJd3UEmT.js.map +1 -0
  66. package/dist/{policy-drift-DKuTJHfc.js → policy-drift-C-m0uWHH.js} +78 -10
  67. package/dist/policy-drift-C-m0uWHH.js.map +1 -0
  68. package/dist/push-index-adoption-Cp7oZxSl.js +22 -0
  69. package/dist/push-index-adoption-Cp7oZxSl.js.map +1 -0
  70. package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-DbwKGtQT.js} +4 -4
  71. package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
  72. package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-CLcgsEPt.js} +2 -2
  73. package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
  74. package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-BthD0E9W.js} +4 -4
  75. package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
  76. package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BgcrroxQ.js} +14 -8
  77. package/dist/push-policy-plan-BgcrroxQ.js.map +1 -0
  78. package/dist/read-routing.d.ts +10 -30
  79. package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Ci3S_SoI.js} +34 -3
  80. package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
  81. package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Dy1EgJU9.js} +10 -10
  82. package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
  83. package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-GHTJnPMV.js} +2 -2
  84. package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
  85. package/dist/rls-bootstrap-sql-kPX4-MB1.js +549 -0
  86. package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
  87. package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-Cc_UhOxb.js} +316 -10
  88. package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
  89. package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
  90. package/dist/rls-settings-BCGMIig3.js.map +1 -0
  91. package/dist/schema/doctor-cli.js +9 -9
  92. package/dist/schema/doctor-cli.js.map +1 -1
  93. package/dist/schema/drizzle-ddl.d.ts +2 -2
  94. package/dist/schema/ensure-collection-policies.d.ts +23 -3
  95. package/dist/schema/generate-drizzle-schema.js +1 -1
  96. package/dist/schema/generate-postgres-ddl-logic.d.ts +14 -1
  97. package/dist/schema/generate-postgres-ddl.js +1 -1
  98. package/dist/schema/index-adoption.d.ts +99 -0
  99. package/dist/schema/introspect-db-logic.d.ts +2 -1
  100. package/dist/schema/introspect-db.js +3 -3
  101. package/dist/schema/migrate-policy-stamps.d.ts +19 -1
  102. package/dist/schema/plan/diff-plan.d.ts +8 -1
  103. package/dist/schema/plan/render-ddl.d.ts +7 -0
  104. package/dist/schema/plan/types.d.ts +15 -0
  105. package/dist/schema/push-index-adoption.d.ts +10 -0
  106. package/dist/schema/push-policy-plan.d.ts +5 -1
  107. package/dist/schema/rls-bootstrap-sql.d.ts +19 -2
  108. package/dist/schema/search-column.d.ts +2 -2
  109. package/dist/search-column-BM-GV6vH.js.map +1 -1
  110. package/dist/security/policy-drift.d.ts +31 -1
  111. package/dist/security/rls-enforcement.d.ts +118 -1
  112. package/dist/security/rls-settings.d.ts +33 -0
  113. package/dist/services/FetchService.d.ts +33 -8
  114. package/dist/services/PersistService.d.ts +75 -4
  115. package/dist/services/RelationService.d.ts +1 -1
  116. package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
  117. package/dist/services/channel-bus/index.d.ts +2 -2
  118. package/dist/services/channel-history.d.ts +2 -2
  119. package/dist/services/channel-presence.d.ts +3 -3
  120. package/dist/services/dataService.d.ts +6 -2
  121. package/dist/services/realtimeService.d.ts +18 -5
  122. package/dist/services/socket-liveness.d.ts +6 -1
  123. package/dist/types.d.ts +1 -1
  124. package/dist/utils/drizzle-conditions.d.ts +12 -0
  125. package/dist/utils/positional-params.d.ts +40 -0
  126. package/dist/{websocket-B33YjKhs.js → websocket-B7ex6AQM.js} +3 -3
  127. package/dist/websocket-B7ex6AQM.js.map +1 -0
  128. package/dist/websocket.d.ts +14 -3
  129. package/package.json +7 -7
  130. package/dist/database-preflight-D5JtPt8i.js.map +0 -1
  131. package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
  132. package/dist/doctor-BaR11xUe.js.map +0 -1
  133. package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
  134. package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
  135. package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
  136. package/dist/generate-postgres-ddl-logic-BC3JA93M.js.map +0 -1
  137. package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
  138. package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
  139. package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
  140. package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
  141. package/dist/open-rebase-CiO_sjMT.js.map +0 -1
  142. package/dist/plan-schema-BYxOzflz.js.map +0 -1
  143. package/dist/policy-drift-DKuTJHfc.js.map +0 -1
  144. package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
  145. package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
  146. package/dist/rls-enforcement-BO618rnr.js.map +0 -1
  147. package/dist/rls-settings-De5NoHHy.js.map +0 -1
  148. package/dist/websocket-B33YjKhs.js.map +0 -1
@@ -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-database.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","/**\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,IAAI;GACA,MAAM,OAAO,UAAU;EAC3B,SAAS,KAAK;GACV,QAAQ,MAAM,MAAM,KAAK,+BAA+B,CAAC;GACzD,QAAQ,MAAM,MAAM,IAAI,mCAAmC,GAAG,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;GAC9G,OAAO;EACX;EAIA,IAAI;GACA,MAAM,sBAAsB,QAAQ,WAAoB;GACxD,QAAQ,IAAI,MAAM,MAAM,4CAA4C,CAAC;EACzE,SAAS,KAAK;GACV,WAAW;GACX,QAAQ,IAAI,EAAE;GACd,QAAQ,MAAM,MAAM,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,CAAC;EAC7E;EAIA,sBAAs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IAAI,CAAC;CACrF;CAEA,MAAM,SAAS,MAAM,UAAU;EAC3B,iBAAiB,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe;EAC5D,YAAY,KAAK,QAAQ,QAAQ,IAAI,GAAG,UAAU;EAClD,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO;EAC5C,aAAa,eAAe,KAAA;CAChC,CAAC;CAED,MAAM,eAAe,MAAM,gBAAgB,iBAAiB,WAAW;CAGvE,MAAM,oBAAoB,iBAAiB,WAAW;CAYtD,MAAM,UAAU;EAAC,OAAO;EAAqB,OAAO;EAAkB,OAAO;CAAgB,CAAC,CACzF,MAAK,UAAS,MAAM,OAAO;CAChC,IAAI,OAAO,QAAQ,SAAS,KAAK,iBAAiB,cAAc,SAC5D,QAAQ,KAAK,CAAC;AAEtB;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAKlB,MAAM,SAAS,gBAAgB,KAAK,QAAQ,IAAI,gBAAgB,QAAQ,IAAI,uBAAuB;CACnG,IAAI,QACA,QAAQ,MAAM,MAAM;MAEpB,QAAQ,MAAM,MAAM,IAAI,sBAAsB,gBAAgB,GAAG,GAAG,CAAC;CAEzE,QAAQ,KAAK,CAAC;AAClB,CAAC"}
1
+ {"version":3,"file":"doctor-cli.js","names":[],"sources":["../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-database.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,IAAI;GACA,MAAM,OAAO,UAAU;EAC3B,SAAS,KAAK;GACV,QAAQ,MAAM,MAAM,KAAK,+BAA+B,CAAC;GACzD,QAAQ,MAAM,MAAM,IAAI,mCAAmC,GAAG,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;GAC9G,OAAO;EACX;EAIA,IAAI;GACA,MAAM,sBAAsB,QAAQ,WAAW;GAC/C,QAAQ,IAAI,MAAM,MAAM,4CAA4C,CAAC;EACzE,SAAS,KAAK;GACV,WAAW;GACX,QAAQ,IAAI,EAAE;GACd,QAAQ,MAAM,MAA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B,WAAW,CAAC,IAAI,CAAC,CAChF;EACA,QAAQ,KAAK,SAAS,MAAK,WAAU,sBAAsB,MAAM,MAAM,CAAC,IAAI,IAAI,CAAC;CACrF;CAEA,MAAM,SAAS,MAAM,UAAU;EAC3B,iBAAiB,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe;EAC5D,YAAY,KAAK,QAAQ,QAAQ,IAAI,GAAG,UAAU;EAClD,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO;EAC5C,aAAa,eAAe,KAAA;CAChC,CAAC;CAED,MAAM,eAAe,MAAM,gBAAgB,iBAAiB,WAAW;CAGvE,MAAM,oBAAoB,iBAAiB,WAAW;CAYtD,MAAM,UAAU;EAAC,OAAO;EAAqB,OAAO;EAAkB,OAAO;CAAgB,CAAC,CACzF,MAAK,UAAS,MAAM,OAAO;CAChC,IAAI,OAAO,QAAQ,SAAS,KAAK,iBAAiB,cAAc,SAC5D,QAAQ,KAAK,CAAC;AAEtB;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAKlB,MAAM,SAAS,gBAAgB,KAAK,QAAQ,IAAI,gBAAgB,QAAQ,IAAI,uBAAuB;CACnG,IAAI,QACA,QAAQ,MAAM,MAAM;MAEpB,QAAQ,MAAM,MAAM,IAAI,sBAAsB,gBAAgB,GAAG,GAAG,CAAC;CAEzE,QAAQ,KAAK,CAAC;AAClB,CAAC"}
@@ -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,26 @@ 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
+ /**
228
+ * Whether the admin-only policies get their `TO rebase_admin_request
229
+ * USING (true)` companions — see `planCollectionPolicies`. Only a boot
230
+ * that has made that role safe (`settleAdminRequestGroup`) says so;
231
+ * anywhere else they are not planned, and any in the database are
232
+ * dropped as orphans.
233
+ */
234
+ adminRequestRoleAvailable?: boolean;
235
+ }): Promise<PolicyEnsureResult>;
216
236
  /**
217
237
  * The warning a boot gives for one entry of {@link PolicyEnsureResult.rulesDropped}:
218
238
  * 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-5spbTyQ6.js";
3
+ import { t as main } from "../generate-drizzle-schema-DcrFr7YX.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,10 @@ 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;
185
+ /** The `TO rebase_admin_request USING (true)` companion of an admin-only policy. */
186
+ adminRequestTarget?: true;
183
187
  restrictive: boolean;
184
188
  /** Its `DROP POLICY IF EXISTS` / `CREATE POLICY` statements — a slice of `policyStatements`. */
185
189
  statements: string[];
@@ -194,7 +198,16 @@ export interface PolicyApplyPlan {
194
198
  * The same policies `policies.sql` carries, from the same plan, so boot and
195
199
  * `db push` produce identical RLS from identical collections.
196
200
  */
197
- export declare const planCollectionPolicies: (allCollections: CollectionConfig[]) => CollectionPolicyPlan[];
201
+ export declare const planCollectionPolicies: (allCollections: CollectionConfig[], options?: {
202
+ adminRoleAvailable?: boolean;
203
+ /**
204
+ * The boot made `rebase_admin_request`, granted it to the admin request
205
+ * roles alone, and checked the connection does not hold its
206
+ * privileges. Only then are the companions planned; otherwise they
207
+ * are left out, and the boot drops any left in the database.
208
+ */
209
+ adminRequestRoleAvailable?: boolean;
210
+ }) => CollectionPolicyPlan[];
198
211
  /**
199
212
  * The `generated column → column it reads` edges a project's `search` blocks
200
213
  * 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-Bl3_D_oP.js";
4
+ import { r as writePostgresDdl } from "../generate-files-CsaVzatS.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-DwqFRIWz.js";
4
+ import { u as pinSearchPath } from "../connection-C1zXTPJq.js";
5
+ import { a as diagnoseDbError } from "../cli-errors-DYTxnLbW.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>;
@@ -28,6 +28,7 @@
28
28
  * already has*, and which of the planned constraints are safe to apply to it.
29
29
  */
30
30
  import type { SchemaPlan } from "./types.js";
31
+ import { type ExistingIndexShape } from "../index-adoption.js";
31
32
  import { type SkippedVectorIndex } from "../vector-index.js";
32
33
  import { type ColumnTypeDrift } from "../column-type-drift.js";
33
34
  /**
@@ -98,6 +99,12 @@ export interface ExistingSchema {
98
99
  * `IF NOT EXISTS` skips it by name forever. Absent means unknown.
99
100
  */
100
101
  invalidIndexes?: Set<string>;
102
+ /**
103
+ * Every index's definition, read from the catalogue, so a declared index
104
+ * adopts an identical one under another name (`index-adoption.ts`) instead
105
+ * of building a twin. Absent means unknown, and nothing is adopted.
106
+ */
107
+ indexShapes?: ExistingIndexShape[];
101
108
  /**
102
109
  * Names of the extensions installed in the database. `CREATE EXTENSION IF
103
110
  * NOT EXISTS` skips by name whatever schema the extension is in, so the name
@@ -195,7 +202,7 @@ export interface DiffOptions {
195
202
  deferLiveIndexes?: boolean;
196
203
  }
197
204
  export interface EnsureAction {
198
- kind: "create-enum" | "create-table" | "enable-rls" | "add-column" | "add-constraint" | "rename-column" | "create-extension" | "create-function" | "create-index" | "comment-column" | "add-enum-value" | "set-not-null" | "drop-not-null" | "set-default" | "create-trigger";
205
+ kind: "create-enum" | "create-table" | "enable-rls" | "add-column" | "add-constraint" | "rename-column" | "create-extension" | "create-function" | "create-index" | "comment-column" | "add-enum-value" | "set-not-null" | "drop-not-null" | "set-default" | "create-trigger" | "rename-index";
199
206
  /** Qualified target, for logging: `public.posts` or `public.posts.title`. */
200
207
  target: string;
201
208
  sql: string;
@@ -53,6 +53,13 @@ export declare const renderDenyingPolicyStatements: (table: Pick<TablePlan, "sch
53
53
  /** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — every generated table is locked. */
54
54
  export declare const renderEnableRls: (table: Pick<TablePlan, "schema" | "table">) => string;
55
55
  export declare function renderPostgresDdl(plan: SchemaPlan, options?: DdlRenderOptions): string;
56
+ /**
57
+ * The statement that creates `rebase_admin`, when a policy in the plan is
58
+ * written `TO` it — so a file of policies is self-contained, as it is for the
59
+ * RLS helpers: CREATE POLICY refuses a role that does not exist. Empty when no
60
+ * policy names it (`rls.adminPolicies: "public"`).
61
+ */
62
+ export declare function adminRolePreamble(plan: SchemaPlan): string;
56
63
  export declare function renderPoliciesDdl(plan: SchemaPlan): string;
57
64
  export declare function renderSearchDdl(plan: SchemaPlan): string;
58
65
  /**
@@ -274,6 +274,21 @@ export interface PolicyPlan {
274
274
  using: string | null;
275
275
  /** Compiled `WITH CHECK` clause, or null when the operation takes none. */
276
276
  withCheck: string | null;
277
+ /** `roles` is `["rebase_admin"]` by the compiler's choice — see `CompiledRulePolicy.adminTarget`. */
278
+ adminTarget?: true;
279
+ /**
280
+ * This policy's `TO rebase_admin_request USING (true)` companion, when
281
+ * every admin request passes it (`CompiledRulePolicy.adminRequestTarget`).
282
+ * Carried here rather than as a policy of the table, so `policies.sql`,
283
+ * migrations and the generated Drizzle schema never hold it: only the boot
284
+ * writes it, and only where it has checked that role is safe
285
+ * (`planCollectionPolicies`'s `adminRequestRoleAvailable`).
286
+ */
287
+ adminRequestCompanion?: {
288
+ name: string;
289
+ using: string | null;
290
+ withCheck: string | null;
291
+ };
277
292
  /**
278
293
  * True when Rebase added this rule rather than the author. They are
279
294
  * permissive, so they OR with the declared rules and widen the ACL beyond
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `db push`'s half of index adoption (`index-adoption.ts`): before Atlas
3
+ * plans, an existing index identical to a declared one takes the declared
4
+ * one's name, so the plan finds it there instead of creating a twin beside it.
5
+ * Boot does the same through its own plan (`diffPlanAgainstCatalogue`).
6
+ */
7
+ import { type CollectionConfig } from "@rebasepro/types";
8
+ import { type IndexAdoption, type ShapeQueryable } from "./index-adoption.js";
9
+ /** The renames that make the database's identical indexes the collections' declared ones. */
10
+ export declare function pushIndexAdoptions(client: ShapeQueryable, collections: CollectionConfig[]): Promise<IndexAdoption[]>;
@@ -27,7 +27,7 @@
27
27
  * push's reconcile step decides.
28
28
  */
29
29
  import type { CollectionConfig } from "@rebasepro/types";
30
- import { type PolicyRef, type Queryable } from "../security/policy-drift.js";
30
+ import { type AdminPoliciesExpectation, type PolicyRef, type Queryable } from "../security/policy-drift.js";
31
31
  export interface PolicyPushPlan {
32
32
  /** Declared tables in the database with row-level security off, as `schema.table`: the push switches it on. */
33
33
  enableRls: string[];
@@ -51,9 +51,13 @@ export interface PolicyPushPlan {
51
51
  * @param options.searchPath the `search_path` the stamps were written under
52
52
  * when the connection's own differs — the one `db push` stamps under.
53
53
  * See {@link readPolicyStamps}.
54
+ * @param options.adminRoleAvailable where the push writes the server-or-admin
55
+ * policies (`TO rebase_admin`, or `TO public` where the admin switch is
56
+ * not live); `"detect"` reads it off the database. Left out, as compiled.
54
57
  */
55
58
  export declare function planPolicyPush(client: Queryable, collections: CollectionConfig[], options?: {
56
59
  searchPath?: string;
60
+ adminRoleAvailable?: AdminPoliciesExpectation;
57
61
  }): Promise<PolicyPushPlan>;
58
62
  /** Whether the push would change any row-level security. Kept and unstamped policies are not changes. */
59
63
  export declare function policyPlanChanges(plan: PolicyPushPlan): boolean;
@@ -196,15 +196,32 @@ export declare function dropLegacyAuthSchema(run: (sql: string) => Promise<Recor
196
196
  * an argument: inside the function `current_user` is its owner. The body is
197
197
  * dynamic SQL so the function can be created before the table exists — in
198
198
  * Atlas's replay of the migrations, for one. With nothing recorded the answer
199
- * is `rebase_user`, as everywhere else.
199
+ * is `rebase_user`, as everywhere else. Each recorded role's admin counterpart
200
+ * (`<role>_admin`, what an admin request switches to) answers `true` as well.
200
201
  *
201
202
  * Created only for a project that asks for `policyTarget: "requestRole"`, so
202
203
  * every other project's migrations and boot are exactly what they were.
203
204
  */
204
- export declare const REQUEST_ROLE_FUNCTION_SQL = "CREATE OR REPLACE FUNCTION rebase.is_request_role(role_name text) RETURNS boolean AS $$\nDECLARE\n request_roles text[];\nBEGIN\n IF to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE 'SELECT string_to_array(value, '','') FROM \"rebase\".\"schema_meta\" WHERE key = ''request_roles'''\n INTO request_roles;\n END IF;\n RETURN role_name = ANY(COALESCE(request_roles, ARRAY['rebase_user']));\nEND\n$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog";
205
+ export declare const REQUEST_ROLE_FUNCTION_SQL = "CREATE OR REPLACE FUNCTION rebase.is_request_role(role_name text) RETURNS boolean AS $$\nDECLARE\n request_roles text[];\nBEGIN\n IF to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE 'SELECT string_to_array(value, '','') FROM \"rebase\".\"schema_meta\" WHERE key = ''request_roles'''\n INTO request_roles;\n END IF;\n request_roles := COALESCE(request_roles, ARRAY['rebase_user']);\n -- An admin request runs as the request role's admin counterpart\n -- (adminRequestRoleFor), which is a request role here too.\n RETURN role_name = ANY(request_roles) OR role_name = ANY(ARRAY(SELECT r || '_admin' FROM unnest(request_roles) AS r));\nEND\n$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog";
205
206
  /**
206
207
  * Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body
207
208
  * differs — replacing an unchanged function would still invalidate every
208
209
  * cached plan of every policy that calls it.
209
210
  */
210
211
  export declare function ensureRequestRoleFunction(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void>;
212
+ /**
213
+ * The statement that creates {@link REBASE_ADMIN_ROLE} when it is missing — a
214
+ * role with no privilege that cannot log in, whose only job is to be what the
215
+ * server-or-admin policies are written `TO`. Guarded in the statement, and a
216
+ * concurrent creator's win taken as success, because a role belongs to the
217
+ * cluster and two databases' boots can race for it.
218
+ */
219
+ export declare const ADMIN_POLICY_ROLE_SQL = "DO $rebase_admin_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rebase_admin') THEN\n CREATE ROLE rebase_admin NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEXCEPTION\n WHEN duplicate_object OR unique_violation THEN NULL;\n WHEN insufficient_privilege THEN\n RAISE EXCEPTION 'Rebase writes its server-or-admin policies TO rebase_admin, which does not exist, and % may not create it.', current_user\n USING HINT = 'Run CREATE ROLE rebase_admin NOLOGIN; as an administrator, or declare database({ rls: { adminPolicies: \"public\" } }) (REBASE_RLS_ADMIN_POLICIES=public) to write them TO public.';\nEND\n$rebase_admin_role$";
220
+ /**
221
+ * Create {@link REBASE_ADMIN_REQUEST_ROLE} unless it exists. Unlike
222
+ * {@link ADMIN_POLICY_ROLE_SQL} it is never in `policies.sql` or a migration:
223
+ * only a boot makes it, and a boot that cannot just plans no companions.
224
+ */
225
+ export declare const ADMIN_REQUEST_ROLE_SQL = "DO $rebase_admin_request_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rebase_admin_request') THEN\n CREATE ROLE rebase_admin_request NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEXCEPTION\n WHEN duplicate_object OR unique_violation THEN NULL;\nEND\n$rebase_admin_request_role$";
226
+ /** Create {@link REBASE_ADMIN_ROLE} unless it exists — one read when it does. */
227
+ export declare function ensureAdminPolicyRole(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void>;
@@ -267,9 +267,9 @@ export declare const isSearchIndexColumn: (column: {
267
267
  * Returns undefined when nothing needs dropping, so the common case keeps using
268
268
  * a plain `select()` and this stays invisible in the generated SQL.
269
269
  */
270
- export declare const visibleColumnProjection: (tableColumns: Record<string, {
270
+ export declare const visibleColumnProjection: <C extends {
271
271
  getSQLType?: () => string;
272
- }> | undefined, collection?: CollectionConfig) => Record<string, unknown> | undefined;
272
+ }>(tableColumns: Record<string, C> | undefined, collection?: CollectionConfig) => Record<string, C> | undefined;
273
273
  /** The same exclusion as a drizzle `db.query` `columns` denylist. */
274
274
  export declare const hiddenColumnsOption: (tableColumns: Record<string, {
275
275
  getSQLType?: () => string;