@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
@@ -1,9 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { a as __require, i as __exportAll, n as require_arg, o as __toESM, r as __commonJSMin } from "./cli-prompt-DXG0yk-h.js";
4
- import { H as withAppClient, rt as redactConnectionPasswords } from "./cli-errors-D8s4z_3g.js";
5
- import { LEGACY_RLS_SCHEMA, REBASE_SCHEMA } from "@rebasepro/types";
6
- import { sqlRows } from "@rebasepro/common";
3
+ import { a as __require, n as require_arg, o as __toESM, r as __commonJSMin } from "./cli-prompt-DXG0yk-h.js";
4
+ import { U as withAppClient, it as redactConnectionPasswords } from "./cli-errors-C73Qy7WJ.js";
5
+ import { g as renderPredicate, m as isRebaseIndexName } from "./source-fZb92pN8.js";
7
6
  import { suggestNearMiss } from "@rebasepro/utils";
8
7
  import process$1, { execArgv, execPath, hrtime, platform } from "node:process";
9
8
  import { constants } from "node:os";
@@ -20,6 +19,164 @@ import { appendFileSync, createReadStream, createWriteStream, readFileSync, stat
20
19
  import { finished } from "node:stream/promises";
21
20
  import { Duplex, PassThrough, Readable, Transform, Writable, getDefaultHighWaterMark } from "node:stream";
22
21
  import { Buffer as Buffer$1 } from "node:buffer";
22
+ //#region src/schema/index-adoption.ts
23
+ /**
24
+ * Adopting an index the database already has, instead of building a twin.
25
+ *
26
+ * A declared index is found by its derived name (`collection-index.ts`), so an
27
+ * index someone made by hand — or one an introspected database arrived with —
28
+ * is invisible to it however exactly it matches the declaration: boot and
29
+ * `db push` built the same index again under the derived name, and every write
30
+ * to the table then maintained two. Declaring the indexes an application
31
+ * already has is the first thing anyone does when they bring a database to
32
+ * Rebase, so that was the common case, not an edge.
33
+ *
34
+ * So before an index is built, an existing one with the same definition on the
35
+ * same table takes the derived name (`ALTER INDEX … RENAME TO …`: a catalogue
36
+ * update, no rebuild, a brief lock). From then on it is the declared index:
37
+ * found by name, kept by push, dropped when the declaration is removed.
38
+ *
39
+ * "The same definition" is read from the catalogue part by part, not by
40
+ * comparing SQL text: the access method, uniqueness, the key columns in order
41
+ * with their direction and NULLS placement, the INCLUDE columns, the predicate,
42
+ * and — because two indexes over the same columns can still answer different
43
+ * queries — that every key uses its type's default operator class and the
44
+ * column's own collation. An index that differs in any of those, is over an
45
+ * expression, backs a constraint, is INVALID, or already carries a Rebase name
46
+ * is left alone, and the declared one is built beside it as before.
47
+ *
48
+ * A partial index is adopted only when the two predicates read the same once
49
+ * Postgres's own spelling is normalised away (identifier quotes, casts on
50
+ * literals, parentheses, case). A wrong adoption would leave a declared index
51
+ * answering a narrower question than the one declared, so a predicate this
52
+ * cannot read as the same is not adopted.
53
+ */
54
+ /**
55
+ * Every index on an ordinary or partitioned table in `schemas`, as
56
+ * {@link ExistingIndexShape} rows. The schema names are written in as quoted
57
+ * literals: the boot's catalogue reader runs its queries without parameters.
58
+ */
59
+ var indexShapesSql = (schemas) => `
60
+ SELECT n.nspname AS "schema",
61
+ t.relname AS "table",
62
+ i.relname AS "index",
63
+ am.amname AS "method",
64
+ x.indisunique AS "unique",
65
+ ARRAY(
66
+ SELECT a.attname::text
67
+ FROM unnest((x.indkey::int2[])[0:x.indnkeyatts - 1]) WITH ORDINALITY AS k(attnum, ord)
68
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND k.attnum > 0
69
+ ORDER BY k.ord
70
+ ) AS "keys",
71
+ ARRAY(SELECT o::int FROM unnest(x.indoption::int2[]) WITH ORDINALITY AS u(o, ord) ORDER BY u.ord) AS "options",
72
+ ARRAY(
73
+ SELECT a.attname::text
74
+ FROM unnest((x.indkey::int2[])[x.indnkeyatts:]) WITH ORDINALITY AS k(attnum, ord)
75
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
76
+ ORDER BY k.ord
77
+ ) AS "include",
78
+ pg_get_expr(x.indpred, x.indrelid) AS "predicate",
79
+ NOT EXISTS (
80
+ SELECT 1
81
+ FROM unnest((x.indclass::oid[])[0:x.indnkeyatts - 1], (x.indcollation::oid[])[0:x.indnkeyatts - 1],
82
+ (x.indkey::int2[])[0:x.indnkeyatts - 1]) AS k(opclass, coll, attnum)
83
+ JOIN pg_opclass oc ON oc.oid = k.opclass
84
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
85
+ WHERE NOT oc.opcdefault OR NULLIF(k.coll, 0) IS DISTINCT FROM NULLIF(a.attcollation, 0)
86
+ ) AS "defaultOpclassAndCollation",
87
+ EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.oid) AS "constraint",
88
+ x.indisvalid AS "valid"
89
+ FROM pg_index x
90
+ JOIN pg_class i ON i.oid = x.indexrelid
91
+ JOIN pg_class t ON t.oid = x.indrelid
92
+ JOIN pg_namespace n ON n.oid = t.relnamespace
93
+ JOIN pg_am am ON am.oid = i.relam
94
+ WHERE n.nspname IN (${[...new Set(schemas)].map((schema) => `'${schema.replace(/'/g, "''")}'`).join(", ")})
95
+ AND t.relkind IN ('r', 'p')
96
+ ORDER BY n.nspname, t.relname, i.relname`;
97
+ /** Read the {@link ExistingIndexShape}s of the given schemas. */
98
+ async function readIndexShapes(client, schemas) {
99
+ if (schemas.length === 0) return [];
100
+ const { rows } = await client.query(indexShapesSql(schemas));
101
+ return rows;
102
+ }
103
+ /**
104
+ * A predicate with Postgres's own spelling taken out: identifier quotes, the
105
+ * casts it puts on literals (`'live'::text`), parentheses, case, whitespace.
106
+ */
107
+ function normalizePredicate(text) {
108
+ return text.replace(/::(?:character varying|double precision|time(?:stamp)?(?: with(?:out)? time zone)?|[a-z_][a-z0-9_]*)(?:\[\])?/gi, "").replace(/"/g, "").replace(/[()]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
109
+ }
110
+ /** Whether `shape` is `spec` under another name. */
111
+ function indexMatchesSpec(spec, shape) {
112
+ if (shape.schema !== spec.schema || shape.table !== spec.table) return false;
113
+ if (shape.constraint || !shape.valid || !shape.defaultOpclassAndCollation) return false;
114
+ if (shape.method !== spec.method || shape.unique !== spec.unique) return false;
115
+ if (shape.keys.length !== spec.keys.length) return false;
116
+ const ordered = spec.method === "btree";
117
+ for (let i = 0; i < spec.keys.length; i++) {
118
+ const key = spec.keys[i];
119
+ if (shape.keys[i] === null || shape.keys[i] !== key.column) return false;
120
+ if (!ordered) continue;
121
+ const desc = (shape.options[i] & 1) === 1;
122
+ const nullsFirst = (shape.options[i] & 2) === 2;
123
+ if (desc !== (key.direction === "desc") || nullsFirst !== (key.nulls === "first")) return false;
124
+ }
125
+ if (shape.include.length !== spec.include.length || shape.include.some((column, i) => column !== spec.include[i])) return false;
126
+ if (shape.predicate === null !== (spec.predicate === null)) return false;
127
+ if (shape.predicate !== null && spec.predicate !== null && normalizePredicate(shape.predicate) !== normalizePredicate(renderPredicate(spec.predicate))) return false;
128
+ return true;
129
+ }
130
+ /**
131
+ * The renames that make existing indexes the declared ones: for each spec
132
+ * whose derived name the catalogue does not hold, the first existing index on
133
+ * its table with the same definition — never one carrying a Rebase name (it is
134
+ * some declaration's, or one a removed declaration left for push to drop), and
135
+ * never the same one twice.
136
+ */
137
+ function planIndexAdoptions(specs, shapes) {
138
+ const held = new Set(shapes.map((shape) => `${shape.schema}.${shape.index}`));
139
+ const taken = /* @__PURE__ */ new Set();
140
+ const adoptions = [];
141
+ for (const spec of specs) {
142
+ if (held.has(`${spec.schema}.${spec.indexName}`)) continue;
143
+ const match = shapes.find((shape) => !taken.has(`${shape.schema}.${shape.index}`) && !isRebaseIndexName(shape.index) && indexMatchesSpec(spec, shape));
144
+ if (!match) continue;
145
+ taken.add(`${match.schema}.${match.index}`);
146
+ held.add(`${spec.schema}.${spec.indexName}`);
147
+ adoptions.push({
148
+ schema: spec.schema,
149
+ table: spec.table,
150
+ from: match.index,
151
+ to: spec.indexName
152
+ });
153
+ }
154
+ return adoptions;
155
+ }
156
+ var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
157
+ /** The `ALTER INDEX … RENAME TO …` for one adoption. */
158
+ function indexAdoptionStatement(adoption) {
159
+ return `ALTER INDEX ${quoteIdent(adoption.schema)}.${quoteIdent(adoption.from)} RENAME TO ${quoteIdent(adoption.to)};`;
160
+ }
161
+ /**
162
+ * A migration's `CREATE INDEX` of a declared (Rebase-named) index, written
163
+ * `CREATE INDEX IF NOT EXISTS`. `rebase db migrate` adopts an identical
164
+ * existing index before it applies — renaming it to the declared name — and
165
+ * the migration's own statement then finds it there instead of failing on the
166
+ * name. An index named any other way is left as Atlas wrote it.
167
+ */
168
+ function declaredIndexesIfNotExists(migrationSql) {
169
+ let rewritten = 0;
170
+ return {
171
+ sql: migrationSql.replace(/\bCREATE\s+(UNIQUE\s+)?INDEX\s+(?!IF\s+NOT\s+EXISTS\b|CONCURRENTLY\b)"([^"]+)"/gi, (statement, unique, name) => {
172
+ if (!isRebaseIndexName(name)) return statement;
173
+ rewritten++;
174
+ return `CREATE ${unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS "${name}"`;
175
+ }),
176
+ rewritten
177
+ };
178
+ }
179
+ //#endregion
23
180
  //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
24
181
  function isPlainObject(value) {
25
182
  if (typeof value !== "object" || value === null) return false;
@@ -6191,459 +6348,6 @@ createExeca(mapNode);
6191
6348
  createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);
6192
6349
  var { sendMessage, getOneMessage, getEachMessage, getCancelSignal } = getIpcExport();
6193
6350
  //#endregion
6194
- //#region src/schema/rls-bootstrap-sql.ts
6195
- var rls_bootstrap_sql_exports = /* @__PURE__ */ __exportAll({
6196
- DROP_LEGACY_AUTH_SCHEMA_SQL: () => DROP_LEGACY_AUTH_SCHEMA_SQL,
6197
- LEGACY_AUTH_SCHEMA_CONTENTS_SQL: () => LEGACY_AUTH_SCHEMA_CONTENTS_SQL,
6198
- LEGACY_RLS_DEPENDENTS_SQL: () => LEGACY_RLS_DEPENDENTS_SQL,
6199
- LEGACY_RLS_FUNCTION_DEPENDENTS_SQL: () => LEGACY_RLS_FUNCTION_DEPENDENTS_SQL,
6200
- RLS_BOOTSTRAP_SQL: () => RLS_BOOTSTRAP_SQL,
6201
- RLS_BOOTSTRAP_STATEMENTS: () => RLS_BOOTSTRAP_STATEMENTS,
6202
- dropLegacyAuthSchema: () => dropLegacyAuthSchema,
6203
- rlsRuntimeIsCurrent: () => rlsRuntimeIsCurrent
6204
- });
6205
- /**
6206
- * Canonical SQL bootstrap for the RLS helper functions.
6207
- *
6208
- * Generated RLS policies reference `rebase.uid()` / `rebase.roles()` /
6209
- * `rebase.jwt()`, so any SQL stream that can contain policies must be
6210
- * self-contained: it has to (re)create these helpers first. This matters for
6211
- * the migration directory in particular — Atlas replays migrations against a
6212
- * clean dev database where no out-of-band bootstrap has ever run, so a
6213
- * migration carrying policies without this preamble fails with
6214
- * "function rebase.uid() does not exist".
6215
- *
6216
- * Idempotent (`IF NOT EXISTS` / `OR REPLACE`) so it can be prepended to every
6217
- * policies block and re-applied freely. The runtime boot path
6218
- * (`auth/ensure-tables.ts`) creates the same functions under an advisory lock
6219
- * for HMR-safety; keep the definitions in sync.
6220
- *
6221
- * ## Creating the `rebase` schema here is now safe, and required
6222
- *
6223
- * It deliberately did not, once. These functions lived in a schema called
6224
- * `auth`, and the note here read: creating `rebase` would leak it into Atlas's
6225
- * replayed migration state, and — absent from the desired `schema.sql` — Atlas
6226
- * would then plan `DROP SCHEMA "rebase" CASCADE`, taking the auth tables with
6227
- * it. That reasoning still holds; what changed is the second half of it. The
6228
- * DDL generator now emits `CREATE SCHEMA IF NOT EXISTS "rebase"`
6229
- * unconditionally, so the schema is always in the desired state and the diff is
6230
- * empty. (It used to appear only when some collection happened to declare
6231
- * `schema: "rebase"` — true for the scaffold's users collection, and not a
6232
- * property anything guaranteed.) `db push` additionally excludes the whole
6233
- * schema from the declarative apply.
6234
- *
6235
- * See `@rebasepro/types`' `rls-functions` for why the functions moved out of
6236
- * `auth` at all: the short version is that the name was Supabase's, and
6237
- * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` cannot be applied over
6238
- * Supabase's `RETURNS uuid` — Postgres refuses, and the refusal used to be
6239
- * swallowed.
6240
- */
6241
- /**
6242
- * The bootstrap as individual statements.
6243
- *
6244
- * Kept as an array because the two consumers need different shapes and only one
6245
- * of them can take a multi-command string: the migration preamble is written to
6246
- * a file and replayed by Atlas, but the boot path runs through drizzle, whose
6247
- * node-postgres handle speaks the extended query protocol and rejects more than
6248
- * one command per call. Splitting a joined string back apart on `$$;` would be
6249
- * a parser for a problem that does not need one.
6250
- */
6251
- var RLS_BOOTSTRAP_STATEMENTS = [
6252
- `CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`,
6253
- `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.uid() RETURNS text AS $$
6254
- SELECT COALESCE(
6255
- NULLIF(current_setting('app.uid', true), ''),
6256
- NULLIF(current_setting('app.user_id', true), '')
6257
- );
6258
- $$ LANGUAGE sql STABLE`,
6259
- `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.jwt() RETURNS jsonb AS $$
6260
- SELECT COALESCE(
6261
- NULLIF(current_setting('app.jwt', true), ''),
6262
- '{}'
6263
- )::jsonb;
6264
- $$ LANGUAGE sql STABLE`,
6265
- `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.roles() RETURNS text AS $$
6266
- SELECT COALESCE(NULLIF(current_setting('app.user_roles', true), ''), '');
6267
- $$ LANGUAGE sql STABLE`,
6268
- `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_anonymous() RETURNS boolean AS $$
6269
- SELECT COALESCE(NULLIF(current_setting('app.is_anonymous', true), ''), 'false')::boolean;
6270
- $$ LANGUAGE sql STABLE`
6271
- ];
6272
- /** Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one comparable string. */
6273
- var describeFunction = (facts) => JSON.stringify([
6274
- facts.returns.toLowerCase(),
6275
- facts.language.toLowerCase(),
6276
- facts.volatility,
6277
- facts.strict,
6278
- facts.parallel,
6279
- facts.securityDefiner,
6280
- facts.leakproof,
6281
- facts.cost,
6282
- facts.hasConfig,
6283
- facts.body
6284
- ]);
6285
- /**
6286
- * What each `CREATE OR REPLACE FUNCTION` in {@link RLS_BOOTSTRAP_STATEMENTS}
6287
- * would leave in the catalogue, by `schema.name`. Parsed
6288
- * from the statements themselves, so the two cannot drift; a statement this
6289
- * does not recognise makes {@link rlsRuntimeIsCurrent} answer "no", and the
6290
- * bootstrap runs as it always did.
6291
- */
6292
- var expectedRlsFunctions = () => {
6293
- const expected = /* @__PURE__ */ new Map();
6294
- for (const statement of RLS_BOOTSTRAP_STATEMENTS) {
6295
- if (/^CREATE SCHEMA IF NOT EXISTS /.test(statement)) continue;
6296
- const match = /^CREATE OR REPLACE FUNCTION (\w+)\.(\w+)\(\) RETURNS (\w+) AS \$\$([\s\S]*)\$\$ LANGUAGE (\w+) (IMMUTABLE|STABLE|VOLATILE)$/.exec(statement);
6297
- if (!match) return void 0;
6298
- const [, schema, name, returns, body, language, volatility] = match;
6299
- expected.set(`${schema}.${name}`, describeFunction({
6300
- returns,
6301
- language,
6302
- volatility: volatility[0].toLowerCase(),
6303
- strict: false,
6304
- parallel: "u",
6305
- securityDefiner: false,
6306
- leakproof: false,
6307
- cost: 100,
6308
- hasConfig: false,
6309
- body
6310
- }));
6311
- }
6312
- return expected;
6313
- };
6314
- /**
6315
- * Whether the `rebase` schema and every RLS helper function are exactly what
6316
- * {@link RLS_BOOTSTRAP_STATEMENTS} would make them — one catalogue read.
6317
- *
6318
- * The boot ran those statements unconditionally, on every boot and on every
6319
- * source: four `CREATE OR REPLACE FUNCTION`s in a transaction under an
6320
- * advisory lock. Replacing a function rewrites its `pg_proc` row even when
6321
- * nothing changed, and every cached plan that inlined it — every plan of every
6322
- * statement a policy applies to, on every connection — is invalidated by it.
6323
- * A function that differs in anything `CREATE OR REPLACE` sets (body,
6324
- * language, volatility, strictness, parallel safety, security, leakproofness,
6325
- * cost, `SET` options), or is missing, answers `false`, and the statements run
6326
- * as before.
6327
- */
6328
- async function rlsRuntimeIsCurrent(run) {
6329
- const expected = expectedRlsFunctions();
6330
- if (!expected) return false;
6331
- const rows = await run(`SELECT n.nspname AS schema, p.proname AS name, pg_get_function_identity_arguments(p.oid) AS args,
6332
- format_type(p.prorettype, NULL) AS returns, l.lanname AS language,
6333
- p.provolatile::text AS volatility, p.proisstrict AS strict, p.proparallel::text AS parallel,
6334
- p.prosecdef AS security_definer, p.proleakproof AS leakproof, p.procost AS cost,
6335
- p.proconfig IS NOT NULL AS has_config, p.prosrc AS body
6336
- FROM pg_proc p
6337
- JOIN pg_namespace n ON p.pronamespace = n.oid
6338
- JOIN pg_language l ON p.prolang = l.oid
6339
- WHERE (n.nspname, p.proname) IN (${[...expected.keys()].map((key) => key.split(".")).map(([schema, name]) => `('${schema}', '${name}')`).join(", ")})`);
6340
- const live = /* @__PURE__ */ new Map();
6341
- for (const row of rows) {
6342
- if (String(row.args ?? "") !== "") continue;
6343
- live.set(`${row.schema}.${row.name}`, describeFunction({
6344
- returns: String(row.returns),
6345
- language: String(row.language),
6346
- volatility: String(row.volatility),
6347
- strict: row.strict === true,
6348
- parallel: String(row.parallel),
6349
- securityDefiner: row.security_definer === true,
6350
- leakproof: row.leakproof === true,
6351
- cost: Number(row.cost),
6352
- hasConfig: row.has_config === true,
6353
- body: String(row.body)
6354
- }));
6355
- }
6356
- for (const [key, definition] of expected) if (live.get(key) !== definition) return false;
6357
- return true;
6358
- }
6359
- /** The same statements as one script, for migration files and raw clients. */
6360
- var RLS_BOOTSTRAP_SQL = "-- Rebase schema + RLS helper functions (required by the policies below)\n" + RLS_BOOTSTRAP_STATEMENTS.map((s) => `${s};`).join("\n\n") + "\n";
6361
- /**
6362
- * The three functions every pre-1.0 release put in `auth`. (The auth tables
6363
- * lived in `rebase`, or wherever the users collection was declared.)
6364
- *
6365
- * `uid()` is matched on either spelling of the principal because Rebase wrote
6366
- * both. Until v0.10.0 its body was
6367
- * `SELECT NULLIF(current_setting('app.user_id', true), '')`; v0.10.0 renamed
6368
- * the GUC to `app.uid` and kept `app.user_id` as a fallback; v0.14.0 moved the
6369
- * helpers to `rebase`. A database last booted before v0.10.0 therefore holds an
6370
- * `auth.uid()` that reads `app.user_id` alone — as does anything that copied
6371
- * that body, the Rebase control plane included — and matching `app.uid` only
6372
- * left every one of them in place, with the schema around it.
6373
- *
6374
- * This is the one place either spelling is listed: the drop and the report of
6375
- * what it left are both generated from it, so they cannot disagree about which
6376
- * functions are Rebase's.
6377
- */
6378
- var LEGACY_AUTH_HELPERS = [
6379
- {
6380
- name: "uid",
6381
- returns: "text",
6382
- reads: ["app.uid", "app.user_id"]
6383
- },
6384
- {
6385
- name: "jwt",
6386
- returns: "jsonb",
6387
- reads: ["app.jwt"]
6388
- },
6389
- {
6390
- name: "roles",
6391
- returns: "text",
6392
- reads: ["app.user_roles"]
6393
- }
6394
- ];
6395
- /**
6396
- * `pg_proc p` has a Rebase helper's name, arity and result type: what
6397
- * `CREATE OR REPLACE` would have left, whatever the body.
6398
- *
6399
- * Two things that share that shape are excluded outright: a body reading
6400
- * `request.jwt` (Supabase's helpers and anything modelled on them) and a
6401
- * function an extension installed (`pg_session_jwt` puts an `auth.jwt()
6402
- * RETURNS jsonb` in the same schema).
6403
- */
6404
- var isLegacyHelperShaped = (helper) => `(
6405
- p.proname = '${helper.name}' AND p.pronargs = 0
6406
- AND pg_get_function_result(p.oid) = '${helper.returns}'
6407
- AND strpos(p.prosrc, 'request.jwt') = 0
6408
- AND NOT EXISTS (
6409
- SELECT 1 FROM pg_depend e
6410
- WHERE e.classid = 'pg_proc'::regclass AND e.objid = p.oid AND e.deptype = 'e'
6411
- ))`;
6412
- /** `pg_proc p` is a helper Rebase wrote: its shape, and a body reading one of its GUCs. */
6413
- var isLegacyHelper = (helper) => `${isLegacyHelperShaped(helper)}
6414
- AND (${helper.reads.map((guc) => `strpos(p.prosrc, '${guc}') > 0`).join(" OR ")})`;
6415
- /**
6416
- * Removes the pre-1.0 `auth` schema, but only when Rebase is what put it there.
6417
- *
6418
- * ## Why this is safe against a Supabase database
6419
- *
6420
- * Two independent guards, and both have to pass:
6421
- *
6422
- * 1. **Each function is identified before it is dropped.** Ours returns `text`
6423
- * and reads the `app.uid` or `app.user_id` GUC; Supabase's returns `uuid`
6424
- * and reads `request.jwt.claims`. Nothing is dropped on a signature we did
6425
- * not write, so a Supabase database — where our `CREATE OR REPLACE` could
6426
- * never have succeeded in the first place, Postgres refusing to change a
6427
- * return type — matches nothing and this is a no-op. See
6428
- * {@link LEGACY_AUTH_HELPERS} for exactly what is matched.
6429
- * 2. **`DROP SCHEMA … RESTRICT`**, never CASCADE. If anything else at all still
6430
- * lives in `auth` (Supabase's `users` table, its other helpers), the drop
6431
- * fails and the schema stays. CASCADE here would be unrecoverable.
6432
- *
6433
- * ## Why it cannot run too early
6434
- *
6435
- * Postgres records a dependency from every RLS policy to the functions its body
6436
- * calls, so `DROP FUNCTION auth.uid()` fails for as long as a single policy
6437
- * still references it. That is the interlock, and it is load-bearing: the drop
6438
- * can only succeed once every policy has been recompiled to \`rebase.uid()\`.
6439
- * Callers therefore run this *after* applying policies, and treat a failure as
6440
- * "not yet — try again next boot" rather than as an error.
6441
- */
6442
- var DROP_LEGACY_AUTH_SCHEMA_SQL = `
6443
- DO $rebase_drop_legacy$
6444
- DECLARE
6445
- dropped_any boolean := false;
6446
- BEGIN
6447
- -- Each function is matched on its own result type and body, so a schema
6448
- -- that merely shares the name keeps everything it has.
6449
- ${LEGACY_AUTH_HELPERS.map((helper) => ` IF EXISTS (
6450
- SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
6451
- WHERE n.nspname = '${LEGACY_RLS_SCHEMA}' AND ${isLegacyHelper(helper)}
6452
- ) THEN
6453
- DROP FUNCTION ${LEGACY_RLS_SCHEMA}.${helper.name}();
6454
- dropped_any := true;
6455
- END IF;`).join("\n\n")}
6456
-
6457
- -- RESTRICT: only an empty schema goes. Anything else in there — including a
6458
- -- Supabase installation left untouched above — keeps it. Swallowed so the
6459
- -- helpers dropped above stay dropped; dropLegacyAuthSchema looks afterwards
6460
- -- and says what is left.
6461
- IF dropped_any THEN
6462
- BEGIN
6463
- EXECUTE 'DROP SCHEMA ${LEGACY_RLS_SCHEMA} RESTRICT';
6464
- EXCEPTION WHEN OTHERS THEN
6465
- NULL;
6466
- END;
6467
- END IF;
6468
- END
6469
- $rebase_drop_legacy$;
6470
- `;
6471
- /**
6472
- * What the `auth` schema holds, one row per object keeping it alive.
6473
- *
6474
- * No rows: the schema does not exist. A single row with a `null` object: it
6475
- * exists and is empty. Read from the namespace entries in `pg_depend`, which
6476
- * are what `DROP SCHEMA … RESTRICT` itself consults — minus whatever goes with
6477
- * its owner (a serial's sequence, an identity column's), which Postgres does not
6478
- * name either.
6479
- */
6480
- var LEGACY_AUTH_SCHEMA_CONTENTS_SQL = `
6481
- SELECT pg_describe_object(d.classid, d.objid, d.objsubid) AS object,
6482
- CASE
6483
- WHEN d.classid <> 'pg_proc'::regclass THEN NULL
6484
- WHEN EXISTS (
6485
- SELECT 1 FROM pg_proc p
6486
- WHERE p.oid = d.objid
6487
- AND (${LEGACY_AUTH_HELPERS.map((helper) => `(${isLegacyHelper(helper)})`).join(" OR ")})
6488
- ) THEN 'ours'
6489
- WHEN EXISTS (
6490
- SELECT 1 FROM pg_proc p
6491
- WHERE p.oid = d.objid
6492
- AND (${LEGACY_AUTH_HELPERS.map(isLegacyHelperShaped).join(" OR ")})
6493
- ) THEN 'lookalike'
6494
- END AS helper
6495
- FROM pg_namespace n
6496
- LEFT JOIN pg_depend d
6497
- ON d.refclassid = 'pg_namespace'::regclass AND d.refobjid = n.oid AND d.deptype = 'n'
6498
- AND NOT EXISTS (
6499
- SELECT 1 FROM pg_depend o
6500
- WHERE o.classid = d.classid AND o.objid = d.objid AND o.deptype IN ('a', 'i')
6501
- )
6502
- WHERE n.nspname = '${LEGACY_RLS_SCHEMA}'
6503
- ORDER BY helper NULLS LAST, object
6504
- `;
6505
- /**
6506
- * Policies whose body still calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
6507
- *
6508
- * Postgres will not drop a function a policy depends on, so this is exactly the
6509
- * set standing between a database and losing the legacy schema. Rebase's own
6510
- * policies leave the list on the next push or boot, when they are recompiled —
6511
- * anything still here afterwards is hand-written, will never be recompiled by
6512
- * anybody, and is the reason the drop keeps being skipped. Silence there would
6513
- * leave an operator staring at a schema the release notes said would go.
6514
- */
6515
- var LEGACY_RLS_DEPENDENTS_SQL = `
6516
- SELECT n.nspname AS schema, c.relname AS "table", p.polname AS policy
6517
- FROM pg_policy p
6518
- JOIN pg_class c ON c.oid = p.polrelid
6519
- JOIN pg_namespace n ON n.oid = c.relnamespace
6520
- WHERE pg_get_expr(p.polqual, p.polrelid) ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
6521
- OR pg_get_expr(p.polwithcheck, p.polrelid) ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
6522
- ORDER BY 1, 2, 3
6523
- `;
6524
- /**
6525
- * Functions whose body calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
6526
- *
6527
- * This is the half `DROP FUNCTION ... RESTRICT` cannot see, and the reason it
6528
- * needs its own query. Postgres records a dependency for a *policy* that calls a
6529
- * function, which is why the drop is safe against the policies above — but a
6530
- * `LANGUAGE sql` function whose body is a **string literal** is not parsed when
6531
- * it is created, so nothing is recorded and `RESTRICT` has nothing to refuse on.
6532
- * The drop succeeds and the caller is left pointing at a function that no longer
6533
- * exists, which fails at *query* time rather than at boot.
6534
- *
6535
- * A downstream project building on these helpers is not hypothetical: the Rebase
6536
- * control plane defined `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`
6537
- * in this very schema, each calling `auth.uid()` in a string body, and eleven of
6538
- * its row-level-security policies went through them. Every one of those would
6539
- * have started failing the first time a recompile left no policy referencing
6540
- * `auth.uid()` directly — the drop's own precondition. (Its migration 0065 has
6541
- * since moved both to `public`, calling `rebase.uid()`.)
6542
- *
6543
- * Matching on the body text is the only option available, and it is deliberately
6544
- * broad: a false positive costs a schema that stays one release longer and says
6545
- * why, while a false negative costs somebody their policies.
6546
- */
6547
- var LEGACY_RLS_FUNCTION_DEPENDENTS_SQL = `
6548
- SELECT n.nspname AS schema, p.proname AS function
6549
- FROM pg_proc p
6550
- JOIN pg_namespace n ON n.oid = p.pronamespace
6551
- WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
6552
- AND NOT (n.nspname = '${LEGACY_RLS_SCHEMA}' AND p.proname IN ('uid', 'jwt', 'roles'))
6553
- AND p.prosrc ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
6554
- ORDER BY 1, 2
6555
- `;
6556
- /**
6557
- * Retire the pre-1.0 `auth` schema, reporting what is holding it back.
6558
- *
6559
- * The shared implementation behind the CLI's post-push step and the runtime's
6560
- * post-policy step. Both used to just fire {@link DROP_LEGACY_AUTH_SCHEMA_SQL}
6561
- * and swallow whatever came back, which is right for the ordinary case — a
6562
- * table not recompiled *yet* — and wrong for the one that never resolves: a
6563
- * hand-written policy nothing will ever rewrite. Then the schema stays forever
6564
- * and nothing ever says why.
6565
- *
6566
- * The drop itself had the same blind spot. A helper it did not recognise as
6567
- * Rebase's stayed, and so did anything else in the schema, behind a
6568
- * `DROP SCHEMA … RESTRICT` whose failure is swallowed so the helpers it did
6569
- * drop stay dropped. The control plane's `auth.uid()` was one such: it read
6570
- * `app.user_id` alone, the drop looked for `app.uid`, and the schema stayed
6571
- * with no word said. So the schema is read twice. Before, so that one with no
6572
- * Rebase helper in it is left alone: one already gone, as on every boot after
6573
- * the drop, or one that was never Rebase's, like Supabase's — whose own
6574
- * policies the checks below would otherwise report as blockers. After, to name
6575
- * whatever is still there.
6576
- */
6577
- async function dropLegacyAuthSchema(run, report) {
6578
- let before;
6579
- try {
6580
- before = sqlRows(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));
6581
- } catch {
6582
- return;
6583
- }
6584
- if (!before.some((o) => o.helper !== null)) return;
6585
- if (!before.some((o) => o.helper === "ours")) {
6586
- report.warn(describeLegacyAuthLeftovers(before, void 0));
6587
- return;
6588
- }
6589
- let blockers;
6590
- try {
6591
- blockers = sqlRows(await run(LEGACY_RLS_DEPENDENTS_SQL));
6592
- } catch {
6593
- return;
6594
- }
6595
- if (blockers.length > 0) {
6596
- report.warn(`The pre-1.0 \`${LEGACY_RLS_SCHEMA}\` schema cannot be removed yet: ${blockers.length} ${blockers.length === 1 ? "policy still calls" : "policies still call"} \`${LEGACY_RLS_SCHEMA}.uid()\` and friends, and Postgres will not drop a function a policy depends on. Rebase's own policies are rewritten automatically — anything listed here is hand-written SQL that has to be updated to \`${REBASE_SCHEMA}.uid()\` by hand, after which the schema goes on its own:\n` + blockers.map((b) => ` • ${b.schema}.${b.table} → "${b.policy}"`).join("\n"));
6597
- return;
6598
- }
6599
- let borrowers;
6600
- try {
6601
- borrowers = sqlRows(await run(LEGACY_RLS_FUNCTION_DEPENDENTS_SQL));
6602
- } catch {
6603
- return;
6604
- }
6605
- if (borrowers.length > 0) {
6606
- report.warn(`The pre-1.0 \`${LEGACY_RLS_SCHEMA}\` schema cannot be removed yet: ${borrowers.length} ${borrowers.length === 1 ? "function calls" : "functions call"} \`${LEGACY_RLS_SCHEMA}.uid()\` and friends from its own body. Postgres records no dependency for that — a SQL body written as a string literal is never parsed — so dropping the helpers would leave these pointing at nothing, and they would fail when a query reached them rather than now. Repoint them at \`${REBASE_SCHEMA}.uid()\`, after which the schema goes on its own:\n` + borrowers.map((b) => ` • ${b.schema}.${b.function}()`).join("\n"));
6607
- return;
6608
- }
6609
- let failure;
6610
- try {
6611
- await run(DROP_LEGACY_AUTH_SCHEMA_SQL);
6612
- } catch (err) {
6613
- const detail = err instanceof Error && "detail" in err && typeof err.detail === "string" ? err.detail : "";
6614
- failure = (err instanceof Error ? err.message : String(err)) + (detail ? ` (${detail.replace(/\n/g, "; ")})` : "");
6615
- }
6616
- let left;
6617
- try {
6618
- left = sqlRows(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));
6619
- } catch {
6620
- if (failure) report.info(`Left the \`${LEGACY_RLS_SCHEMA}\` schema in place: ${failure}`);
6621
- return;
6622
- }
6623
- if (left.length === 0) return;
6624
- report.warn(describeLegacyAuthLeftovers(left, failure));
6625
- }
6626
- /** At most this many objects are named; a schema this full is plainly in use. */
6627
- var MAX_LEFTOVERS_NAMED = 20;
6628
- /**
6629
- * The warning for an `auth` schema the drop left standing.
6630
- *
6631
- * Said once for objects that are not Rebase's: on the next boot the schema holds
6632
- * no helper, so {@link dropLegacyAuthSchema} leaves it alone — it is somebody
6633
- * else's schema by then. A helper that is still there, Rebase's or a lookalike,
6634
- * keeps it said on every boot until it goes.
6635
- */
6636
- function describeLegacyAuthLeftovers(left, failure) {
6637
- const schema = LEGACY_RLS_SCHEMA;
6638
- const objects = left.filter((o) => o.object !== null);
6639
- if (objects.length === 0) return `The pre-1.0 \`${schema}\` schema is empty, but this connection could not drop it — most likely because it does not own the schema. Run \`DROP SCHEMA ${schema};\` as its owner.`;
6640
- const why = failure ? `dropping Rebase's old helpers from it failed: ${failure}.` : "`DROP SCHEMA … RESTRICT` refuses a schema that is not empty, and Rebase drops only the helpers it can tell are its own.";
6641
- const lines = objects.slice(0, MAX_LEFTOVERS_NAMED).map((o) => o.helper === "ours" ? ` • ${o.object} — Rebase's old helper, which could not be dropped` : o.helper === "lookalike" ? ` • ${o.object} — named and typed like Rebase's old helper, but no release wrote this body, so it was left alone; drop it by hand if nothing of yours calls it` : ` • ${o.object}`);
6642
- if (objects.length > MAX_LEFTOVERS_NAMED) lines.push(` • …and ${objects.length - MAX_LEFTOVERS_NAMED} more`);
6643
- return `The pre-1.0 \`${schema}\` schema is still here: ${why} Still in it:\n` + lines.join("\n") + `
6644
- Anything of yours can stay where it is — Rebase no longer uses this schema — or move out with \`ALTER … SET SCHEMA\`. Once the schema is empty, \`DROP SCHEMA ${schema};\` removes it.`;
6645
- }
6646
- //#endregion
6647
6351
  //#region src/cli-flags.ts
