@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
@@ -28,6 +28,7 @@
28
28
  * already has*, and which of the planned constraints are safe to apply to it.
29
29
  */
30
30
  import type { SchemaPlan } from "./types.js";
31
+ import { type ExistingIndexShape } from "../index-adoption.js";
31
32
  import { type SkippedVectorIndex } from "../vector-index.js";
32
33
  import { type ColumnTypeDrift } from "../column-type-drift.js";
33
34
  /**
@@ -79,7 +80,10 @@ export interface ExistingSchema {
79
80
  * `numeric(10,2)`).
80
81
  */
81
82
  columnTypes?: Map<string, string>;
82
- /** `schema.table.trigger` of every trigger that already exists. */
83
+ /**
84
+ * `schema.table.trigger` of every trigger that already exists, and the
85
+ * same with its arguments — {@link triggerArgumentsKey}.
86
+ */
83
87
  triggers?: Set<string>;
84
88
  /**
85
89
  * `schema.name` of every index (any relation of kind `i`/`I`) that already
@@ -95,6 +99,12 @@ export interface ExistingSchema {
95
99
  * `IF NOT EXISTS` skips it by name forever. Absent means unknown.
96
100
  */
97
101
  invalidIndexes?: Set<string>;
102
+ /**
103
+ * Every index's definition, read from the catalogue, so a declared index
104
+ * adopts an identical one under another name (`index-adoption.ts`) instead
105
+ * of building a twin. Absent means unknown, and nothing is adopted.
106
+ */
107
+ indexShapes?: ExistingIndexShape[];
98
108
  /**
99
109
  * Names of the extensions installed in the database. `CREATE EXTENSION IF
100
110
  * NOT EXISTS` skips by name whatever schema the extension is in, so the name
@@ -116,6 +126,8 @@ export interface ExistingSchema {
116
126
  * which is what all of them were before.
117
127
  */
118
128
  export declare const HELPER_FUNCTIONS: readonly string[];
129
+ /** A trigger's catalogue key with the arguments it is bound with. */
130
+ export declare const triggerArgumentsKey: (key: string, args: readonly string[]) => string;
119
131
  /**
120
132
  * Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one string.
121
133
  *
@@ -190,7 +202,7 @@ export interface DiffOptions {
190
202
  deferLiveIndexes?: boolean;
191
203
  }
192
204
  export interface EnsureAction {
193
- kind: "create-enum" | "create-table" | "enable-rls" | "add-column" | "add-constraint" | "rename-column" | "create-extension" | "create-function" | "create-index" | "comment-column" | "add-enum-value" | "set-not-null" | "drop-not-null" | "set-default" | "create-trigger";
205
+ kind: "create-enum" | "create-table" | "enable-rls" | "add-column" | "add-constraint" | "rename-column" | "create-extension" | "create-function" | "create-index" | "comment-column" | "add-enum-value" | "set-not-null" | "drop-not-null" | "set-default" | "create-trigger" | "rename-index";
194
206
  /** Qualified target, for logging: `public.posts` or `public.posts.title`. */
195
207
  target: string;
196
208
  sql: string;
