@rebasepro/server-postgres 0.22.0 → 0.24.0

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 (123) hide show
  1. package/dist/{BranchService-CucnFcSE.js → BranchService-BRt78gfa.js} +35 -18
  2. package/dist/BranchService-BRt78gfa.js.map +1 -0
  3. package/dist/PostgresBackendDriver.d.ts +116 -4
  4. package/dist/auth/services.d.ts +99 -22
  5. package/dist/{auth-users-columns-D2LBFrMH.js → auth-users-columns-C72EMoDJ.js} +17 -1
  6. package/dist/{auth-users-columns-D2LBFrMH.js.map → auth-users-columns-C72EMoDJ.js.map} +1 -1
  7. package/dist/backup/backup-cli.d.ts +22 -0
  8. package/dist/{backup-cli-DqBakiMO.js → backup-cli-DW5p9_zv.js} +17 -14
  9. package/dist/backup-cli-DW5p9_zv.js.map +1 -0
  10. package/dist/{backup-service-CaMOS76G.js → backup-service-EwcDVG-8.js} +7 -9
  11. package/dist/{backup-service-CaMOS76G.js.map → backup-service-EwcDVG-8.js.map} +1 -1
  12. package/dist/{cli-errors-Dka89exj.js → cli-errors-DsA-K9uP.js} +101 -1
  13. package/dist/cli-errors-DsA-K9uP.js.map +1 -0
  14. package/dist/cli-errors.d.ts +42 -0
  15. package/dist/cli-flags-BglvpjHv.js +138 -0
  16. package/dist/cli-flags-BglvpjHv.js.map +1 -0
  17. package/dist/cli-flags.d.ts +28 -0
  18. package/dist/cli-helpers.d.ts +18 -12
  19. package/dist/cli-scratch-database.d.ts +34 -0
  20. package/dist/cli.js +177 -287
  21. package/dist/cli.js.map +1 -1
  22. package/dist/{column-plan-helpers-CpILzHJS.js → column-plan-helpers-1-LQD0yI.js} +44 -38
  23. package/dist/column-plan-helpers-1-LQD0yI.js.map +1 -0
  24. package/dist/data-transformer.d.ts +0 -8
  25. package/dist/{doctor-CU9IogdL.js → doctor-C-sYWbmt.js} +228 -46
  26. package/dist/doctor-C-sYWbmt.js.map +1 -0
  27. package/dist/{ensure-collection-policies-Dzd-2S81.js → ensure-collection-policies-B1ureSIV.js} +73 -18
  28. package/dist/ensure-collection-policies-B1ureSIV.js.map +1 -0
  29. package/dist/{ensure-collection-tables-CpAgy51F.js → ensure-collection-tables-kkkHk8oo.js} +124 -37
  30. package/dist/ensure-collection-tables-kkkHk8oo.js.map +1 -0
  31. package/dist/{ensure-tables-Cr5B4UmH.js → ensure-tables-BmI_tRxc.js} +10 -3
  32. package/dist/ensure-tables-BmI_tRxc.js.map +1 -0
  33. package/dist/{generate-drizzle-schema-B537GIvz.js → generate-drizzle-schema-93M0lUxK.js} +2 -2
  34. package/dist/{generate-drizzle-schema-B537GIvz.js.map → generate-drizzle-schema-93M0lUxK.js.map} +1 -1
  35. package/dist/{generate-drizzle-schema-logic-BcMl7VSy.js → generate-drizzle-schema-logic-sSFDp6LR.js} +26 -8
  36. package/dist/generate-drizzle-schema-logic-sSFDp6LR.js.map +1 -0
  37. package/dist/generate-postgres-ddl-logic-BJsLaVNX.js +152 -0
  38. package/dist/generate-postgres-ddl-logic-BJsLaVNX.js.map +1 -0
  39. package/dist/generated-sql.d.ts +28 -0
  40. package/dist/index.es.js +4768 -1117
  41. package/dist/index.es.js.map +1 -1
  42. package/dist/{introspect-db-logic-C6LQdTxj.js → introspect-db-logic-kCETE8TY.js} +532 -39
  43. package/dist/introspect-db-logic-kCETE8TY.js.map +1 -0
  44. package/dist/introspect-db-queries-C_Q5VgQw.js +317 -0
  45. package/dist/introspect-db-queries-C_Q5VgQw.js.map +1 -0
  46. package/dist/{plan-schema-CboAIwLN.js → plan-schema-DU9exq6C.js} +291 -529
  47. package/dist/plan-schema-DU9exq6C.js.map +1 -0
  48. package/dist/{policy-drift-xJfy9xG7.js → policy-drift-B-J2hhm0.js} +3 -3
  49. package/dist/policy-drift-B-J2hhm0.js.map +1 -0
  50. package/dist/{generate-postgres-ddl-logic-D7imhYV8.js → render-ddl-Ds2t_d9V.js} +11 -149
  51. package/dist/render-ddl-Ds2t_d9V.js.map +1 -0
  52. package/dist/{rls-bootstrap-sql-H3rCFi3F.js → rls-bootstrap-sql-_KNnjanK.js} +562 -35
  53. package/dist/rls-bootstrap-sql-_KNnjanK.js.map +1 -0
  54. package/dist/{rls-enforcement-C6Xk0lA6.js → rls-enforcement-CfXOJJaW.js} +10 -2
  55. package/dist/rls-enforcement-CfXOJJaW.js.map +1 -0
  56. package/dist/schema/atlas-argv.d.ts +15 -0
  57. package/dist/schema/auth-schema.d.ts +170 -0
  58. package/dist/schema/classify-change.d.ts +29 -1
  59. package/dist/schema/column-plan-helpers.d.ts +51 -20
  60. package/dist/schema/destructive-sql.d.ts +71 -1
  61. package/dist/schema/doctor-cli.js +4 -4
  62. package/dist/schema/doctor.d.ts +34 -1
  63. package/dist/schema/ensure-collection-policies.d.ts +22 -0
  64. package/dist/schema/generate-drizzle-schema.js +1 -1
  65. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
  66. package/dist/schema/generate-postgres-ddl.js +1 -1
  67. package/dist/schema/generate-schema-commit.d.ts +12 -0
  68. package/dist/schema/introspect-db-logic.d.ts +31 -0
  69. package/dist/schema/introspect-db-queries.d.ts +1 -1
  70. package/dist/schema/introspect-db-search.d.ts +22 -0
  71. package/dist/schema/introspect-db-storage.d.ts +83 -0
  72. package/dist/schema/introspect-db.js +15 -314
  73. package/dist/schema/introspect-db.js.map +1 -1
  74. package/dist/schema/plan/diff-plan.d.ts +4 -3
  75. package/dist/schema/plan/plan-schema.d.ts +26 -11
  76. package/dist/schema/plan/render-ddl.d.ts +6 -0
  77. package/dist/schema/plan/types.d.ts +43 -12
  78. package/dist/search-column-BM-GV6vH.js +442 -0
  79. package/dist/search-column-BM-GV6vH.js.map +1 -0
  80. package/dist/security/policy-drift.d.ts +1 -1
  81. package/dist/security/rls-enforcement.d.ts +7 -0
  82. package/dist/services/BranchService.d.ts +22 -1
  83. package/dist/services/FetchService.d.ts +102 -32
  84. package/dist/services/PersistService.d.ts +41 -5
  85. package/dist/services/RelationService.d.ts +29 -0
  86. package/dist/services/RelationWriteService.d.ts +6 -0
  87. package/dist/services/cdc/CdcListener.d.ts +15 -5
  88. package/dist/services/cdc/identity-columns.d.ts +19 -0
  89. package/dist/services/cdc/trigger-cdc.d.ts +45 -7
  90. package/dist/services/channel-bus/PostgresChannelBus.d.ts +12 -7
  91. package/dist/services/channel-history.d.ts +17 -1
  92. package/dist/services/collection-helpers.d.ts +21 -0
  93. package/dist/services/dataService.d.ts +3 -20
  94. package/dist/services/field-op-sql.d.ts +71 -0
  95. package/dist/services/junction-writes.d.ts +19 -3
  96. package/dist/services/pg-notify-listener.d.ts +95 -6
  97. package/dist/services/read-field-access.d.ts +19 -0
  98. package/dist/services/realtimeService.d.ts +232 -44
  99. package/dist/services/row-pipeline.d.ts +5 -0
  100. package/dist/services/socket-liveness.d.ts +45 -0
  101. package/dist/services/soft-delete.d.ts +12 -2
  102. package/dist/services/sql-script.d.ts +71 -0
  103. package/dist/services/write-depth.d.ts +16 -0
  104. package/dist/services/write-transaction-scope.d.ts +42 -0
  105. package/dist/utils/drizzle-conditions.d.ts +49 -4
  106. package/dist/utils/sql-redaction.d.ts +21 -0
  107. package/dist/websocket.d.ts +57 -18
  108. package/package.json +9 -9
  109. package/dist/BranchService-CucnFcSE.js.map +0 -1
  110. package/dist/backup-cli-DqBakiMO.js.map +0 -1
  111. package/dist/cli-errors-Dka89exj.js.map +0 -1
  112. package/dist/column-plan-helpers-CpILzHJS.js.map +0 -1
  113. package/dist/doctor-CU9IogdL.js.map +0 -1
  114. package/dist/ensure-collection-policies-Dzd-2S81.js.map +0 -1
  115. package/dist/ensure-collection-tables-CpAgy51F.js.map +0 -1
  116. package/dist/ensure-tables-Cr5B4UmH.js.map +0 -1
  117. package/dist/generate-drizzle-schema-logic-BcMl7VSy.js.map +0 -1
  118. package/dist/generate-postgres-ddl-logic-D7imhYV8.js.map +0 -1
  119. package/dist/introspect-db-logic-C6LQdTxj.js.map +0 -1
  120. package/dist/plan-schema-CboAIwLN.js.map +0 -1
  121. package/dist/policy-drift-xJfy9xG7.js.map +0 -1
  122. package/dist/rls-bootstrap-sql-H3rCFi3F.js.map +0 -1
  123. package/dist/rls-enforcement-C6Xk0lA6.js.map +0 -1
