@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
package/dist/cli.js CHANGED
@@ -1,10 +1,12 @@
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 { $ as isSyncedPlan, A as getTriggerExcludes, B as readViewsDdl, C as diagnoseMissingBin, D as getForeignIndexExcludes, E as ensureDevDatabaseExists, F as queryGeneratedColumnDependencies, G as GENERATED_SQL_DIR, H as withAppClient, I as queryUndeclarableConstraints, J as decidePushSafety, K as generatedSqlDir, L as readSearchDdl, M as getVectorExcludes, N as loadCollectionsForCli, O as getSearchExcludes, P as queryColumnTypes, Q as fromAlterTable, R as readTriggersDdl, S as detectProjectPackageManager, T as dropGeneratedColumns, U as workspaceMemberDir, V as resolveLocalBin, W as DESIRED_STATE_URL, X as detectDestructiveStatements, Y as destructiveOptInFlag, Z as extractPlanStatements, _ as atlasDevDatabaseUrl, a as diagnoseDbError, b as describeDevAddCommand, c as isEconnrefused, d as reportCommandFailure, et as warnIfYesApprovedDestructive, f as ExcludeIntrospectionError, g as applyViewsDdl, h as applyVectorDdl, i as diagnoseAtlasFailure, j as getUndeclaredConstraintExcludes, k as getTableExcludes, l as isSslNotEnabled, m as applyTriggersDdl, o as formatForeignGeneratedColumnBanner, p as applySearchDdl, q as prepareGeneratedSqlDir, rt as redactConnectionPasswords, s as isAuthFailure, t as checkDatabaseConnectivity, tt as forAtlas, v as closeAppClients, w as dropDevDatabase, x as describeReinstallCommand, y as describeBuildScriptRemedy, z as readVectorDdl } from "./cli-errors-D8s4z_3g.js";
4
+ import { $ as fromAlterTable, A as getTableExcludes, B as readVectorDdl, C as detectProjectPackageManager, D as ensureDevDatabaseExists, E as dropGeneratedColumns, F as queryColumnTypes, G as DESIRED_STATE_URL, H as resolveLocalBin, I as queryGeneratedColumnDependencies, J as prepareGeneratedSqlDir, K as GENERATED_SQL_DIR, L as queryUndeclarableConstraints, M as getUndeclaredConstraintExcludes, N as getVectorExcludes, O as getForeignIndexExcludes, P as loadCollectionsForCli, Q as extractPlanStatements, R as readSearchDdl, S as describeReinstallCommand, T as dropDevDatabase, U as withAppClient, V as readViewsDdl, W as workspaceMemberDir, X as destructiveOptInFlag, Y as decidePushSafety, Z as detectDestructiveStatements, _ as atlasDevDatabaseUrl, a as diagnoseDbError, b as describeBuildScriptRemedy, c as isEconnrefused, d as reportCommandFailure, et as isSyncedPlan, f as ExcludeIntrospectionError, g as applyViewsDdl, h as applyVectorDdl, i as diagnoseAtlasFailure, it as redactConnectionPasswords, j as getTriggerExcludes, k as getSearchExcludes, l as isSslNotEnabled, m as applyTriggersDdl, nt as forAtlas, o as formatForeignGeneratedColumnBanner, p as applySearchDdl, q as generatedSqlDir, s as isAuthFailure, t as checkDatabaseConnectivity, tt as warnIfYesApprovedDestructive, w as diagnoseMissingBin, x as describeDevAddCommand, y as closeAppClients, z as readTriggersDdl } from "./cli-errors-C73Qy7WJ.js";
5
+ import { a as dropLegacyAuthSchema, n as REQUEST_ROLE_FUNCTION_SQL, r as RLS_BOOTSTRAP_SQL, t as ADMIN_POLICY_ROLE_SQL } from "./rls-bootstrap-sql-CxszeSc7.js";
5
6
  import { a as outWarn, i as outError, o as atlasExcludePattern, r as out, s as excludePatternParts, t as chalk } from "./source-fZb92pN8.js";
7
+ import { C as declaredIndexesIfNotExists, S as execa, b as parseDriverLine, c as isDriverDbSubcommand, d as branchNameIn, f as branchSourceIn, g as assertKnownFlags, i as latestRecordedMigration, l as backupActionOf, m as unexpectedBranchArgs, o as planBaseline, p as resolveBranchSwitches, r as describeBaselinePlan, s as DRIVER_DB_SUBCOMMANDS, t as baselineVersionProblem, v as collectionsPathIn, w as indexAdoptionStatement, x as resolveDriverSwitches } from "./migrate-baseline-CveNQli3.js";
6
8
  import { t as nextStepAfterDbGenerate } from "./generate-next-step-DgK5BlBn.js";
7
- import { D as execa, S as RLS_BOOTSTRAP_SQL, b as parseDriverLine, c as isDriverDbSubcommand, d as branchNameIn, f as branchSourceIn, g as assertKnownFlags, i as latestRecordedMigration, l as backupActionOf, m as unexpectedBranchArgs, o as planBaseline, p as resolveBranchSwitches, r as describeBaselinePlan, s as DRIVER_DB_SUBCOMMANDS, t as baselineVersionProblem, v as collectionsPathIn, w as dropLegacyAuthSchema, x as resolveDriverSwitches } from "./migrate-baseline-BeepEphh.js";
9
+ import { REBASE_ADMIN_ROLE, declaredRlsPolicyShape } from "@rebasepro/types";
8
10
  import { formatRelativeTime } from "@rebasepro/utils";
