@rebasepro/server-postgres 0.29.1 → 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 (147) hide show
  1. package/dist/{BranchService-BIIBF5ZL.js → BranchService-X9R505mP.js} +3 -3
  2. package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-X9R505mP.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +64 -4
  4. package/dist/PostgresBootstrapper.d.ts +20 -0
  5. package/dist/auth/ensure-tables.d.ts +2 -2
  6. package/dist/auth/schema-version.d.ts +5 -5
  7. package/dist/auth/services.d.ts +9 -9
  8. package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CwiJEp_J.js} +3 -3
  9. package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
  10. package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CbZj9ovZ.js} +2 -2
  11. package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
  12. package/dist/{cli-console-DTsm96lW.js → cli-console-DDkNetCz.js} +6 -6
  13. package/dist/{cli-console-DTsm96lW.js.map → cli-console-DDkNetCz.js.map} +1 -1
  14. package/dist/{cli-errors-DwqFRIWz.js → cli-errors-C73Qy7WJ.js} +5 -5
  15. package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
  16. package/dist/cli.js +165 -49
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
  19. package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
  20. package/dist/data-transformer.d.ts +2 -2
  21. package/dist/database-health.d.ts +2 -1
  22. package/dist/{database-preflight-D5JtPt8i.js → database-preflight-DIauc8i5.js} +36 -3
  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/{deferred-index-build-B8feKnUj.js → deferred-index-build-DDdnjaOW.js} +18 -6
  27. package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
  28. package/dist/{doctor-BaR11xUe.js → doctor-DwMXljiq.js} +11 -11
  29. package/dist/doctor-DwMXljiq.js.map +1 -0
  30. package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
  31. package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-h1mUO7Uu.js} +11 -8
  33. package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
  34. package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-CUqYgMvo.js} +4 -4
  35. package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
  36. package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-z7ustOl_.js} +3 -3
  37. package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
  38. package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
  39. package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
  40. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
  41. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
  42. package/dist/{generate-files-Bl3_D_oP.js → generate-files-BkiRFoV1.js} +3 -3
  43. package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-BkiRFoV1.js.map} +1 -1
  44. package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
  45. package/dist/{generate-postgres-ddl-logic-BC3JA93M.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
  46. package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-D2soazQU.js} +8 -5
  47. package/dist/generated-schema-diff-D2soazQU.js.map +1 -0
  48. package/dist/history/HistoryService.d.ts +2 -3
  49. package/dist/history/ensure-history-table.d.ts +8 -3
  50. package/dist/index.es.js +15 -15
  51. package/dist/interfaces.d.ts +24 -2
  52. package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
  53. package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
  54. package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CveNQli3.js} +163 -502
  55. package/dist/migrate-baseline-CveNQli3.js.map +1 -0
  56. package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
  57. package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
  58. package/dist/{open-rebase-CiO_sjMT.js → open-rebase-Cvid3iwR.js} +1395 -656
  59. package/dist/open-rebase-Cvid3iwR.js.map +1 -0
  60. package/dist/open-rebase.d.ts +1 -1
  61. package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-80uTIHQs.js} +2 -2
  62. package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
  63. package/dist/pipelined-transaction.d.ts +24 -37
  64. package/dist/{plan-schema-BYxOzflz.js → plan-schema-CMhNYEYF.js} +21 -6
  65. package/dist/plan-schema-CMhNYEYF.js.map +1 -0
  66. package/dist/{policy-drift-DKuTJHfc.js → policy-drift-Bx6663KD.js} +29 -6
  67. package/dist/policy-drift-Bx6663KD.js.map +1 -0
  68. package/dist/push-index-adoption-C-TpM445.js +22 -0
  69. package/dist/push-index-adoption-C-TpM445.js.map +1 -0
  70. package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-xbpgZEJK.js} +4 -4
  71. package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
  72. package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
  73. package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
  74. package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-7UKspspl.js} +4 -4
  75. package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
  76. package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BOw5PtU8.js} +14 -8
  77. package/dist/push-policy-plan-BOw5PtU8.js.map +1 -0
  78. package/dist/read-routing.d.ts +10 -30
  79. package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Di-fTGti.js} +15 -2
  80. package/dist/render-ddl-Di-fTGti.js.map +1 -0
  81. package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Bxxskru9.js} +10 -10
  82. package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Bxxskru9.js.map} +1 -1
  83. package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-BCW4v0rq.js} +2 -2
  84. package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-BCW4v0rq.js.map} +1 -1
  85. package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
  86. package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
  87. package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-CyUCPDH8.js} +213 -10
  88. package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
  89. package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
  90. package/dist/rls-settings-BCGMIig3.js.map +1 -0
  91. package/dist/schema/doctor-cli.js +9 -9
  92. package/dist/schema/doctor-cli.js.map +1 -1
  93. package/dist/schema/drizzle-ddl.d.ts +2 -2
  94. package/dist/schema/ensure-collection-policies.d.ts +15 -3
  95. package/dist/schema/generate-drizzle-schema.js +1 -1
  96. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -1
  97. package/dist/schema/generate-postgres-ddl.js +1 -1
  98. package/dist/schema/index-adoption.d.ts +99 -0
  99. package/dist/schema/introspect-db-logic.d.ts +2 -1
  100. package/dist/schema/introspect-db.js +3 -3
  101. package/dist/schema/migrate-policy-stamps.d.ts +19 -1
  102. package/dist/schema/plan/diff-plan.d.ts +8 -1
  103. package/dist/schema/plan/render-ddl.d.ts +7 -0
  104. package/dist/schema/plan/types.d.ts +2 -0
  105. package/dist/schema/push-index-adoption.d.ts +10 -0
  106. package/dist/schema/push-policy-plan.d.ts +5 -1
  107. package/dist/schema/rls-bootstrap-sql.d.ts +13 -2
  108. package/dist/schema/search-column.d.ts +2 -2
  109. package/dist/search-column-BM-GV6vH.js.map +1 -1
  110. package/dist/security/policy-drift.d.ts +19 -1
  111. package/dist/security/rls-enforcement.d.ts +87 -1
  112. package/dist/security/rls-settings.d.ts +33 -0
  113. package/dist/services/FetchService.d.ts +33 -8
  114. package/dist/services/PersistService.d.ts +75 -4
  115. package/dist/services/RelationService.d.ts +1 -1
  116. package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
  117. package/dist/services/channel-bus/index.d.ts +2 -2
  118. package/dist/services/channel-history.d.ts +2 -2
  119. package/dist/services/channel-presence.d.ts +3 -3
  120. package/dist/services/dataService.d.ts +6 -2
  121. package/dist/services/realtimeService.d.ts +18 -5
  122. package/dist/services/socket-liveness.d.ts +6 -1
  123. package/dist/types.d.ts +1 -1
  124. package/dist/utils/drizzle-conditions.d.ts +12 -0
  125. package/dist/utils/positional-params.d.ts +40 -0
  126. package/dist/{websocket-B33YjKhs.js → websocket-BSYV_KSw.js} +3 -3
  127. package/dist/websocket-BSYV_KSw.js.map +1 -0
  128. package/dist/websocket.d.ts +14 -3
  129. package/package.json +7 -7
  130. package/dist/database-preflight-D5JtPt8i.js.map +0 -1
  131. package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
  132. package/dist/doctor-BaR11xUe.js.map +0 -1
  133. package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
  134. package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
  135. package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
  136. package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
  137. package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
  138. package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
  139. package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
  140. package/dist/open-rebase-CiO_sjMT.js.map +0 -1
  141. package/dist/plan-schema-BYxOzflz.js.map +0 -1
  142. package/dist/policy-drift-DKuTJHfc.js.map +0 -1
  143. package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
  144. package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
  145. package/dist/rls-enforcement-BO618rnr.js.map +0 -1
  146. package/dist/rls-settings-De5NoHHy.js.map +0 -1
  147. package/dist/websocket-B33YjKhs.js.map +0 -1