@@ -102,7 +102,7 @@ export interface DiffOptions {
102
102
  constraints?: ConstraintPolicy;
103
103
  }
104
104
  export interface EnsureAction {
105
- kind: "create-enum" | "create-table" | "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";
105
+ 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";
106
106
  /** Qualified target, for logging: `public.posts` or `public.posts.title`. */
107
107
  target: string;
108
108
  sql: string;
@@ -120,11 +120,12 @@ export interface OrphanedRequiredColumn {
120
120
  export interface WithheldConstraint {
121
121
  /** `schema.table.column`. */
122
122
  target: string;
123
- kind: "not-null";
123
+ kind: "not-null" | "unique";
124
124
  /**
125
125
  * Why, in a sentence that names the obstacle rather than the rule. The
126
126
  * reader is looking at a column that is nullable when they asked for
127
- * required, and needs to know what to do about it.
127
+ * required, or accepts duplicates when they asked for unique, and needs to
128
+ * know what to do about it.
128
129
  */
129
130
  reason: string;
130
131
  /** What would make it applicable. */
@@ -12,7 +12,7 @@
12
12
  * imported would not be comparable with itself.
13
13
  *
14
14
  * It **throws** rather than guessing. A configuration no renderer can honour —
15
- * an empty enum, two `isId` properties, `isId: "cuid"`, an unknown
15
+ * an empty enum, `isId: "cuid"`, a foreign key into a composite key, an unknown
16
16
  * `columnType`, a relation to a collection that is not in the bundle, a
17
17
  * `search` block on a collection Postgres does not store — used to fail
18
18
  * differently in each of the three emitters, or not at all, and the failure
@@ -55,11 +55,27 @@ export declare const defaultBelongsToOnDelete: (required: boolean | undefined) =
55
55
  * The type a column pointing at this collection's primary key must have — a
56
56
  * junction endpoint, a `belongsTo` foreign key, a `reference`.
57
57
  *
58
- * One function because it was three: the ladder was spelled inline in
59
- * `generatePostgresDdl`, again in `planJunctionTables` and a third time in the
60
- * Drizzle generator.
58
+ * The key's own column type, from the same functions that typed the key: a
59
+ * foreign key only holds between compatible types, so any second reading of
60
+ * the key is a constraint waiting to fail. This used to look at the id
61
+ * strategy alone, so `id: { isId: true, columnType: "uuid" }` was referenced by
62
+ * TEXT columns (42804 — the constraint was never created) and a `bigint` key by
63
+ * INTEGER ones, which overflow at 2^31.
64
+ *
65
+ * One exception: a `serial` key owns a sequence, and a column pointing at it is
66
+ * the plain integer of the same width — `SERIAL` there would give every
67
+ * referencing column a sequence of its own.
68
+ *
69
+ * @param via the link asking, named if the collection's key is composite and so
70
+ * cannot be pointed at — see `getPrimaryKeyProp`.
71
+ */
72
+ export declare const primaryKeyPgType: (collection: CollectionConfig, via: string) => PgType;
73
+ /**
74
+ * The DEFAULT of the implicit `id TEXT PRIMARY KEY` a collection that declares
75
+ * no key gets: a uuid, as text. The same generator `isId: "uuid"` uses, cast to
76
+ * the column the key has always been.
61
77
  */
62
- export declare const primaryKeyPgType: (collection: CollectionConfig) => PgType;
78
+ export declare const IMPLICIT_ID_DEFAULT = "gen_random_uuid()::text";
63
79
  /**
64
80
  * The Postgres type a property's column has.
65
81
  *
@@ -72,12 +88,11 @@ export declare const columnPgType: (propName: string, prop: Property, collection
72
88
  /**
73
89
  * One security rule, compiled to the clauses a policy is made of.
74
90
  *
75
- * The desugaring (`access` / `ownerField` / `roles` / structured condition /
76
- * raw SQL → `PolicyExpression`) and the SQL compilation are `@rebasepro/common`'s,
77
- * which is what the client-side evaluator uses too — so the UI, the DDL and the
78
- * database agree about who can read a row. What lives here is only the shape:
79
- * which operations a rule expands to, which clauses each operation takes, and
80
- * the deny-all fallback for a clause that compiled to nothing.
91
+ * The compilation is `compileRulePolicies` in `@rebasepro/common`, which the
92
+ * Studio's RLS editor also compares the live database against — so the UI, the
93
+ * DDL and the database agree about who can read a row. What this adds is only
94
+ * the planner's bookkeeping: which rule a policy came from, and whether Rebase
95
+ * injected it.
81
96
  */
82
97
  export declare const compileSecurityRule: (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection, injected: boolean, ruleKey?: string) => PolicyPlan[];
83
98
  export declare function planSchema(allCollections: CollectionConfig[], options?: PlanOptions): SchemaPlan;
@@ -25,6 +25,12 @@ export declare const renderPgType: (type: PgType) => string;
25
25
  * DEFAULT, which is why it is rendered here and not in the DEFAULT slot.
26
26
  */
27
27
  export declare const renderColumnDefinition: (column: ColumnPlan) => string;
28
+ /**
29
+ * `PRIMARY KEY ("a", "b")`, the clause a composite key takes inside a
30
+ * `CREATE TABLE`. Shared by `schema.sql` and boot-ensure's `CREATE TABLE`, so
31
+ * the two cannot list the columns differently.
32
+ */
33
+ export declare const renderPrimaryKeyConstraint: (table: Pick<TablePlan, "primaryKey">) => string;
28
34
  /**
29
35
  * One policy as its `DROP` / `CREATE` pair — each a complete statement.
30
36
  *
@@ -200,6 +200,13 @@ export interface ColumnPlan {
200
200
  column: string;
201
201
  type: PgType;
202
202
  nullable: boolean;
203
+ /**
204
+ * This column alone is the table's primary key, declared inline on it.
205
+ *
206
+ * `false` for a column of a composite key: several inline `PRIMARY KEY`
207
+ * clauses would be several primary keys, so a composite key is one table
208
+ * constraint over {@link TablePlan.primaryKey} instead.
209
+ */
203
210
  primaryKey: boolean;
204
211
  unique: boolean;
205
212
  default?: ColumnDefault;
@@ -288,7 +295,12 @@ export interface EnumPlan {
288
295
  schema: string;
289
296
  /** Type name, unqualified: `<table>_<column>`. A frozen derived name. */
290
297
  name: string;
291
- /** `schema.name` — the key `readExistingSchema` returns. */
298
+ /**
299
+ * `schema.name`, with the name cut to the 63 bytes Postgres keeps — the key
300
+ * `readExistingSchema` returns. `name` itself is emitted in full, and
301
+ * Postgres truncates it the same way; comparing the full name against the
302
+ * catalogue found a long one missing on every boot.
303
+ */
292
304
  qualified: string;
293
305
  /**
294
306
  * The schema the collection *declared*, before the `public` fallback.
@@ -321,7 +333,13 @@ export interface TablePlan {
321
333
  */
322
334
  declaringSlugs?: string[];
323
335
  columns: ColumnPlan[];
324
- /** Column names, in order. One entry for a collection, two for a junction. */
336
+ /**
337
+ * The primary key's column names, in key order.
338
+ *
339
+ * One entry is a key declared inline on its column ({@link ColumnPlan.primaryKey}).
340
+ * Several — a junction's two endpoints, or a collection marking several
341
+ * properties `isId` — are rendered as one `PRIMARY KEY (a, b)` constraint.
342
+ */
325
343
  primaryKey: string[];
326
344
  /** The declared `indexes:` block, with its frozen names. */
327
345
  indexes: CollectionIndexSpec[];
@@ -350,23 +368,35 @@ export interface TablePlan {
350
368
  * pair them; the rule that derives it is `sharedRelationName`, which both sides
351
369
  * compute independently from the table that owns the column.
352
370
  */
353
- export interface RelationPlan {
371
+ export type RelationPlan = OneRelationPlan | ManyRelationPlan;
372
+ interface RelationPlanBase {
354
373
  /** The Drizzle table variable this entry belongs to. */
355
374
  tableVar: string;
356
375
  /** The key in the relations object. */
357
376
  key: string;
358
- kind: "one" | "many";
359
377
  targetVar: string;
360
- /**
361
- * Absent only for a `hasOne` inverse, which is the documented FK-less form:
362
- * `one(target)` with no config. `one(target, { relationName })` is not a
363
- * `RelationConfig` (TS2345) and throws at runtime besides.
364
- */
365
- relationName?: string;
378
+ relationName: string;
379
+ }
380
+ /**
381
+ * A `one()`. Every one names its join — Drizzle has no `one()` paired by
382
+ * `relationName` alone, and one paired by table is ambiguous as soon as two
383
+ * links join the same pair of tables.
384
+ */
385
+ export interface OneRelationPlan extends RelationPlanBase {
386
+ kind: "one";
366
387
  /** Property keys on this table. */
367
- fields?: string[];
388
+ fields: string[];
368
389
  /** Property keys on the target table. */
369
- references?: string[];
390
+ references: string[];
391
+ /**
392
+ * Set on a `hasOne`, whose `fields` are this table's own key: the target
393
+ * row may not exist although every column in `fields` is NOT NULL, which
394
+ * is what Drizzle reads a `one()`'s nullability from.
395
+ */
396
+ nullable?: true;
397
+ }
398
+ export interface ManyRelationPlan extends RelationPlanBase {
399
+ kind: "many";
370
400
  }
371
401
  export interface PlanOptions {
372
402
  /**
@@ -408,3 +438,4 @@ export interface SchemaPlan {
408
438
  collections: CollectionConfig[];
409
439
  options: PlanOptions;
410
440
  }
441
+ export {};
@@ -0,0 +1,442 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { DEFAULT_FUZZY_THRESHOLD, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, isPostgresCollectionConfig } from "@rebasepro/types";
4
+ import { getTableName } from "@rebasepro/common";
5
+ import { toPostgresIdentifier, toSnakeCase } from "@rebasepro/utils";
6
+ import { createHash } from "node:crypto";
7
+ //#region src/schema/search-column.ts
8
+ /**
9
+ * The one place a collection's `search` block becomes SQL.
10
+ *
11
+ * Four things describe a Postgres table in this codebase — the DDL generator,
12
+ * the Drizzle schema generator, the runtime table builder for BaaS mode, and
13
+ * the boot-time schema ensure — and each of them has, at some point, described
14
+ * a column differently from the others. The `varchar(255)` note in
15
+ * `generate-postgres-ddl-logic` is one such scar: the same property produced a
16
+ * capped column down one path and an uncapped one down the other, and nothing
17
+ * failed until a user hit the cap.
18
+ *
19
+ * So the search column is not implemented four times. It is computed once,
20
+ * here, and every generator renders the same {@link SearchColumnSpec}. There is
21
+ * a test asserting exactly that (`search-column-contract.test.ts`); the point of
22
+ * this module is that the test has something to assert *about*.
23
+ *
24
+ * ## Why the expressions look the way they do
25
+ *
26
+ * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and
27
+ * Postgres is stricter here than intuition. Verified against PostgreSQL 18:
28
+ *
29
+ * | expression | immutable |
30
+ * |-----------------------------------------|-----------|
31
+ * | `to_tsvector('spanish', col)` | yes |
32
+ * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |
33
+ * | `array_to_string(col, ' ')` | **no** |
34
+ * | `col::text` on `text[]` | **no** |
35
+ * | `to_jsonb(col)` | **no** |
36
+ * | `unaccent(col)` | **no** — dictionary lookup is STABLE |
37
+ * | `jsonb_to_tsvector('spanish', j, '["string"]')` | yes |
38
+ * | `setweight(...) || setweight(...)` | yes |
39
+ *
40
+ * Three of the four things a real search column needs are therefore unavailable
41
+ * directly, which is why {@link searchHelperFunctions} exists: each wraps a
42
+ * stable built-in in an SQL function declared IMMUTABLE. That declaration is a
43
+ * promise, and it is a true one for these three — array joining, JSON string
44
+ * extraction and accent folding are all deterministic for a given input; the
45
+ * built-ins are marked stable only because they must account for element types
46
+ * and dictionaries in general.
47
+ *
48
+ * The alternative was to skip `unaccent` and text arrays entirely. That is not
49
+ * a real option in an accented language: Postgres stems `auditoría` to
50
+ * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query
51
+ * typed without accents misses every row that carries them.
52
+ */
53
+ /** Schema-qualified so a collection outside `public` still resolves them. */
54
+ var HELPER_SCHEMA = "public";
55
+ /**
56
+ * Names of the helper functions. Frozen: they are recorded in the stored
57
+ * generation expression of every search column ever created, so renaming one
58
+ * orphans every table that already has a search column.
59
+ */
60
+ var SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;
61
+ var SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;
62
+ /** Raised when a `search` block names something that cannot be searched. */
63
+ var SearchConfigError = class extends Error {
64
+ constructor(message) {
65
+ super(message);
66
+ this.name = "SearchConfigError";
67
+ }
68
+ };
69
+ /** The `search` block of a collection, or undefined when it has none. */
70
+ var getSearchConfig = (collection) => isPostgresCollectionConfig(collection) ? collection.search : void 0;
71
+ /**
72
+ * Refuse a `search` block on a collection this engine does not store.
73
+ *
74
+ * The type only permits one on a `PostgresCollectionConfig`, so TypeScript
75
+ * already stops the ordinary case. This catches the rest — a JS config, a cast,
76
+ * a collection whose `engine` was changed after the block was written — because
77
+ * the alternative is the exact failure the block exists to prevent: a developer
78
+ * who declared what to index, saw no error, and got the substring fallback.
79
+ *
80
+ * Called with *every* collection, before the Postgres ones are filtered out.
81
+ */
82
+ var assertSearchIsPostgresOnly = (collections) => {
83
+ for (const collection of collections) {
84
+ if (isPostgresCollectionConfig(collection)) continue;
85
+ if (!collection.search) continue;
86
+ const engine = collection.engine ?? "non-postgres";
87
+ throw new SearchConfigError(`${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \`${engine}\`. Remove the block — it would otherwise look configured while \`.search()\` kept using the default substring match.`);
88
+ }
89
+ };
90
+ var columnNameOf = (propName, prop) => prop && "columnName" in prop && typeof prop.columnName === "string" ? prop.columnName : toSnakeCase(propName);
91
+ /**
92
+ * Classify a property for search purposes.
93
+ *
94
+ * Deliberately narrower than the schema plan's `PgType`: search only cares
95
+ * whether a value reaches text, and the mapping from property to *physical*
96
+ * type is asserted against the plan in the contract test rather than duplicated
97
+ * here.
98
+ *
99
+ * Returns null for anything that is not text-bearing, which the caller turns
100
+ * into a boot error naming the property.
101
+ */
102
+ var classify = (prop) => {
103
+ switch (prop.type) {
104
+ case "string": {
105
+ const sp = prop;
106
+ if (sp.enum) return {
107
+ kind: "text",
108
+ reason: "enum"
109
+ };
110
+ if (sp.isId === "uuid" || sp.columnType === "uuid") return {
111
+ kind: "text",
112
+ reason: "uuid"
113
+ };
114
+ return { kind: "text" };
115
+ }
116
+ case "map":
117
+ if (prop.columnType === "json") return {
118
+ kind: "jsonb",
119
+ reason: "json"
120
+ };
121
+ return { kind: "jsonb" };
122
+ case "array": {
123
+ const ap = prop;
124
+ let colType = ap.columnType;
125
+ if (!colType && ap.of && !Array.isArray(ap.of)) {
126
+ const of = ap.of;
127
+ if (of.type === "string") colType = "text[]";
128
+ else if (of.type === "number") colType = of.validation?.integer ? "integer[]" : "numeric[]";
129
+ else if (of.type === "boolean") colType = "boolean[]";
130
+ }
131
+ if (colType === "text[]") return { kind: "text_array" };
132
+ if (colType === "json") return {
133
+ kind: "jsonb",
134
+ reason: "json"
135
+ };
136
+ if (colType === "integer[]" || colType === "boolean[]" || colType === "numeric[]") return {
137
+ kind: "text_array",
138
+ reason: "non_text_array"
139
+ };
140
+ return { kind: "jsonb" };
141
+ }
142
+ default: return null;
143
+ }
144
+ };
145
+ var normalize = (inner, unaccent) => unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;
146
+ /** SQL reading one field as plain text, before normalization. */
147
+ var rawTextSql = (field) => {
148
+ const col = `"${field.column}"`;
149
+ if (field.kind === "text") return `coalesce(${col}, '')`;
150
+ if (field.kind === "text_array") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;
151
+ return `${SEARCH_TEXT_FN}(coalesce(${field.jsonPath.length === 0 ? col : field.jsonPath.length === 1 ? `${col} -> ${quote(field.jsonPath[0])}` : `${col} #> ${quote(`{${field.jsonPath.join(",")}}`)}`}, '{}'::jsonb))`;
152
+ };
153
+ var quote = (v) => `'${v.replace(/'/g, "''")}'`;
154
+ /**
155
+ * Resolve and validate one declared field path.
156
+ *
157
+ * A path that does not resolve throws. The whole point of an explicit block is
158
+ * that the author knows what is indexed; a silently dropped field would make it
159
+ * a guess again, and the failure — a search that returns nothing for content
160
+ * that is plainly in the row — is invisible from the outside.
161
+ */
162
+ var resolveField = (entry, collection, cfg) => {
163
+ const path = typeof entry === "string" ? entry : entry.path;
164
+ const weight = (typeof entry === "string" ? void 0 : entry.weight) ?? DEFAULT_SEARCH_WEIGHT;
165
+ const where = `${collection.slug}.search`;
166
+ if (!path || typeof path !== "string") throw new SearchConfigError(`${where}: every entry in \`fields\` needs a property path.`);
167
+ const [head, ...rest] = path.split(".");
168
+ const prop = collection.properties?.[head];
169
+ if (!prop) throw new SearchConfigError(`${where}: "${path}" starts at property "${head}", which this collection does not declare. Known properties: ${Object.keys(collection.properties ?? {}).join(", ")}.`);
170
+ const classified = classify(prop);
171
+ if (!classified) throw new SearchConfigError(`${where}: "${path}" is a \`${prop.type}\` property, which holds no text to search. Searchable kinds are \`string\`, \`string[]\` and \`map\` (or a path inside one).`);
172
+ if (classified.reason === "enum") throw new SearchConfigError(`${where}: "${path}" is an enum. Enums are a fixed vocabulary — filter on them with \`where\` instead, which is exact and uses an index.`);
173
+ if (classified.reason === "uuid") throw new SearchConfigError(`${where}: "${path}" is a UUID column. Look it up by id rather than searching it.`);
174
+ if (classified.reason === "json") throw new SearchConfigError(`${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.`);
175
+ if (classified.reason === "non_text_array") throw new SearchConfigError(`${where}: "${path}" is an array of numbers or booleans. Only \`string[]\` carries text to search.`);
176
+ if (rest.length > 0 && classified.kind !== "jsonb") throw new SearchConfigError(`${where}: "${path}" addresses a path inside "${head}", but "${head}" is a \`${prop.type}\` property, not a \`map\`. Only map properties have paths inside them.`);
177
+ const column = columnNameOf(head, prop);
178
+ const raw = rawTextSql({
179
+ column,
180
+ jsonPath: rest,
181
+ kind: classified.kind
182
+ });
183
+ const textSql = normalize(raw, cfg.unaccent === true);
184
+ const language = cfg.language ?? DEFAULT_SEARCH_LANGUAGE;
185
+ return {
186
+ path,
187
+ column,
188
+ jsonPath: rest,
189
+ kind: classified.kind,
190
+ weight,
191
+ sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,
192
+ textSql,
193
+ foldedTextSql: normalize(raw, true)
194
+ };
195
+ };
196
+ /**
197
+ * Build the full spec for a collection, or undefined when it has not opted in.
198
+ *
199
+ * Throws {@link SearchConfigError} on a config that cannot be honoured. Callers
200
+ * at boot surface that as a startup failure — a search block that half-works is
201
+ * worse than one that refuses.
202
+ */
203
+ var buildSearchColumnSpec = (collection) => {
204
+ const cfg = getSearchConfig(collection);
205
+ if (!cfg) return void 0;
206
+ if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) throw new SearchConfigError(`${collection.slug}.search: \`fields\` is empty. Name the properties to index, or remove the \`search\` block to keep the default ILIKE behaviour.`);
207
+ const table = getTableName(collection);
208
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
209
+ const column = cfg.column ?? DEFAULT_SEARCH_COLUMN;
210
+ if (collection.properties?.[column]) throw new SearchConfigError(`${collection.slug}.search: the generated column "${column}" collides with a declared property of the same name. Set \`search.column\` to something else.`);
211
+ const fields = cfg.fields.map((entry) => resolveField(entry, collection, cfg));
212
+ const seen = /* @__PURE__ */ new Set();
213
+ for (const f of fields) {
214
+ if (seen.has(f.path)) throw new SearchConfigError(`${collection.slug}.search: "${f.path}" is listed twice.`);
215
+ seen.add(f.path);
216
+ }
217
+ const mode = cfg.mode ?? DEFAULT_SEARCH_MODE;
218
+ const extensions = [];
219
+ if (cfg.unaccent || mode === "hybrid") extensions.push("unaccent");
220
+ if (cfg.fuzzy) extensions.push("pg_trgm");
221
+ const spec = {
222
+ schema,
223
+ table,
224
+ column,
225
+ language: cfg.language ?? DEFAULT_SEARCH_LANGUAGE,
226
+ unaccent: cfg.unaccent === true,
227
+ mode,
228
+ fields,
229
+ expression: fields.map((f) => f.sql).join(" || "),
230
+ indexName: toPostgresIdentifier(`${table}_${column}_gin`),
231
+ extensions
232
+ };
233
+ if (cfg.fuzzy) {
234
+ const fuzzyColumn = `${column}_text`;
235
+ if (collection.properties?.[fuzzyColumn]) throw new SearchConfigError(`${collection.slug}.search: \`fuzzy\` needs the column "${fuzzyColumn}", which collides with a declared property. Set \`search.column\` to something else.`);
236
+ spec.fuzzy = {
237
+ column: fuzzyColumn,
238
+ expression: fields.map((f) => f.textSql).join(" || ' ' || "),
239
+ indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),
240
+ threshold: cfg.fuzzyThreshold ?? DEFAULT_FUZZY_THRESHOLD
241
+ };
242
+ }
243
+ return spec;
244
+ };
245
+ /**
246
+ * The IMMUTABLE wrappers the generated expressions call.
247
+ *
248
+ * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather
249
+ * than an error, and idempotent for the same reason every other boot-time DDL
250
+ * statement here is.
251
+ *
252
+ * The bodies are stable built-ins wrapped in an immutable promise — see the
253
+ * module comment for why that promise is sound. `STRICT` matters: it makes NULL
254
+ * in mean NULL out without executing the body, which is what the `coalesce` at
255
+ * each call site then absorbs.
256
+ */
257
+ var searchHelperFunctions = (spec) => {
258
+ const statements = [`CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT array_to_string($1, ' ') $$;`, `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT coalesce(string_agg(v, ' '), '')\n FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == "string")')) AS v $$;`];
259
+ if (spec.unaccent || spec.mode === "hybrid") statements.push(`CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`);
260
+ return statements;
261
+ };
262
+ /**
263
+ * `CREATE EXTENSION` statements the spec's expressions depend on.
264
+ *
265
+ * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified
266
+ * `CREATE EXTENSION` installs into the first schema on `search_path`, which
267
+ * defaults to `"$user", public` — and the scaffold's database role is named
268
+ * `rebase`, the same as the schema the generator creates one statement earlier.
269
+ * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the
270
+ * dictionary in `rebase`, and every reference to `public.unaccent` below fails
271
+ * with "text search dictionary does not exist". Observed, not theorised.
272
+ */
273
+ var searchExtensionStatements = (spec) => spec.extensions.map((e) => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);
274
+ /**
275
+ * Everything after the column name — the type and the generation expression.
276
+ *
277
+ * Split out because four emitters need it and only two of them have a place to
278
+ * put the name: `CREATE TABLE` and `ADD COLUMN` write `"col" <this>`, while the
279
+ * schema plan carries it as the column's SQL definition and the boot-time
280
+ * rebuild statement interpolates it on its own.
281
+ */
282
+ var searchColumnTypeSql = (expression, kind) => `${kind} GENERATED ALWAYS AS (${expression}) STORED`;
283
+ /** The column definition as it appears inside `CREATE TABLE`. */
284
+ var searchColumnDefinition = (spec) => `"${spec.column}" ${searchColumnTypeSql(spec.expression, "tsvector")}`;
285
+ /** The fuzzy column definition, when the spec asks for one. */
286
+ var fuzzyColumnDefinition = (spec) => spec.fuzzy ? `"${spec.fuzzy.column}" ${searchColumnTypeSql(spec.fuzzy.expression, "text")}` : void 0;
287
+ /**
288
+ * Index statements for the spec.
289
+ *
290
+ * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a
291
+ * SQL file replayed as one unit — a migration, or `search.sql` — where a
292
+ * concurrent build is not allowed. The boot-time ensure path runs statement by
293
+ * statement against tables that are live and populated, and uses the
294
+ * concurrent form instead; see `ensureSearchColumns`.
295
+ */
296
+ var searchIndexStatements = (spec) => {
297
+ const statements = [`CREATE INDEX IF NOT EXISTS "${spec.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.column}");`];
298
+ if (spec.fuzzy) statements.push(`CREATE INDEX IF NOT EXISTS "${spec.fuzzy.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.fuzzy.column}" ${HELPER_SCHEMA}.gin_trgm_ops);`);
299
+ return statements;
300
+ };
301
+ /**
302
+ * Marker on the comment of every generated search column this module creates.
303
+ *
304
+ * Versioned because the fingerprint below is only comparable against itself: a
305
+ * future change to how it is computed has to read as "not stamped by this
306
+ * version" rather than as drift on every existing column.
307
+ */
308
+ var SEARCH_STAMP_PREFIX = "rebase:search:v1:";
309
+ /**
310
+ * A stable fingerprint of one generated column's expression.
311
+ *
312
+ * Why a stamp rather than reading the expression back: Postgres stores a
313
+ * generated column's expression *parsed*, and hands it back deparsed — casts
314
+ * made explicit, identifiers requoted, schema qualifications added or dropped
315
+ * according to `search_path`. Comparing that text to the text we generated
316
+ * would report drift on wording, and this comparison decides whether a boot
317
+ * refuses, so a false positive is an outage. The stamp is written by the same
318
+ * code that writes the column, so equality means what it says.
319
+ */
320
+ var searchExpressionFingerprint = (expression) => `${SEARCH_STAMP_PREFIX}${createHash("sha256").update(expression).digest("hex").slice(0, 16)}`;
321
+ /**
322
+ * The stamps for a spec's generated columns — one per column, never shared.
323
+ *
324
+ * Per column on purpose: turning `fuzzy` on adds a second column and changes
325
+ * nothing about the first, and a spec-wide fingerprint would report the
326
+ * untouched `tsvector` column as drifted and refuse a boot over a change that
327
+ * is purely additive.
328
+ */
329
+ var searchColumnStamps = (spec) => {
330
+ const stamp = (column, expression) => {
331
+ const fingerprint = searchExpressionFingerprint(expression);
332
+ return {
333
+ column,
334
+ expression,
335
+ fingerprint,
336
+ sql: `COMMENT ON COLUMN "${spec.schema}"."${spec.table}"."${column}" IS ${quote(fingerprint)};`
337
+ };
338
+ };
339
+ const stamps = [stamp(spec.column, spec.expression)];
340
+ if (spec.fuzzy) stamps.push(stamp(spec.fuzzy.column, spec.fuzzy.expression));
341
+ return stamps;
342
+ };
343
+ /**
344
+ * The same drift check as the boot ensure, for the SQL file.
345
+ *
346
+ * Needed because {@link searchColumnStamps} would otherwise *launder* drift on
347
+ * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that
348
+ * exists, so a re-generated `search.sql` would stamp a stale column with the
349
+ * new block's fingerprint and the next boot would find them in agreement.
350
+ * Guarding first means the file refuses instead — `rebase db push` is attended,
351
+ * and the operator reading the failure is the person who changed the block.
352
+ */
353
+ var searchStampGuards = (spec) => searchColumnStamps(spec).map((stamp) => {
354
+ const relation = quote(`"${spec.schema}"."${spec.table}"`);
355
+ return `DO $rebase_search$
356
+ DECLARE recorded text;
357
+ BEGIN
358
+ SELECT col_description(a.attrelid, a.attnum) INTO recorded
359
+ FROM pg_attribute a
360
+ WHERE a.attrelid = ${relation}::regclass AND a.attname = ${quote(stamp.column)} AND NOT a.attisdropped;
361
+ IF recorded LIKE ${quote(`${SEARCH_STAMP_PREFIX}%`)} AND recorded <> ${quote(stamp.fingerprint)} THEN
362
+ 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;
363
+ END IF;
364
+ END
365
+ $rebase_search$;`;
366
+ });
367
+ /**
368
+ * The index names the spec creates.
369
+ *
370
+ * Needed by name, not just by statement, so Atlas can be told to exclude them
371
+ * from its diff — see `searchExcludePatterns`.
372
+ */
373
+ var searchIndexNames = (spec) => spec.fuzzy ? [spec.indexName, spec.fuzzy.indexName] : [spec.indexName];
374
+ /**
375
+ * The generated column names a collection's search block adds, if any.
376
+ *
377
+ * These are physical columns on the table, so `SELECT *` returns them. They are
378
+ * an index in column form — a list of lexeme positions, or a concatenation of
379
+ * every searchable field on the row — and nothing outside the query planner has
380
+ * any use for them. Left in, every list response carries a second, larger copy
381
+ * of the row's text.
382
+ */
383
+ var searchColumnNames = (collection) => {
384
+ let spec;
385
+ try {
386
+ spec = buildSearchColumnSpec(collection);
387
+ } catch {
388
+ return [];
389
+ }
390
+ if (!spec) return [];
391
+ return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];
392
+ };
393
+ /**
394
+ * True for a column whose type only ever holds a search index.
395
+ *
396
+ * Independent of any collection config on purpose: an introspected database
397
+ * (BaaS mode) can carry a `tsvector` column this framework never created —
398
+ * Pagila's `film.fulltext` is the canonical one — and it should not be returned
399
+ * to callers either. `isDerivedIndexColumn` already keeps such a column out of
400
+ * the *properties*; this keeps it out of the *rows*.
401
+ */
402
+ var isSearchIndexColumn = (column) => {
403
+ const sqlType = typeof column?.getSQLType === "function" ? column.getSQLType().toLowerCase() : "";
404
+ return sqlType === "tsvector" || sqlType === "tsquery";
405
+ };
406
+ /**
407
+ * A drizzle select projection over `table` with the search columns dropped.
408
+ *
409
+ * Returns undefined when nothing needs dropping, so the common case keeps using
410
+ * a plain `select()` and this stays invisible in the generated SQL.
411
+ */
412
+ var visibleColumnProjection = (tableColumns, collection) => {
413
+ const excluded = excludedColumnNames(tableColumns, collection);
414
+ if (!tableColumns || excluded.length === 0) return void 0;
415
+ const projection = {};
416
+ for (const [name, column] of Object.entries(tableColumns)) if (!excluded.includes(name)) projection[name] = column;
417
+ return projection;
418
+ };
419
+ /** The same exclusion as a drizzle `db.query` `columns` denylist. */
420
+ var hiddenColumnsOption = (tableColumns, collection) => {
421
+ const excluded = excludedColumnNames(tableColumns, collection);
422
+ if (excluded.length === 0) return void 0;
423
+ return Object.fromEntries(excluded.map((name) => [name, false]));
424
+ };
425
+ /**
426
+ * The columns to keep out of a response, by name.
427
+ *
428
+ * `tableColumns` is whatever `getTableColumns` returned, which is `undefined`
429
+ * for anything that is not a real drizzle table — a stub in a test, a derived
430
+ * or nested path with no table behind it. Nothing to exclude is the right
431
+ * answer there, and it has to be an answer rather than a throw: this runs on
432
+ * the read path of every collection, opted in or not.
433
+ */
434
+ var excludedColumnNames = (tableColumns, collection) => {
435
+ if (!tableColumns || typeof tableColumns !== "object") return [];
436
+ const byName = new Set(collection ? searchColumnNames(collection) : []);
437
+ return Object.keys(tableColumns).filter((name) => byName.has(name) || isSearchIndexColumn(tableColumns[name]));
438
+ };
439
+ //#endregion
440
+ export { visibleColumnProjection as _, buildSearchColumnSpec as a, searchColumnDefinition as c, searchColumnTypeSql as d, searchExtensionStatements as f, searchStampGuards as g, searchIndexStatements as h, assertSearchIsPostgresOnly as i, searchColumnNames as l, searchIndexNames as m, SEARCH_TEXT_FN as n, fuzzyColumnDefinition as o, searchHelperFunctions as p, SEARCH_UNACCENT_FN as r, hiddenColumnsOption as s, SEARCH_STAMP_PREFIX as t, searchColumnStamps as u };
441
+
442
+ //# sourceMappingURL=search-column-BM-GV6vH.js.map