9
11
  import path from "path";
10
12
  import fs from "fs";
@@ -1121,6 +1123,14 @@ function planPrune(input, options = {}) {
1121
1123
  }
1122
1124
  //#endregion
1123
1125
  //#region src/cli.ts
1126
+ /**
1127
+ * The RLS helpers a migration or a push creates ahead of the policies — with
1128
+ * `rebase.is_request_role` for a project that declared
1129
+ * `rls.policyTarget: "requestRole"`, whose every permissive policy calls it.
1130
+ * (`policies.sql` itself creates the `rebase_admin` role its server-or-admin
1131
+ * policies are written `TO` — `adminRolePreamble`.)
1132
+ */
1133
+ var rlsBootstrapSql = () => declaredRlsPolicyShape().policyTarget === "requestRole" ? `${RLS_BOOTSTRAP_SQL}\n${REQUEST_ROLE_FUNCTION_SQL};\n` : RLS_BOOTSTRAP_SQL;
1124
1134
  var __cliDirname = path.dirname(fileURLToPath(import.meta.url));
1125
1135
  /**
1126
1136
  * A script this CLI spawns, and how to run it.
@@ -1207,7 +1217,7 @@ function generatesInProcess() {
1207
1217
  async function generateInProcess(what, label, run) {
1208
1218
  let generators;
1209
1219
  try {
1210
- generators = await import("./generate-files-DbwU8Btx.js").then((n) => n.t);
1220
+ generators = await import("./generate-files-BkiRFoV1.js").then((n) => n.t);
1211
1221
  } catch (err) {
1212
1222
  outError(chalk.red(`✗ Failed to run ${what}: ${err instanceof Error ? err.message : String(err)}`));
1213
1223
  process.exit(1);
@@ -1254,7 +1264,7 @@ async function runPluginCommand(args) {
1254
1264
  else if (domain === "schema") await schemaCommand(subcommand, args);
1255
1265
  else if (domain === "doctor") await doctorPluginCommand(args);
1256
1266
  else if (domain === "console") {
1257
- const { consoleCommand } = await import("./cli-console-DPdZCWTi.js");
1267
+ const { consoleCommand } = await import("./cli-console-DDkNetCz.js");
1258
1268
  process.exitCode = await consoleCommand(args);
1259
1269
  } else {
1260
1270
  outError(chalk.red(`Unknown domain command: ${domain}`));
@@ -1334,6 +1344,25 @@ async function stripCarvedOutFromNewestMigration(collectionsPath) {
1334
1344
  return !result.empty;
1335
1345
  }
1336
1346
  /**
1347
+ * The newest migration's declared indexes as `CREATE INDEX IF NOT EXISTS`, so
1348
+ * `rebase db migrate` can adopt an identical existing index under the declared
1349
+ * name before applying it (`adoptIdenticalIndexes`) and the statement then
1350
+ * finds it there. Re-hashes the directory when it rewrote anything.
1351
+ */
1352
+ async function makeDeclaredIndexesAdoptable(collectionsPath) {
1353
+ const newest = listMigrationFiles().at(-1);
1354
+ if (!newest) return;
1355
+ const file = path.resolve(process.cwd(), "drizzle", "migrations", newest);
1356
+ const result = declaredIndexesIfNotExists(fs.readFileSync(file, "utf-8"));
1357
+ if (result.rewritten === 0) return;
1358
+ fs.writeFileSync(file, result.sql, "utf-8");
1359
+ await runAtlas("migrate", [
1360
+ "hash",
1361
+ "--dir",
1362
+ "file://drizzle/migrations"
1363
+ ], collectionsPath);
1364
+ }
1365
+ /**
1337
1366
  * One line per destructive statement, as `db push` prints them — shared by
1338
1367
  * push, `db generate` and `db migrate --refuse-destructive`, so the three
1339
1368
  * describe the same statement the same way.
@@ -1420,8 +1449,18 @@ async function dbCommand(subcommand, rawArgs) {
1420
1449
  await branchCommand(rawArgs);
1421
1450
  return;
1422
1451
  }
1452
+ if (subcommand === "request-role") {
1453
+ const { requestRoleCommand } = await import("./request-role-cli-Bxxskru9.js").then((n) => n.r);
1454
+ await requestRoleCommand(rawArgs);
1455
+ return;
1456
+ }
1457
+ if (subcommand === "provision") {
1458
+ const { provisionCommand } = await import("./request-role-cli-Bxxskru9.js").then((n) => n.r);
1459
+ await provisionCommand(rawArgs);
1460
+ return;
1461
+ }
1423
1462
  if (subcommand === "backup" || subcommand === "restore" || subcommand === "backups") {
1424
- const { backupCommand, restoreCommand, backupsCommand } = await import("./backup-cli-D_aKXPyX.js").then((n) => n.t);
1463
+ const { backupCommand, restoreCommand, backupsCommand } = await import("./backup-cli-CwiJEp_J.js").then((n) => n.t);
1425
1464
  if (subcommand === "backup" && backupActionOf(rawArgs) === "list") await backupsCommand(rawArgs);
1426
1465
  else if (subcommand === "backup") await backupCommand(rawArgs);
1427
1466
  else if (subcommand === "restore") await restoreCommand(rawArgs);
@@ -1452,6 +1491,7 @@ async function dbCommand(subcommand, rawArgs) {
1452
1491
  ], collectionsPath);
1453
1492
  let wroteNewMigration = listMigrationFiles().length > migrationsBefore.length;
1454
1493
  if (wroteNewMigration) wroteNewMigration = await stripCarvedOutFromNewestMigration(collectionsPath);
1494
+ if (wroteNewMigration) await makeDeclaredIndexesAdoptable(collectionsPath);
1455
1495
  const newestWritten = wroteNewMigration ? listMigrationFiles().at(-1) : void 0;
1456
1496
  if (newestWritten) await reportDestructiveMigration(fs.readFileSync(path.resolve(process.cwd(), "drizzle", "migrations", newestWritten), "utf-8"), newestWritten, process.env.DATABASE_URL);
1457
1497
  const migrationsDir = path.resolve(process.cwd(), "drizzle", "migrations");
@@ -1468,7 +1508,7 @@ async function dbCommand(subcommand, rawArgs) {
1468
1508
  }
1469
1509
  const searchContent = readSearchDdl();
1470
1510
  if (searchContent) {
1471
- const { searchColumnDependencies } = await import("./generate-postgres-ddl-logic-ISVgsP34.js").then((n) => n.s);
1511
+ const { searchColumnDependencies } = await import("./generate-postgres-ddl-logic-G9PvjHrr.js").then((n) => n.s);
1472
1512
  const migrationConflicts = findGeneratedColumnConflicts(parseColumnMutations(migrationContent), searchColumnDependencies(await loadCollectionsForCli(collectionsPath)));
1473
1513
  const preamble = migrationDropPreamble(migrationConflicts);
1474
1514
  if (preamble) {
@@ -1492,7 +1532,7 @@ async function dbCommand(subcommand, rawArgs) {
1492
1532
  const policiesFile = path.join(generatedSqlDir(), "policies.sql");
1493
1533
  if (fs.existsSync(policiesFile)) {
1494
1534
  const policiesContent = fs.readFileSync(policiesFile, "utf-8");
1495
- fs.appendFileSync(newestMigrationFile, "\n\n" + RLS_BOOTSTRAP_SQL + "\n" + policiesContent);
1535
+ fs.appendFileSync(newestMigrationFile, "\n\n" + rlsBootstrapSql() + "\n" + policiesContent);
1496
1536
  out(chalk.gray(` ✓ Appended RLS policies to migration file: ${path.basename(newestMigrationFile)}`));
1497
1537
  out(chalk.gray(" Re-hashing migration files..."));
1498
1538
  await runAtlas("migrate", [
@@ -1546,6 +1586,7 @@ async function dbCommand(subcommand, rawArgs) {
1546
1586
  const databaseUrl = process.env.DATABASE_URL;
1547
1587
  if (databaseUrl && !dryRun) await ensureAuthSchemaAndFunctions(databaseUrl);
1548
1588
  if (databaseUrl) await renameLegacyForeignKeys(databaseUrl, collectionsPath, dryRun);
1589
+ if (databaseUrl) await adoptIdenticalIndexes(databaseUrl, collectionsPath, dryRun);
1549
1590
  const prebuilt = databaseUrl ? await prebuildForeignKeyIndexes(databaseUrl, collectionsPath, dryRun) : [];
1550
1591
  if (databaseUrl) await keepDatabaseOwnedDefaults(databaseUrl, collectionsPath);
1551
1592
  const plan = await runAtlas("schema", [
@@ -1694,9 +1735,9 @@ async function dbCommand(subcommand, rawArgs) {
1694
1735
  await applySearchDdl(databaseUrl);
1695
1736
  await applyTriggersDdl(databaseUrl);
1696
1737
  await applyViewsDdl(databaseUrl);
1738
+ await ensureRlsUserRole(databaseUrl);
1697
1739
  await applyPolicies(databaseUrl, collectionsPath);
1698
1740
  await reconcilePolicies(databaseUrl, collectionsPath);
1699
- await ensureRlsUserRole(databaseUrl);
1700
1741
  await retireLegacyAuthSchema(databaseUrl);
1701
1742
  }
1702
1743
  });
@@ -1727,7 +1768,10 @@ async function dbCommand(subcommand, rawArgs) {
1727
1768
  out(chalk.gray(` --refuse-destructive: ${extractPlanStatements(plan).length} pending statement(s), none destructive.`));
1728
1769
  out("");
1729
1770
  }
1730
- if (databaseUrl) await ensureAuthSchemaAndFunctions(databaseUrl);
1771
+ if (databaseUrl) {
1772
+ await ensureAuthSchemaAndFunctions(databaseUrl);
1773
+ if (collectionsPath) await adoptIdenticalIndexes(databaseUrl, collectionsPath, false);
1774
+ }
1731
1775
  if (baseline && baselinePlan) {
1732
1776
  out(chalk.gray(` ${describeBaselinePlan(baseline, baselinePlan)}`));
1733
1777
  out("");
@@ -1742,8 +1786,10 @@ async function dbCommand(subcommand, rawArgs) {
1742
1786
  if (databaseUrl) {
1743
1787
  await ensureRlsUserRole(databaseUrl);
1744
1788
  await retireLegacyAuthSchema(databaseUrl);
1745
- const { stampMigratedPolicies } = await import("./migrate-policy-stamps-cYMJ_9Ha.js");
1746
- await stampMigratedPolicies(databaseUrl, collectionsPath);
1789
+ const adminRoleAvailable = await readAdminPoliciesLive(databaseUrl);
1790
+ if (!adminRoleAvailable) await moveAdminPoliciesToPublic(databaseUrl, collectionsPath);
1791
+ const { stampMigratedPolicies } = await import("./migrate-policy-stamps-C4qbQ0jK.js");
1792
+ await stampMigratedPolicies(databaseUrl, collectionsPath, adminRoleAvailable);
1747
1793
  }
1748
1794
  }
1749
1795
  out("");
@@ -1770,8 +1816,8 @@ async function dbCommand(subcommand, rawArgs) {
1770
1816
  * no such column reads nothing.
1771
1817
  */