@@ -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,g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SAAS,SAAS,IAAI,GAAG,WAAW,QAAQ;CAErD,OAAO;AACX;;AAGA,IAAa,uBACT,cACA,eACoC;CACpC,MAAM,WAAW,oBAAoB,cAAc,UAAU;CAC7D,IAAI,SAAS,WAAW,GAAG,OAAO,KAAA;CAClC,OAAO,OAAO,YAAY,SAAS,KAAI,SAAQ,CAAC,MAAM,KAAc,CAAC,CAAC;AAC1E;;;;;;;;;;AAWA,IAAM,uBACF,cACA,eACW;CACX,IAAI,CAAC,gBAAgB,OAAO,iBAAiB,UAAU,OAAO,CAAC;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,sFAAs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AAY,SAAS,KAAI,SAAQ,CAAC,MAAM,KAAc,CAAC,CAAC;AAC1E;;;;;;;;;;AAWA,IAAM,uBACF,cACA,eACW;CACX,IAAI,CAAC,gBAAgB,OAAO,iBAAiB,UAAU,OAAO,CAAC;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"}
@@ -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
  *
@@ -1,7 +1,7 @@
1
1
  import { SQL } from "drizzle-orm";
2
2
  import { SecurityRule } from "@rebasepro/types";
3
3
  import { REBASE_USER_ROLE } from "@rebasepro/common";