@@ -53,6 +53,13 @@ export declare const renderDenyingPolicyStatements: (table: Pick<TablePlan, "sch
53
53
  /** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — every generated table is locked. */
54
54
  export declare const renderEnableRls: (table: Pick<TablePlan, "schema" | "table">) => string;
55
55
  export declare function renderPostgresDdl(plan: SchemaPlan, options?: DdlRenderOptions): string;
56
+ /**
57
+ * The statement that creates `rebase_admin`, when a policy in the plan is
58
+ * written `TO` it — so a file of policies is self-contained, as it is for the
59
+ * RLS helpers: CREATE POLICY refuses a role that does not exist. Empty when no
60
+ * policy names it (`rls.adminPolicies: "public"`).
61
+ */
62
+ export declare function adminRolePreamble(plan: SchemaPlan): string;
56
63
  export declare function renderPoliciesDdl(plan: SchemaPlan): string;
57
64
  export declare function renderSearchDdl(plan: SchemaPlan): string;
58
65
  /**
@@ -83,9 +90,16 @@ export declare const viewComment: (view: ViewPlan) => string;
83
90
  /**
84
91
  * The statements that create one view as planned, comment included, for
85
92
  * `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the
86
- * policies of the tables it reads decide what each caller sees; a
87
- * materialized view gets a unique index on its id columns, which
88
- * `REFRESH MATERIALIZED VIEW CONCURRENTLY` needs.
93
+ * policies of the tables it reads decide what each caller sees.
94
+ *
95
+ * A materialized view is two objects (see `view-names.ts`): its rows, stored
96
+ * under {@link viewRowsName} with a unique index on the id columns (which
97
+ * `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —
98
+ * a `security_barrier` view that reads them with the owner's rights and serves
99
+ * them to the collection's roles and to the server (no uid). It reads the
100
+ * settings directly rather than through `rebase.roles()`, which a first boot
101
+ * creates after the views. It carries each row's `xmin`, for `fingerprint()`;
102
+ * the catalogue reader leaves that column out of the collection.
89
103
  */
90
104
  export declare function viewCreateStatements(view: ViewPlan): string[];
91
105
  /**
@@ -0,0 +1,9 @@
1
+ import type { TriggerPlan } from "./types.js";
2
+ /** The one trigger function, qualified. A frozen derived name. */
3
+ export declare const KEEP_TENANT_FN = "rebase.keep_tenant";
4
+ /** The trigger's name on `table`. A frozen derived name. */
5
+ export declare const keepTenantTriggerName: (table: string) => string;
6
+ export declare const keepTenantFunction: () => string;
7
+ /** The arguments the binding passes: the column, then each bypass role. */
8
+ export declare const keepTenantArguments: (plan: TriggerPlan) => string[];
9
+ export declare const createKeepTenantStatement: (plan: TriggerPlan) => string;
@@ -274,6 +274,8 @@ export interface PolicyPlan {
274
274
  using: string | null;
275
275
  /** Compiled `WITH CHECK` clause, or null when the operation takes none. */
276
276
  withCheck: string | null;
277
+ /** `roles` is `["rebase_admin"]` by the compiler's choice — see `CompiledRulePolicy.adminTarget`. */
278
+ adminTarget?: true;
277
279
  /**
278
280
  * True when Rebase added this rule rather than the author. They are
279
281
  * permissive, so they OR with the declared rules and widen the ACL beyond
@@ -297,6 +299,14 @@ export interface TriggerPlan {
297
299
  column: string;
298
300
  /** Frozen derived name — see `contracts/derived-names.txt`. */
299
301
  name: string;
302
+ /**
303
+ * What the trigger does: `touch` stamps `column` with `now()` on every
304
+ * update (`autoValue: "on_update"`, the default); `keep-tenant` refuses an
305
+ * update that changes the tenant `column` (see `tenant-keep-trigger.ts`).
306
+ */
307
+ kind?: "touch" | "keep-tenant";
308
+ /** `keep-tenant` only: the roles that may move a row between tenants. */
309
+ bypassRoles?: string[];
300
310
  }
301
311
  /** A Postgres enum type one or more columns reference. */
302
312
  export interface EnumPlan {
@@ -422,8 +432,15 @@ export interface ViewPlan {
422
432
  qualified: string;
423
433
  query: string;
424
434
  materialized: boolean;
435
+ /**
436
+ * Materialized only: the roles its gate serves (`view.roles`, default
437
+ * `["admin"]`). See `viewRowsName`.
438
+ */
439
+ roles: string[];
425
440
  /** The `isId` columns: a materialized view gets a unique index on them, which `REFRESH … CONCURRENTLY` needs. */
426
441
  idColumns: string[];
442
+ /** Materialized only: the `CREATE INDEX` of each declared index, on the stored rows. */
443
+ indexes: string[];
427
444
  /** The other planned views this one's query names, which must exist first. */
428
445
  dependsOn: string[];
429
446
  /**
@@ -18,5 +18,5 @@ export declare const setUpdatedAtFunction: () => string;
18
18
  */
19
19
  export declare const dropTriggerStatement: (plan: TriggerPlan) => string;
20
20
  export declare const createTriggerStatement: (plan: TriggerPlan) => string;
21
- /** Both statements, in the order they must run. */
21
+ /** Both statements, in the order they must run — for either kind of trigger. */
22
22
  export declare const triggerStatements: (plan: TriggerPlan) => string[];
@@ -0,0 +1,6 @@
1
+ /** The roles a materialized view is served to when it names none. */
2
+ export declare const DEFAULT_VIEW_ROLES: readonly string[];
3
+ /** Where a materialized view's rows are stored. A frozen derived name. */
4
+ export declare const viewRowsName: (name: string) => string;
5
+ /** The comment the stored rows carry, beside the gate's `rebase:view:<hash>`. */
6
+ export declare const VIEW_ROWS_COMMENT_PREFIX = "rebase:view-rows:";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `db push`'s half of index adoption (`index-adoption.ts`): before Atlas
3
+ * plans, an existing index identical to a declared one takes the declared
4
+ * one's name, so the plan finds it there instead of creating a twin beside it.
5
+ * Boot does the same through its own plan (`diffPlanAgainstCatalogue`).
6
+ */
7
+ import { type CollectionConfig } from "@rebasepro/types";
8
+ import { type IndexAdoption, type ShapeQueryable } from "./index-adoption.js";
9
+ /** The renames that make the database's identical indexes the collections' declared ones. */
10
+ export declare function pushIndexAdoptions(client: ShapeQueryable, collections: CollectionConfig[]): Promise<IndexAdoption[]>;
@@ -27,7 +27,7 @@
27
27
  * push's reconcile step decides.
28
28
  */
29
29
  import type { CollectionConfig } from "@rebasepro/types";
30
- import { type PolicyRef, type Queryable } from "../security/policy-drift.js";
30
+ import { type AdminPoliciesExpectation, type PolicyRef, type Queryable } from "../security/policy-drift.js";
31
31
  export interface PolicyPushPlan {
32
32
  /** Declared tables in the database with row-level security off, as `schema.table`: the push switches it on. */
33
33
  enableRls: string[];
@@ -51,9 +51,13 @@ export interface PolicyPushPlan {
51
51
  * @param options.searchPath the `search_path` the stamps were written under
52
52
  * when the connection's own differs — the one `db push` stamps under.
53
53
  * See {@link readPolicyStamps}.
54
+ * @param options.adminRoleAvailable where the push writes the server-or-admin
55
+ * policies (`TO rebase_admin`, or `TO public` where the admin switch is
56
+ * not live); `"detect"` reads it off the database. Left out, as compiled.
54
57
  */
55
58
  export declare function planPolicyPush(client: Queryable, collections: CollectionConfig[], options?: {
56
59
  searchPath?: string;
60
+ adminRoleAvailable?: AdminPoliciesExpectation;
57
61
  }): Promise<PolicyPushPlan>;
58
62
  /** Whether the push would change any row-level security. Kept and unstamped policies are not changes. */
59
63
  export declare function policyPlanChanges(plan: PolicyPushPlan): boolean;
@@ -185,3 +185,37 @@ export declare function dropLegacyAuthSchema(run: (sql: string) => Promise<Recor
185
185
  info: (m: string) => void;
186
186
  warn: (m: string) => void;
187
187
  }): Promise<void>;
188
+ /**
189
+ * `rebase.is_request_role(role)` — is `role` one of the roles this database's
190
+ * requests run as? The predicate `rls.policyTarget: "requestRole"` ANDs into
191
+ * every permissive policy (`RLS_IS_REQUEST_ROLE_SQL`), called with
192
+ * `current_user`.
193
+ *
194
+ * SECURITY DEFINER because the recorded roles live in `rebase.schema_meta`,
195
+ * which the request roles cannot read. That is also why the caller's role is
196
+ * an argument: inside the function `current_user` is its owner. The body is
197
+ * dynamic SQL so the function can be created before the table exists — in
198
+ * Atlas's replay of the migrations, for one. With nothing recorded the answer
199
+ * is `rebase_user`, as everywhere else. Each recorded role's admin counterpart
200
+ * (`<role>_admin`, what an admin request switches to) answers `true` as well.
201
+ *
202
+ * Created only for a project that asks for `policyTarget: "requestRole"`, so
203
+ * every other project's migrations and boot are exactly what they were.
204
+ */
205
+ export declare const REQUEST_ROLE_FUNCTION_SQL = "CREATE OR REPLACE FUNCTION rebase.is_request_role(role_name text) RETURNS boolean AS $$\nDECLARE\n request_roles text[];\nBEGIN\n IF to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE 'SELECT string_to_array(value, '','') FROM \"rebase\".\"schema_meta\" WHERE key = ''request_roles'''\n INTO request_roles;\n END IF;\n request_roles := COALESCE(request_roles, ARRAY['rebase_user']);\n -- An admin request runs as the request role's admin counterpart\n -- (adminRequestRoleFor), which is a request role here too.\n RETURN role_name = ANY(request_roles) OR role_name = ANY(ARRAY(SELECT r || '_admin' FROM unnest(request_roles) AS r));\nEND\n$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog";
206
+ /**
207
+ * Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body
208
+ * differs — replacing an unchanged function would still invalidate every
209
+ * cached plan of every policy that calls it.
210
+ */
211
+ export declare function ensureRequestRoleFunction(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void>;
212
+ /**
213
+ * The statement that creates {@link REBASE_ADMIN_ROLE} when it is missing — a
214
+ * role with no privilege that cannot log in, whose only job is to be what the
215
+ * server-or-admin policies are written `TO`. Guarded in the statement, and a
216
+ * concurrent creator's win taken as success, because a role belongs to the
217
+ * cluster and two databases' boots can race for it.
218
+ */
219
+ export declare const ADMIN_POLICY_ROLE_SQL = "DO $rebase_admin_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rebase_admin') THEN\n CREATE ROLE rebase_admin NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEXCEPTION\n WHEN duplicate_object OR unique_violation THEN NULL;\n WHEN insufficient_privilege THEN\n RAISE EXCEPTION 'Rebase writes its server-or-admin policies TO rebase_admin, which does not exist, and % may not create it.', current_user\n USING HINT = 'Run CREATE ROLE rebase_admin NOLOGIN; as an administrator, or declare database({ rls: { adminPolicies: \"public\" } }) (REBASE_RLS_ADMIN_POLICIES=public) to write them TO public.';\nEND\n$rebase_admin_role$";
220
+ /** Create {@link REBASE_ADMIN_ROLE} unless it exists — one read when it does. */
221
+ export declare function ensureAdminPolicyRole(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void>;
@@ -267,9 +267,9 @@ export declare const isSearchIndexColumn: (column: {
267
267
  * Returns undefined when nothing needs dropping, so the common case keeps using
268
268
  * a plain `select()` and this stays invisible in the generated SQL.
269
269
  */
270
- export declare const visibleColumnProjection: (tableColumns: Record<string, {
270
+ export declare const visibleColumnProjection: <C extends {
271
271
  getSQLType?: () => string;
272
- }> | undefined, collection?: CollectionConfig) => Record<string, unknown> | undefined;
272
+ }>(tableColumns: Record<string, C> | undefined, collection?: CollectionConfig) => Record<string, C> | undefined;
273
273
  /** The same exclusion as a drizzle `db.query` `columns` denylist. */
274
274
  export declare const hiddenColumnsOption: (tableColumns: Record<string, {
275
275
  getSQLType?: () => string;
@@ -1 +1 @@
1
- {"version":3,"file":"search-column-BM-GV6vH.js","names":[],"sources":["../src/schema/search-column.ts"],"sourcesContent":["/**\n * The one place a collection's `search` block becomes SQL.\n *\n * Four things describe a Postgres table in this codebase — the DDL generator,\n * the Drizzle schema generator, the runtime table builder for BaaS mode, and\n * the boot-time schema ensure — and each of them has, at some point, described\n * a column differently from the others. The `varchar(255)` note in\n * `generate-postgres-ddl-logic` is one such scar: the same property produced a\n * capped column down one path and an uncapped one down the other, and nothing\n * failed until a user hit the cap.\n *\n * So the search column is not implemented four times. It is computed once,\n * here, and every generator renders the same {@link SearchColumnSpec}. There is\n * a test asserting exactly that (`search-column-contract.test.ts`); the point of\n * this module is that the test has something to assert *about*.\n *\n * ## Why the expressions look the way they do\n *\n * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and\n * Postgres is stricter here than intuition. Verified against PostgreSQL 18:\n *\n * | expression | immutable |\n * |-----------------------------------------|-----------|\n * | `to_tsvector('spanish', col)` | yes |\n * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |\n * | `array_to_string(col, ' ')` | **no** |\n * | `col::text` on `text[]` | **no** |\n * | `to_jsonb(col)` | **no** |\n * | `unaccent(col)` | **no** — dictionary lookup is STABLE |\n * | `jsonb_to_tsvector('spanish', j, '[\"string\"]')` | yes |\n * | `setweight(...) || setweight(...)` | yes |\n *\n * Three of the four things a real search column needs are therefore unavailable\n * directly, which is why {@link searchHelperFunctions} exists: each wraps a\n * stable built-in in an SQL function declared IMMUTABLE. That declaration is a\n * promise, and it is a true one for these three — array joining, JSON string\n * extraction and accent folding are all deterministic for a given input; the\n * built-ins are marked stable only because they must account for element types\n * and dictionaries in general.\n *\n * The alternative was to skip `unaccent` and text arrays entirely. That is not\n * a real option in an accented language: Postgres stems `auditoría` to\n * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query\n * typed without accents misses every row that carries them.\n */\nimport {\n CollectionConfig,\n Property,\n StringProperty,\n ArrayProperty,\n MapProperty,\n SearchConfig,\n SearchField,\n SearchMode,\n SearchWeight,\n isPostgresCollectionConfig,\n DEFAULT_SEARCH_COLUMN,\n DEFAULT_SEARCH_MODE,\n DEFAULT_SEARCH_LANGUAGE,\n DEFAULT_SEARCH_WEIGHT,\n DEFAULT_FUZZY_THRESHOLD\n} from \"@rebasepro/types\";\nimport { createHash } from \"node:crypto\";\nimport { getTableName } from \"@rebasepro/common\";\nimport { toSnakeCase, toPostgresIdentifier } from \"@rebasepro/utils\";\n\n/** Schema-qualified so a collection outside `public` still resolves them. */\nconst HELPER_SCHEMA = \"public\";\n\n/**\n * Names of the helper functions. Frozen: they are recorded in the stored\n * generation expression of every search column ever created, so renaming one\n * orphans every table that already has a search column.\n */\nexport const SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;\nexport const SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;\n\n/** How a declared path reaches text, which decides the SQL that extracts it. */\ntype FieldKind = \"text\" | \"text_array\" | \"jsonb\";\n\n/** One resolved field: where it lives, how to read it, what it is worth. */\nexport interface ResolvedSearchField {\n /** The path exactly as the author wrote it, for error messages. */\n path: string;\n /** The physical column the path starts at. */\n column: string;\n /** Dotted remainder addressed inside a JSONB column, if any. */\n jsonPath: string[];\n kind: FieldKind;\n weight: SearchWeight;\n /** The `setweight(to_tsvector(…), 'X')` term this field contributes. */\n sql: string;\n /** The plain-text term this field contributes, for the fuzzy column. */\n textSql: string;\n /**\n * The same text with accents folded **unconditionally**, for the substring\n * half of {@link SearchMode} `\"hybrid\"`.\n *\n * Separate from {@link textSql} rather than replacing it, and that\n * separation is the whole migration story for `mode`. `textSql` feeds the\n * *stored* generated columns, so changing it changes their generation\n * expression, which changes the fingerprint, which makes the next boot\n * refuse (see `searchStampGuards`). This one is only ever interpolated into\n * a WHERE clause, so a collection can switch to `\"hybrid\"` — and gain\n * accent folding on the substring half — without rebuilding a column or\n * taking an ACCESS EXCLUSIVE lock.\n */\n foldedTextSql: string;\n}\n\n/** Everything the generators need to render one collection's search column. */\nexport interface SearchColumnSpec {\n schema: string;\n table: string;\n /** The generated `tsvector` column. */\n column: string;\n language: string;\n unaccent: boolean;\n /**\n * How the query side matches. Deliberately absent from\n * {@link SearchColumnSpec.expression} and from every fingerprint: it\n * describes the WHERE clause, not the column.\n */\n mode: SearchMode;\n fields: ResolvedSearchField[];\n /** Body of `GENERATED ALWAYS AS ( … ) STORED` for the tsvector column. */\n expression: string;\n indexName: string;\n /** Extensions that must exist before the column can be created. */\n extensions: string[];\n fuzzy?: {\n column: string;\n expression: string;\n indexName: string;\n threshold: number;\n };\n}\n\n/** Raised when a `search` block names something that cannot be searched. */\nexport class SearchConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SearchConfigError\";\n }\n}\n\n/** The `search` block of a collection, or undefined when it has none. */\nexport const getSearchConfig = (collection: CollectionConfig): SearchConfig | undefined =>\n isPostgresCollectionConfig(collection) ? collection.search : undefined;\n\n/**\n * Refuse a `search` block on a collection this engine does not store.\n *\n * The type only permits one on a `PostgresCollectionConfig`, so TypeScript\n * already stops the ordinary case. This catches the rest — a JS config, a cast,\n * a collection whose `engine` was changed after the block was written — because\n * the alternative is the exact failure the block exists to prevent: a developer\n * who declared what to index, saw no error, and got the substring fallback.\n *\n * Called with *every* collection, before the Postgres ones are filtered out.\n */\nexport const assertSearchIsPostgresOnly = (collections: CollectionConfig[]): void => {\n for (const collection of collections) {\n if (isPostgresCollectionConfig(collection)) continue;\n if (!(collection as { search?: unknown }).search) continue;\n const engine = (collection as { engine?: string }).engine ?? \"non-postgres\";\n throw new SearchConfigError(\n `${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \\`${engine}\\`. ` +\n \"Remove the block — it would otherwise look configured while `.search()` kept using the default substring match.\"\n );\n }\n};\n\nconst columnNameOf = (propName: string, prop?: Property | null): string =>\n prop && \"columnName\" in prop && typeof prop.columnName === \"string\" ? prop.columnName : toSnakeCase(propName);\n\n/**\n * Classify a property for search purposes.\n *\n * Deliberately narrower than the schema plan's `PgType`: search only cares\n * whether a value reaches text, and the mapping from property to *physical*\n * type is asserted against the plan in the contract test rather than duplicated\n * here.\n *\n * Returns null for anything that is not text-bearing, which the caller turns\n * into a boot error naming the property.\n */\nconst classify = (prop: Property): { kind: FieldKind; reason?: string } | null => {\n switch (prop.type) {\n case \"string\": {\n const sp = prop as StringProperty;\n if (sp.enum) {\n return { kind: \"text\", reason: \"enum\" };\n }\n if (sp.isId === \"uuid\" || sp.columnType === \"uuid\") {\n return { kind: \"text\", reason: \"uuid\" };\n }\n return { kind: \"text\" };\n }\n case \"map\": {\n const mp = prop as MapProperty;\n // A `json` column is not `jsonb`, and the cast between them is not\n // immutable. Declaring `columnType: \"json\"` puts the value out of\n // reach of a generated column.\n if (mp.columnType === \"json\") return { kind: \"jsonb\", reason: \"json\" };\n return { kind: \"jsonb\" };\n }\n case \"array\": {\n const ap = prop as ArrayProperty;\n let colType = ap.columnType;\n if (!colType && ap.of && !Array.isArray(ap.of)) {\n const of = ap.of as Property;\n if (of.type === \"string\") colType = \"text[]\";\n else if (of.type === \"number\") colType = of.validation?.integer ? \"integer[]\" : \"numeric[]\";\n else if (of.type === \"boolean\") colType = \"boolean[]\";\n }\n if (colType === \"text[]\") return { kind: \"text_array\" };\n if (colType === \"json\") return { kind: \"jsonb\", reason: \"json\" };\n if (colType === \"integer[]\" || colType === \"boolean[]\" || colType === \"numeric[]\") {\n return { kind: \"text_array\", reason: \"non_text_array\" };\n }\n // Everything else lands in JSONB, which the JSON extractor handles.\n return { kind: \"jsonb\" };\n }\n default:\n return null;\n }\n};\n\nconst normalize = (inner: string, unaccent: boolean): string =>\n unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;\n\n/** SQL reading one field as plain text, before normalization. */\nconst rawTextSql = (field: { column: string; jsonPath: string[]; kind: FieldKind }): string => {\n const col = `\"${field.column}\"`;\n if (field.kind === \"text\") return `coalesce(${col}, '')`;\n if (field.kind === \"text_array\") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;\n // JSONB, optionally addressed at a path inside the document.\n const target = field.jsonPath.length === 0\n ? col\n : field.jsonPath.length === 1\n ? `${col} -> ${quote(field.jsonPath[0])}`\n : `${col} #> ${quote(`{${field.jsonPath.join(\",\")}}`)}`;\n return `${SEARCH_TEXT_FN}(coalesce(${target}, '{}'::jsonb))`;\n};\n\nconst quote = (v: string): string => `'${v.replace(/'/g, \"''\")}'`;\n\n/**\n * Resolve and validate one declared field path.\n *\n * A path that does not resolve throws. The whole point of an explicit block is\n * that the author knows what is indexed; a silently dropped field would make it\n * a guess again, and the failure — a search that returns nothing for content\n * that is plainly in the row — is invisible from the outside.\n */\nconst resolveField = (\n entry: string | SearchField,\n collection: CollectionConfig,\n cfg: SearchConfig\n): ResolvedSearchField => {\n const path = typeof entry === \"string\" ? entry : entry.path;\n const weight = (typeof entry === \"string\" ? undefined : entry.weight) ?? DEFAULT_SEARCH_WEIGHT;\n const where = `${collection.slug}.search`;\n\n if (!path || typeof path !== \"string\") {\n throw new SearchConfigError(`${where}: every entry in \\`fields\\` needs a property path.`);\n }\n\n const [head, ...rest] = path.split(\".\");\n const prop = collection.properties?.[head] as Property | undefined;\n if (!prop) {\n const known = Object.keys(collection.properties ?? {}).join(\", \");\n throw new SearchConfigError(\n `${where}: \"${path}\" starts at property \"${head}\", which this collection does not declare. Known properties: ${known}.`\n );\n }\n\n const classified = classify(prop);\n if (!classified) {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a \\`${prop.type}\\` property, which holds no text to search. ` +\n `Searchable kinds are \\`string\\`, \\`string[]\\` and \\`map\\` (or a path inside one).`\n );\n }\n if (classified.reason === \"enum\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an enum. Enums are a fixed vocabulary — filter on them with \\`where\\` instead, which is exact and uses an index.`\n );\n }\n if (classified.reason === \"uuid\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a UUID column. Look it up by id rather than searching it.`\n );\n }\n if (classified.reason === \"json\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a \\`json\\` column, and the cast from \\`json\\` to \\`jsonb\\` is not immutable, so it cannot feed a generated column. Declare the property as \\`jsonb\\` (the default) to search it.`\n );\n }\n if (classified.reason === \"non_text_array\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an array of numbers or booleans. Only \\`string[]\\` carries text to search.`\n );\n }\n\n if (rest.length > 0 && classified.kind !== \"jsonb\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" addresses a path inside \"${head}\", but \"${head}\" is a \\`${prop.type}\\` property, not a \\`map\\`. Only map properties have paths inside them.`\n );\n }\n\n const column = columnNameOf(head, prop);\n const field = { column, jsonPath: rest, kind: classified.kind };\n const raw = rawTextSql(field);\n const textSql = normalize(raw, cfg.unaccent === true);\n const language = cfg.language ?? DEFAULT_SEARCH_LANGUAGE;\n\n return {\n path,\n column,\n jsonPath: rest,\n kind: classified.kind,\n weight,\n sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,\n textSql,\n foldedTextSql: normalize(raw, true)\n };\n};\n\n/**\n * Build the full spec for a collection, or undefined when it has not opted in.\n *\n * Throws {@link SearchConfigError} on a config that cannot be honoured. Callers\n * at boot surface that as a startup failure — a search block that half-works is\n * worse than one that refuses.\n */\nexport const buildSearchColumnSpec = (collection: CollectionConfig): SearchColumnSpec | undefined => {\n const cfg = getSearchConfig(collection);\n if (!cfg) return undefined;\n\n if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) {\n throw new SearchConfigError(\n `${collection.slug}.search: \\`fields\\` is empty. Name the properties to index, or remove the \\`search\\` block to keep the default ILIKE behaviour.`\n );\n }\n\n const table = getTableName(collection);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const column = cfg.column ?? DEFAULT_SEARCH_COLUMN;\n\n if (collection.properties?.[column]) {\n throw new SearchConfigError(\n `${collection.slug}.search: the generated column \"${column}\" collides with a declared property of the same name. Set \\`search.column\\` to something else.`\n );\n }\n\n const fields = cfg.fields.map(entry => resolveField(entry, collection, cfg));\n\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.path)) {\n throw new SearchConfigError(`${collection.slug}.search: \"${f.path}\" is listed twice.`);\n }\n seen.add(f.path);\n }\n\n const mode = cfg.mode ?? DEFAULT_SEARCH_MODE;\n\n const extensions: string[] = [];\n // `hybrid` folds accents on its substring half whatever `unaccent` says, so\n // it needs the dictionary and the helper even on a block that never asked\n // for folding in the stored column. Both statements are idempotent, which\n // is what keeps turning the mode on out of the column-rebuild business.\n if (cfg.unaccent || mode === \"hybrid\") extensions.push(\"unaccent\");\n if (cfg.fuzzy) extensions.push(\"pg_trgm\");\n\n const spec: SearchColumnSpec = {\n schema,\n table,\n column,\n language: cfg.language ?? DEFAULT_SEARCH_LANGUAGE,\n unaccent: cfg.unaccent === true,\n mode,\n fields,\n expression: fields.map(f => f.sql).join(\" || \"),\n indexName: toPostgresIdentifier(`${table}_${column}_gin`),\n extensions\n };\n\n if (cfg.fuzzy) {\n const fuzzyColumn = `${column}_text`;\n if (collection.properties?.[fuzzyColumn]) {\n throw new SearchConfigError(\n `${collection.slug}.search: \\`fuzzy\\` needs the column \"${fuzzyColumn}\", which collides with a declared property. Set \\`search.column\\` to something else.`\n );\n }\n spec.fuzzy = {\n column: fuzzyColumn,\n // Concatenated with spaces so a trigram never spans two fields.\n expression: fields.map(f => f.textSql).join(\" || ' ' || \"),\n indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),\n threshold: cfg.fuzzyThreshold ?? DEFAULT_FUZZY_THRESHOLD\n };\n }\n\n return spec;\n};\n\n/**\n * The IMMUTABLE wrappers the generated expressions call.\n *\n * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather\n * than an error, and idempotent for the same reason every other boot-time DDL\n * statement here is.\n *\n * The bodies are stable built-ins wrapped in an immutable promise — see the\n * module comment for why that promise is sound. `STRICT` matters: it makes NULL\n * in mean NULL out without executing the body, which is what the `coalesce` at\n * each call site then absorbs.\n */\nexport const searchHelperFunctions = (spec: SearchColumnSpec): string[] => {\n const statements: string[] = [\n // text[] → \" \"-joined text.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT array_to_string($1, ' ') $$;`,\n // jsonb → every string value at or below the node, space-joined. Keys\n // are not values: indexing them would make `certifications` itself a\n // search term on every row that has the field at all.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT coalesce(string_agg(v, ' '), '')\\n` +\n ` FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == \"string\")')) AS v $$;`\n ];\n if (spec.unaccent || spec.mode === \"hybrid\") {\n // The two-argument form with an explicit dictionary is the one that can\n // honestly be called immutable: the single-argument form resolves the\n // dictionary through the current search_path at call time.\n statements.push(\n `CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`\n );\n }\n return statements;\n};\n\n/**\n * `CREATE EXTENSION` statements the spec's expressions depend on.\n *\n * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified\n * `CREATE EXTENSION` installs into the first schema on `search_path`, which\n * defaults to `\"$user\", public` — and the scaffold's database role is named\n * `rebase`, the same as the schema the generator creates one statement earlier.\n * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the\n * dictionary in `rebase`, and every reference to `public.unaccent` below fails\n * with \"text search dictionary does not exist\". Observed, not theorised.\n */\nexport const searchExtensionStatements = (spec: SearchColumnSpec): string[] =>\n spec.extensions.map(e => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);\n\n/**\n * Everything after the column name — the type and the generation expression.\n *\n * Split out because four emitters need it and only two of them have a place to\n * put the name: `CREATE TABLE` and `ADD COLUMN` write `\"col\" <this>`, while the\n * schema plan carries it as the column's SQL definition and the boot-time\n * rebuild statement interpolates it on its own.\n */\nexport const searchColumnTypeSql = (expression: string, kind: \"tsvector\" | \"text\"): string =>\n `${kind} GENERATED ALWAYS AS (${expression}) STORED`;\n\n/** The column definition as it appears inside `CREATE TABLE`. */\nexport const searchColumnDefinition = (spec: SearchColumnSpec): string =>\n `\"${spec.column}\" ${searchColumnTypeSql(spec.expression, \"tsvector\")}`;\n\n/** The fuzzy column definition, when the spec asks for one. */\nexport const fuzzyColumnDefinition = (spec: SearchColumnSpec): string | undefined =>\n spec.fuzzy ? `\"${spec.fuzzy.column}\" ${searchColumnTypeSql(spec.fuzzy.expression, \"text\")}` : undefined;\n\n/**\n * Index statements for the spec.\n *\n * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a\n * SQL file replayed as one unit — a migration, or `search.sql` — where a\n * concurrent build is not allowed. The boot-time ensure path runs statement by\n * statement against tables that are live and populated, and uses the\n * concurrent form instead; see `ensureSearchColumns`.\n */\nexport const searchIndexStatements = (spec: SearchColumnSpec): string[] => {\n const statements = [\n `CREATE INDEX IF NOT EXISTS \"${spec.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.column}\");`\n ];\n if (spec.fuzzy) {\n statements.push(\n // The operator class is resolved through `search_path` like any\n // other object, so it is qualified for the same reason the\n // extension is installed explicitly.\n `CREATE INDEX IF NOT EXISTS \"${spec.fuzzy.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.fuzzy.column}\" ${HELPER_SCHEMA}.gin_trgm_ops);`\n );\n }\n return statements;\n};\n\n// ── Telling a changed `search` block from an unchanged one ──────────────────\n\n/**\n * Marker on the comment of every generated search column this module creates.\n *\n * Versioned because the fingerprint below is only comparable against itself: a\n * future change to how it is computed has to read as \"not stamped by this\n * version\" rather than as drift on every existing column.\n */\nexport const SEARCH_STAMP_PREFIX = \"rebase:search:v1:\";\n\n/**\n * A stable fingerprint of one generated column's expression.\n *\n * Why a stamp rather than reading the expression back: Postgres stores a\n * generated column's expression *parsed*, and hands it back deparsed — casts\n * made explicit, identifiers requoted, schema qualifications added or dropped\n * according to `search_path`. Comparing that text to the text we generated\n * would report drift on wording, and this comparison decides whether a boot\n * refuses, so a false positive is an outage. The stamp is written by the same\n * code that writes the column, so equality means what it says.\n */\nexport const searchExpressionFingerprint = (expression: string): string =>\n `${SEARCH_STAMP_PREFIX}${createHash(\"sha256\").update(expression).digest(\"hex\").slice(0, 16)}`;\n\n/** One generated column, with the fingerprint that identifies its expression. */\nexport interface SearchColumnStamp {\n column: string;\n /** The expression the column is generated from. */\n expression: string;\n fingerprint: string;\n /** `COMMENT ON COLUMN …`, which is where the fingerprint is recorded. */\n sql: string;\n}\n\n/**\n * The stamps for a spec's generated columns — one per column, never shared.\n *\n * Per column on purpose: turning `fuzzy` on adds a second column and changes\n * nothing about the first, and a spec-wide fingerprint would report the\n * untouched `tsvector` column as drifted and refuse a boot over a change that\n * is purely additive.\n */\nexport const searchColumnStamps = (spec: SearchColumnSpec): SearchColumnStamp[] => {\n const stamp = (column: string, expression: string): SearchColumnStamp => {\n const fingerprint = searchExpressionFingerprint(expression);\n return {\n column,\n expression,\n fingerprint,\n sql: `COMMENT ON COLUMN \"${spec.schema}\".\"${spec.table}\".\"${column}\" IS ${quote(fingerprint)};`\n };\n };\n const stamps = [stamp(spec.column, spec.expression)];\n if (spec.fuzzy) stamps.push(stamp(spec.fuzzy.column, spec.fuzzy.expression));\n return stamps;\n};\n\n/**\n * The same drift check as the boot ensure, for the SQL file.\n *\n * Needed because {@link searchColumnStamps} would otherwise *launder* drift on\n * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that\n * exists, so a re-generated `search.sql` would stamp a stale column with the\n * new block's fingerprint and the next boot would find them in agreement.\n * Guarding first means the file refuses instead — `rebase db push` is attended,\n * and the operator reading the failure is the person who changed the block.\n */\nexport const searchStampGuards = (spec: SearchColumnSpec): string[] =>\n searchColumnStamps(spec).map(stamp => {\n const relation = quote(`\"${spec.schema}\".\"${spec.table}\"`);\n return `DO $rebase_search$\nDECLARE recorded text;\nBEGIN\n SELECT col_description(a.attrelid, a.attnum) INTO recorded\n FROM pg_attribute a\n WHERE a.attrelid = ${relation}::regclass AND a.attname = ${quote(stamp.column)} AND NOT a.attisdropped;\n IF recorded LIKE ${quote(`${SEARCH_STAMP_PREFIX}%`)} AND recorded <> ${quote(stamp.fingerprint)} THEN\n RAISE EXCEPTION 'Rebase: the search block for ${spec.schema}.${spec.table} changed after the generated column \"${stamp.column}\" was built (recorded %, expected ${stamp.fingerprint}). Postgres cannot alter a generated expression in place. Drop the column and re-apply this file — it rewrites the table and rebuilds the index: ALTER TABLE ${relation.slice(1, -1)} DROP COLUMN \"${stamp.column}\";', recorded;\n END IF;\nEND\n$rebase_search$;`;\n });\n\n/**\n * The index names the spec creates.\n *\n * Needed by name, not just by statement, so Atlas can be told to exclude them\n * from its diff — see `searchExcludePatterns`.\n */\nexport const searchIndexNames = (spec: SearchColumnSpec): string[] =>\n spec.fuzzy ? [spec.indexName, spec.fuzzy.indexName] : [spec.indexName];\n\n// ── Keeping the generated columns out of responses ──────────────────────────\n\n/**\n * The generated column names a collection's search block adds, if any.\n *\n * These are physical columns on the table, so `SELECT *` returns them. They are\n * an index in column form — a list of lexeme positions, or a concatenation of\n * every searchable field on the row — and nothing outside the query planner has\n * any use for them. Left in, every list response carries a second, larger copy\n * of the row's text.\n */\nexport const searchColumnNames = (collection: CollectionConfig): string[] => {\n let spec: SearchColumnSpec | undefined;\n try {\n spec = buildSearchColumnSpec(collection);\n } catch {\n // A malformed block is reported at boot, loudly. A read is the wrong\n // place to raise it a second time, and returning the row without the\n // exclusion would be worse than returning it with.\n return [];\n }\n if (!spec) return [];\n return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];\n};\n\n/**\n * True for a column whose type only ever holds a search index.\n *\n * Independent of any collection config on purpose: an introspected database\n * (BaaS mode) can carry a `tsvector` column this framework never created —\n * Pagila's `film.fulltext` is the canonical one — and it should not be returned\n * to callers either. `isDerivedIndexColumn` already keeps such a column out of\n * the *properties*; this keeps it out of the *rows*.\n */\nexport const isSearchIndexColumn = (column: { getSQLType?: () => string }): boolean => {\n const sqlType = typeof column?.getSQLType === \"function\" ? column.getSQLType().toLowerCase() : \"\";\n return sqlType === \"tsvector\" || sqlType === \"tsquery\";\n};\n\n/**\n * A drizzle select projection over `table` with the search columns dropped.\n *\n * Returns undefined when nothing needs dropping, so the common case keeps using\n * a plain `select()` and this stays invisible in the generated SQL.\n */\nexport const visibleColumnProjection = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): Record<string, unknown> | undefined => {\n const excluded = excludedColumnNames(tableColumns, collection);\n if (!tableColumns || excluded.length === 0) return undefined;\n const projection: Record<string, unknown> = {};\n for (const [name, column] of Object.entries(tableColumns)) {\n if (!excluded.includes(name)) projection[name] = column;\n }\n return projection;\n};\n\n/** The same exclusion as a drizzle `db.query` `columns` denylist. */\nexport const hiddenColumnsOption = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): Record<string, false> | undefined => {\n const excluded = excludedColumnNames(tableColumns, collection);\n if (excluded.length === 0) return undefined;\n return Object.fromEntries(excluded.map(name => [name, false as const]));\n};\n\n/**\n * The columns to keep out of a response, by name.\n *\n * `tableColumns` is whatever `getTableColumns` returned, which is `undefined`\n * for anything that is not a real drizzle table — a stub in a test, a derived\n * or nested path with no table behind it. Nothing to exclude is the right\n * answer there, and it has to be an answer rather than a throw: this runs on\n * the read path of every collection, opted in or not.\n */\nconst excludedColumnNames = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): string[] => {\n if (!tableColumns || typeof tableColumns !== \"object\") return [];\n const byName = new Set(collection ? searchColumnNames(collection) : []);\n return Object.keys(tableColumns).filter(\n name => byName.has(name) || isSearchIndexColumn(tableColumns[name])\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,IAAM,gBAAgB;;;;;;AAOtB,IAAa,iBAAiB,GAAG,cAAc;AAC/C,IAAa,qBAAqB,GAAG,cAAc;;AAgEnD,IAAa,oBAAb,cAAuC,MAAM;CACzC,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;;AAGA,IAAa,mBAAmB,eAC5B,2BAA2B,UAAU,IAAI,WAAW,SAAS,KAAA;;;;;;;;;;;;AAajE,IAAa,8BAA8B,gBAA0C;CACjF,KAAK,MAAM,cAAc,aAAa;EAClC,IAAI,2BAA2B,UAAU,GAAG;EAC5C,IAAI,CAAE,WAAoC,QAAQ;EAClD,MAAM,SAAU,WAAmC,UAAU;EAC7D,MAAM,IAAI,kBACN,GAAG,WAAW,KAAK,sFAAsF,OAAO,sHAEpH;CACJ;AACJ;AAEA,IAAM,gBAAgB,UAAkB,SACpC,QAAQ,gBAAgB,QAAQ,OAAO,KAAK,eAAe,WAAW,KAAK,aAAa,YAAY,QAAQ;;;;;;;;;;;;AAahH,I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AC;CAC/D,MAAM,SAAS,IAAI,IAAI,aAAa,kBAAkB,UAAU,IAAI,CAAC,CAAC;CACtE,OAAO,OAAO,KAAK,YAAY,CAAC,CAAC,QAC7B,SAAQ,OAAO,IAAI,IAAI,KAAK,oBAAoB,aAAa,KAAK,CACtE;AACJ"}
1
+ {"version":3,"file":"search-column-BM-GV6vH.js","names":[],"sources":["../src/schema/search-column.ts"],"sourcesContent":["/**\n * The one place a collection's `search` block becomes SQL.\n *\n * Four things describe a Postgres table in this codebase — the DDL generator,\n * the Drizzle schema generator, the runtime table builder for BaaS mode, and\n * the boot-time schema ensure — and each of them has, at some point, described\n * a column differently from the others. The `varchar(255)` note in\n * `generate-postgres-ddl-logic` is one such scar: the same property produced a\n * capped column down one path and an uncapped one down the other, and nothing\n * failed until a user hit the cap.\n *\n * So the search column is not implemented four times. It is computed once,\n * here, and every generator renders the same {@link SearchColumnSpec}. There is\n * a test asserting exactly that (`search-column-contract.test.ts`); the point of\n * this module is that the test has something to assert *about*.\n *\n * ## Why the expressions look the way they do\n *\n * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and\n * Postgres is stricter here than intuition. Verified against PostgreSQL 18:\n *\n * | expression | immutable |\n * |-----------------------------------------|-----------|\n * | `to_tsvector('spanish', col)` | yes |\n * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |\n * | `array_to_string(col, ' ')` | **no** |\n * | `col::text` on `text[]` | **no** |\n * | `to_jsonb(col)` | **no** |\n * | `unaccent(col)` | **no** — dictionary lookup is STABLE |\n * | `jsonb_to_tsvector('spanish', j, '[\"string\"]')` | yes |\n * | `setweight(...) || setweight(...)` | yes |\n *\n * Three of the four things a real search column needs are therefore unavailable\n * directly, which is why {@link searchHelperFunctions} exists: each wraps a\n * stable built-in in an SQL function declared IMMUTABLE. That declaration is a\n * promise, and it is a true one for these three — array joining, JSON string\n * extraction and accent folding are all deterministic for a given input; the\n * built-ins are marked stable only because they must account for element types\n * and dictionaries in general.\n *\n * The alternative was to skip `unaccent` and text arrays entirely. That is not\n * a real option in an accented language: Postgres stems `auditoría` to\n * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query\n * typed without accents misses every row that carries them.\n */\nimport {\n CollectionConfig,\n Property,\n StringProperty,\n ArrayProperty,\n MapProperty,\n SearchConfig,\n SearchField,\n SearchMode,\n SearchWeight,\n isPostgresCollectionConfig,\n DEFAULT_SEARCH_COLUMN,\n DEFAULT_SEARCH_MODE,\n DEFAULT_SEARCH_LANGUAGE,\n DEFAULT_SEARCH_WEIGHT,\n DEFAULT_FUZZY_THRESHOLD\n} from \"@rebasepro/types\";\nimport { createHash } from \"node:crypto\";\nimport { getTableName } from \"@rebasepro/common\";\nimport { toSnakeCase, toPostgresIdentifier } from \"@rebasepro/utils\";\n\n/** Schema-qualified so a collection outside `public` still resolves them. */\nconst HELPER_SCHEMA = \"public\";\n\n/**\n * Names of the helper functions. Frozen: they are recorded in the stored\n * generation expression of every search column ever created, so renaming one\n * orphans every table that already has a search column.\n */\nexport const SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;\nexport const SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;\n\n/** How a declared path reaches text, which decides the SQL that extracts it. */\ntype FieldKind = \"text\" | \"text_array\" | \"jsonb\";\n\n/** One resolved field: where it lives, how to read it, what it is worth. */\nexport interface ResolvedSearchField {\n /** The path exactly as the author wrote it, for error messages. */\n path: string;\n /** The physical column the path starts at. */\n column: string;\n /** Dotted remainder addressed inside a JSONB column, if any. */\n jsonPath: string[];\n kind: FieldKind;\n weight: SearchWeight;\n /** The `setweight(to_tsvector(…), 'X')` term this field contributes. */\n sql: string;\n /** The plain-text term this field contributes, for the fuzzy column. */\n textSql: string;\n /**\n * The same text with accents folded **unconditionally**, for the substring\n * half of {@link SearchMode} `\"hybrid\"`.\n *\n * Separate from {@link textSql} rather than replacing it, and that\n * separation is the whole migration story for `mode`. `textSql` feeds the\n * *stored* generated columns, so changing it changes their generation\n * expression, which changes the fingerprint, which makes the next boot\n * refuse (see `searchStampGuards`). This one is only ever interpolated into\n * a WHERE clause, so a collection can switch to `\"hybrid\"` — and gain\n * accent folding on the substring half — without rebuilding a column or\n * taking an ACCESS EXCLUSIVE lock.\n */\n foldedTextSql: string;\n}\n\n/** Everything the generators need to render one collection's search column. */\nexport interface SearchColumnSpec {\n schema: string;\n table: string;\n /** The generated `tsvector` column. */\n column: string;\n language: string;\n unaccent: boolean;\n /**\n * How the query side matches. Deliberately absent from\n * {@link SearchColumnSpec.expression} and from every fingerprint: it\n * describes the WHERE clause, not the column.\n */\n mode: SearchMode;\n fields: ResolvedSearchField[];\n /** Body of `GENERATED ALWAYS AS ( … ) STORED` for the tsvector column. */\n expression: string;\n indexName: string;\n /** Extensions that must exist before the column can be created. */\n extensions: string[];\n fuzzy?: {\n column: string;\n expression: string;\n indexName: string;\n threshold: number;\n };\n}\n\n/** Raised when a `search` block names something that cannot be searched. */\nexport class SearchConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SearchConfigError\";\n }\n}\n\n/** The `search` block of a collection, or undefined when it has none. */\nexport const getSearchConfig = (collection: CollectionConfig): SearchConfig | undefined =>\n isPostgresCollectionConfig(collection) ? collection.search : undefined;\n\n/**\n * Refuse a `search` block on a collection this engine does not store.\n *\n * The type only permits one on a `PostgresCollectionConfig`, so TypeScript\n * already stops the ordinary case. This catches the rest — a JS config, a cast,\n * a collection whose `engine` was changed after the block was written — because\n * the alternative is the exact failure the block exists to prevent: a developer\n * who declared what to index, saw no error, and got the substring fallback.\n *\n * Called with *every* collection, before the Postgres ones are filtered out.\n */\nexport const assertSearchIsPostgresOnly = (collections: CollectionConfig[]): void => {\n for (const collection of collections) {\n if (isPostgresCollectionConfig(collection)) continue;\n if (!(collection as { search?: unknown }).search) continue;\n const engine = (collection as { engine?: string }).engine ?? \"non-postgres\";\n throw new SearchConfigError(\n `${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \\`${engine}\\`. ` +\n \"Remove the block — it would otherwise look configured while `.search()` kept using the default substring match.\"\n );\n }\n};\n\nconst columnNameOf = (propName: string, prop?: Property | null): string =>\n prop && \"columnName\" in prop && typeof prop.columnName === \"string\" ? prop.columnName : toSnakeCase(propName);\n\n/**\n * Classify a property for search purposes.\n *\n * Deliberately narrower than the schema plan's `PgType`: search only cares\n * whether a value reaches text, and the mapping from property to *physical*\n * type is asserted against the plan in the contract test rather than duplicated\n * here.\n *\n * Returns null for anything that is not text-bearing, which the caller turns\n * into a boot error naming the property.\n */\nconst classify = (prop: Property): { kind: FieldKind; reason?: string } | null => {\n switch (prop.type) {\n case \"string\": {\n const sp = prop as StringProperty;\n if (sp.enum) {\n return { kind: \"text\", reason: \"enum\" };\n }\n if (sp.isId === \"uuid\" || sp.columnType === \"uuid\") {\n return { kind: \"text\", reason: \"uuid\" };\n }\n return { kind: \"text\" };\n }\n case \"map\": {\n const mp = prop as MapProperty;\n // A `json` column is not `jsonb`, and the cast between them is not\n // immutable. Declaring `columnType: \"json\"` puts the value out of\n // reach of a generated column.\n if (mp.columnType === \"json\") return { kind: \"jsonb\", reason: \"json\" };\n return { kind: \"jsonb\" };\n }\n case \"array\": {\n const ap = prop as ArrayProperty;\n let colType = ap.columnType;\n if (!colType && ap.of && !Array.isArray(ap.of)) {\n const of = ap.of as Property;\n if (of.type === \"string\") colType = \"text[]\";\n else if (of.type === \"number\") colType = of.validation?.integer ? \"integer[]\" : \"numeric[]\";\n else if (of.type === \"boolean\") colType = \"boolean[]\";\n }\n if (colType === \"text[]\") return { kind: \"text_array\" };\n if (colType === \"json\") return { kind: \"jsonb\", reason: \"json\" };\n if (colType === \"integer[]\" || colType === \"boolean[]\" || colType === \"numeric[]\") {\n return { kind: \"text_array\", reason: \"non_text_array\" };\n }\n // Everything else lands in JSONB, which the JSON extractor handles.\n return { kind: \"jsonb\" };\n }\n default:\n return null;\n }\n};\n\nconst normalize = (inner: string, unaccent: boolean): string =>\n unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;\n\n/** SQL reading one field as plain text, before normalization. */\nconst rawTextSql = (field: { column: string; jsonPath: string[]; kind: FieldKind }): string => {\n const col = `\"${field.column}\"`;\n if (field.kind === \"text\") return `coalesce(${col}, '')`;\n if (field.kind === \"text_array\") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;\n // JSONB, optionally addressed at a path inside the document.\n const target = field.jsonPath.length === 0\n ? col\n : field.jsonPath.length === 1\n ? `${col} -> ${quote(field.jsonPath[0])}`\n : `${col} #> ${quote(`{${field.jsonPath.join(\",\")}}`)}`;\n return `${SEARCH_TEXT_FN}(coalesce(${target}, '{}'::jsonb))`;\n};\n\nconst quote = (v: string): string => `'${v.replace(/'/g, \"''\")}'`;\n\n/**\n * Resolve and validate one declared field path.\n *\n * A path that does not resolve throws. The whole point of an explicit block is\n * that the author knows what is indexed; a silently dropped field would make it\n * a guess again, and the failure — a search that returns nothing for content\n * that is plainly in the row — is invisible from the outside.\n */\nconst resolveField = (\n entry: string | SearchField,\n collection: CollectionConfig,\n cfg: SearchConfig\n): ResolvedSearchField => {\n const path = typeof entry === \"string\" ? entry : entry.path;\n const weight = (typeof entry === \"string\" ? undefined : entry.weight) ?? DEFAULT_SEARCH_WEIGHT;\n const where = `${collection.slug}.search`;\n\n if (!path || typeof path !== \"string\") {\n throw new SearchConfigError(`${where}: every entry in \\`fields\\` needs a property path.`);\n }\n\n const [head, ...rest] = path.split(\".\");\n const prop = collection.properties?.[head] as Property | undefined;\n if (!prop) {\n const known = Object.keys(collection.properties ?? {}).join(\", \");\n throw new SearchConfigError(\n `${where}: \"${path}\" starts at property \"${head}\", which this collection does not declare. Known properties: ${known}.`\n );\n }\n\n const classified = classify(prop);\n if (!classified) {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a \\`${prop.type}\\` property, which holds no text to search. ` +\n `Searchable kinds are \\`string\\`, \\`string[]\\` and \\`map\\` (or a path inside one).`\n );\n }\n if (classified.reason === \"enum\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an enum. Enums are a fixed vocabulary — filter on them with \\`where\\` instead, which is exact and uses an index.`\n );\n }\n if (classified.reason === \"uuid\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a UUID column. Look it up by id rather than searching it.`\n );\n }\n if (classified.reason === \"json\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a \\`json\\` column, and the cast from \\`json\\` to \\`jsonb\\` is not immutable, so it cannot feed a generated column. Declare the property as \\`jsonb\\` (the default) to search it.`\n );\n }\n if (classified.reason === \"non_text_array\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an array of numbers or booleans. Only \\`string[]\\` carries text to search.`\n );\n }\n\n if (rest.length > 0 && classified.kind !== \"jsonb\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" addresses a path inside \"${head}\", but \"${head}\" is a \\`${prop.type}\\` property, not a \\`map\\`. Only map properties have paths inside them.`\n );\n }\n\n const column = columnNameOf(head, prop);\n const field = { column, jsonPath: rest, kind: classified.kind };\n const raw = rawTextSql(field);\n const textSql = normalize(raw, cfg.unaccent === true);\n const language = cfg.language ?? DEFAULT_SEARCH_LANGUAGE;\n\n return {\n path,\n column,\n jsonPath: rest,\n kind: classified.kind,\n weight,\n sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,\n textSql,\n foldedTextSql: normalize(raw, true)\n };\n};\n\n/**\n * Build the full spec for a collection, or undefined when it has not opted in.\n *\n * Throws {@link SearchConfigError} on a config that cannot be honoured. Callers\n * at boot surface that as a startup failure — a search block that half-works is\n * worse than one that refuses.\n */\nexport const buildSearchColumnSpec = (collection: CollectionConfig): SearchColumnSpec | undefined => {\n const cfg = getSearchConfig(collection);\n if (!cfg) return undefined;\n\n if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) {\n throw new SearchConfigError(\n `${collection.slug}.search: \\`fields\\` is empty. Name the properties to index, or remove the \\`search\\` block to keep the default ILIKE behaviour.`\n );\n }\n\n const table = getTableName(collection);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const column = cfg.column ?? DEFAULT_SEARCH_COLUMN;\n\n if (collection.properties?.[column]) {\n throw new SearchConfigError(\n `${collection.slug}.search: the generated column \"${column}\" collides with a declared property of the same name. Set \\`search.column\\` to something else.`\n );\n }\n\n const fields = cfg.fields.map(entry => resolveField(entry, collection, cfg));\n\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.path)) {\n throw new SearchConfigError(`${collection.slug}.search: \"${f.path}\" is listed twice.`);\n }\n seen.add(f.path);\n }\n\n const mode = cfg.mode ?? DEFAULT_SEARCH_MODE;\n\n const extensions: string[] = [];\n // `hybrid` folds accents on its substring half whatever `unaccent` says, so\n // it needs the dictionary and the helper even on a block that never asked\n // for folding in the stored column. Both statements are idempotent, which\n // is what keeps turning the mode on out of the column-rebuild business.\n if (cfg.unaccent || mode === \"hybrid\") extensions.push(\"unaccent\");\n if (cfg.fuzzy) extensions.push(\"pg_trgm\");\n\n const spec: SearchColumnSpec = {\n schema,\n table,\n column,\n language: cfg.language ?? DEFAULT_SEARCH_LANGUAGE,\n unaccent: cfg.unaccent === true,\n mode,\n fields,\n expression: fields.map(f => f.sql).join(\" || \"),\n indexName: toPostgresIdentifier(`${table}_${column}_gin`),\n extensions\n };\n\n if (cfg.fuzzy) {\n const fuzzyColumn = `${column}_text`;\n if (collection.properties?.[fuzzyColumn]) {\n throw new SearchConfigError(\n `${collection.slug}.search: \\`fuzzy\\` needs the column \"${fuzzyColumn}\", which collides with a declared property. Set \\`search.column\\` to something else.`\n );\n }\n spec.fuzzy = {\n column: fuzzyColumn,\n // Concatenated with spaces so a trigram never spans two fields.\n expression: fields.map(f => f.textSql).join(\" || ' ' || \"),\n indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),\n threshold: cfg.fuzzyThreshold ?? DEFAULT_FUZZY_THRESHOLD\n };\n }\n\n return spec;\n};\n\n/**\n * The IMMUTABLE wrappers the generated expressions call.\n *\n * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather\n * than an error, and idempotent for the same reason every other boot-time DDL\n * statement here is.\n *\n * The bodies are stable built-ins wrapped in an immutable promise — see the\n * module comment for why that promise is sound. `STRICT` matters: it makes NULL\n * in mean NULL out without executing the body, which is what the `coalesce` at\n * each call site then absorbs.\n */\nexport const searchHelperFunctions = (spec: SearchColumnSpec): string[] => {\n const statements: string[] = [\n // text[] → \" \"-joined text.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT array_to_string($1, ' ') $$;`,\n // jsonb → every string value at or below the node, space-joined. Keys\n // are not values: indexing them would make `certifications` itself a\n // search term on every row that has the field at all.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT coalesce(string_agg(v, ' '), '')\\n` +\n ` FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == \"string\")')) AS v $$;`\n ];\n if (spec.unaccent || spec.mode === \"hybrid\") {\n // The two-argument form with an explicit dictionary is the one that can\n // honestly be called immutable: the single-argument form resolves the\n // dictionary through the current search_path at call time.\n statements.push(\n `CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`\n );\n }\n return statements;\n};\n\n/**\n * `CREATE EXTENSION` statements the spec's expressions depend on.\n *\n * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified\n * `CREATE EXTENSION` installs into the first schema on `search_path`, which\n * defaults to `\"$user\", public` — and the scaffold's database role is named\n * `rebase`, the same as the schema the generator creates one statement earlier.\n * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the\n * dictionary in `rebase`, and every reference to `public.unaccent` below fails\n * with \"text search dictionary does not exist\". Observed, not theorised.\n */\nexport const searchExtensionStatements = (spec: SearchColumnSpec): string[] =>\n spec.extensions.map(e => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);\n\n/**\n * Everything after the column name — the type and the generation expression.\n *\n * Split out because four emitters need it and only two of them have a place to\n * put the name: `CREATE TABLE` and `ADD COLUMN` write `\"col\" <this>`, while the\n * schema plan carries it as the column's SQL definition and the boot-time\n * rebuild statement interpolates it on its own.\n */\nexport const searchColumnTypeSql = (expression: string, kind: \"tsvector\" | \"text\"): string =>\n `${kind} GENERATED ALWAYS AS (${expression}) STORED`;\n\n/** The column definition as it appears inside `CREATE TABLE`. */\nexport const searchColumnDefinition = (spec: SearchColumnSpec): string =>\n `\"${spec.column}\" ${searchColumnTypeSql(spec.expression, \"tsvector\")}`;\n\n/** The fuzzy column definition, when the spec asks for one. */\nexport const fuzzyColumnDefinition = (spec: SearchColumnSpec): string | undefined =>\n spec.fuzzy ? `\"${spec.fuzzy.column}\" ${searchColumnTypeSql(spec.fuzzy.expression, \"text\")}` : undefined;\n\n/**\n * Index statements for the spec.\n *\n * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a\n * SQL file replayed as one unit — a migration, or `search.sql` — where a\n * concurrent build is not allowed. The boot-time ensure path runs statement by\n * statement against tables that are live and populated, and uses the\n * concurrent form instead; see `ensureSearchColumns`.\n */\nexport const searchIndexStatements = (spec: SearchColumnSpec): string[] => {\n const statements = [\n `CREATE INDEX IF NOT EXISTS \"${spec.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.column}\");`\n ];\n if (spec.fuzzy) {\n statements.push(\n // The operator class is resolved through `search_path` like any\n // other object, so it is qualified for the same reason the\n // extension is installed explicitly.\n `CREATE INDEX IF NOT EXISTS \"${spec.fuzzy.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.fuzzy.column}\" ${HELPER_SCHEMA}.gin_trgm_ops);`\n );\n }\n return statements;\n};\n\n// ── Telling a changed `search` block from an unchanged one ──────────────────\n\n/**\n * Marker on the comment of every generated search column this module creates.\n *\n * Versioned because the fingerprint below is only comparable against itself: a\n * future change to how it is computed has to read as \"not stamped by this\n * version\" rather than as drift on every existing column.\n */\nexport const SEARCH_STAMP_PREFIX = \"rebase:search:v1:\";\n\n/**\n * A stable fingerprint of one generated column's expression.\n *\n * Why a stamp rather than reading the expression back: Postgres stores a\n * generated column's expression *parsed*, and hands it back deparsed — casts\n * made explicit, identifiers requoted, schema qualifications added or dropped\n * according to `search_path`. Comparing that text to the text we generated\n * would report drift on wording, and this comparison decides whether a boot\n * refuses, so a false positive is an outage. The stamp is written by the same\n * code that writes the column, so equality means what it says.\n */\nexport const searchExpressionFingerprint = (expression: string): string =>\n `${SEARCH_STAMP_PREFIX}${createHash(\"sha256\").update(expression).digest(\"hex\").slice(0, 16)}`;\n\n/** One generated column, with the fingerprint that identifies its expression. */\nexport interface SearchColumnStamp {\n column: string;\n /** The expression the column is generated from. */\n expression: string;\n fingerprint: string;\n /** `COMMENT ON COLUMN …`, which is where the fingerprint is recorded. */\n sql: string;\n}\n\n/**\n * The stamps for a spec's generated columns — one per column, never shared.\n *\n * Per column on purpose: turning `fuzzy` on adds a second column and changes\n * nothing about the first, and a spec-wide fingerprint would report the\n * untouched `tsvector` column as drifted and refuse a boot over a change that\n * is purely additive.\n */\nexport const searchColumnStamps = (spec: SearchColumnSpec): SearchColumnStamp[] => {\n const stamp = (column: string, expression: string): SearchColumnStamp => {\n const fingerprint = searchExpressionFingerprint(expression);\n return {\n column,\n expression,\n fingerprint,\n sql: `COMMENT ON COLUMN \"${spec.schema}\".\"${spec.table}\".\"${column}\" IS ${quote(fingerprint)};`\n };\n };\n const stamps = [stamp(spec.column, spec.expression)];\n if (spec.fuzzy) stamps.push(stamp(spec.fuzzy.column, spec.fuzzy.expression));\n return stamps;\n};\n\n/**\n * The same drift check as the boot ensure, for the SQL file.\n *\n * Needed because {@link searchColumnStamps} would otherwise *launder* drift on\n * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that\n * exists, so a re-generated `search.sql` would stamp a stale column with the\n * new block's fingerprint and the next boot would find them in agreement.\n * Guarding first means the file refuses instead — `rebase db push` is attended,\n * and the operator reading the failure is the person who changed the block.\n */\nexport const searchStampGuards = (spec: SearchColumnSpec): string[] =>\n searchColumnStamps(spec).map(stamp => {\n const relation = quote(`\"${spec.schema}\".\"${spec.table}\"`);\n return `DO $rebase_search$\nDECLARE recorded text;\nBEGIN\n SELECT col_description(a.attrelid, a.attnum) INTO recorded\n FROM pg_attribute a\n WHERE a.attrelid = ${relation}::regclass AND a.attname = ${quote(stamp.column)} AND NOT a.attisdropped;\n IF recorded LIKE ${quote(`${SEARCH_STAMP_PREFIX}%`)} AND recorded <> ${quote(stamp.fingerprint)} THEN\n RAISE EXCEPTION 'Rebase: the search block for ${spec.schema}.${spec.table} changed after the generated column \"${stamp.column}\" was built (recorded %, expected ${stamp.fingerprint}). Postgres cannot alter a generated expression in place. Drop the column and re-apply this file — it rewrites the table and rebuilds the index: ALTER TABLE ${relation.slice(1, -1)} DROP COLUMN \"${stamp.column}\";', recorded;\n END IF;\nEND\n$rebase_search$;`;\n });\n\n/**\n * The index names the spec creates.\n *\n * Needed by name, not just by statement, so Atlas can be told to exclude them\n * from its diff — see `searchExcludePatterns`.\n */\nexport const searchIndexNames = (spec: SearchColumnSpec): string[] =>\n spec.fuzzy ? [spec.indexName, spec.fuzzy.indexName] : [spec.indexName];\n\n// ── Keeping the generated columns out of responses ──────────────────────────\n\n/**\n * The generated column names a collection's search block adds, if any.\n *\n * These are physical columns on the table, so `SELECT *` returns them. They are\n * an index in column form — a list of lexeme positions, or a concatenation of\n * every searchable field on the row — and nothing outside the query planner has\n * any use for them. Left in, every list response carries a second, larger copy\n * of the row's text.\n */\nexport const searchColumnNames = (collection: CollectionConfig): string[] => {\n let spec: SearchColumnSpec | undefined;\n try {\n spec = buildSearchColumnSpec(collection);\n } catch {\n // A malformed block is reported at boot, loudly. A read is the wrong\n // place to raise it a second time, and returning the row without the\n // exclusion would be worse than returning it with.\n return [];\n }\n if (!spec) return [];\n return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];\n};\n\n/**\n * True for a column whose type only ever holds a search index.\n *\n * Independent of any collection config on purpose: an introspected database\n * (BaaS mode) can carry a `tsvector` column this framework never created —\n * Pagila's `film.fulltext` is the canonical one — and it should not be returned\n * to callers either. `isDerivedIndexColumn` already keeps such a column out of\n * the *properties*; this keeps it out of the *rows*.\n */\nexport const isSearchIndexColumn = (column: { getSQLType?: () => string }): boolean => {\n const sqlType = typeof column?.getSQLType === \"function\" ? column.getSQLType().toLowerCase() : \"\";\n return sqlType === \"tsvector\" || sqlType === \"tsquery\";\n};\n\n/**\n * A drizzle select projection over `table` with the search columns dropped.\n *\n * Returns undefined when nothing needs dropping, so the common case keeps using\n * a plain `select()` and this stays invisible in the generated SQL.\n */\nexport const visibleColumnProjection = <C extends { getSQLType?: () => string }>(\n tableColumns: Record<string, C> | undefined,\n collection?: CollectionConfig\n): Record<string, C> | undefined => {\n const excluded = excludedColumnNames(tableColumns, collection);\n if (!tableColumns || excluded.length === 0) return undefined;\n const projection: Record<string, C> = {};\n for (const [name, column] of Object.entries(tableColumns)) {\n if (!excluded.includes(name)) projection[name] = column;\n }\n return projection;\n};\n\n/** The same exclusion as a drizzle `db.query` `columns` denylist. */\nexport const hiddenColumnsOption = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): Record<string, false> | undefined => {\n const excluded = excludedColumnNames(tableColumns, collection);\n if (excluded.length === 0) return undefined;\n return Object.fromEntries(excluded.map(name => [name, false as const]));\n};\n\n/**\n * The columns to keep out of a response, by name.\n *\n * `tableColumns` is whatever `getTableColumns` returned, which is `undefined`\n * for anything that is not a real drizzle table — a stub in a test, a derived\n * or nested path with no table behind it. Nothing to exclude is the right\n * answer there, and it has to be an answer rather than a throw: this runs on\n * the read path of every collection, opted in or not.\n */\nconst excludedColumnNames = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): string[] => {\n if (!tableColumns || typeof tableColumns !== \"object\") return [];\n const byName = new Set(collection ? searchColumnNames(collection) : []);\n return Object.keys(tableColumns).filter(\n name => byName.has(name) || isSearchIndexColumn(tableColumns[name])\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,IAAM,gBAAgB;;;;;;AAOtB,IAAa,iBAAiB,GAAG,cAAc;AAC/C,IAAa,qBAAqB,GAAG,cAAc;;AAgEnD,IAAa,oBAAb,cAAuC,MAAM;CACzC,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;;AAGA,IAAa,mBAAmB,eAC5B,2BAA2B,UAAU,IAAI,WAAW,SAAS,KAAA;;;;;;;;;;;;AAajE,IAAa,8BAA8B,gBAA0C;CACjF,KAAK,MAAM,cAAc,aAAa;EAClC,IAAI,2BAA2B,UAAU,GAAG;EAC5C,IAAI,CAAE,WAAoC,QAAQ;EAClD,MAAM,SAAU,WAAmC,UAAU;EAC7D,MAAM,IAAI,kBACN,GAAG,WAAW,KAAK,sFAAsF,OAAO,sHAEpH;CACJ;AACJ;AAEA,IAAM,gBAAgB,UAAkB,SACpC,QAAQ,gBAAgB,QAAQ,OAAO,KAAK,eAAe,WAAW,KAAK,aAAa,YAAY,QAAQ;;;;;;;;;;;;AAahH,IAAM,YAAY,SAAgE;CAC9E,QAAQ,KAAK,MAAb;EACI,KAAK,UAAU;GACX,MAAM,KAAK;GACX,IAAI,GAAG,MACH,OAAO;IAAE,MAAM;IAAQ,QAAQ;GAAO;GAE1C,IAAI,GAAG,SAAS,UAAU,GAAG,eAAe,QAC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"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The columns a caller may not read, taken out of what their SQL returned.
3
+ *
4
+ * Per-field read rules (`access.read`, and `excludeFromApi`, which is
5
+ * `read: []`) are not something Postgres can hold for one request role shared
6
+ * by every user, so the SDK applies them to each row it serves
7
+ * (`stripUnreadable`). SQL run as the caller (`DataDriver.sql`) returns rows
8
+ * the SDK never walked — and `SELECT *` from a users table would hand over the
9
+ * password hash.
10
+ *
11
+ * Postgres says where each result column came from: the row description
12
+ * carries the table's oid and the column's number for every column that is a
13
+ * plain reference to one, aliased or not, `RETURNING` included. A column whose
14
+ * origin is a collection property this caller cannot read is dropped from
15
+ * every row, the way the API drops it.
16
+ *
17
+ * What it cannot see is a value computed from such a column — `md5(hash)`,
18
+ * `hash || ''` — whose origin Postgres reports as none. That is the query
19
+ * text's business, and the query text is the application's (see
20
+ * `caller-sql.ts`).
21
+ *
22
+ * A driver that reports no origins at all (PGlite) has its result columns
23
+ * matched by name instead, against every restricted column of every
24
+ * collection: it may drop a column of the same name from another table, never
25
+ * keep one it should drop.
26
+ */
27
+ import { type FieldViewer } from "@rebasepro/common";
28
+ import { type CollectionConfig } from "@rebasepro/types";
29
+ /** A result column as the driver describes it. */
30
+ export interface ResultField {
31
+ name: string;
32
+ /** The originating table's oid; 0 for a computed column. Absent when the driver does not say (PGlite). */
33
+ tableID?: number;
34
+ /** The originating column's number within it. */
35
+ columnID?: number;
36
+ }
37
+ /** The columns of a result, from a pg `QueryResult` (or the last of several). */
38
+ export declare function fieldsOfResult(result: unknown): ResultField[];
39
+ type CatalogueRunner = (text: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
40
+ interface Relation {
41
+ schema: string;
42
+ name: string;
43
+ /** `attnum` → `attname`. */
44
+ columns: Map<number, string>;
45
+ }
46
+ /**
47
+ * The relations result columns came from, by oid, read from the catalogue the
48
+ * first time an oid is seen. An oid never changes meaning: a table that is
49
+ * dropped and created again gets a new one, which is read when it appears.
50
+ */
51
+ export declare class ColumnOrigins {
52
+ private readonly relations;
53
+ describe(oids: number[], run: CatalogueRunner): Promise<Map<number, Relation | null>>;
54
+ }
55
+ /**
56
+ * `rows` without the columns `viewer` may not read, by the origins `fields`
57
+ * describe. The rows are changed in place and returned.
58
+ */
59
+ export declare function withoutUnreadableColumns(rows: Record<string, unknown>[], fields: ResultField[], viewer: FieldViewer, collections: CollectionConfig[], origins: ColumnOrigins, run: CatalogueRunner): Promise<Record<string, unknown>[]>;
60
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The query with every string literal, dollar-quoted body and comment
3
+ * replaced by a space. Quoted identifiers are kept, quotes and all, so a name
4
+ * written `"set_config"` still reads as one.
5
+ */
6
+ export declare function maskSqlLiterals(text: string): string;
7
+ /** Throw `SQL_NOT_ALLOWED` unless `text` may run as the caller (see the module docs). */
8
+ export declare function assertCallerSql(text: string): void;
@@ -0,0 +1,24 @@
1
+ import { type ManagedTable, type RawSqlRunner } from "./rls-enforcement.js";
2
+ import type { RlsSettings } from "./rls-settings.js";
3
+ /**
4
+ * What `rebase doctor --database` checks: whether this database can host
5
+ * Rebase's request role(s) under the project's `rls` settings, read from the
6
+ * catalogue without changing anything.
7
+ *
8
+ * Every finding that is not "ok" carries the SQL to run as an administrator, the
9
+ * `rls` setting that would adapt Rebase to the database instead, or both — the
10
+ * two ways out of any of them.
11
+ */
12
+ export interface PreflightFinding {
13
+ level: "ok" | "warn" | "fail";
14
+ check: string;
15
+ detail: string;
16
+ /** SQL that fixes it, run as a database administrator. */
17
+ sql?: string;
18
+ /** The `rls` setting that would fit Rebase to the database as it is. */
19
+ setting?: string;
20
+ }
21
+ export declare function preflightDatabase(run: RawSqlRunner, settings: RlsSettings, options: {
22
+ schemas: readonly string[];
23
+ managedTables: readonly ManagedTable[];
24
+ }): Promise<PreflightFinding[]>;
@@ -112,6 +112,22 @@ export interface Queryable {
112
112
  * `policies.sql` created it.
113
113
  */
114
114
  export declare function parseExpectedPolicies(ddl: string): PolicyRef[];
115
+ /**
116
+ * Where the server-or-admin policies are expected: `TO rebase_admin` (`true`),
117
+ * `TO public` (`false`), or `"detect"` — read off the database as a boot on
118
+ * this connection would decide it (`adminPoliciesLiveForCli`). A boot whose
119
+ * admin switch is not live writes them `TO public`, and that is not drift.
120
+ */
121
+ export type AdminPoliciesExpectation = boolean | "detect";
122
+ /** {@link AdminPoliciesExpectation} as a yes or no. Left out, `TO rebase_admin`, as compiled. */
123
+ export declare function resolveAdminPolicies(client: Queryable, expectation: AdminPoliciesExpectation | undefined): Promise<boolean>;
124
+ /**
125
+ * The policies the collections declare, parsed from the DDL `db push` writes —
126
+ * with the ones the compiler put `TO rebase_admin` read as `TO public` where
127
+ * `adminRoleAvailable` is false, as the boot and the push then write them. A
128
+ * rule that names `rebase_admin` itself keeps it.
129
+ */
130
+ export declare function expectedPolicies(collections: CollectionConfig[], adminRoleAvailable: boolean): PolicyRef[];
115
131
  /**
116
132
  * Diff expected against live.
117
133
  *
@@ -128,7 +144,9 @@ export declare function parseExpectedPolicies(ddl: string): PolicyRef[];
128
144
  * whose `qual` was NULL, matching on every field this checked and denying 100%
129
145
  * of reads. The same blindness would hide a policy that fails open.
130
146
  */
131
- export declare function checkPolicyDrift(client: Queryable, collections: CollectionConfig[]): Promise<PolicyDrift>;
147
+ export declare function checkPolicyDrift(client: Queryable, collections: CollectionConfig[], options?: {
148
+ adminRoleAvailable?: AdminPoliciesExpectation;
149
+ }): Promise<PolicyDrift>;
132
150
  /**
133
151
  * Does this name look like one the generator produced for this table?
134
152
  *
@@ -0,0 +1,36 @@
1
+ import { type RawSqlRunner } from "./rls-enforcement.js";
2
+ /**
3
+ * Move a database from one set of request roles to another — what
4
+ * `rebase db request-role migrate --to …` runs.
5
+ *
6
+ * A role belongs to the cluster, so renaming one (`ALTER ROLE … RENAME`) moves
7
+ * every database's grants at once, including another project's that shares
8
+ * it. This instead creates the new role(s) and re-issues, in THIS database
9
+ * only, every grant the old ones hold here: tables and views, columns,
10
+ * sequences, schemas, functions, the default privileges this connection set,
11
+ * and the memberships that carry other roles' policies (`rls.inheritRoles`).
12
+ * Policies that name an old role in their `TO` list are re-pointed. The old
13
+ * roles are left as they are — another database may still use them — and the
14
+ * statements to take their grants back here are returned for the operator.
15
+ */
16
+ export interface RequestRoleMigrationPlan {
17
+ /** What to run, in order, to give the new roles what the old ones hold here. */
18
+ statements: string[];
19
+ /** What would take the old roles' grants back in this database, for the operator to run once satisfied. */
20
+ revokeOld: string[];
21
+ }
22
+ /**
23
+ * Read the catalogue and plan the move. Writes nothing; {@link migrateRequestRoles}
24
+ * runs the plan.
25
+ */
26
+ export declare function planRequestRoleMigration(run: RawSqlRunner, from: readonly string[], to: readonly string[]): Promise<RequestRoleMigrationPlan>;
27
+ /**
28
+ * Provision the new role(s), run the plan, and record the new roles — in one
29
+ * transaction where the runner has one, so a failure leaves the database on
30
+ * its old roles. Returns the plan that ran.
31
+ */
32
+ export declare function migrateRequestRoles(run: RawSqlRunner, options: {
33
+ from: readonly string[];
34
+ to: readonly string[];
35
+ schemas: readonly string[];
36
+ }): Promise<RequestRoleMigrationPlan>;