1772
1818
  async function keepDatabaseOwnedDefaults(databaseUrl, collectionsPath) {
1773
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
1774
- const { databaseOwnedDefaultColumns, readKeptDefaults, withKeptDefaults } = await import("./push-kept-defaults-CLbsuSmo.js");
1819
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
1820
+ const { databaseOwnedDefaultColumns, readKeptDefaults, withKeptDefaults } = await import("./push-kept-defaults-D-JEv0Gn.js");
1775
1821
  const columns = databaseOwnedDefaultColumns(await loadCollections(path.resolve(process.cwd(), collectionsPath)));
1776
1822
  if (columns.length === 0) return;
1777
1823
  let kept;
@@ -1796,8 +1842,8 @@ async function keepDatabaseOwnedDefaults(databaseUrl, collectionsPath) {
1796
1842
  async function renameLegacyForeignKeys(databaseUrl, collectionsPath, dryRun) {
1797
1843
  let renames;
1798
1844
  try {
1799
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
1800
- const { legacyForeignKeyRenames } = await import("./push-legacy-renames-DeW_HTLJ.js");
1845
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
1846
+ const { legacyForeignKeyRenames } = await import("./push-legacy-renames-7UKspspl.js");
1801
1847
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1802
1848
  renames = await withAppClient(databaseUrl, (client) => legacyForeignKeyRenames({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections));
1803
1849
  } catch {
@@ -1813,11 +1859,31 @@ async function renameLegacyForeignKeys(databaseUrl, collectionsPath, dryRun) {
1813
1859
  out(chalk.gray(" To keep an old name instead, name the column on the relation (`localKey`, or `through` on a many-to-many)."));
1814
1860
  out("");
1815
1861
  }
1862
+ /** Renames identical existing indexes to the declared ones' names, as boot does; a dry-run only names them. */
1863
+ async function adoptIdenticalIndexes(databaseUrl, collectionsPath, dryRun) {
1864
+ let adoptions;
1865
+ try {
1866
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
1867
+ const { pushIndexAdoptions } = await import("./push-index-adoption-C-TpM445.js");
1868
+ const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1869
+ adoptions = await withAppClient(databaseUrl, (client) => pushIndexAdoptions({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections));
1870
+ } catch {
1871
+ return;
1872
+ }
1873
+ if (adoptions.length === 0) return;
1874
+ out(chalk.gray(dryRun ? ` ${adoptions.length} existing index(es) match a declared index; a push renames each to the declared name instead of` : ` Adopting ${adoptions.length} existing index(es) that match a declared index (renamed, not rebuilt):`));
1875
+ if (dryRun) out(chalk.gray(" building it again (the plan below still creates them, because nothing ran):"));
1876
+ for (const adoption of adoptions) out(chalk.gray(` ${adoption.schema}.${adoption.table}: "${adoption.from}" → "${adoption.to}"`));
1877
+ if (!dryRun) await withAppClient(databaseUrl, async (client) => {
1878
+ for (const adoption of adoptions) await client.query(indexAdoptionStatement(adoption));
1879
+ });
1880
+ out("");
1881
+ }
1816
1882
  /** Names the enum labels the database keeps after the collections dropped them. See `schema/enum-labels-kept.ts`. */
1817
1883
  async function reportKeptEnumLabels(databaseUrl, collectionsPath) {
1818
1884
  try {
1819
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
1820
- const { keptEnumLabels, formatKeptEnumLabelsNotice } = await import("./enum-labels-kept-DyFE4Gaq.js");
1885
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
1886
+ const { keptEnumLabels, formatKeptEnumLabelsNotice } = await import("./enum-labels-kept-z7ustOl_.js");
1821
1887
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1822
1888
  const kept = await withAppClient(databaseUrl, (client) => keptEnumLabels({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections));
1823
1889
  if (kept.length > 0) outWarn(chalk.yellow(formatKeptEnumLabelsNotice(kept)));
@@ -1826,8 +1892,8 @@ async function reportKeptEnumLabels(databaseUrl, collectionsPath) {
1826
1892
  async function prebuildForeignKeyIndexes(databaseUrl, collectionsPath, dryRun) {
1827
1893
  let missing;
1828
1894
  try {
1829
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
1830
- const { missingForeignKeyIndexes } = await import("./push-index-prebuild-CIvajIrL.js");
1895
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
1896
+ const { missingForeignKeyIndexes } = await import("./push-index-prebuild-xbpgZEJK.js");
1831
1897
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1832
1898
  missing = await withAppClient(databaseUrl, (client) => missingForeignKeyIndexes({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections));
1833
1899
  } catch {
@@ -1837,7 +1903,7 @@ async function prebuildForeignKeyIndexes(databaseUrl, collectionsPath, dryRun) {
1837
1903
  if (missing.length === 0 || dryRun) return names;
1838
1904
  out(chalk.gray(` Building ${missing.length} foreign-key index(es) on existing tables first — CONCURRENTLY, so writes go on:`));
1839
1905
  try {
1840
- const { buildDeferredIndexes } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
1906
+ const { buildDeferredIndexes } = await import("./deferred-index-build-DDdnjaOW.js").then((n) => n.r);
1841
1907
  const outcome = await withAppClient(databaseUrl, (client) => buildDeferredIndexes(async () => ({
1842
1908
  dedicated: true,
1843
1909
  query: async (text) => ({ rows: (await client.query(text)).rows }),
@@ -1853,7 +1919,7 @@ async function prebuildForeignKeyIndexes(databaseUrl, collectionsPath, dryRun) {
1853
1919
  async function ensureAuthSchemaAndFunctions(databaseUrl) {
1854
1920
  try {
1855
1921
  await withAppClient(databaseUrl, async (client) => {
1856
- await client.query(RLS_BOOTSTRAP_SQL);
1922
+ await client.query(rlsBootstrapSql());
1857
1923
  });
1858
1924
  } catch (err) {
1859
1925
  if (isEconnrefused(err) || isAuthFailure(err) || isSslNotEnabled(err)) {
@@ -1885,11 +1951,19 @@ async function lockManagedTables(databaseUrl, collectionsPath) {
1885
1951
  let unsecured;
1886
1952
  let userRole;
1887
1953
  try {
1888
- const { lockCollectionTables } = await import("./ensure-collection-policies-DUpWJb5D.js");
1889
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
1890
- userRole = (await import("./rls-enforcement-jZTv1yci.js").then((n) => n.u)).REBASE_USER_ROLE;
1954
+ const { lockCollectionTables } = await import("./ensure-collection-policies-DJsOMpaI.js");
1955
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
1956
+ const { readRecordedRequestRoles } = await import("./rls-enforcement-CyUCPDH8.js").then((n) => n.y);
1957
+ const { cliRlsSettings } = await import("./rls-settings-BCGMIig3.js").then((n) => n.a);
1891
1958
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1892
- ({unsecured} = await withAppClient(databaseUrl, (client) => lockCollectionTables({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections)));
1959
+ ({unsecured, userRole} = await withAppClient(databaseUrl, async (client) => {
1960
+ const runSql = async (text) => (await client.query(text)).rows;
1961
+ const roles = cliRlsSettings(await readRecordedRequestRoles(runSql)).roles;
1962
+ return {
1963
+ unsecured: (await lockCollectionTables({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections)).unsecured,
1964
+ userRole: roles.join(", ")
1965
+ };
1966
+ }));
1893
1967
  } catch (err) {
1894
1968
  outError(chalk.red(`\n ✗ The schema was applied, but row-level security could not be switched on for its tables: ${err instanceof Error ? err.message : String(err)}`));
1895
1969
  outError(chalk.gray(" A table this push created may be readable and writable by every authenticated request\n until it is. Re-run `rebase db push` — it locks every collection table before anything else."));
@@ -1922,8 +1996,8 @@ async function lockManagedTables(databaseUrl, collectionsPath) {
1922
1996
  async function ensureAuthTables(databaseUrl, collectionsPath) {
1923
1997
  try {
1924
1998
  const { drizzle } = await import("drizzle-orm/node-postgres");
1925
- const { ensureAuthTablesExist } = await import("./ensure-tables-Bx1DYarz.js").then((n) => n.n);
1926
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
1999
+ const { ensureAuthTablesExist } = await import("./ensure-tables-CUqYgMvo.js").then((n) => n.n);
2000
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
1927
2001
  const authCollection = (await loadCollections(path.resolve(process.cwd(), collectionsPath))).find((c) => {
1928
2002
  const a = c.auth;
1929
2003
  return a === true || typeof a === "object" && a !== null && a.enabled === true;
@@ -1943,22 +2017,36 @@ async function ensureRlsUserRole(databaseUrl) {
1943
2017
  const schemas = ["public", "rebase"];
1944
2018
  let rls;
1945
2019
  try {
1946
- rls = await import("./rls-enforcement-jZTv1yci.js").then((n) => n.u);
2020
+ rls = await import("./rls-enforcement-CyUCPDH8.js").then((n) => n.y);
1947
2021
  } catch (err) {
1948
2022
  outError(chalk.red(`\n ✗ Could not load the RLS provisioning module: ${err instanceof Error ? err.message : String(err)}`));
1949
2023
  return;
1950
2024
  }
2025
+ let connectionRole;
2026
+ let settings;
1951
2027
  try {
1952
2028
  await withAppClient(databaseUrl, async (client) => {
1953
2029
  const runSql = async (text) => (await client.query(text)).rows;
1954
- if ((await rls.detectConnectionPosture(runSql)).privileged) {
1955
- await rls.ensureAppRole(runSql, schemas);
1956
- out(chalk.gray(` ✓ RLS role "${rls.REBASE_USER_ROLE}" provisioned/refreshed.`));
2030
+ const posture = await rls.detectConnectionPosture(runSql);
2031
+ connectionRole = posture.role;
2032
+ if (posture.privileged) {
2033
+ const recorded = await rls.readRecordedRequestRoles(runSql);
2034
+ settings = (await import("./rls-settings-BCGMIig3.js").then((n) => n.a)).cliRlsSettings(recorded);
2035
+ rls.assertRecordedRequestRoles(settings.roles, recorded, await rls.roleHoldsTableGrants(runSql, schemas));
2036
+ if (recorded ? recorded.join(",") !== settings.roles.join(",") : settings.roles.join(",") !== rls.REBASE_USER_ROLE) await rls.recordRequestRoles(runSql, settings.roles);
2037
+ for (const role of settings.roles) await rls.ensureAppRole(runSql, schemas, {
2038
+ role,
2039
+ provisionRole: settings.provisionRole,
2040
+ grants: settings.grants
2041
+ });
2042
+ await rls.settleAdminSwitch(runSql, schemas, settings, { provision: true });
2043
+ out(chalk.gray(` ✓ RLS role ${settings.roles.map((r) => `"${r}"`).join(", ")} provisioned/refreshed.`));
1957
2044
  }
1958
2045
  });
1959
2046
  } catch (err) {
1960
- outError(chalk.red(`\n ✗ The schema change was applied, but the "${rls.REBASE_USER_ROLE}" role could not be provisioned: ${err instanceof Error ? err.message : String(err)}`));
1961
- outError(chalk.gray(rls.appRoleSetupInstructions("your database user", schemas)));
2047
+ const setup = err instanceof rls.AppRoleSetupError;
2048
+ outError(chalk.red(`\n ✗ The schema change was applied, but the "${settings?.defaultRole ?? rls.REBASE_USER_ROLE}" role could not be provisioned: ${setup ? err.message.slice(0, -err.instructions.length).trimEnd() : err instanceof Error ? err.message : String(err)}`));
2049
+ outError(chalk.gray(setup ? err.instructions : rls.appRoleSetupInstructions(connectionRole, schemas, settings?.defaultRole, settings?.grants)));
1962
2050
  }
1963
2051
  }
1964
2052
  /**
@@ -1984,8 +2072,13 @@ async function applyPolicies(databaseUrl, collectionsPath) {
1984
2072
  if (!fs.existsSync(policiesPath)) return;
1985
2073
  out(chalk.gray(" Step 3/3: Applying RLS policies to database..."));
1986
2074
  out("");
1987
- const policiesContent = fs.readFileSync(policiesPath, "utf-8");
1988
- const stamping = await policyStamping(databaseUrl, collectionsPath, policiesContent);
2075
+ let policiesContent = fs.readFileSync(policiesPath, "utf-8");
2076
+ const adminRoleAvailable = policiesContent.includes(`"${REBASE_ADMIN_ROLE}"`) ? await readAdminPoliciesLive(databaseUrl) : true;
2077
+ if (!adminRoleAvailable) {
2078
+ out(chalk.gray(` The server-or-admin policies are written TO public: the admin request roles are not set up for this database (\`rebase doctor --database\` says what is missing). A server boot that sets them up moves them TO ${REBASE_ADMIN_ROLE}.`));
2079
+ policiesContent = (await policiesToPublic(collectionsPath, policiesContent)).split(`${ADMIN_POLICY_ROLE_SQL};`).join("");
2080
+ }
2081
+ const stamping = await policyStamping(databaseUrl, collectionsPath, policiesContent, adminRoleAvailable);
1989
2082
  const { stampError } = await withAppClient(databaseUrl, (client) => applyPoliciesFile(client, policiesContent, stamping));
1990
2083
  out(chalk.green(" ✓ RLS policies applied successfully."));
1991
2084
  if (stampError) outWarn(chalk.yellow(` ⚠️ The policies could not be stamped (${stampError}); the next boot applies them again.`));
@@ -1997,18 +2090,74 @@ async function applyPolicies(databaseUrl, collectionsPath) {
1997
2090
  }
1998
2091
  }
1999
2092
  /**
2093
+ * Whether the server-or-admin policies belong `TO rebase_admin` on this
2094
+ * database (`adminPoliciesLiveForCli`): the one answer the push writes, plans
2095
+ * and reconciles against, so its dry run and the next push agree with what it
2096
+ * wrote. Anything unreadable answers `false`, `TO public`.
2097
+ *
2098
+ * Judged on this connection. A push run as a different, privileged login can
2099
+ * see a switch the server's own login cannot use; that server's boot then
2100
+ * writes the policies `TO public` itself.
2101
+ */
2102
+ async function readAdminPoliciesLive(databaseUrl) {
2103
+ try {
2104
+ const { adminPoliciesLiveForCli } = await import("./rls-enforcement-CyUCPDH8.js").then((n) => n.y);
2105
+ return await withAppClient(databaseUrl, (client) => adminPoliciesLiveForCli(async (text) => (await client.query(text)).rows));
2106
+ } catch {
2107
+ return false;
2108
+ }
2109
+ }
2110
+ /**
2111
+ * After a migration: the server-or-admin policies it wrote `TO rebase_admin`
2112
+ * go `TO public` where the admin switch is not live, as `applyPolicies` writes
2113
+ * them on a push. Fatal when it fails — those policies refuse every admin
2114
+ * caller, and a boot without provisioning would leave them so.
2115
+ */
2116
+ async function moveAdminPoliciesToPublic(databaseUrl, collectionsPath) {
2117
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
2118
+ const { moveMigratedAdminPoliciesToPublic } = await import("./migrate-policy-stamps-C4qbQ0jK.js");
2119
+ const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
2120
+ try {
2121
+ if (await withAppClient(databaseUrl, (client) => moveMigratedAdminPoliciesToPublic({ query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) }, collections, (message) => outWarn(chalk.yellow(` ⚠️ ${message}`)))) > 0) out(chalk.gray(` The server-or-admin policies are written TO public: the admin request roles are not set up for this database (\`rebase doctor --database\` says what is missing). A server boot that sets them up moves them TO ${REBASE_ADMIN_ROLE}.`));
2122
+ } catch (err) {
2123
+ outError(chalk.red(` ✗ Could not write the server-or-admin policies TO public: ${err instanceof Error ? err.message : String(err)}`));
2124
+ outError(chalk.gray(` They are TO ${REBASE_ADMIN_ROLE}, which admin requests cannot use here, so admins read no rows. Run \`rebase db push\` or boot the server with provisioning on.`));
2125
+ process.exit(1);
2126
+ }
2127
+ }
2128
+ /**
2000
2129
  * The stamps a boot looks for, for the policies `policies.sql` is about to
2001
2130
  * create — see `applyPoliciesFile`. None when the collections cannot be read
2002
2131
  * here, which costs only the shortcut: the next boot re-applies, as before.
2003
2132
  */
2004
- async function policyStamping(databaseUrl, collectionsPath, policiesSql) {
2133
+ /**
2134
+ * `policies.sql` with each policy the compiler wrote `TO rebase_admin`
2135
+ * rewritten `TO public` — statement for statement, from the two plans, so a
2136
+ * rule that names `rebase_admin` itself is left exactly as written.
2137
+ */
2138
+ async function policiesToPublic(collectionsPath, policiesSql) {
2139
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
2140
+ const { planCollectionPolicies } = await import("./generate-postgres-ddl-logic-G9PvjHrr.js").then((n) => n.s);
2141
+ const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
2142
+ const fallback = new Map(planCollectionPolicies(collections, { adminRoleAvailable: false }).flatMap((plan) => plan.policies.map((policy) => [`${plan.qualified}.${policy.name}`, policy.statements])));
2143
+ let sql = policiesSql;
2144
+ for (const plan of planCollectionPolicies(collections)) for (const policy of plan.policies) {
2145
+ if (!policy.adminTarget) continue;
2146
+ const replacement = fallback.get(`${plan.qualified}.${policy.name}`) ?? [];
2147
+ policy.statements.forEach((statement, i) => {
2148
+ if (replacement[i]) sql = sql.split(statement).join(replacement[i]);
2149
+ });
2150
+ }
2151
+ return sql;
2152
+ }
2153
+ async function policyStamping(databaseUrl, collectionsPath, policiesSql, adminRoleAvailable = true) {
2005
2154
  try {
2006
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
2007
- const { planCollectionPolicies } = await import("./generate-postgres-ddl-logic-ISVgsP34.js").then((n) => n.s);
2008
- const { policyStampSql } = await import("./ensure-collection-policies-DUpWJb5D.js");
2009
- const { pinSearchPath } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
2155
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
2156
+ const { planCollectionPolicies } = await import("./generate-postgres-ddl-logic-G9PvjHrr.js").then((n) => n.s);
2157
+ const { policyStampSql } = await import("./ensure-collection-policies-DJsOMpaI.js");
2158
+ const { pinSearchPath } = await import("./connection-C1zXTPJq.js").then((n) => n.r);
2010
2159
  return {
2011
- statements: stampableTables(planCollectionPolicies(await loadCollections(path.resolve(process.cwd(), collectionsPath))), policiesSql).map((plan) => policyStampSql(plan)).filter((statement) => statement !== void 0),
2160
+ statements: stampableTables(planCollectionPolicies(await loadCollections(path.resolve(process.cwd(), collectionsPath)), { adminRoleAvailable }), policiesSql).map((plan) => policyStampSql(plan)).filter((statement) => statement !== void 0),
2012
2161
  searchPath: pinSearchPath(databaseUrl) === databaseUrl ? void 0 : "public"
2013
2162
  };
2014
2163
  } catch {
@@ -2023,11 +2172,15 @@ async function policyStamping(databaseUrl, collectionsPath, policiesSql) {
2023
2172
  */
2024
2173
  async function readPolicyPushPlan(databaseUrl, collectionsPath) {
2025
2174
  try {
2026
- const { formatPolicyPushPlan, planPolicyPush, summarizePolicyPushPlan } = await import("./push-policy-plan--oRXOj4X.js");
2027
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
2028
- const { pinSearchPath } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
2175
+ const { formatPolicyPushPlan, planPolicyPush, summarizePolicyPushPlan } = await import("./push-policy-plan-BOw5PtU8.js");
2176
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
2177
+ const { pinSearchPath } = await import("./connection-C1zXTPJq.js").then((n) => n.r);
2029
2178
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
2030
- const plan = await withAppClient(databaseUrl, (client) => planPolicyPush({ query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) }, collections, { searchPath: pinSearchPath(databaseUrl) === databaseUrl ? void 0 : "public" }));
2179
+ const adminRoleAvailable = await readAdminPoliciesLive(databaseUrl);
2180
+ const plan = await withAppClient(databaseUrl, (client) => planPolicyPush({ query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) }, collections, {
2181
+ searchPath: pinSearchPath(databaseUrl) === databaseUrl ? void 0 : "public",
2182
+ adminRoleAvailable
2183
+ }));
2031
2184
  return {
2032
2185
  ...formatPolicyPushPlan(plan),
2033
2186
  summary: summarizePolicyPushPlan(plan)
@@ -2052,11 +2205,12 @@ async function readPolicyPushPlan(databaseUrl, collectionsPath) {
2052
2205
  */
2053
2206
  async function reconcilePolicies(databaseUrl, collectionsPath) {
2054
2207
  try {
2055
- const { checkPolicyDrift, dropOrphanedPolicies, formatPolicyDrift, hasDrift } = await import("./policy-drift-IjD2AUD-.js").then((n) => n.s);
2056
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
2208
+ const { checkPolicyDrift, dropOrphanedPolicies, formatPolicyDrift, hasDrift } = await import("./policy-drift-Bx6663KD.js").then((n) => n.s);
2209
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
2057
2210
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
2211
+ const adminRoleAvailable = await readAdminPoliciesLive(databaseUrl);
2058
2212
  await withAppClient(databaseUrl, async (client) => {
2059
- const drift = await checkPolicyDrift(client, collections);
2213
+ const drift = await checkPolicyDrift(client, collections, { adminRoleAvailable });
2060
2214
  const { dropped, kept } = await dropOrphanedPolicies(client, drift, collections);
2061
2215
  for (const p of dropped) out(chalk.gray(` ✓ Dropped superseded policy "${p.name}" on ${p.schema}.${p.table}`));
2062
2216
  if (dropped.length > 0) out(chalk.green(` ✓ Removed ${dropped.length} superseded RLS ${dropped.length === 1 ? "policy" : "policies"}.`));
@@ -2138,8 +2292,8 @@ async function branchCommand(rawArgs) {
2138
2292
  outError(chalk.red("✗ DATABASE_URL is not set. Make sure your .env file is configured."));
2139
2293
  process.exit(1);
2140
2294
  }
2141
- const { DatabasePoolManager } = await import("./databasePoolManager-7hXVurmG.js").then((n) => n.n);
2142
- const { BranchService, reopenClosedDatabases, reopenedDatabasesNotice } = await import("./BranchService-JiYJ_n9E.js").then((n) => n.n);
2295
+ const { DatabasePoolManager } = await import("./databasePoolManager-DIjzlTK4.js").then((n) => n.n);
2296
+ const { BranchService, reopenClosedDatabases, reopenedDatabasesNotice } = await import("./BranchService-X9R505mP.js").then((n) => n.n);
2143
2297
  const { drizzle } = await import("drizzle-orm/node-postgres");
2144
2298
  const { Pool } = await import("pg");
2145
2299
  const healed = await reopenClosedDatabases(databaseUrl, [branchAction === "create" ? createSource(rawArgs) : void 0, process.env[ACTIVE_BRANCH_DATABASE_ENV]]);
@@ -2686,9 +2840,9 @@ async function schemaStaleCommand(rawArgs) {
2686
2840
  const schemaFile = path.resolve(process.cwd(), outputPath);
2687
2841
  const fix = Boolean(argsList["--fix"]);
2688
2842
  const generatedExists = fs.existsSync(schemaFile);
2689
- const { loadCollections } = await import("./doctor-_g2tHRtG.js").then((n) => n.t);
2843
+ const { loadCollections } = await import("./doctor-DwMXljiq.js").then((n) => n.t);
2690
2844
  const { findLegacyForeignKeyNames, compareGeneratedDeclarations, staleVerdict } = await import("./generated-schema-staleness-BvNF3i-s.js").then((n) => n.r);
2691
- const { generateSchema } = await import("./generate-drizzle-schema-logic-DpFA1UVd.js").then((n) => n.n);
2845
+ const { generateSchema } = await import("./generate-drizzle-schema-logic-BBXjxm5z.js").then((n) => n.n);
2692
2846
  const { relationalCollections } = await import("@rebasepro/common");
2693
2847
  let stale = [];
2694
2848
  let differences = [];
@@ -2849,6 +3003,7 @@ async function doctorPluginCommand(rawArgs) {
2849
3003
  "--schema": String,
2850
3004
  "--sdk": String,
2851
3005
  "--policies": Boolean,
3006
+ "--database": Boolean,
2852
3007
  "-c": "--collections",
2853
3008
  "-s": "--schema",
2854
3009
  "-k": "--sdk"
@@ -2870,7 +3025,8 @@ async function doctorPluginCommand(rawArgs) {
2870
3025
  `--collections=${collectionsPath}`,
2871
3026
  `--schema=${schemaPath}`,
2872
3027
  `--sdk=${sdkPath}`,
2873
- ...parsedArgs["--policies"] ? ["--policies"] : []
3028
+ ...parsedArgs["--policies"] ? ["--policies"] : [],
3029
+ ...parsedArgs["--database"] ? ["--database"] : []
2874
3030
  ];
2875
3031
  try {
2876
3032
  await execa(cmdParts[0], cmdParts.slice(1), {