4
- import type { GrantsMode, ProvisionRoleMode, RequestIdentity } from "./rls-settings.js";
4
+ import { type GrantsMode, type ProvisionRoleMode, type RequestIdentity, type RlsSettings } from "./rls-settings.js";
5
5
  /**
6
6
  * Unified RLS enforcement — the "user context vs server context" model.
7
7
  *
@@ -378,6 +378,92 @@ export interface AppRoleGrantOptions {
378
378
  * that is refused rather than done.
379
379
  */
380
380
  export declare function ensureInheritedRoles(run: RawSqlRunner, role: string, inheritRoles: readonly string[]): Promise<void>;
381
+ /**
382
+ * Provision the role admin requests run as for one request role:
383
+ * `<role>_admin`, inheriting `role` — its grants, and every policy written
384
+ * for it — and {@link REBASE_ADMIN_ROLE}, with the connection able to switch
385
+ * to it. The role itself goes through {@link ensureAppRole} (created NOLOGIN
386
+ * NOSUPERUSER NOBYPASSRLS, checked as restricted when found, the switch
387
+ * proved), with no grants of its own: everything it can reach, it reaches as
388
+ * `role` does.
389
+ *
390
+ * Inheriting is per grant from PostgreSQL 16 (`WITH INHERIT TRUE`); before
391
+ * that it is the role's own `INHERIT` attribute, harmless here because this
392
+ * role belongs to exactly the two roles granted below.
393
+ */
394
+ export declare function ensureAdminRequestRole(run: RawSqlRunner, schemas: string[], options: {
395
+ role: string;
396
+ adminRole: string;
397
+ provisionRole?: ProvisionRoleMode;
398
+ }): Promise<void>;
399
+ /**
400
+ * Let the connection role itself pass the server-or-admin policies, by
401
+ * inheriting {@link REBASE_ADMIN_ROLE} — which is what `TO public` gave it.
402
+ *
403
+ * It matters where the connection is subject to RLS: always, when it owns
404
+ * none of the tables (requests then run as the connection itself, so the
405
+ * server context and admins depend on it), and on any table it does not own
406
+ * otherwise. Best effort: a connection that cannot be granted the role is
407
+ * told what to run, and its server-context and admin reads of those tables are
408
+ * refused — closed, never wider — until someone does.
409
+ */
410
+ export declare function ensureConnectionInheritsAdminRole(run: RawSqlRunner, options: {
411
+ provision: boolean;
412
+ }): Promise<void>;
413
+ /**
414
+ * The request identity a boot hands the driver and the realtime refetch, with
415
+ * the admin switch on when every admin request role is ready: provisioned
416
+ * here, or — on a boot that provisions nothing — found existing, inheriting
417
+ * what it should and switchable. Otherwise admin requests run as the request
418
+ * role, as before, and the boot says why: under `adminPolicies: "adminRole"`,
419
+ * policies already written `TO rebase_admin` then refuse them.
420
+ */
421
+ export declare function settleAdminRequestRoles(run: RawSqlRunner, schemas: string[], settings: RlsSettings, options: {
422
+ provision: boolean;
423
+ }): Promise<RequestIdentity>;
424
+ /**
425
+ * Whether policies written `TO rebase_admin` reach every caller they are for on
426
+ * this connection, read from the catalogue without changing anything: the role
427
+ * exists, the connection passes it (exempt from RLS, or inheriting it — the
428
+ * server context on tables it does not own), and each of `adminRoles` exists,
429
+ * inherits its request role and `rebase_admin`, and the connection can switch
430
+ * into it. The state {@link settleAdminRequestRoles} and
431
+ * {@link ensureConnectionInheritsAdminRole} leave when both succeed.
432
+ *
433
+ * With `existingOnly`, an admin role that does not exist is passed over, but at
434
+ * least one must be ready: for a role list read back from the database, which
435
+ * does not say which role is an anonymous one with no admin counterpart.
436
+ *
437
+ * Anything it cannot read answers `false`, and `false` means `TO public`: the
438
+ * shape every caller passes, as before the admin role existed.
439
+ */
440
+ export declare function adminSwitchLive(run: RawSqlRunner, adminRoles: ReadonlyMap<string, string>, options?: {
441
+ existingOnly?: boolean;
442
+ }): Promise<boolean>;
443
+ /**
444
+ * The admin switch for a boot whose requests switch roles: settle the admin
445
+ * request roles and the connection's `rebase_admin`, then say whether the
446
+ * switch is live — which is what decides where the policies step writes the
447
+ * server-or-admin policies. `TO rebase_admin` only when it is: written there
448
+ * while admin requests still run as the request role, they refuse every admin
449
+ * caller, `dataAsAdmin` included, as an empty table. Otherwise `TO public`, the
450
+ * documented fallback, which the request role passes.
451
+ */
452
+ export declare function settleAdminSwitch(run: RawSqlRunner, schemas: string[], settings: RlsSettings, options: {
453
+ provision: boolean;
454
+ }): Promise<{
455
+ request: RequestIdentity;
456
+ adminPoliciesLive: boolean;
457
+ }>;
458
+ /**
459
+ * Where `db push` and `rebase doctor` expect the server-or-admin policies, for
460
+ * the request roles this database records (or the configured ones): `TO
461
+ * rebase_admin` only when {@link adminSwitchLive} says a server on this
462
+ * connection would have the switch live, `TO public` otherwise — the same
463
+ * answer a boot reaches, without provisioning anything. Settings that do not
464
+ * resolve answer `false`.
465
+ */
466
+ export declare function adminPoliciesLiveForCli(run: RawSqlRunner): Promise<boolean>;
381
467
  /**
382
468
  * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
383
469
  * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
@@ -70,6 +70,23 @@ export interface PostgresRlsConfig {
70
70
  * Env: `REBASE_RLS_POLICY_TARGET`.
71
71
  */