6648
6352
  var import_arg = /* @__PURE__ */ __toESM(require_arg(), 1);
6649
6353
  /**
@@ -7135,7 +6839,9 @@ var DRIVER_DB_SUBCOMMANDS = [
7135
6839
  "branch",
7136
6840
  "backup",
7137
6841
  "restore",
7138
- "backups"
6842
+ "backups",
6843
+ "request-role",
6844
+ "provision"
7139
6845
  ];
7140
6846
  /** Is `word` a `db` subcommand this driver answers? */
7141
6847
  function isDriverDbSubcommand(word) {
@@ -7238,6 +6944,6 @@ async function latestRecordedMigration(databaseUrl) {
7238
6944
  });
7239
6945
  }
7240
6946
  //#endregion
7241
- export { RLS_BOOTSTRAP_STATEMENTS as C, execa as D, rls_bootstrap_sql_exports as E, RLS_BOOTSTRAP_SQL as S, rlsRuntimeIsCurrent as T, closestWord as _, migrationVersionOf as a, parseDriverLine as b, isDriverDbSubcommand as c, branchNameIn as d, branchSourceIn as f, assertKnownFlags as g, RELAYED_FLAGS as h, latestRecordedMigration as i, backupActionOf as l, unexpectedBranchArgs as m, compareMigrationVersions as n, planBaseline as o, resolveBranchSwitches as p, describeBaselinePlan as r, DRIVER_DB_SUBCOMMANDS as s, baselineVersionProblem as t, assertKnownBranchFlags as u, collectionsPathIn as v, dropLegacyAuthSchema as w, resolveDriverSwitches as x, parseCommandFlags as y };
6947
+ export { declaredIndexesIfNotExists as C, readIndexShapes as E, execa as S, planIndexAdoptions as T, closestWord as _, migrationVersionOf as a, parseDriverLine as b, isDriverDbSubcommand as c, branchNameIn as d, branchSourceIn as f, assertKnownFlags as g, RELAYED_FLAGS as h, latestRecordedMigration as i, backupActionOf as l, unexpectedBranchArgs as m, compareMigrationVersions as n, planBaseline as o, resolveBranchSwitches as p, describeBaselinePlan as r, DRIVER_DB_SUBCOMMANDS as s, baselineVersionProblem as t, assertKnownBranchFlags as u, collectionsPathIn as v, indexAdoptionStatement as w, resolveDriverSwitches as x, parseCommandFlags as y };
7242
6948
 
7243
- //# sourceMappingURL=migrate-baseline-BeepEphh.js.map
6949
+ //# sourceMappingURL=migrate-baseline-CveNQli3.js.map