72
72
  policyTarget?: PolicyTargetMode;
73
+ /**
74
+ * Whom the policies that only the server context or an admin can pass apply
75
+ * to — the injected `<table>_default_admin_*` baseline, and any permissive
76
+ * rule whose every clause needs one of the two, such as `roles: ["admin"]`.
77
+ *
78
+ * - `"adminRole"` (default): `TO rebase_admin`, a role that holds nothing
79
+ * and cannot log in. Admin requests run as `<request role>_admin`, which
80
+ * inherits the request role and `rebase_admin`; a signed-in user's plan
81
+ * never sees those policies, so an owner-scoped list or count uses the
82
+ * owner index instead of scanning the table.
83
+ * - `"public"`: `TO public`, every request as the request role — what
84
+ * Rebase did before. For a database where `rebase_admin` cannot be
85
+ * created, or a connection that is subject to RLS and cannot be granted it.
86
+ *
87
+ * Env: `REBASE_RLS_ADMIN_POLICIES`.
88
+ */
89
+ adminPolicies?: AdminPoliciesMode;
73
90
  /**
74
91
  * `false` drops the injected server-or-admin baseline from every
75
92
  * collection, as `disableDefaultPolicies` does for one. Default `true`.
@@ -116,6 +133,7 @@ export interface RequestRoleMap {
116
133
  export type ProvisionRoleMode = "auto" | "never";
117
134
  export type GrantsMode = "schema" | "managed" | "none";
118
135
  export type PolicyTargetMode = "public" | "requestRole";
136
+ export type AdminPoliciesMode = "adminRole" | "public";
119
137
  export type IdentityMode = "rebase" | "supabase";
120
138
  export type SharedRoleMode = "warn" | "refuse" | "ignore";
121
139
  /**
@@ -125,6 +143,14 @@ export type SharedRoleMode = "warn" | "refuse" | "ignore";
125
143
  export interface RequestIdentity {
126
144
  roleFor(auth: AuthContext): string;
127
145
  settingsFor(auth: AuthContext, role: string): readonly (readonly [string, string])[];
146
+ /**
147
+ * The role a request holding the `admin` role runs as instead of `role`
148
+ * (`<role>_admin`, under `adminPolicies: "adminRole"`), or `undefined` to
149
+ * run it as `role`. Set by the boot once those roles are known to exist and
150
+ * be switchable — see `settleAdminRequestRoles`. The identity settings are
151
+ * still `role`'s: the switch changes which policies apply, not who asks.
152
+ */
153
+ adminRoleFor?(role: string): string | undefined;
128
154
  }
129
155
  /** {@link PostgresRlsConfig}, resolved: every setting decided, every name checked. */
130
156
  export interface RlsSettings {
@@ -136,6 +162,13 @@ export interface RlsSettings {
136
162
  provisionRole: ProvisionRoleMode;
137
163
  grants: GrantsMode;
138
164
  policyTarget: PolicyTargetMode;
165
+ adminPolicies: AdminPoliciesMode;
166
+ /**
167
+ * Under `adminPolicies: "adminRole"`, each request role an admin request can
168
+ * arrive as, mapped to the role it switches to instead — every role but the
169
+ * anonymous one of a `{ anonymous, signedIn }` pair. Empty under `"public"`.
170
+ */
171
+ adminRoles: ReadonlyMap<string, string>;
139
172
  defaultPolicies: boolean;
140
173
  inheritRoles: readonly string[];
141
174
  /**
@@ -33,6 +33,22 @@ import { type ReadCallContextProvider } from "./read-scope.js";
33
33
  export declare function numericAggregateAliases(aggregates: DriverAggregate[], properties: Record<string, {
34
34
  type?: string;
35
35
  }>): Set<string>;
36
+ /**
37
+ * What `fingerprint()` computes over a table's row versions, from their tuple
38
+ * headers alone: no column is read, decoded or turned into text.
39
+ *
40
+ * Every row version has the xmin of the transaction that wrote it: an insert
41
+ * or an update adds a new one, a delete takes one away. The count and the xmin
42
+ * sum alone are linear, and cancel: a transaction that deletes one row,
43
+ * updates another and inserts a third keeps both whenever the two xmins it
44
+ * removed add up to twice its own, which two concurrent sessions reach. So
45
+ * each version also adds a hash of its xmin, which no such arithmetic
46
+ * cancels: a write only ever adds versions under its own new xid, so the
47
+ * multiset of xmins after it can never equal the one before. The xmin alone,
48
+ * and not the ctid beside it, because a materialized view's collection is a
49
+ * view over its stored rows that passes their `xmin` through and no `ctid`.
50
+ */
51
+ export declare function rowVersionsFingerprint(xmin: SQL): SQL;
36
52
  export declare class FetchService {
37
53
  private db;
38
54
  private registry;
@@ -113,6 +129,12 @@ export declare class FetchService {
113
129
  * Delegates to DrizzleConditionBuilder.buildFilterConditions
114
130
  */
115
131
  buildFilterConditions<M extends Record<string, unknown>>(filter: FilterValues<Extract<keyof M, string>>, table: PgTable<any>, collectionPath: string): SQL[];
132
+ /**
133
+ * A filter and a logical group as conditions, compiled as a read compiles
134
+ * them: for a write whose rows the filter chooses (`updateWhere`,
135
+ * `deleteWhere`).
136
+ */
137
+ buildWriteConditions(filter: FilterValues<string> | undefined, logical: LogicalCondition | undefined, table: PgTable<any>, collectionPath: string): SQL[];
116
138
  /**
117
139
  * Resolves the correct Drizzle column for sorting.
118
140
  * Automatically maps owning relation property keys to their underlying foreign key column.
@@ -132,7 +154,7 @@ export declare class FetchService {
132
154
  * `_score` is only meaningful for a collection that declared a `search`
133
155
  * block *and* for a request that carried a search string — ranking rows
134
156
  * against no query ranks them all at zero. Outside those two conditions it
135
- * is an unknown field and gets the same 400 as any other typo, which is the
157
+ * is an unknown field and gets the same 400 as every other typo, which is the
136
158
  * behaviour that matters: a sort that is silently dropped returns 200 with
137
159
  * rows in arbitrary order, and paging over that repeats and skips rows.
138
160
  */
@@ -691,13 +713,16 @@ export declare class FetchService {
691
713
  * `toRestRow`. For a row the statement itself wrote, with nothing written
692
714
  * after it, `RETURNING` those same columns is that row — the same values
693
715
  * through the same column decoders, in the same order, rendered the same
694
- * way. Two things narrow the read and not the statement, and either one
695
- * keeps the read:
696
- *
697
- * - a `beforeQuery` adds conditions to the read (and runs application
698
- * code): a row outside them is no answer today, and would be one from
699
- * `RETURNING`;
700
- * - per-field read access, which projects the read for the viewer.
716
+ * way. One thing narrows the read and not the statement, and keeps the
717
+ * read: a `beforeQuery` adds conditions to it (and runs application code),
718
+ * so a row outside them is no answer today, and would be one from
719
+ * `RETURNING`.
720
+ *
721
+ * Per-field read access does not: the read selects the same columns and
722
+ * withholds what the caller may not read when it renders the row
723
+ * (`toRestRow` → `stripUnreadable`), which is the render here too — so an
724
+ * `excludeFromApi` column is written, and not answered, without a read
725
+ * back per row.
701
726
  *
702
727
  * Row-level security is the same either way. `INSERT … RETURNING` holds
703
728
  * the new row to the table's SELECT policies and refuses one they hide
@@ -1,10 +1,11 @@
1
- import { Properties } from "@rebasepro/types";
1
+ import { FilterValues, type LogicalCondition, Properties } from "@rebasepro/types";
2
2
  import { RelationService } from "./RelationService.js";
3
3
  import { type ReadCallContextProvider } from "./read-scope.js";
4
4
  import { RelationWriteService } from "./RelationWriteService.js";
5
5
  import { FetchService } from "./FetchService.js";
6
6
  import { DrizzleClient } from "../interfaces.js";
7
7
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry.js";
8
+ import { ApiError } from "@rebasepro/server";
8
9
  /**
9
10
  * The top-level properties whose value is stamped once, when the row is
10
11
  * created: `on_create` dates and `user_on_create` identities.
@@ -38,12 +39,35 @@ export interface PersistSaveOptions {
38
39
  * instead of assuming it.
39
40
  */
40
41
  unreadRow?: boolean;
42
+ /**
43
+ * Nothing follows this write in its transaction, so its last statement
44
+ * may carry the `COMMIT` — see `commitWithNextStatement`. Honoured only
45
+ * where the row is the last thing written (no relation or junction
46
+ * write after it).
47
+ */
48
+ commitsTransaction?: boolean;
49
+ }
50
+ /**
51
+ * How an upsert treats a row already on its conflict target, beyond replacing
52
+ * it: leave it as it is (`ignoreDuplicates`), or replace it only when it
53
+ * matches `conflictWhere`. A row left alone is answered as `undefined`.
54
+ */
55
+ export interface ConflictRule {
56
+ /** `ON CONFLICT DO NOTHING`. */
57
+ ignoreDuplicates?: boolean;
58
+ /** `ON CONFLICT DO UPDATE … WHERE`, over the stored row's columns. */
59
+ conflictWhere?: FilterValues<string>;
41
60
  }
42
61
  /** One row of a {@link PersistService.saveRows} batch: its values and what its INSERT alone may write. */
43
62
  export interface PersistBatchRow {
44
63
  values: Record<string, unknown>;
45
64
  insertOnlyKeys?: readonly string[];
46
65
  }
66
+ /**
67
+ * A filtered write whose filter compiled to no condition: it would address
68
+ * every row, and is refused rather than run.
69
+ */
70
+ export declare function filterRequired(collectionPath: string): ApiError;
47
71
  /**
48
72
  * Service for handling all row write operations.
49
73
  * Handles saving, deleting, and updating rows.
@@ -103,9 +127,12 @@ export declare class PersistService {
103
127
  */
104
128
  lockRow(collectionPath: string, id: string | number): Promise<void>;
105
129
  /**
106
- * Delete an row by ID
130
+ * Delete a row by ID. `options.commitsTransaction`: see
131
+ * {@link PersistSaveOptions.commitsTransaction}.
107
132
  */
108
- delete(collectionPath: string, id: string | number, _databaseId?: string): Promise<void>;
133
+ delete(collectionPath: string, id: string | number, _databaseId?: string, options?: {
134
+ commitsTransaction?: boolean;
135
+ }): Promise<void>;
109
136
  /**
110
137
  * Delete all rows from a collection
111
138
  */
@@ -149,6 +176,11 @@ export declare class PersistService {
149
176
  * not have. What they compile to is `field-op-sql.ts`.
150
177
  */
151
178
  save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string, options?: PersistSaveOptions): Promise<Record<string, unknown>>;
179
+ /**
180
+ * {@link save}, for an upsert with a {@link ConflictRule}: `undefined`
181
+ * when the rule left the stored row on the conflict target as it was.
182
+ */
183
+ saveUnlessKept<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string, options?: PersistSaveOptions & ConflictRule): Promise<Record<string, unknown> | undefined>;
152
184
  /**
153
185
  * Write a batch of new rows — inserted, or upserted with `options.upsert` —
154
186
  * as multi-row statements, and return each row as {@link save} returns it.
@@ -177,7 +209,8 @@ export declare class PersistService {
177
209
  saveRows(collectionPath: string, rows: readonly PersistBatchRow[], options?: {
178
210
  upsert?: boolean;
179
211
  onConflict?: readonly string[];
180
- }): Promise<Record<string, unknown>[] | undefined>;
212
+ commitsTransaction?: boolean;
213
+ } & ConflictRule): Promise<(Record<string, unknown> | undefined)[] | undefined>;
181
214
  /**
182
215
  * Update rows by id, each with its own values, as
183
216
  * `UPDATE … FROM (VALUES …) … RETURNING` statements, and return each row as
@@ -196,6 +229,44 @@ export declare class PersistService {
196
229
  id: string | number;
197
230
  values: Record<string, unknown>;
198
231
  }[]): Promise<Record<string, unknown>[] | undefined>;
232
+ /**
233
+ * Update every row the conditions match, in one
234
+ * `UPDATE … SET … WHERE … RETURNING` statement, and return each row as
235
+ * {@link save} returns it. Field operations are compiled as for one row,
236
+ * and their declared bounds are checked by the same statement: a matched
237
+ * row an operation would take out of bounds fails the call.
238
+ *
239
+ * `undefined`, before anything is written, for a write that needs what
240
+ * only the row-by-row update does: a relation in the values, or a
241
+ * collection whose rows the statement cannot return (`beforeQuery`,
242
+ * per-field read access). `options.commitsTransaction`: see
243
+ * {@link PersistSaveOptions.commitsTransaction}; not honoured when bounds
244
+ * are checked, which takes a statement after the update.
245
+ */
246
+ updateWhere(collectionPath: string, filter: FilterValues<string> | undefined, logical: LogicalCondition | undefined, values: Record<string, unknown>, options?: {
247
+ commitsTransaction?: boolean;
248
+ }): Promise<Record<string, unknown>[] | undefined>;
249
+ /**
250
+ * Delete every row the conditions match, in one `DELETE … WHERE …
251
+ * RETURNING` statement, and return each deleted row's key columns.
252
+ * `options.commitsTransaction`: see {@link PersistSaveOptions.commitsTransaction}.
253
+ */
254
+ deleteWhere(collectionPath: string, filter: FilterValues<string> | undefined, logical: LogicalCondition | undefined, options?: {
255
+ commitsTransaction?: boolean;
256
+ }): Promise<Record<string, unknown>[]>;
257
+ /**
258
+ * Whether the row `id` addresses matches `filter`, as the caller reads
259
+ * it: for an upsert under a `conflictWhere` that found its row first.
260
+ */
261
+ rowMatches(collectionPath: string, id: string | number, filter: FilterValues<string>): Promise<boolean>;
262
+ /**
263
+ * Whether the stored row on an upsert's conflict target is one the
264
+ * caller's write may not change at all — outside their `beforeQuery`
265
+ * scope, or in the trash — rather than one a {@link ConflictRule} kept.
266
+ * Asked only when there is a scope or a trash: without either, nothing
267
+ * but the rule can have kept it, and no statement is sent.
268
+ */
269
+ private storedRowRefusesWrite;
199
270
  /**
200
271
  * The caller's `beforeQuery` scope over this table, as one condition: what
201
272
  * a stored row must satisfy for a write that meets it to change it. The
@@ -13,7 +13,7 @@ import { type ReadCallContextProvider } from "./read-scope.js";
13
13
  * the gap with a single confined cast.
14
14
  *
15
15
  * Exported so `data-transformer` uses this one rather than restating the same
16
- * fact — it wrote `query.innerJoin(...) as unknown as typeof query`, which is
16
+ * fact — it double-cast `query.innerJoin(...)` to `typeof query`, which is
17
17
  * the same claim about the same drizzle behaviour in a second spelling.
18
18
  */
19
19
  export declare function applyDynamicJoin<T>(query: T, joinTable: PgTable, condition: SQL): T;
@@ -27,9 +27,9 @@
27
27
  * the client's history replay, so a lost frame costs a live update rather
28
28
  * than correctness. That is what makes coalescing safe.
29
29
  */
30
- import { NodePgDatabase } from "drizzle-orm/node-postgres";
31
30
  import { type PgNotifyListenerStatus } from "../pg-notify-listener.js";
32
31
  import { ChannelBus, ChannelBusFrame, ChannelBusHandler } from "./ChannelBus.js";
32
+ import type { PgSqlDatabase } from "../../interfaces.js";
33
33
  /** NOTIFY channel carrying channel-bus frames. */
34
34
  export declare const CHANNEL_BUS_NOTIFY_CHANNEL = "rebase_channel_bus";
35
35
  /**
@@ -64,7 +64,7 @@ export declare class PostgresChannelBus implements ChannelBus {
64
64
  private pendingBytes;
65
65
  private windowTimer?;
66
66
  private stopped;
67
- constructor(db: NodePgDatabase<Record<string, unknown>>, connectionString: string, options?: {
67
+ constructor(db: PgSqlDatabase<Record<string, unknown>>, connectionString: string, options?: {
68
68
  batchWindowMs?: number;
69
69
  });
70
70
  start(handler: ChannelBusHandler): Promise<void>;
@@ -14,12 +14,12 @@
14
14
  * without this file learning about it. See `@rebasepro/types` →
15
15
  * `types/channel_bus.ts` for the contract such a package implements.
16
16
  */
17
- import { NodePgDatabase } from "drizzle-orm/node-postgres";
18
17
  import { type ChannelBus, type ChannelBusSetting } from "@rebasepro/types";
18
+ import type { PgSqlDatabase } from "../../interfaces.js";
19
19
  export * from "./ChannelBus.js";
20
20
  export { PostgresChannelBus, CHANNEL_BUS_NOTIFY_CHANNEL, PG_NOTIFY_MAX_PAYLOAD_BYTES, DEFAULT_BATCH_WINDOW_MS, parseChannelBusFrame, parseChannelBusPayload } from "./PostgresChannelBus.js";
21
21
  export interface ChannelBusDeps {
22
- db: NodePgDatabase<Record<string, unknown>>;
22
+ db: PgSqlDatabase<Record<string, unknown>>;
23
23
  /**
24
24
  * Direct (non-pooled) Postgres URL for the LISTEN client. `LISTEN` is
25
25
  * session state, so behind PgBouncer in transaction mode this must be the