@rebasepro/server-postgres 0.16.0 → 0.16.1-canary.g0d7af95

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 (99) hide show
  1. package/dist/PostgresAdapter.d.ts +1 -1
  2. package/dist/PostgresBackendDriver.d.ts +75 -12
  3. package/dist/PostgresBootstrapper.d.ts +6 -6
  4. package/dist/auth/services.d.ts +1 -1
  5. package/dist/backup/backup-cron.d.ts +1 -1
  6. package/dist/backup/backup-service.d.ts +2 -2
  7. package/dist/backup/index.d.ts +4 -4
  8. package/dist/{backup-service-BZoixhVl.js → backup-service-BtgHxfFm.js} +5 -4
  9. package/dist/{backup-service-BZoixhVl.js.map → backup-service-BtgHxfFm.js.map} +1 -1
  10. package/dist/cli-helpers.d.ts +41 -0
  11. package/dist/{auth-users-columns-CgyPWQ18.js → collection-index-DxJBvVTH.js} +486 -503
  12. package/dist/collection-index-DxJBvVTH.js.map +1 -0
  13. package/dist/collections/PostgresCollectionRegistry.d.ts +1 -1
  14. package/dist/collections/buildRegistry.d.ts +1 -1
  15. package/dist/collections/validate-relations.d.ts +1 -1
  16. package/dist/{connection-BuZ97wsr.js → connection-GOKU3Hu5.js} +34 -7
  17. package/dist/connection-GOKU3Hu5.js.map +1 -0
  18. package/dist/connection.d.ts +16 -0
  19. package/dist/data-transformer.d.ts +1 -1
  20. package/dist/{ensure-collection-policies-BVFb2olB.js → ensure-collection-policies-DFpOl8SM.js} +4 -4
  21. package/dist/{ensure-collection-policies-BVFb2olB.js.map → ensure-collection-policies-DFpOl8SM.js.map} +1 -1
  22. package/dist/ensure-collection-tables-DMjOkeRy.js +1952 -0
  23. package/dist/ensure-collection-tables-DMjOkeRy.js.map +1 -0
  24. package/dist/index.d.ts +16 -16
  25. package/dist/index.es.js +19 -7128
  26. package/dist/index.es.js.map +1 -1
  27. package/dist/{rls-bootstrap-sql-B5Sajku6.js → rls-bootstrap-sql-DNzaWd4C.js} +3 -3
  28. package/dist/{rls-bootstrap-sql-B5Sajku6.js.map → rls-bootstrap-sql-DNzaWd4C.js.map} +1 -1
  29. package/dist/{rls-enforcement-Ch0T6OwW.js → rls-enforcement-CInuYj1-.js} +14 -4
  30. package/dist/rls-enforcement-CInuYj1-.js.map +1 -0
  31. package/dist/schema/classify-change.d.ts +82 -0
  32. package/dist/schema/collection-index.d.ts +182 -0
  33. package/dist/schema/dynamic-tables.d.ts +1 -1
  34. package/dist/schema/ensure-collection-policies.d.ts +1 -1
  35. package/dist/schema/ensure-collection-tables.d.ts +93 -2
  36. package/dist/schema/generate-schema-commit.d.ts +136 -0
  37. package/dist/schema/generated-schema-staleness.d.ts +19 -0
  38. package/dist/schema/introspect-db-constraints.d.ts +1 -1
  39. package/dist/schema/introspect-db-logic.d.ts +3 -3
  40. package/dist/schema/introspect-db-project.d.ts +1 -1
  41. package/dist/schema/introspect-db-queries.d.ts +1 -1
  42. package/dist/schema/introspect-db-structure.d.ts +2 -2
  43. package/dist/schema/introspect-runtime.d.ts +1 -1
  44. package/dist/schema/vector-index.d.ts +88 -0
  45. package/dist/services/BranchService.d.ts +2 -2
  46. package/dist/services/FetchService.d.ts +4 -4
  47. package/dist/services/PersistService.d.ts +5 -5
  48. package/dist/services/RelationService.d.ts +3 -3
  49. package/dist/services/RelationWriteService.d.ts +3 -3
  50. package/dist/services/cdc/junction-tables.d.ts +1 -1
  51. package/dist/services/cdc/trigger-cdc.d.ts +1 -1
  52. package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -1
  53. package/dist/services/channel-bus/index.d.ts +2 -2
  54. package/dist/services/collection-helpers.d.ts +1 -1
  55. package/dist/services/dataService.d.ts +10 -10
  56. package/dist/services/index.d.ts +4 -4
  57. package/dist/services/junction-writes.d.ts +2 -2
  58. package/dist/services/nested-path.d.ts +1 -1
  59. package/dist/services/realtimeService.d.ts +3 -3
  60. package/dist/services/row-pipeline.d.ts +1 -1
  61. package/dist/services/write-denial.d.ts +1 -1
  62. package/dist/{src-BBFsDaeA.js → src-DiDgtX8P.js} +97 -1
  63. package/dist/src-DiDgtX8P.js.map +1 -0
  64. package/dist/utils/drizzle-conditions.d.ts +2 -2
  65. package/dist/websocket-CUnpSe8v.js +8188 -0
  66. package/dist/websocket-CUnpSe8v.js.map +1 -0
  67. package/dist/websocket.d.ts +29 -2
  68. package/package.json +7 -7
  69. package/src/PostgresBackendDriver.ts +190 -59
  70. package/src/backup/backup-service.ts +1 -1
  71. package/src/cli-helpers.ts +117 -2
  72. package/src/cli.ts +22 -0
  73. package/src/connection.ts +37 -3
  74. package/src/databasePoolManager.ts +5 -2
  75. package/src/schema/classify-change.ts +436 -0
  76. package/src/schema/collection-index.ts +427 -0
  77. package/src/schema/ensure-collection-tables.test.ts +168 -1
  78. package/src/schema/ensure-collection-tables.ts +365 -14
  79. package/src/schema/generate-drizzle-schema-logic.ts +23 -11
  80. package/src/schema/generate-drizzle-schema.ts +13 -2
  81. package/src/schema/generate-postgres-ddl-logic.ts +33 -6
  82. package/src/schema/generate-postgres-ddl.ts +13 -2
  83. package/src/schema/generate-schema-commit.ts +242 -0
  84. package/src/schema/generated-schema-staleness.ts +114 -1
  85. package/src/schema/vector-index.ts +278 -0
  86. package/src/services/collection-helpers.ts +3 -2
  87. package/src/websocket.ts +47 -3
  88. package/dist/auth-users-columns-CgyPWQ18.js.map +0 -1
  89. package/dist/connection-BuZ97wsr.js.map +0 -1
  90. package/dist/data_driver-ULAyJEi9.js +0 -193
  91. package/dist/data_driver-ULAyJEi9.js.map +0 -1
  92. package/dist/ensure-collection-tables-BY1pHRD_.js +0 -840
  93. package/dist/ensure-collection-tables-BY1pHRD_.js.map +0 -1
  94. package/dist/rls-enforcement-Ch0T6OwW.js.map +0 -1
  95. package/dist/src-BBFsDaeA.js.map +0 -1
  96. package/dist/utils/table-classification.d.ts +0 -8
  97. package/dist/websocket-BVgDVO-V.js +0 -614
  98. package/dist/websocket-BVgDVO-V.js.map +0 -1
  99. package/src/utils/table-classification.ts +0 -16
@@ -0,0 +1,1952 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import "process";
3
+ __createRequire(import.meta.url);
4
+ import { u as __exportAll } from "./connection-GOKU3Hu5.js";
5
+ import { B as getPolicyNamesForRule, C as getTableName, I as generateForeignKeyName, L as legacyForeignKeyName, R as toPostgresIdentifier, T as resolveCollectionRelations, W as toSnakeCase, Z as isManyToMany, _ as securityRuleToConditions, b as findRelation, d as getJunctionCollectionConfig, f as getJunctionSecurityRules, g as policyToPostgres, h as getInjectedSecurityRules, i as collectionIndexStatements, m as getEffectiveSecurityRules, n as buildCollectionIndexSpecs, p as resolveJunctionSpecs, r as collectionIndexStatement, t as buildCollectionIndexPlan, u as relationalCollections } from "./collection-index-DxJBvVTH.js";
6
+ import { c as isPostgresCollectionConfig, n as REBASE_SCHEMA } from "./src-DiDgtX8P.js";
7
+ import { isConcurrentDdlRace, isDuplicateObjectRace, logger } from "@rebasepro/server";
8
+ import { createHash } from "node:crypto";
9
+ /**
10
+ * How wide a `varchar`/`char` column should be for a given property.
11
+ *
12
+ * One definition, three call sites, because they used to disagree. For the same
13
+ * `columnType: "varchar"` property the DDL generator emitted `VARCHAR(255)`
14
+ * while the Drizzle generator emitted a bare `varchar("col")` — which Postgres
15
+ * reads as *unbounded* — so which of the two you ran decided whether the column
16
+ * had a limit at all. Introspection then dropped the length entirely, so reading
17
+ * an existing `character varying(500)` column back and regenerating it produced
18
+ * a `VARCHAR(255)`: a silent narrowing of a column with data already in it.
19
+ *
20
+ * `validation.max` is the property's own statement about how long the value may
21
+ * be, so it is the only sensible source for the column's width — and it keeps
22
+ * the constraint the database enforces in step with the one the app enforces,
23
+ * rather than inventing a second, different limit underneath it.
24
+ */
25
+ function resolveStringColumnLength(prop) {
26
+ const max = prop.validation?.max;
27
+ return typeof max === "number" && Number.isInteger(max) && max > 0 ? max : 255;
28
+ }
29
+ //#endregion
30
+ //#region src/schema/search-column.ts
31
+ /**
32
+ * The one place a collection's `search` block becomes SQL.
33
+ *
34
+ * Four things describe a Postgres table in this codebase — the DDL generator,
35
+ * the Drizzle schema generator, the runtime table builder for BaaS mode, and
36
+ * the boot-time schema ensure — and each of them has, at some point, described
37
+ * a column differently from the others. The `varchar(255)` note in
38
+ * `generate-postgres-ddl-logic` is one such scar: the same property produced a
39
+ * capped column down one path and an uncapped one down the other, and nothing
40
+ * failed until a user hit the cap.
41
+ *
42
+ * So the search column is not implemented four times. It is computed once,
43
+ * here, and every generator renders the same {@link SearchColumnSpec}. There is
44
+ * a test asserting exactly that (`search-column-contract.test.ts`); the point of
45
+ * this module is that the test has something to assert *about*.
46
+ *
47
+ * ## Why the expressions look the way they do
48
+ *
49
+ * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and
50
+ * Postgres is stricter here than intuition. Verified against PostgreSQL 18:
51
+ *
52
+ * | expression | immutable |
53
+ * |-----------------------------------------|-----------|
54
+ * | `to_tsvector('spanish', col)` | yes |
55
+ * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |
56
+ * | `array_to_string(col, ' ')` | **no** |
57
+ * | `col::text` on `text[]` | **no** |
58
+ * | `to_jsonb(col)` | **no** |
59
+ * | `unaccent(col)` | **no** — dictionary lookup is STABLE |
60
+ * | `jsonb_to_tsvector('spanish', j, '["string"]')` | yes |
61
+ * | `setweight(...) || setweight(...)` | yes |
62
+ *
63
+ * Three of the four things a real search column needs are therefore unavailable
64
+ * directly, which is why {@link searchHelperFunctions} exists: each wraps a
65
+ * stable built-in in an SQL function declared IMMUTABLE. That declaration is a
66
+ * promise, and it is a true one for these three — array joining, JSON string
67
+ * extraction and accent folding are all deterministic for a given input; the
68
+ * built-ins are marked stable only because they must account for element types
69
+ * and dictionaries in general.
70
+ *
71
+ * The alternative was to skip `unaccent` and text arrays entirely. That is not
72
+ * a real option in an accented language: Postgres stems `auditoría` to
73
+ * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query
74
+ * typed without accents misses every row that carries them.
75
+ */
76
+ /** Schema-qualified so a collection outside `public` still resolves them. */
77
+ var HELPER_SCHEMA = "public";
78
+ /**
79
+ * Names of the helper functions. Frozen: they are recorded in the stored
80
+ * generation expression of every search column ever created, so renaming one
81
+ * orphans every table that already has a search column.
82
+ */
83
+ var SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;
84
+ var SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;
85
+ /** Raised when a `search` block names something that cannot be searched. */
86
+ var SearchConfigError = class extends Error {
87
+ constructor(message) {
88
+ super(message);
89
+ this.name = "SearchConfigError";
90
+ }
91
+ };
92
+ /** The `search` block of a collection, or undefined when it has none. */
93
+ var getSearchConfig = (collection) => isPostgresCollectionConfig(collection) ? collection.search : void 0;
94
+ /**
95
+ * Refuse a `search` block on a collection this engine does not store.
96
+ *
97
+ * The type only permits one on a `PostgresCollectionConfig`, so TypeScript
98
+ * already stops the ordinary case. This catches the rest — a JS config, a cast,
99
+ * a collection whose `engine` was changed after the block was written — because
100
+ * the alternative is the exact failure the block exists to prevent: a developer
101
+ * who declared what to index, saw no error, and got the substring fallback.
102
+ *
103
+ * Called with *every* collection, before the Postgres ones are filtered out.
104
+ */
105
+ var assertSearchIsPostgresOnly = (collections) => {
106
+ for (const collection of collections) {
107
+ if (isPostgresCollectionConfig(collection)) continue;
108
+ if (!collection.search) continue;
109
+ const engine = collection.engine ?? "non-postgres";
110
+ throw new SearchConfigError(`${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \`${engine}\`. Remove the block — it would otherwise look configured while \`.search()\` kept using the default substring match.`);
111
+ }
112
+ };
113
+ var columnNameOf = (propName, prop) => prop && "columnName" in prop && typeof prop.columnName === "string" ? prop.columnName : toSnakeCase(propName);
114
+ /**
115
+ * Classify a property for search purposes.
116
+ *
117
+ * Deliberately narrower than `getSqlColumnType`: search only cares whether a
118
+ * value reaches text, and the mapping from property to *physical* type is
119
+ * asserted against `getSqlColumnType` in the contract test rather than
120
+ * duplicated here.
121
+ *
122
+ * Returns null for anything that is not text-bearing, which the caller turns
123
+ * into a boot error naming the property.
124
+ */
125
+ var classify = (prop) => {
126
+ switch (prop.type) {
127
+ case "string": {
128
+ const sp = prop;
129
+ if (sp.enum) return {
130
+ kind: "text",
131
+ reason: "enum"
132
+ };
133
+ if (sp.isId === "uuid" || sp.columnType === "uuid") return {
134
+ kind: "text",
135
+ reason: "uuid"
136
+ };
137
+ return { kind: "text" };
138
+ }
139
+ case "map":
140
+ if (prop.columnType === "json") return {
141
+ kind: "jsonb",
142
+ reason: "json"
143
+ };
144
+ return { kind: "jsonb" };
145
+ case "array": {
146
+ const ap = prop;
147
+ let colType = ap.columnType;
148
+ if (!colType && ap.of && !Array.isArray(ap.of)) {
149
+ const of = ap.of;
150
+ if (of.type === "string") colType = "text[]";
151
+ else if (of.type === "number") colType = of.validation?.integer ? "integer[]" : "numeric[]";
152
+ else if (of.type === "boolean") colType = "boolean[]";
153
+ }
154
+ if (colType === "text[]") return { kind: "text_array" };
155
+ if (colType === "json") return {
156
+ kind: "jsonb",
157
+ reason: "json"
158
+ };
159
+ if (colType === "integer[]" || colType === "boolean[]" || colType === "numeric[]") return {
160
+ kind: "text_array",
161
+ reason: "non_text_array"
162
+ };
163
+ return { kind: "jsonb" };
164
+ }
165
+ default: return null;
166
+ }
167
+ };
168
+ var normalize = (inner, unaccent) => unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;
169
+ /** SQL reading one field as plain text, before normalization. */
170
+ var rawTextSql = (field) => {
171
+ const col = `"${field.column}"`;
172
+ if (field.kind === "text") return `coalesce(${col}, '')`;
173
+ if (field.kind === "text_array") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;
174
+ return `${SEARCH_TEXT_FN}(coalesce(${field.jsonPath.length === 0 ? col : field.jsonPath.length === 1 ? `${col} -> ${quote(field.jsonPath[0])}` : `${col} #> ${quote(`{${field.jsonPath.join(",")}}`)}`}, '{}'::jsonb))`;
175
+ };
176
+ var quote = (v) => `'${v.replace(/'/g, "''")}'`;
177
+ /**
178
+ * Resolve and validate one declared field path.
179
+ *
180
+ * A path that does not resolve throws. The whole point of an explicit block is
181
+ * that the author knows what is indexed; a silently dropped field would make it
182
+ * a guess again, and the failure — a search that returns nothing for content
183
+ * that is plainly in the row — is invisible from the outside.
184
+ */
185
+ var resolveField = (entry, collection, cfg) => {
186
+ const path = typeof entry === "string" ? entry : entry.path;
187
+ const weight = (typeof entry === "string" ? void 0 : entry.weight) ?? "B";
188
+ const where = `${collection.slug}.search`;
189
+ if (!path || typeof path !== "string") throw new SearchConfigError(`${where}: every entry in \`fields\` needs a property path.`);
190
+ const [head, ...rest] = path.split(".");
191
+ const prop = collection.properties?.[head];
192
+ if (!prop) throw new SearchConfigError(`${where}: "${path}" starts at property "${head}", which this collection does not declare. Known properties: ${Object.keys(collection.properties ?? {}).join(", ")}.`);
193
+ const classified = classify(prop);
194
+ if (!classified) throw new SearchConfigError(`${where}: "${path}" is a \`${prop.type}\` property, which holds no text to search. Searchable kinds are \`string\`, \`string[]\` and \`map\` (or a path inside one).`);
195
+ if (classified.reason === "enum") throw new SearchConfigError(`${where}: "${path}" is an enum. Enums are a fixed vocabulary — filter on them with \`where\` instead, which is exact and uses an index.`);
196
+ if (classified.reason === "uuid") throw new SearchConfigError(`${where}: "${path}" is a UUID column. Look it up by id rather than searching it.`);
197
+ if (classified.reason === "json") throw new SearchConfigError(`${where}: "${path}" is a \`json\` column, and the cast from \`json\` to \`jsonb\` is not immutable, so it cannot feed a generated column. Declare the property as \`jsonb\` (the default) to search it.`);
198
+ if (classified.reason === "non_text_array") throw new SearchConfigError(`${where}: "${path}" is an array of numbers or booleans. Only \`string[]\` carries text to search.`);
199
+ if (rest.length > 0 && classified.kind !== "jsonb") throw new SearchConfigError(`${where}: "${path}" addresses a path inside "${head}", but "${head}" is a \`${prop.type}\` property, not a \`map\`. Only map properties have paths inside them.`);
200
+ const column = columnNameOf(head, prop);
201
+ const textSql = normalize(rawTextSql({
202
+ column,
203
+ jsonPath: rest,
204
+ kind: classified.kind
205
+ }), cfg.unaccent === true);
206
+ const language = cfg.language ?? "simple";
207
+ return {
208
+ path,
209
+ column,
210
+ jsonPath: rest,
211
+ kind: classified.kind,
212
+ weight,
213
+ sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,
214
+ textSql
215
+ };
216
+ };
217
+ /**
218
+ * Build the full spec for a collection, or undefined when it has not opted in.
219
+ *
220
+ * Throws {@link SearchConfigError} on a config that cannot be honoured. Callers
221
+ * at boot surface that as a startup failure — a search block that half-works is
222
+ * worse than one that refuses.
223
+ */
224
+ var buildSearchColumnSpec = (collection) => {
225
+ const cfg = getSearchConfig(collection);
226
+ if (!cfg) return void 0;
227
+ if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) throw new SearchConfigError(`${collection.slug}.search: \`fields\` is empty. Name the properties to index, or remove the \`search\` block to keep the default ILIKE behaviour.`);
228
+ const table = getTableName(collection);
229
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
230
+ const column = cfg.column ?? "search_vector";
231
+ if (collection.properties?.[column]) throw new SearchConfigError(`${collection.slug}.search: the generated column "${column}" collides with a declared property of the same name. Set \`search.column\` to something else.`);
232
+ const fields = cfg.fields.map((entry) => resolveField(entry, collection, cfg));
233
+ const seen = /* @__PURE__ */ new Set();
234
+ for (const f of fields) {
235
+ if (seen.has(f.path)) throw new SearchConfigError(`${collection.slug}.search: "${f.path}" is listed twice.`);
236
+ seen.add(f.path);
237
+ }
238
+ const extensions = [];
239
+ if (cfg.unaccent) extensions.push("unaccent");
240
+ if (cfg.fuzzy) extensions.push("pg_trgm");
241
+ const spec = {
242
+ schema,
243
+ table,
244
+ column,
245
+ language: cfg.language ?? "simple",
246
+ unaccent: cfg.unaccent === true,
247
+ fields,
248
+ expression: fields.map((f) => f.sql).join(" || "),
249
+ indexName: toPostgresIdentifier(`${table}_${column}_gin`),
250
+ extensions
251
+ };
252
+ if (cfg.fuzzy) {
253
+ const fuzzyColumn = `${column}_text`;
254
+ if (collection.properties?.[fuzzyColumn]) throw new SearchConfigError(`${collection.slug}.search: \`fuzzy\` needs the column "${fuzzyColumn}", which collides with a declared property. Set \`search.column\` to something else.`);
255
+ spec.fuzzy = {
256
+ column: fuzzyColumn,
257
+ expression: fields.map((f) => f.textSql).join(" || ' ' || "),
258
+ indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),
259
+ threshold: cfg.fuzzyThreshold ?? .3
260
+ };
261
+ }
262
+ return spec;
263
+ };
264
+ /**
265
+ * The IMMUTABLE wrappers the generated expressions call.
266
+ *
267
+ * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather
268
+ * than an error, and idempotent for the same reason every other boot-time DDL
269
+ * statement here is.
270
+ *
271
+ * The bodies are stable built-ins wrapped in an immutable promise — see the
272
+ * module comment for why that promise is sound. `STRICT` matters: it makes NULL
273
+ * in mean NULL out without executing the body, which is what the `coalesce` at
274
+ * each call site then absorbs.
275
+ */
276
+ var searchHelperFunctions = (spec) => {
277
+ const statements = [`CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT array_to_string($1, ' ') $$;`, `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT coalesce(string_agg(v, ' '), '')\n FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == "string")')) AS v $$;`];
278
+ if (spec.unaccent) statements.push(`CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`);
279
+ return statements;
280
+ };
281
+ /**
282
+ * `CREATE EXTENSION` statements the spec's expressions depend on.
283
+ *
284
+ * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified
285
+ * `CREATE EXTENSION` installs into the first schema on `search_path`, which
286
+ * defaults to `"$user", public` — and the scaffold's database role is named
287
+ * `rebase`, the same as the schema the generator creates one statement earlier.
288
+ * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the
289
+ * dictionary in `rebase`, and every reference to `public.unaccent` below fails
290
+ * with "text search dictionary does not exist". Observed, not theorised.
291
+ */
292
+ var searchExtensionStatements = (spec) => spec.extensions.map((e) => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);
293
+ /** The column definition as it appears inside `CREATE TABLE`. */
294
+ var searchColumnDefinition = (spec) => `"${spec.column}" tsvector GENERATED ALWAYS AS (${spec.expression}) STORED`;
295
+ /** The fuzzy column definition, when the spec asks for one. */
296
+ var fuzzyColumnDefinition = (spec) => spec.fuzzy ? `"${spec.fuzzy.column}" text GENERATED ALWAYS AS (${spec.fuzzy.expression}) STORED` : void 0;
297
+ /**
298
+ * Index statements for the spec.
299
+ *
300
+ * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a
301
+ * SQL file replayed as one unit — a migration, or `search.sql` — where a
302
+ * concurrent build is not allowed. The boot-time ensure path runs statement by
303
+ * statement against tables that are live and populated, and uses the
304
+ * concurrent form instead; see `ensureSearchColumns`.
305
+ */
306
+ var searchIndexStatements = (spec) => {
307
+ const statements = [`CREATE INDEX IF NOT EXISTS "${spec.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.column}");`];
308
+ if (spec.fuzzy) statements.push(`CREATE INDEX IF NOT EXISTS "${spec.fuzzy.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.fuzzy.column}" ${HELPER_SCHEMA}.gin_trgm_ops);`);
309
+ return statements;
310
+ };
311
+ /**
312
+ * Marker on the comment of every generated search column this module creates.
313
+ *
314
+ * Versioned because the fingerprint below is only comparable against itself: a
315
+ * future change to how it is computed has to read as "not stamped by this
316
+ * version" rather than as drift on every existing column.
317
+ */
318
+ var SEARCH_STAMP_PREFIX = "rebase:search:v1:";
319
+ /**
320
+ * A stable fingerprint of one generated column's expression.
321
+ *
322
+ * Why a stamp rather than reading the expression back: Postgres stores a
323
+ * generated column's expression *parsed*, and hands it back deparsed — casts
324
+ * made explicit, identifiers requoted, schema qualifications added or dropped
325
+ * according to `search_path`. Comparing that text to the text we generated
326
+ * would report drift on wording, and this comparison decides whether a boot
327
+ * refuses, so a false positive is an outage. The stamp is written by the same
328
+ * code that writes the column, so equality means what it says.
329
+ */
330
+ var searchExpressionFingerprint = (expression) => `${SEARCH_STAMP_PREFIX}${createHash("sha256").update(expression).digest("hex").slice(0, 16)}`;
331
+ /**
332
+ * The stamps for a spec's generated columns — one per column, never shared.
333
+ *
334
+ * Per column on purpose: turning `fuzzy` on adds a second column and changes
335
+ * nothing about the first, and a spec-wide fingerprint would report the
336
+ * untouched `tsvector` column as drifted and refuse a boot over a change that
337
+ * is purely additive.
338
+ */
339
+ var searchColumnStamps = (spec) => {
340
+ const stamp = (column, expression) => {
341
+ const fingerprint = searchExpressionFingerprint(expression);
342
+ return {
343
+ column,
344
+ expression,
345
+ fingerprint,
346
+ sql: `COMMENT ON COLUMN "${spec.schema}"."${spec.table}"."${column}" IS ${quote(fingerprint)};`
347
+ };
348
+ };
349
+ const stamps = [stamp(spec.column, spec.expression)];
350
+ if (spec.fuzzy) stamps.push(stamp(spec.fuzzy.column, spec.fuzzy.expression));
351
+ return stamps;
352
+ };
353
+ /**
354
+ * The same drift check as the boot ensure, for the SQL file.
355
+ *
356
+ * Needed because {@link searchColumnStamps} would otherwise *launder* drift on
357
+ * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that
358
+ * exists, so a re-generated `search.sql` would stamp a stale column with the
359
+ * new block's fingerprint and the next boot would find them in agreement.
360
+ * Guarding first means the file refuses instead — `rebase db push` is attended,
361
+ * and the operator reading the failure is the person who changed the block.
362
+ */
363
+ var searchStampGuards = (spec) => searchColumnStamps(spec).map((stamp) => {
364
+ const relation = quote(`"${spec.schema}"."${spec.table}"`);
365
+ return `DO $rebase_search$
366
+ DECLARE recorded text;
367
+ BEGIN
368
+ SELECT col_description(a.attrelid, a.attnum) INTO recorded
369
+ FROM pg_attribute a
370
+ WHERE a.attrelid = ${relation}::regclass AND a.attname = ${quote(stamp.column)} AND NOT a.attisdropped;
371
+ IF recorded LIKE ${quote(`${SEARCH_STAMP_PREFIX}%`)} AND recorded <> ${quote(stamp.fingerprint)} THEN
372
+ 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;
373
+ END IF;
374
+ END
375
+ $rebase_search$;`;
376
+ });
377
+ /**
378
+ * The generated column names a collection's search block adds, if any.
379
+ *
380
+ * These are physical columns on the table, so `SELECT *` returns them. They are
381
+ * an index in column form — a list of lexeme positions, or a concatenation of
382
+ * every searchable field on the row — and nothing outside the query planner has
383
+ * any use for them. Left in, every list response carries a second, larger copy
384
+ * of the row's text.
385
+ */
386
+ var searchColumnNames = (collection) => {
387
+ let spec;
388
+ try {
389
+ spec = buildSearchColumnSpec(collection);
390
+ } catch {
391
+ return [];
392
+ }
393
+ if (!spec) return [];
394
+ return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];
395
+ };
396
+ /**
397
+ * True for a column whose type only ever holds a search index.
398
+ *
399
+ * Independent of any collection config on purpose: an introspected database
400
+ * (BaaS mode) can carry a `tsvector` column this framework never created —
401
+ * Pagila's `film.fulltext` is the canonical one — and it should not be returned
402
+ * to callers either. `isDerivedIndexColumn` already keeps such a column out of
403
+ * the *properties*; this keeps it out of the *rows*.
404
+ */
405
+ var isSearchIndexColumn = (column) => {
406
+ const sqlType = typeof column?.getSQLType === "function" ? column.getSQLType().toLowerCase() : "";
407
+ return sqlType === "tsvector" || sqlType === "tsquery";
408
+ };
409
+ /**
410
+ * A drizzle select projection over `table` with the search columns dropped.
411
+ *
412
+ * Returns undefined when nothing needs dropping, so the common case keeps using
413
+ * a plain `select()` and this stays invisible in the generated SQL.
414
+ */
415
+ var visibleColumnProjection = (tableColumns, collection) => {
416
+ const excluded = excludedColumnNames(tableColumns, collection);
417
+ if (!tableColumns || excluded.length === 0) return void 0;
418
+ const projection = {};
419
+ for (const [name, column] of Object.entries(tableColumns)) if (!excluded.includes(name)) projection[name] = column;
420
+ return projection;
421
+ };
422
+ /** The same exclusion as a drizzle `db.query` `columns` denylist. */
423
+ var hiddenColumnsOption = (tableColumns, collection) => {
424
+ const excluded = excludedColumnNames(tableColumns, collection);
425
+ if (excluded.length === 0) return void 0;
426
+ return Object.fromEntries(excluded.map((name) => [name, false]));
427
+ };
428
+ /**
429
+ * The columns to keep out of a response, by name.
430
+ *
431
+ * `tableColumns` is whatever `getTableColumns` returned, which is `undefined`
432
+ * for anything that is not a real drizzle table — a stub in a test, a derived
433
+ * or nested path with no table behind it. Nothing to exclude is the right
434
+ * answer there, and it has to be an answer rather than a throw: this runs on
435
+ * the read path of every collection, opted in or not.
436
+ */
437
+ var excludedColumnNames = (tableColumns, collection) => {
438
+ if (!tableColumns || typeof tableColumns !== "object") return [];
439
+ const byName = new Set(collection ? searchColumnNames(collection) : []);
440
+ return Object.keys(tableColumns).filter((name) => byName.has(name) || isSearchIndexColumn(tableColumns[name]));
441
+ };
442
+ //#endregion
443
+ //#region src/schema/auth-users-columns.ts
444
+ /**
445
+ * `email` is NOT NULL on purpose, and the anonymous sign-in route depends on it
446
+ * — it synthesizes `anon_<32 hex>@anonymous.local` rather than inserting NULL.
447
+ * The 320-char bound (RFC 5321) is a CHECK rather than a `VARCHAR(n)`, added
448
+ * separately by `ensureAuthTablesExist` so it can be `NOT VALID` on an adopted
449
+ * table that already holds a longer row.
450
+ */
451
+ var AUTH_USERS_COLUMNS = [
452
+ {
453
+ column: "email",
454
+ type: "TEXT",
455
+ notNull: true
456
+ },
457
+ {
458
+ column: "display_name",
459
+ type: "TEXT"
460
+ },
461
+ {
462
+ column: "photo_url",
463
+ type: "TEXT"
464
+ },
465
+ {
466
+ column: "roles",
467
+ type: "TEXT[]",
468
+ default: "'{}'",
469
+ notNull: true
470
+ },
471
+ {
472
+ column: "password_hash",
473
+ type: "TEXT"
474
+ },
475
+ {
476
+ column: "email_verified",
477
+ type: "BOOLEAN",
478
+ default: "FALSE",
479
+ notNull: true
480
+ },
481
+ {
482
+ column: "email_verification_token",
483
+ type: "TEXT"
484
+ },
485
+ {
486
+ column: "email_verification_sent_at",
487
+ type: "TIMESTAMP WITH TIME ZONE"
488
+ },
489
+ {
490
+ column: "is_anonymous",
491
+ type: "BOOLEAN",
492
+ default: "FALSE",
493
+ notNull: true
494
+ },
495
+ {
496
+ column: "metadata",
497
+ type: "JSONB",
498
+ default: "'{}'",
499
+ notNull: true
500
+ },
501
+ {
502
+ column: "tokens_valid_after",
503
+ type: "TIMESTAMP WITH TIME ZONE"
504
+ },
505
+ {
506
+ column: "created_at",
507
+ type: "TIMESTAMP WITH TIME ZONE",
508
+ default: "NOW()",
509
+ notNull: true
510
+ },
511
+ {
512
+ column: "updated_at",
513
+ type: "TIMESTAMP WITH TIME ZONE",
514
+ default: "NOW()",
515
+ notNull: true
516
+ }
517
+ ];
518
+ var BY_COLUMN = new Map(AUTH_USERS_COLUMNS.map((c) => [c.column, c]));
519
+ /** Type + inline constraints, as they appear after the column name. */
520
+ function authUsersColumnSql(spec) {
521
+ return [
522
+ spec.type,
523
+ spec.default !== void 0 ? `DEFAULT ${spec.default}` : "",
524
+ spec.notNull ? "NOT NULL" : ""
525
+ ].filter(Boolean).join(" ");
526
+ }
527
+ /**
528
+ * The auth-owned definition for a physical column name, or `undefined` when
529
+ * auth does not own it.
530
+ *
531
+ * Callers pass the RESOLVED column name (after `columnName` mapping), because
532
+ * that is the only name the three creators agree on: the scaffold's users
533
+ * collection spells the property `displayName` and the column `display_name`.
534
+ */
535
+ function authUsersColumnDefinition(column) {
536
+ const spec = BY_COLUMN.get(column);
537
+ return spec ? authUsersColumnSql(spec) : void 0;
538
+ }
539
+ /**
540
+ * Whether a collection is an auth collection, i.e. whether the definitions in
541
+ * this module apply to its table at all.
542
+ *
543
+ * Duplicated in shape from `@rebasepro/common`'s policy defaults on purpose:
544
+ * that one takes a `CollectionConfig`, this one is called from DDL code paths
545
+ * that hold looser objects, and both spellings must accept `auth: true` as well
546
+ * as `auth: { enabled: true }`.
547
+ */
548
+ function isAuthCollection(collection) {
549
+ const auth = collection?.auth;
550
+ if (auth === true) return true;
551
+ return typeof auth === "object" && auth !== null && auth.enabled === true;
552
+ }
553
+ //#endregion
554
+ //#region src/schema/vector-index.ts
555
+ /**
556
+ * The widest `vector` pgvector will build an HNSW or IVFFlat index over.
557
+ * Storage and exact search are unaffected by this limit.
558
+ */
559
+ var MAX_INDEXABLE_VECTOR_DIMENSIONS = 2e3;
560
+ /**
561
+ * Operator class per distance. These strings are part of the database contract:
562
+ * they appear in `CREATE INDEX`, so renaming one renames an index.
563
+ */
564
+ var OPERATOR_CLASS = {
565
+ cosine: "vector_cosine_ops",
566
+ l2: "vector_l2_ops",
567
+ inner_product: "vector_ip_ops"
568
+ };
569
+ /** Short, stable tag per distance, used to name the index. */
570
+ var DISTANCE_TAG = {
571
+ cosine: "cosine",
572
+ l2: "l2",
573
+ inner_product: "ip"
574
+ };
575
+ var VectorIndexConfigError = class extends Error {
576
+ constructor(message) {
577
+ super(message);
578
+ this.name = "VectorIndexConfigError";
579
+ }
580
+ };
581
+ var isVectorProperty = (prop) => !!prop && typeof prop === "object" && prop.type === "vector";
582
+ var asDistances = (config, label) => {
583
+ const raw = config.distance ?? "cosine";
584
+ const list = Array.isArray(raw) ? raw : [raw];
585
+ if (list.length === 0) throw new VectorIndexConfigError(`${label}: \`index.distance\` is an empty array. Name at least one distance, or set \`index: false\` to create no index.`);
586
+ const seen = /* @__PURE__ */ new Set();
587
+ for (const distance of list) {
588
+ if (!(distance in OPERATOR_CLASS)) throw new VectorIndexConfigError(`${label}: \`index.distance\` is "${distance}", which is not a pgvector distance. Use ${Object.keys(OPERATOR_CLASS).map((d) => `"${d}"`).join(", ")}.`);
589
+ if (seen.has(distance)) throw new VectorIndexConfigError(`${label}: \`index.distance\` lists "${distance}" twice.`);
590
+ seen.add(distance);
591
+ }
592
+ return list;
593
+ };
594
+ var assertPositiveInteger = (value, key, label) => {
595
+ if (value === void 0) return;
596
+ if (!Number.isInteger(value) || value <= 0) throw new VectorIndexConfigError(`${label}: \`index.${key}\` is ${JSON.stringify(value)}. It must be a positive integer.`);
597
+ };
598
+ /**
599
+ * Index parameters for one method. Parameters belonging to the *other* method
600
+ * are rejected rather than ignored, because a silently dropped `lists` on an
601
+ * HNSW index reads, from the config, exactly like a tuned index.
602
+ */
603
+ var parametersFor = (method, config, label) => {
604
+ assertPositiveInteger(config.m, "m", label);
605
+ assertPositiveInteger(config.efConstruction, "efConstruction", label);
606
+ assertPositiveInteger(config.lists, "lists", label);
607
+ if (method === "hnsw") {
608
+ if (config.lists !== void 0) throw new VectorIndexConfigError(`${label}: \`index.lists\` only applies to \`method: "ivfflat"\`. Remove it, or switch the method.`);
609
+ const params = [];
610
+ if (config.m !== void 0) params.push(["m", config.m]);
611
+ if (config.efConstruction !== void 0) params.push(["ef_construction", config.efConstruction]);
612
+ return params;
613
+ }
614
+ for (const key of ["m", "efConstruction"]) if (config[key] !== void 0) throw new VectorIndexConfigError(`${label}: \`index.${key}\` only applies to \`method: "hnsw"\`. Remove it, or switch the method.`);
615
+ return config.lists !== void 0 ? [["lists", config.lists]] : [];
616
+ };
617
+ /**
618
+ * Every ANN index a collection's vector properties call for.
619
+ *
620
+ * `resolveColumn` is passed in rather than imported so that this module stays
621
+ * free of the DDL generator, which imports *it*. Both callers hand it the same
622
+ * `resolveColumnName`, and a contract test asserts the names agree.
623
+ */
624
+ var buildVectorIndexPlan = (collection, resolveColumn) => {
625
+ const specs = [];
626
+ const skipped = [];
627
+ const properties = collection.properties ?? {};
628
+ const table = getTableName(collection);
629
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
630
+ for (const [propName, prop] of Object.entries(properties)) {
631
+ if (!isVectorProperty(prop)) continue;
632
+ if (prop.index === false) continue;
633
+ const label = `${collection.slug}.${propName}`;
634
+ const column = resolveColumn(propName, prop);
635
+ const config = prop.index ?? {};
636
+ const method = config.method ?? "hnsw";
637
+ if (method !== "hnsw" && method !== "ivfflat") throw new VectorIndexConfigError(`${label}: \`index.method\` is "${method}". Use "hnsw" or "ivfflat".`);
638
+ const distances = asDistances(config, label);
639
+ const parameters = parametersFor(method, config, label);
640
+ if (!Number.isInteger(prop.dimensions) || prop.dimensions <= 0) throw new VectorIndexConfigError(`${label}: \`dimensions\` is ${JSON.stringify(prop.dimensions)}. It must be a positive integer.`);
641
+ if (prop.dimensions > 2e3) {
642
+ skipped.push({
643
+ schema,
644
+ table,
645
+ column,
646
+ dimensions: prop.dimensions,
647
+ reason: `pgvector cannot index a vector wider than ${MAX_INDEXABLE_VECTOR_DIMENSIONS} dimensions, and ${label} declares ${prop.dimensions}. The column works and \`vectorSearch\` still answers, as an exact scan. To index it, reduce the dimensions (many embedding models support a shorter output) or set \`index: false\` to state that the scan is intended.`
648
+ });
649
+ continue;
650
+ }
651
+ for (const distance of distances) specs.push({
652
+ schema,
653
+ table,
654
+ column,
655
+ indexName: toPostgresIdentifier(`${table}_${column}_${method}_${DISTANCE_TAG[distance]}`),
656
+ method,
657
+ distance,
658
+ operatorClass: OPERATOR_CLASS[distance],
659
+ parameters
660
+ });
661
+ }
662
+ return {
663
+ specs,
664
+ skipped
665
+ };
666
+ };
667
+ /**
668
+ * The `CREATE INDEX` for one spec.
669
+ *
670
+ * `CONCURRENTLY` is deliberately absent, for the same reason it is absent from
671
+ * `searchIndexStatements`: this form is replayed as part of a migration, where
672
+ * a concurrent build is not allowed. The boot-time ensure rewrites it — see
673
+ * `ensureCollectionTables`.
674
+ */
675
+ var vectorIndexStatement = (spec) => {
676
+ const params = spec.parameters.length ? ` WITH (${spec.parameters.map(([key, value]) => `${key} = ${value}`).join(", ")})` : "";
677
+ return `CREATE INDEX IF NOT EXISTS "${spec.indexName}" ON "${spec.schema}"."${spec.table}" USING ${spec.method} ("${spec.column}" ${spec.operatorClass})${params};`;
678
+ };
679
+ /** Every statement for a plan, in a stable order. */
680
+ var vectorIndexStatements = (plan) => plan.specs.map(vectorIndexStatement);
681
+ //#endregion
682
+ //#region src/schema/generate-postgres-ddl-logic.ts
683
+ var resolveColumnName = (propName, prop) => {
684
+ if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
685
+ return toSnakeCase(propName);
686
+ };
687
+ var getPrimaryKeyProp = (collection) => {
688
+ if (collection.properties) {
689
+ const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => "isId" in prop && Boolean(prop.isId));
690
+ if (idPropEntry) {
691
+ const prop = idPropEntry[1];
692
+ const isUuid = prop.type === "string" && "isId" in prop && prop.isId === "uuid";
693
+ return {
694
+ name: idPropEntry[0],
695
+ type: prop.type === "number" ? "number" : "string",
696
+ isUuid
697
+ };
698
+ }
699
+ }
700
+ const idProp = collection.properties?.["id"];
701
+ if (idProp?.type === "number") return {
702
+ name: "id",
703
+ type: "number",
704
+ isUuid: false
705
+ };
706
+ return {
707
+ name: "id",
708
+ type: "string",
709
+ isUuid: idProp?.type === "string" && "isId" in idProp && idProp.isId === "uuid"
710
+ };
711
+ };
712
+ var isNumericId = (collection) => {
713
+ return getPrimaryKeyProp(collection).type === "number";
714
+ };
715
+ var getPrimaryKeyName = (collection) => {
716
+ return getPrimaryKeyProp(collection).name;
717
+ };
718
+ /** The column type a junction holds for one endpoint's primary key. */
719
+ var junctionKeyType = (collection) => isNumericId(collection) ? "INTEGER" : getPrimaryKeyProp(collection).isUuid ? "UUID" : "TEXT";
720
+ var isIdProperty = (propName, prop, collection) => {
721
+ if ("isId" in prop && Boolean(prop.isId)) return true;
722
+ return !Object.values(collection.properties ?? {}).some((p) => "isId" in p && Boolean(p.isId)) && propName === "id";
723
+ };
724
+ /**
725
+ * Render statements produced by {@link generatePolicyStatements} back into the
726
+ * exact string the DDL/policies files have always carried: each statement on
727
+ * its own line, terminated by a newline. Keeping the string form derived from
728
+ * the statement array means the two can never drift — the boot-time applier and
729
+ * the generated `policies.sql` emit the same SQL, from the same source.
730
+ */
731
+ var statementsToDdl = (statements) => statements.map((s) => `${s}\n`).join("");
732
+ var generatePolicyDdl = (collection, rule, resolveCollection) => statementsToDdl(generatePolicyStatements(collection, rule, resolveCollection));
733
+ /**
734
+ * The individual SQL statements a single security rule compiles to: a
735
+ * `DROP POLICY IF EXISTS` / `CREATE POLICY` pair per operation, each a complete
736
+ * statement (terminated by `;`, no trailing newline).
737
+ *
738
+ * This is the primitive the boot-time RLS applier runs one statement at a time
739
+ * (the runtime's DB handle speaks the extended query protocol, which forbids
740
+ * multiple commands in one execute), while `db push` writes the joined string.
741
+ */
742
+ var generatePolicyStatements = (collection, rule, resolveCollection) => {
743
+ const tableName = getTableName(collection);
744
+ const ops = rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? "all"];
745
+ const policyNames = getPolicyNamesForRule(rule, tableName);
746
+ return ops.flatMap((op, opIdx) => {
747
+ return generateSinglePolicyStatements(collection, rule, op, policyNames[opIdx], resolveCollection);
748
+ });
749
+ };
750
+ var generateSinglePolicyStatements = (collection, rule, operation, policyName, resolveCollection) => {
751
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
752
+ const tableName = getTableName(collection);
753
+ const mode = (rule.mode ?? "permissive").toUpperCase();
754
+ const operationUpper = operation.toUpperCase();
755
+ const pgRoles = rule.pgRoles ? [...rule.pgRoles].sort() : ["public"];
756
+ const needsUsing = operation !== "insert";
757
+ const needsWithCheck = operation !== "select" && operation !== "delete";
758
+ const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
759
+ let usingClause = needsUsing && usingExpr ? policyToPostgres(usingExpr, collection, { resolveCollection }) : null;
760
+ let withCheckClause = needsWithCheck && withCheckExpr ? policyToPostgres(withCheckExpr, collection, { resolveCollection }) : null;
761
+ if (!usingClause && needsUsing) usingClause = "false";
762
+ if (!withCheckClause && needsWithCheck) withCheckClause = "false";
763
+ const drop = `DROP POLICY IF EXISTS "${policyName}" ON "${schema}"."${tableName}";`;
764
+ let create = `CREATE POLICY "${policyName}" ON "${schema}"."${tableName}" AS ${mode} FOR ${operationUpper} TO ${pgRoles.map((r) => `"${r}"`).join(", ")}`;
765
+ if (usingClause) create += ` USING (${usingClause})`;
766
+ if (withCheckClause) create += ` WITH CHECK (${withCheckClause})`;
767
+ create += ";";
768
+ return [drop, create];
769
+ };
770
+ /**
771
+ * Single-quote escaping for a SQL string literal (PostgreSQL doubles the
772
+ * quote). Enum labels come straight from user-authored collection config, so a
773
+ * label like `it's` closes the literal early and the whole generated file stops
774
+ * parsing at the `CREATE TYPE`. Lives here rather than next to its other caller
775
+ * because ensure-collection-tables already imports from this module — the
776
+ * reverse would be a cycle.
777
+ */
778
+ var quoteSqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
779
+ var getSqlColumnType = (propName, prop, collection, collections) => {
780
+ switch (prop.type) {
781
+ case "string": {
782
+ const stringProp = prop;
783
+ if (stringProp.enum) {
784
+ const tableName = getTableName(collection);
785
+ const colName = resolveColumnName(propName, prop);
786
+ return `"${isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public"}"."${tableName}_${colName}"`;
787
+ }
788
+ if (stringProp.isId === "uuid" || stringProp.columnType === "uuid") return "UUID";
789
+ if (stringProp.columnType === "char") return `CHAR(${resolveStringColumnLength(stringProp)})`;
790
+ if (stringProp.columnType === "varchar") return `VARCHAR(${resolveStringColumnLength(stringProp)})`;
791
+ return "TEXT";
792
+ }
793
+ case "number": {
794
+ const numProp = prop;
795
+ const isId = isIdProperty(propName, prop, collection);
796
+ if ("isId" in numProp && numProp.isId === "increment") return "INTEGER GENERATED BY DEFAULT AS IDENTITY";
797
+ if (numProp.columnType) {
798
+ if (numProp.columnType === "double precision") return "DOUBLE PRECISION";
799
+ return numProp.columnType.toUpperCase();
800
+ }
801
+ return numProp.validation?.integer || isId ? "INTEGER" : "NUMERIC";
802
+ }
803
+ case "boolean": return "BOOLEAN";
804
+ case "date": {
805
+ const dateProp = prop;
806
+ if (dateProp.columnType === "date") return "DATE";
807
+ if (dateProp.columnType === "time") return "TIME";
808
+ return "TIMESTAMP WITH TIME ZONE";
809
+ }
810
+ case "map": return prop.columnType === "json" ? "JSON" : "JSONB";
811
+ case "geopoint": return "JSONB";
812
+ case "array": {
813
+ const arrayProp = prop;
814
+ let colType = arrayProp.columnType;
815
+ if (!colType && arrayProp.of && !Array.isArray(arrayProp.of)) {
816
+ const ofProp = arrayProp.of;
817
+ if (ofProp.type === "string") colType = "text[]";
818
+ else if (ofProp.type === "number") colType = ofProp.validation?.integer ? "integer[]" : "numeric[]";
819
+ else if (ofProp.type === "boolean") colType = "boolean[]";
820
+ }
821
+ if (colType === "json") return "JSON";
822
+ if (colType === "text[]") return "TEXT[]";
823
+ if (colType === "integer[]") return "INTEGER[]";
824
+ if (colType === "boolean[]") return "BOOLEAN[]";
825
+ if (colType === "numeric[]") return "NUMERIC[]";
826
+ return "JSONB";
827
+ }
828
+ case "vector": return `VECTOR(${prop.dimensions})`;
829
+ case "binary": return "BYTEA";
830
+ case "relation": {
831
+ const refProp = prop;
832
+ const relation = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
833
+ if (relation?.kind !== "belongsTo") throw new Error(`Relation ${propName} does not put a column on this table (only \`belongsTo\` does)`);
834
+ let targetCollection;
835
+ try {
836
+ targetCollection = relation.target();
837
+ } catch {
838
+ return "TEXT";
839
+ }
840
+ const pkProp = getPrimaryKeyProp(targetCollection);
841
+ return pkProp.type === "number" ? "INTEGER" : pkProp.isUuid ? "UUID" : "TEXT";
842
+ }
843
+ case "reference": {
844
+ const refProp = prop;
845
+ const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
846
+ if (!targetCollection) return "TEXT";
847
+ const pkProp = getPrimaryKeyProp(targetCollection);
848
+ return pkProp.type === "number" ? "INTEGER" : pkProp.isUuid ? "UUID" : "TEXT";
849
+ }
850
+ default: throw new Error(`No Postgres column type for property '${propName}' of type '${prop.type}' in collection '${collection.slug}'. Add a case to \`getSqlColumnType\` (and to \`getDrizzleColumn\`, which must agree).`);
851
+ }
852
+ };
853
+ var generatePostgresSearchDdl = (allCollections) => {
854
+ const collections = relationalCollections(allCollections);
855
+ const specs = collections.map((c) => buildSearchColumnSpec(c)).filter((s) => s !== void 0);
856
+ if (specs.length === 0) return "";
857
+ const extensions = Array.from(new Set(specs.flatMap(searchExtensionStatements)));
858
+ const helpers = Array.from(new Set(specs.flatMap(searchHelperFunctions)));
859
+ let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n";
860
+ ddl += "--\n";
861
+ ddl += "-- Full-text search for the collections declaring a `search` block.\n";
862
+ ddl += "-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\n\n";
863
+ extensions.forEach((s) => {
864
+ ddl += `${s}\n`;
865
+ });
866
+ if (extensions.length > 0) ddl += "\n";
867
+ helpers.forEach((s) => {
868
+ ddl += `${s}\n\n`;
869
+ });
870
+ for (const collection of collections) {
871
+ const spec = buildSearchColumnSpec(collection);
872
+ if (!spec) continue;
873
+ const table = `"${isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public"}"."${getTableName(collection)}"`;
874
+ searchStampGuards(spec).forEach((s) => {
875
+ ddl += `${s}\n`;
876
+ });
877
+ ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\n`;
878
+ const fuzzyDef = fuzzyColumnDefinition(spec);
879
+ if (fuzzyDef) ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${fuzzyDef};\n`;
880
+ searchColumnStamps(spec).forEach((s) => {
881
+ ddl += `${s.sql}\n`;
882
+ });
883
+ searchIndexStatements(spec).forEach((s) => {
884
+ ddl += `${s}\n`;
885
+ });
886
+ ddl += "\n";
887
+ }
888
+ return ddl;
889
+ };
890
+ var generatePostgresDdl = async (allCollections, options = {
891
+ includePolicies: true,
892
+ includeSearch: true
893
+ }) => {
894
+ const collections = relationalCollections(allCollections);
895
+ let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n\n";
896
+ const uniqueSchemas = Array.from(/* @__PURE__ */ new Set([REBASE_SCHEMA, ...collections.map((c) => isPostgresCollectionConfig(c) ? c.schema : void 0).filter(Boolean)]));
897
+ uniqueSchemas.forEach((schema) => {
898
+ if (schema) ddl += `CREATE SCHEMA IF NOT EXISTS "${schema}";\n`;
899
+ });
900
+ if (uniqueSchemas.length > 0) ddl += "\n";
901
+ const searchSpecs = collections.map((c) => buildSearchColumnSpec(c)).filter((s) => s !== void 0);
902
+ if (searchSpecs.length > 0) if (options.includeSearch === false) ddl += "-- Full-text search support lives in `search.sql`, applied separately.\n\n";
903
+ else {
904
+ const extensions = Array.from(new Set(searchSpecs.flatMap(searchExtensionStatements)));
905
+ const helpers = Array.from(new Set(searchSpecs.flatMap(searchHelperFunctions)));
906
+ ddl += "-- Full-text search support (collections declaring a `search` block)\n";
907
+ extensions.forEach((s) => {
908
+ ddl += `${s}\n`;
909
+ });
910
+ if (extensions.length > 0) ddl += "\n";
911
+ helpers.forEach((s) => {
912
+ ddl += `${s}\n\n`;
913
+ });
914
+ }
915
+ const emittedEnums = /* @__PURE__ */ new Set();
916
+ collections.forEach((collection) => {
917
+ const collectionTable = getTableName(collection);
918
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
919
+ Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
920
+ if ("enum" in prop && (prop.type === "string" || prop.type === "number") && prop.enum) {
921
+ const enumDbName = `${collectionTable}_${resolveColumnName(propName, prop)}`;
922
+ const values = Array.isArray(prop.enum) ? prop.enum.map((v) => String(typeof v === "object" && v !== null && "id" in v ? v.id : v)) : Object.keys(prop.enum);
923
+ if (values.length > 0 && !emittedEnums.has(`${schema}.${enumDbName}`)) {
924
+ emittedEnums.add(`${schema}.${enumDbName}`);
925
+ ddl += `CREATE TYPE "${schema}"."${enumDbName}" AS ENUM (${values.map(quoteSqlLiteral).join(", ")});\n`;
926
+ }
927
+ }
928
+ });
929
+ });
930
+ if (ddl.endsWith(";\n")) ddl += "\n";
931
+ const junctionSpecs = resolveJunctionSpecs(collections);
932
+ const allTablesToGenerate = /* @__PURE__ */ new Map();
933
+ for (const collection of collections) {
934
+ const tableName = getTableName(collection);
935
+ if (tableName) allTablesToGenerate.set(tableName, { collection });
936
+ const resolvedRelations = resolveCollectionRelations(collection);
937
+ for (const relation of Object.values(resolvedRelations)) if (isManyToMany(relation)) {
938
+ const junctionTableName = relation.through.table;
939
+ if (!allTablesToGenerate.has(junctionTableName)) allTablesToGenerate.set(junctionTableName, {
940
+ collection: {
941
+ table: junctionTableName,
942
+ properties: {}
943
+ },
944
+ isJunction: true,
945
+ relation,
946
+ sourceCollection: collection
947
+ });
948
+ }
949
+ }
950
+ const fkStatements = [];
951
+ const indexStatements = [];
952
+ const policyStatements = [];
953
+ for (const [tableName, { collection, isJunction, relation, sourceCollection }] of allTablesToGenerate.entries()) {
954
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
955
+ const baseTableName = tableName.includes(".") ? tableName.split(".").pop() : tableName;
956
+ if (isJunction && relation && sourceCollection && isManyToMany(relation)) {
957
+ const targetCollection = relation.target();
958
+ const sourceTable = getTableName(sourceCollection);
959
+ const targetTable = getTableName(targetCollection);
960
+ const sourceSchema = isPostgresCollectionConfig(sourceCollection) && sourceCollection.schema ? sourceCollection.schema : "public";
961
+ const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
962
+ const { sourceColumn, targetColumn } = relation.through;
963
+ const sourceColType = isNumericId(sourceCollection) ? "INTEGER" : getPrimaryKeyProp(sourceCollection).isUuid ? "UUID" : "TEXT";
964
+ const targetColType = isNumericId(targetCollection) ? "INTEGER" : getPrimaryKeyProp(targetCollection).isUuid ? "UUID" : "TEXT";
965
+ const sourceId = getPrimaryKeyName(sourceCollection);
966
+ const targetId = getPrimaryKeyName(targetCollection);
967
+ const onDelete = relation.onDelete ?? "CASCADE";
968
+ ddl += `CREATE TABLE "${schema}"."${baseTableName}" (\n`;
969
+ ddl += ` "${sourceColumn}" ${sourceColType} NOT NULL,\n`;
970
+ ddl += ` "${targetColumn}" ${targetColType} NOT NULL,\n`;
971
+ ddl += ` PRIMARY KEY ("${sourceColumn}", "${targetColumn}")\n`;
972
+ ddl += `);\n\n`;
973
+ fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${sourceColumn}_fkey`)}" FOREIGN KEY ("${sourceColumn}") REFERENCES "${sourceSchema}"."${sourceTable}" ("${sourceId}") ON DELETE ${onDelete.toUpperCase()};`);
974
+ fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${targetColumn}_fkey`)}" FOREIGN KEY ("${targetColumn}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDelete.toUpperCase()};`);
975
+ if (options.includePolicies) {
976
+ ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
977
+ ddl += `\n`;
978
+ const spec = junctionSpecs.get(baseTableName);
979
+ if (spec) {
980
+ const junctionCollection = getJunctionCollectionConfig(spec);
981
+ const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
982
+ getJunctionSecurityRules(spec).forEach((rule) => {
983
+ policyStatements.push(generatePolicyDdl(junctionCollection, rule, resolveCollection));
984
+ });
985
+ }
986
+ }
987
+ } else if (!isJunction) {
988
+ ddl += `CREATE TABLE "${schema}"."${baseTableName}" (\n`;
989
+ const columns = [];
990
+ Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
991
+ if (prop.type === "relation") {
992
+ const refProp = prop;
993
+ const relInfo = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
994
+ if (relInfo?.kind !== "belongsTo") return;
995
+ if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) return;
996
+ let targetCollection;
997
+ try {
998
+ targetCollection = relInfo.target();
999
+ } catch {
1000
+ return;
1001
+ }
1002
+ const targetTable = getTableName(targetCollection);
1003
+ const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
1004
+ const targetId = getPrimaryKeyName(targetCollection);
1005
+ const fkColType = getSqlColumnType(propName, prop, collection, collections);
1006
+ const onUpdate = relInfo.onUpdate ? ` ON UPDATE ${relInfo.onUpdate.toUpperCase()}` : "";
1007
+ const required = prop.validation?.required;
1008
+ const onDeleteVal = relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL");
1009
+ let colDef = ` "${relInfo.localKey}" ${fkColType}`;
1010
+ if (required) colDef += " NOT NULL";
1011
+ columns.push(colDef);
1012
+ fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${relInfo.localKey}_fkey`)}" FOREIGN KEY ("${relInfo.localKey}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDeleteVal.toUpperCase()}${onUpdate};`);
1013
+ } else if (prop.type === "reference") {
1014
+ const refProp = prop;
1015
+ const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
1016
+ const colName = resolveColumnName(propName, prop);
1017
+ const colType = getSqlColumnType(propName, prop, collection, collections);
1018
+ const required = prop.validation?.required;
1019
+ if (!targetCollection) {
1020
+ let colDef = ` "${colName}" ${colType}`;
1021
+ if (required) colDef += " NOT NULL";
1022
+ columns.push(colDef);
1023
+ } else {
1024
+ const targetTable = getTableName(targetCollection);
1025
+ const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
1026
+ const targetId = getPrimaryKeyName(targetCollection);
1027
+ const onDelete = required ? "CASCADE" : "SET NULL";
1028
+ let colDef = ` "${colName}" ${colType}`;
1029
+ if (required) colDef += " NOT NULL";
1030
+ columns.push(colDef);
1031
+ fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${colName}_fkey`)}" FOREIGN KEY ("${colName}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDelete.toUpperCase()};`);
1032
+ }
1033
+ } else {
1034
+ const colName = resolveColumnName(propName, prop);
1035
+ const authDefinition = isAuthCollection(collection) ? authUsersColumnDefinition(colName) : void 0;
1036
+ if (authDefinition && !isIdProperty(propName, prop, collection)) {
1037
+ columns.push(` "${colName}" ${authDefinition}`);
1038
+ return;
1039
+ }
1040
+ let colDef = ` "${colName}" ${getSqlColumnType(propName, prop, collection, collections)}`;
1041
+ if (isIdProperty(propName, prop, collection)) colDef += " PRIMARY KEY";
1042
+ if ("isId" in prop && prop.isId !== "manual" && prop.isId !== true && prop.isId !== "increment") {
1043
+ if (prop.isId === "uuid") colDef += " DEFAULT gen_random_uuid()";
1044
+ else if (prop.isId === "cuid") colDef += " DEFAULT cuid()";
1045
+ else if (typeof prop.isId === "string") colDef += ` DEFAULT ${prop.isId}`;
1046
+ }
1047
+ if (!isIdProperty(propName, prop, collection) && prop.validation?.unique) colDef += " UNIQUE";
1048
+ if (prop.type === "date") {
1049
+ const dateProp = prop;
1050
+ if (dateProp.autoValue === "on_create" || dateProp.autoValue === "on_update") colDef += " DEFAULT now()";
1051
+ }
1052
+ if (prop.validation?.required && !colDef.includes("PRIMARY KEY")) colDef += " NOT NULL";
1053
+ columns.push(colDef);
1054
+ }
1055
+ });
1056
+ if (isAuthCollection(collection)) {
1057
+ const declared = new Set(Object.entries(collection.properties ?? {}).map(([name, prop]) => resolveColumnName(name, prop)));
1058
+ for (const spec of AUTH_USERS_COLUMNS) {
1059
+ if (declared.has(spec.column)) continue;
1060
+ columns.push(` "${spec.column}" ${authUsersColumnSql(spec)}`);
1061
+ }
1062
+ }
1063
+ const searchSpec = options.includeSearch === false ? void 0 : buildSearchColumnSpec(collection);
1064
+ if (searchSpec) {
1065
+ columns.push(` ${searchColumnDefinition(searchSpec)}`);
1066
+ const fuzzyDef = fuzzyColumnDefinition(searchSpec);
1067
+ if (fuzzyDef) columns.push(` ${fuzzyDef}`);
1068
+ indexStatements.push(...searchIndexStatements(searchSpec));
1069
+ }
1070
+ const vectorPlan = buildVectorIndexPlan(collection, resolveColumnName);
1071
+ indexStatements.push(...vectorIndexStatements(vectorPlan));
1072
+ for (const skip of vectorPlan.skipped) indexStatements.push(`-- No ANN index on "${skip.schema}"."${skip.table}"."${skip.column}": ${skip.reason}`);
1073
+ indexStatements.push(...collectionIndexStatements(buildCollectionIndexSpecs(collection, resolveColumnName)));
1074
+ if (!columns.some((c) => c.includes("PRIMARY KEY"))) columns.unshift(" \"id\" TEXT PRIMARY KEY");
1075
+ ddl += columns.join(",\n");
1076
+ ddl += `\n);\n\n`;
1077
+ if (options.includePolicies) {
1078
+ ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
1079
+ ddl += `\n`;
1080
+ const securityRules = getEffectiveSecurityRules(collection);
1081
+ if (securityRules.length > 0) {
1082
+ const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
1083
+ securityRules.forEach((rule) => {
1084
+ policyStatements.push(generatePolicyDdl(collection, rule, resolveCollection));
1085
+ });
1086
+ }
1087
+ }
1088
+ }
1089
+ }
1090
+ if (indexStatements.length > 0) {
1091
+ ddl += "-- Indexes\n";
1092
+ ddl += indexStatements.join("\n") + "\n\n";
1093
+ }
1094
+ if (fkStatements.length > 0) {
1095
+ ddl += "-- Foreign Key Constraints\n";
1096
+ ddl += fkStatements.join("\n") + "\n\n";
1097
+ }
1098
+ if (policyStatements.length > 0) {
1099
+ ddl += "-- Row Level Security Policies\n";
1100
+ ddl += policyStatements.join("");
1101
+ ddl += "\n";
1102
+ }
1103
+ return ddl;
1104
+ };
1105
+ var schemaOfCollection = (collection) => isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
1106
+ var bareTableName = (name) => name.includes(".") ? name.split(".").pop() : name;
1107
+ /**
1108
+ * Truncate a derived identifier the way Postgres does: to 63 bytes, silently.
1109
+ *
1110
+ * This is not cosmetic, and not really a naming choice at all — it is agreeing
1111
+ * with the name the database ALREADY stored. `ADD CONSTRAINT` on a longer name
1112
+ * succeeds and records the truncated form, so the untruncated name this used to
1113
+ * derive matched nothing in the catalogue. Boot-ensure compares its planned
1114
+ * constraints against `readExistingSchema`, which reads catalogue names, so the
1115
+ * comparison could never hit: every boot re-issued `ADD CONSTRAINT` for the same
1116
+ * constraint, forever, and got "already exists" every time. Non-fatal (foreign
1117
+ * keys are the one action allowed to fail) and therefore permanent — an error in
1118
+ * the log on every restart of a project whose table and column names happened to
1119
+ * be long.
1120
+ *
1121
+ * Byte length, not string length: NAMEDATALEN is 64 bytes, and a multi-byte
1122
+ * character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.
1123
+ */
1124
+ var foreignKeyPlan = (args) => {
1125
+ const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);
1126
+ const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : "";
1127
+ return {
1128
+ constraintName,
1129
+ schema: args.schema,
1130
+ table: args.table,
1131
+ column: args.column,
1132
+ targetSchema: args.targetSchema,
1133
+ targetTable: args.targetTable,
1134
+ targetColumn: args.targetColumn,
1135
+ sql: `ALTER TABLE "${args.schema}"."${args.table}" ADD CONSTRAINT "${constraintName}" FOREIGN KEY ("${args.column}") REFERENCES "${args.targetSchema}"."${args.targetTable}" ("${args.targetColumn}") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate};`
1136
+ };
1137
+ };
1138
+ /**
1139
+ * The FK columns the declared collections own — one entry per `relation`
1140
+ * (`belongsTo` side) or `reference` property.
1141
+ *
1142
+ * Split out of {@link generatePostgresDdl} so the boot-time schema ensure can
1143
+ * create the same columns with the same names, types and constraints. Before
1144
+ * this it skipped them outright, which was survivable only because `db push`
1145
+ * always followed; on a managed tenant nothing follows, so a table arrived
1146
+ * without the column its own collection reads and wrote 400 on every insert.
1147
+ *
1148
+ * A relation whose target is not in the bundle yields no column at all (the
1149
+ * generator returns early on an unresolvable target); a `reference` whose target
1150
+ * is unknown yields the column without a constraint. Both mirror the generator
1151
+ * exactly — a divergence here is a schema fork between boot and `db push`.
1152
+ */
1153
+ var planRelationalColumns = (allCollections) => {
1154
+ const collections = relationalCollections(allCollections);
1155
+ const plans = [];
1156
+ for (const collection of collections) {
1157
+ const tableName = getTableName(collection);
1158
+ if (!tableName) continue;
1159
+ const schema = schemaOfCollection(collection);
1160
+ const table = bareTableName(tableName);
1161
+ for (const [propName, rawProp] of Object.entries(collection.properties ?? {})) {
1162
+ const prop = rawProp;
1163
+ if (prop.type === "relation") {
1164
+ const refProp = prop;
1165
+ const relInfo = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
1166
+ if (relInfo?.kind !== "belongsTo") continue;
1167
+ if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) continue;
1168
+ let targetCollection;
1169
+ try {
1170
+ targetCollection = relInfo.target();
1171
+ } catch {
1172
+ continue;
1173
+ }
1174
+ if (!targetCollection) continue;
1175
+ const required = prop.validation?.required;
1176
+ const relationName = refProp.relation?.relationName ?? propName;
1177
+ const legacyKey = legacyForeignKeyName(relationName);
1178
+ const derived = relInfo.localKey === generateForeignKeyName(relationName);
1179
+ plans.push({
1180
+ schema,
1181
+ table,
1182
+ column: relInfo.localKey,
1183
+ legacyColumn: derived && legacyKey !== relInfo.localKey ? legacyKey : void 0,
1184
+ type: getSqlColumnType(propName, prop, collection, collections),
1185
+ foreignKey: foreignKeyPlan({
1186
+ schema,
1187
+ table,
1188
+ column: relInfo.localKey,
1189
+ targetSchema: schemaOfCollection(targetCollection),
1190
+ targetTable: bareTableName(getTableName(targetCollection)),
1191
+ targetColumn: getPrimaryKeyName(targetCollection),
1192
+ onDelete: relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL"),
1193
+ onUpdate: relInfo.onUpdate
1194
+ })
1195
+ });
1196
+ } else if (prop.type === "reference") {
1197
+ const refProp = prop;
1198
+ const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
1199
+ const column = resolveColumnName(propName, prop);
1200
+ const type = getSqlColumnType(propName, prop, collection, collections);
1201
+ const required = prop.validation?.required;
1202
+ plans.push({
1203
+ schema,
1204
+ table,
1205
+ column,
1206
+ type,
1207
+ foreignKey: targetCollection ? foreignKeyPlan({
1208
+ schema,
1209
+ table,
1210
+ column,
1211
+ targetSchema: schemaOfCollection(targetCollection),
1212
+ targetTable: bareTableName(getTableName(targetCollection)),
1213
+ targetColumn: getPrimaryKeyName(targetCollection),
1214
+ onDelete: required ? "CASCADE" : "SET NULL"
1215
+ }) : void 0
1216
+ });
1217
+ }
1218
+ }
1219
+ }
1220
+ return plans;
1221
+ };
1222
+ /**
1223
+ * The junction tables a bundle's many-to-many relations imply.
1224
+ *
1225
+ * Derived from {@link resolveJunctionSpecs}, the same source the junction RLS
1226
+ * comes from, so a table created here always has policies planned for it — a
1227
+ * junction with row-level security left off is readable and writable by every
1228
+ * signed-in user, which is why the two must ship together.
1229
+ */
1230
+ var planJunctionTables = (allCollections) => {
1231
+ const collections = relationalCollections(allCollections);
1232
+ const plans = [];
1233
+ for (const spec of resolveJunctionSpecs(collections).values()) {
1234
+ const [source, target] = spec.endpoints;
1235
+ const legacyFor = (endpoint) => {
1236
+ const slug = toSnakeCase(endpoint.collection.slug ?? endpoint.collection.name ?? "");
1237
+ const legacy = legacyForeignKeyName(slug);
1238
+ return endpoint.junctionColumn === generateForeignKeyName(slug) && legacy !== endpoint.junctionColumn ? legacy : void 0;
1239
+ };
1240
+ const columns = [{
1241
+ name: source.junctionColumn,
1242
+ type: junctionKeyType(source.collection),
1243
+ legacyName: legacyFor(source)
1244
+ }, {
1245
+ name: target.junctionColumn,
1246
+ type: junctionKeyType(target.collection),
1247
+ legacyName: legacyFor(target)
1248
+ }];
1249
+ const onDelete = spec.declaringSides[0]?.relation.onDelete ?? "CASCADE";
1250
+ plans.push({
1251
+ schema: spec.schema,
1252
+ table: spec.table,
1253
+ columns,
1254
+ createTable: `CREATE TABLE IF NOT EXISTS "${spec.schema}"."${spec.table}" (` + columns.map((c) => `"${c.name}" ${c.type} NOT NULL`).join(", ") + `, PRIMARY KEY (${columns.map((c) => `"${c.name}"`).join(", ")}));`,
1255
+ foreignKeys: [source, target].map((endpoint, i) => foreignKeyPlan({
1256
+ schema: spec.schema,
1257
+ table: spec.table,
1258
+ column: columns[i].name,
1259
+ targetSchema: schemaOfCollection(endpoint.collection),
1260
+ targetTable: bareTableName(getTableName(endpoint.collection)),
1261
+ targetColumn: getPrimaryKeyName(endpoint.collection),
1262
+ onDelete
1263
+ }))
1264
+ });
1265
+ }
1266
+ return plans;
1267
+ };
1268
+ /**
1269
+ * The per-table RLS plan for the *declared* collections, as executable
1270
+ * statements — what the managed runtime applies at boot so a freshly
1271
+ * provisioned tenant database serves data instead of 401ing every read.
1272
+ *
1273
+ * Mirrors {@link generatePostgresPoliciesDdl} exactly (same
1274
+ * `generatePolicyStatements`, same enable-RLS, same effective rules, same
1275
+ * derived junction rules), so boot and `db push` produce identical policies from
1276
+ * identical collections.
1277
+ *
1278
+ * Junction tables are included, and have to be: boot creates them now
1279
+ * ({@link planJunctionTables}), and a junction with RLS left off is readable and
1280
+ * writable by every signed-in user. A junction whose table is still absent is
1281
+ * skipped by the applier, not planned away here.
1282
+ */
1283
+ var planCollectionPolicies = (allCollections) => {
1284
+ const collections = relationalCollections(allCollections);
1285
+ const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
1286
+ const plans = [];
1287
+ const seen = /* @__PURE__ */ new Set();
1288
+ for (const collection of collections) {
1289
+ const tableName = getTableName(collection);
1290
+ if (!tableName) continue;
1291
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
1292
+ const baseTableName = tableName.includes(".") ? tableName.split(".").pop() : tableName;
1293
+ const qualified = `${schema}.${baseTableName}`;
1294
+ if (seen.has(qualified)) continue;
1295
+ seen.add(qualified);
1296
+ const policyStatements = [];
1297
+ for (const rule of getEffectiveSecurityRules(collection)) policyStatements.push(...generatePolicyStatements(collection, rule, resolveCollection));
1298
+ plans.push({
1299
+ schema,
1300
+ table: baseTableName,
1301
+ qualified,
1302
+ enableRls: `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;`,
1303
+ policyStatements
1304
+ });
1305
+ }
1306
+ for (const spec of resolveJunctionSpecs(collections).values()) {
1307
+ const qualified = `${spec.schema}.${spec.table}`;
1308
+ if (seen.has(qualified)) continue;
1309
+ seen.add(qualified);
1310
+ const junctionCollection = getJunctionCollectionConfig(spec);
1311
+ const policyStatements = [];
1312
+ for (const rule of getJunctionSecurityRules(spec)) policyStatements.push(...generatePolicyStatements(junctionCollection, rule, resolveCollection));
1313
+ plans.push({
1314
+ schema: spec.schema,
1315
+ table: spec.table,
1316
+ qualified,
1317
+ enableRls: `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;`,
1318
+ policyStatements
1319
+ });
1320
+ }
1321
+ return plans;
1322
+ };
1323
+ var generatePostgresPoliciesDdl = (allCollections) => {
1324
+ const collections = relationalCollections(allCollections);
1325
+ let ddl = "-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\n\n";
1326
+ const allTablesToGenerate = /* @__PURE__ */ new Map();
1327
+ for (const collection of collections) {
1328
+ const tableName = getTableName(collection);
1329
+ if (tableName) allTablesToGenerate.set(tableName, { collection });
1330
+ }
1331
+ for (const [tableName, { collection }] of allTablesToGenerate.entries()) {
1332
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
1333
+ const baseTableName = tableName.includes(".") ? tableName.split(".").pop() : tableName;
1334
+ ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
1335
+ ddl += `\n`;
1336
+ const securityRules = getEffectiveSecurityRules(collection);
1337
+ if (securityRules.length > 0) {
1338
+ const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
1339
+ const injectedNames = new Set(getInjectedSecurityRules(collection).map((rule) => rule.name));
1340
+ securityRules.forEach((rule) => {
1341
+ if (rule.name && injectedNames.has(rule.name)) {
1342
+ ddl += `-- Injected by Rebase (not from this collection's securityRules).\n`;
1343
+ ddl += `-- Set \`disableDefaultPolicies: true\` on "${collection.slug}" to drop these and own its RLS outright.\n`;
1344
+ }
1345
+ ddl += generatePolicyDdl(collection, rule, resolveCollection);
1346
+ });
1347
+ ddl += "\n";
1348
+ }
1349
+ }
1350
+ const junctionSpecs = resolveJunctionSpecs(collections);
1351
+ for (const spec of junctionSpecs.values()) {
1352
+ ddl += `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;\n`;
1353
+ ddl += `\n`;
1354
+ const junctionRules = getJunctionSecurityRules(spec);
1355
+ if (junctionRules.length === 0) continue;
1356
+ const junctionCollection = getJunctionCollectionConfig(spec);
1357
+ const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
1358
+ const declaringSlugs = spec.declaringSides.map((s) => s.collection.slug).join("\", \"");
1359
+ ddl += `-- Derived by Rebase for the junction "${spec.table}" (no collection declares it).\n`;
1360
+ ddl += `-- Reads require both endpoint rows to be visible; writes follow the update\n`;
1361
+ ddl += `-- rules of "${declaringSlugs}". Set \`disableDefaultPolicies: true\` on the\n`;
1362
+ ddl += `-- declaring collection(s) to drop these and police the junction yourself.\n`;
1363
+ junctionRules.forEach((rule) => {
1364
+ ddl += generatePolicyDdl(junctionCollection, rule, resolveCollection);
1365
+ });
1366
+ ddl += "\n";
1367
+ }
1368
+ return ddl;
1369
+ };
1370
+ //#endregion
1371
+ //#region src/schema/ensure-collection-tables.ts
1372
+ /**
1373
+ * Bringing a database up to date with a bundle's collections, additively.
1374
+ *
1375
+ * ## Why this exists
1376
+ *
1377
+ * A managed runtime boots someone else's compiled project against a database it
1378
+ * has never seen. Auth tables are ensured at boot already, but collection tables
1379
+ * were not created by anything: the platform ran the app and every `/api/data/*`
1380
+ * request answered 500 on a missing relation. `rebase db push` cannot help — it
1381
+ * is an Atlas-driven CLI command, and the runtime image ships no CLI.
1382
+ *
1383
+ * ## Why additive-only, forever
1384
+ *
1385
+ * This runs unattended, against a database with customers' data in it, with no
1386
+ * human reading a diff. So it may only ever do things that cannot lose data:
1387
+ * create a missing table, add a missing column, create a missing enum type.
1388
+ *
1389
+ * It will **never** drop a table or a column, narrow a type, or alter a
1390
+ * constraint. A removed field leaves its column behind; a renamed field looks
1391
+ * like an addition and the old column stays. That is the correct trade for an
1392
+ * automated path — the alternative is an unattended process that can silently
1393
+ * destroy a column, which is precisely the failure `db push` was hardened
1394
+ * against. Destructive changes stay a deliberate, human-reviewed migration.
1395
+ *
1396
+ * Because of that, this is safe to run on every boot, and re-running it is a
1397
+ * no-op.
1398
+ */
1399
+ var ensure_collection_tables_exports = /* @__PURE__ */ __exportAll({
1400
+ ensureCollectionTables: () => ensureCollectionTables,
1401
+ planCollectionSchemaEnsure: () => planCollectionSchemaEnsure,
1402
+ readExistingSchema: () => readExistingSchema,
1403
+ readSchemaFactsFor: () => readSchemaFactsFor
1404
+ });
1405
+ /** Postgres identifiers this module is willing to interpolate. */
1406
+ var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
1407
+ function assertSafeIdentifier(value, what) {
1408
+ if (!SAFE_IDENTIFIER.test(value)) throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);
1409
+ return value;
1410
+ }
1411
+ function schemaOf(collection) {
1412
+ return isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
1413
+ }
1414
+ function qualified(collection) {
1415
+ return `${schemaOf(collection)}.${getTableName(collection)}`;
1416
+ }
1417
+ /**
1418
+ * Enum types a collection's properties require, as `schema.typename`.
1419
+ *
1420
+ * Named exactly as the DDL generator names them (`<table>_<column>`), because
1421
+ * a column added here has to reference the same type the generator would have
1422
+ * created — a second, differently-named type for the same field would be a
1423
+ * silent schema fork.
1424
+ */
1425
+ function requiredEnums(collection) {
1426
+ const table = getTableName(collection);
1427
+ const schema = schemaOf(collection);
1428
+ const out = [];
1429
+ for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
1430
+ const p = prop;
1431
+ if (!("enum" in p) || !p.enum) continue;
1432
+ if (p.type !== "string" && p.type !== "number") continue;
1433
+ const values = p.enum.map((entry) => entry && typeof entry === "object" && "id" in entry ? String(entry.id) : String(entry)).filter((v) => v.length > 0);
1434
+ if (values.length === 0) continue;
1435
+ out.push({
1436
+ name: `${schema}.${table}_${resolveColumnName(propName, p)}`,
1437
+ values
1438
+ });
1439
+ }
1440
+ return out;
1441
+ }
1442
+ /**
1443
+ * Decide what to add. Pure — the caller supplies what exists and runs the result.
1444
+ *
1445
+ * Ordering matters and is deliberate: enum types before the tables and columns
1446
+ * that reference them, tables before the columns added to other tables (a new
1447
+ * table may be the target of a relation), and nothing is emitted twice.
1448
+ */
1449
+ function planCollectionSchemaEnsure(allCollections, existing, options = {}) {
1450
+ const constraintPolicy = options.constraints ?? "additive";
1451
+ const withheldConstraints = [];
1452
+ assertSearchIsPostgresOnly(allCollections);
1453
+ const collections = relationalCollections(allCollections);
1454
+ const actions = [];
1455
+ const plannedEnums = /* @__PURE__ */ new Set();
1456
+ for (const collection of collections) for (const { name, values } of requiredEnums(collection)) {
1457
+ if (existing.enums.has(name) || plannedEnums.has(name)) {
1458
+ const current = existing.enumValues?.get(name);
1459
+ if (!current || plannedEnums.has(name)) continue;
1460
+ const [schema, typeName] = name.split(".");
1461
+ for (const value of values) {
1462
+ if (current.includes(value)) continue;
1463
+ actions.push({
1464
+ kind: "add-enum-value",
1465
+ target: `${name}.${value}`,
1466
+ sql: `ALTER TYPE "${schema}"."${typeName}" ADD VALUE IF NOT EXISTS ${quoteSqlLiteral(value)};`
1467
+ });
1468
+ }
1469
+ continue;
1470
+ }
1471
+ plannedEnums.add(name);
1472
+ const [schema, typeName] = name.split(".");
1473
+ actions.push({
1474
+ kind: "create-enum",
1475
+ target: name,
1476
+ sql: `CREATE TYPE "${schema}"."${typeName}" AS ENUM (${values.map(quoteSqlLiteral).join(", ")});`
1477
+ });
1478
+ }
1479
+ const searchSpecs = collections.map((c) => buildSearchColumnSpec(c)).filter((spec) => spec !== void 0);
1480
+ const plannedExtensions = /* @__PURE__ */ new Set();
1481
+ for (const spec of searchSpecs) for (const statement of searchExtensionStatements(spec)) {
1482
+ if (plannedExtensions.has(statement)) continue;
1483
+ plannedExtensions.add(statement);
1484
+ actions.push({
1485
+ kind: "create-extension",
1486
+ target: statement.replace(/^CREATE EXTENSION IF NOT EXISTS |;$/g, ""),
1487
+ sql: statement
1488
+ });
1489
+ }
1490
+ const plannedFunctions = /* @__PURE__ */ new Set();
1491
+ for (const spec of searchSpecs) for (const statement of searchHelperFunctions(spec)) {
1492
+ if (plannedFunctions.has(statement)) continue;
1493
+ plannedFunctions.add(statement);
1494
+ actions.push({
1495
+ kind: "create-function",
1496
+ target: statement.includes("unaccent") ? SEARCH_UNACCENT_FN : SEARCH_TEXT_FN,
1497
+ sql: statement
1498
+ });
1499
+ }
1500
+ const created = /* @__PURE__ */ new Set();
1501
+ for (const collection of collections) {
1502
+ const key = qualified(collection);
1503
+ if (existing.tables.has(key) || created.has(key)) continue;
1504
+ created.add(key);
1505
+ const schema = schemaOf(collection);
1506
+ const table = getTableName(collection);
1507
+ const idEntry = Object.entries(collection.properties ?? {}).find(([n, p]) => isIdProperty(n, p, collection));
1508
+ const idName = idEntry ? resolveColumnName(idEntry[0], idEntry[1]) : "id";
1509
+ const idProp = idEntry?.[1];
1510
+ let idDef = `"${idName}" ${idProp ? getSqlColumnType(idEntry[0], idProp, collection, collections) : "TEXT"} PRIMARY KEY`;
1511
+ if (idProp?.type === "string" && idProp.isId === "uuid") idDef += " DEFAULT gen_random_uuid()";
1512
+ actions.push({
1513
+ kind: "create-table",
1514
+ target: key,
1515
+ sql: `CREATE TABLE IF NOT EXISTS "${schema}"."${table}" (${idDef});`
1516
+ });
1517
+ }
1518
+ const junctions = planJunctionTables(collections);
1519
+ for (const junction of junctions) {
1520
+ const key = `${junction.schema}.${junction.table}`;
1521
+ if (existing.tables.has(key) || created.has(key)) continue;
1522
+ created.add(key);
1523
+ actions.push({
1524
+ kind: "create-table",
1525
+ target: key,
1526
+ sql: junction.createTable
1527
+ });
1528
+ }
1529
+ const legacyForeignKeys = [];
1530
+ /**
1531
+ * Move a relation column that is only missing because it was renamed.
1532
+ *
1533
+ * Returns true when it handled the column, so the caller skips the ordinary
1534
+ * ADD. Adding here would be the wrong move and a quiet one: the data is in
1535
+ * the old column, `ADD COLUMN` creates the new one empty beside it, every
1536
+ * statement succeeds, and the relation reads the empty one. A rename is
1537
+ * metadata-only in Postgres, keeps the values, and carries the column's
1538
+ * indexes and constraints with it.
1539
+ *
1540
+ * Only ever reached when the new name is absent and the old name is
1541
+ * present, so there is nothing to overwrite and nothing to choose between.
1542
+ */
1543
+ const renameLegacyColumn = (key, schema, table, column, legacyName) => {
1544
+ const present = existing.tables.get(key);
1545
+ if (!legacyName || !present) return false;
1546
+ if (present.has(column) || !present.has(legacyName)) return false;
1547
+ legacyForeignKeys.push({
1548
+ table: key,
1549
+ expected: column,
1550
+ legacy: legacyName
1551
+ });
1552
+ actions.push({
1553
+ kind: "rename-column",
1554
+ target: `${key}.${column}`,
1555
+ sql: `ALTER TABLE "${schema}"."${table}" RENAME COLUMN "${legacyName}" TO "${column}";`
1556
+ });
1557
+ return true;
1558
+ };
1559
+ const addColumn = (key, schema, table, column, definition) => {
1560
+ if (existing.tables.get(key)?.has(column)) return;
1561
+ actions.push({
1562
+ kind: "add-column",
1563
+ target: `${key}.${column}`,
1564
+ sql: `ALTER TABLE "${schema}"."${table}" ADD COLUMN IF NOT EXISTS "${column}" ${definition};`
1565
+ });
1566
+ };
1567
+ for (const collection of collections) {
1568
+ const key = qualified(collection);
1569
+ const schema = schemaOf(collection);
1570
+ const table = getTableName(collection);
1571
+ const fresh = created.has(key);
1572
+ const auth = isAuthCollection(collection);
1573
+ for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
1574
+ const p = prop;
1575
+ if (isIdProperty(propName, p, collection)) continue;
1576
+ if (p.type === "reference" || p.type === "relation") continue;
1577
+ const column = resolveColumnName(propName, p);
1578
+ const authDefinition = auth ? authUsersColumnDefinition(column) : void 0;
1579
+ if (authDefinition) {
1580
+ addColumn(key, schema, table, column, authDefinition);
1581
+ continue;
1582
+ }
1583
+ let definition = getSqlColumnType(propName, p, collection, collections);
1584
+ if (fresh && p.validation?.unique) definition += " UNIQUE";
1585
+ const autoValue = p.autoValue;
1586
+ const hasDefault = p.type === "date" && (autoValue === "on_create" || autoValue === "on_update");
1587
+ if (hasDefault) definition += " DEFAULT now()";
1588
+ const required = p.validation?.required === true;
1589
+ const columnKey = `${key}.${column}`;
1590
+ const columnExists = existing.tables.get(key)?.has(column) === true;
1591
+ const tableIsEmpty = existing.populatedTables !== void 0 && existing.tables.has(key) && !existing.populatedTables.has(key);
1592
+ const notNullIsSafe = fresh || tableIsEmpty || hasDefault;
1593
+ if (required && !columnExists) if (notNullIsSafe) definition += " NOT NULL";
1594
+ else withheldConstraints.push({
1595
+ target: columnKey,
1596
+ kind: "not-null",
1597
+ reason: `"${column}" is required, but "${key}" already holds rows and the column has no default to backfill them with, so NOT NULL would be checked against data that does not have a value yet.`,
1598
+ remedy: "Backfill the column, then add the constraint — or give the property a default so every existing row gets one."
1599
+ });
1600
+ addColumn(key, schema, table, column, definition);
1601
+ if (columnExists && constraintPolicy === "converge") {
1602
+ const isNotNull = existing.notNullColumns?.has(columnKey) === true;
1603
+ if (required && !isNotNull) if (tableIsEmpty) actions.push({
1604
+ kind: "set-not-null",
1605
+ target: columnKey,
1606
+ sql: `ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${column}" SET NOT NULL;`
1607
+ });
1608
+ else withheldConstraints.push({
1609
+ target: columnKey,
1610
+ kind: "not-null",
1611
+ reason: `"${column}" became required, but "${key}" holds rows and any of them with no value would make SET NOT NULL fail.`,
1612
+ remedy: "Backfill the column first — `UPDATE … SET \"" + column + "\" = … WHERE \"" + column + "\" IS NULL` — then apply this again."
1613
+ });
1614
+ if (!required && isNotNull) actions.push({
1615
+ kind: "drop-not-null",
1616
+ target: columnKey,
1617
+ sql: `ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${column}" DROP NOT NULL;`
1618
+ });
1619
+ }
1620
+ }
1621
+ if (auth) {
1622
+ const declared = new Set(Object.entries(collection.properties ?? {}).map(([name, prop]) => resolveColumnName(name, prop)));
1623
+ for (const spec of AUTH_USERS_COLUMNS) {
1624
+ if (declared.has(spec.column)) continue;
1625
+ addColumn(key, schema, table, spec.column, authUsersColumnSql(spec));
1626
+ }
1627
+ }
1628
+ }
1629
+ const searchDrift = [];
1630
+ const searchAdopted = [];
1631
+ for (const spec of searchSpecs) {
1632
+ const key = `${spec.schema}.${spec.table}`;
1633
+ const definitions = { [spec.column]: `tsvector GENERATED ALWAYS AS (${spec.expression}) STORED` };
1634
+ if (spec.fuzzy) definitions[spec.fuzzy.column] = `text GENERATED ALWAYS AS (${spec.fuzzy.expression}) STORED`;
1635
+ for (const stamp of searchColumnStamps(spec)) {
1636
+ const definition = definitions[stamp.column];
1637
+ const exists = existing.tables.get(key)?.has(stamp.column) === true;
1638
+ const recorded = existing.columnComments?.get(`${key}.${stamp.column}`);
1639
+ if (exists && recorded?.startsWith("rebase:search:v1:") && recorded !== stamp.fingerprint) {
1640
+ searchDrift.push({
1641
+ table: key,
1642
+ column: stamp.column,
1643
+ found: recorded,
1644
+ expected: stamp.fingerprint,
1645
+ rebuild: [
1646
+ `ALTER TABLE "${spec.schema}"."${spec.table}" DROP COLUMN "${stamp.column}";`,
1647
+ `ALTER TABLE "${spec.schema}"."${spec.table}" ADD COLUMN "${stamp.column}" ${definition};`,
1648
+ stamp.sql
1649
+ ]
1650
+ });
1651
+ continue;
1652
+ }
1653
+ addColumn(key, spec.schema, spec.table, stamp.column, definition);
1654
+ if (exists && recorded === void 0) searchAdopted.push({
1655
+ table: key,
1656
+ column: stamp.column
1657
+ });
1658
+ if (recorded !== stamp.fingerprint) actions.push({
1659
+ kind: "comment-column",
1660
+ target: `${key}.${stamp.column}`,
1661
+ sql: stamp.sql
1662
+ });
1663
+ }
1664
+ }
1665
+ for (const junction of junctions) {
1666
+ const key = `${junction.schema}.${junction.table}`;
1667
+ if (created.has(key)) continue;
1668
+ for (const column of junction.columns) {
1669
+ if (renameLegacyColumn(key, junction.schema, junction.table, column.name, column.legacyName)) continue;
1670
+ addColumn(key, junction.schema, junction.table, column.name, column.type);
1671
+ }
1672
+ }
1673
+ for (const relational of planRelationalColumns(collections)) {
1674
+ const relKey = `${relational.schema}.${relational.table}`;
1675
+ if (renameLegacyColumn(relKey, relational.schema, relational.table, relational.column, relational.legacyColumn)) continue;
1676
+ addColumn(relKey, relational.schema, relational.table, relational.column, relational.type);
1677
+ }
1678
+ const knownConstraints = existing.constraints ?? /* @__PURE__ */ new Set();
1679
+ const plannedConstraints = /* @__PURE__ */ new Set();
1680
+ const foreignKeys = [...planRelationalColumns(collections).map((r) => r.foreignKey), ...junctions.flatMap((j) => j.foreignKeys)];
1681
+ for (const fk of foreignKeys) {
1682
+ if (!fk) continue;
1683
+ const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;
1684
+ if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;
1685
+ plannedConstraints.add(name);
1686
+ actions.push({
1687
+ kind: "add-constraint",
1688
+ target: `${fk.schema}.${fk.table}.${fk.constraintName}`,
1689
+ sql: fk.sql
1690
+ });
1691
+ }
1692
+ for (const spec of searchSpecs) for (const statement of searchIndexStatements(spec)) actions.push({
1693
+ kind: "create-index",
1694
+ target: `${spec.schema}.${spec.table}`,
1695
+ sql: statement.replace("CREATE INDEX IF NOT EXISTS", "CREATE INDEX CONCURRENTLY IF NOT EXISTS")
1696
+ });
1697
+ const vectorIndexSkipped = [];
1698
+ for (const collection of collections) {
1699
+ const plan = buildVectorIndexPlan(collection, resolveColumnName);
1700
+ for (const spec of plan.specs) actions.push({
1701
+ kind: "create-index",
1702
+ target: `${spec.schema}.${spec.table}`,
1703
+ sql: vectorIndexStatement(spec).replace("CREATE INDEX IF NOT EXISTS", "CREATE INDEX CONCURRENTLY IF NOT EXISTS")
1704
+ });
1705
+ vectorIndexSkipped.push(...plan.skipped);
1706
+ }
1707
+ for (const spec of buildCollectionIndexPlan(collections, resolveColumnName)) actions.push({
1708
+ kind: "create-index",
1709
+ target: `${spec.schema}.${spec.table}`,
1710
+ sql: collectionIndexStatement(spec, {
1711
+ concurrently: true,
1712
+ ifNotExists: true
1713
+ })
1714
+ });
1715
+ return {
1716
+ actions,
1717
+ statements: actions.map((a) => a.sql),
1718
+ legacyForeignKeys,
1719
+ searchDrift,
1720
+ searchAdopted,
1721
+ vectorIndexSkipped,
1722
+ withheldConstraints
1723
+ };
1724
+ }
1725
+ /** Read what the database has, for the schemas the collections live in. */
1726
+ async function readExistingSchema(client, schemas) {
1727
+ const tables = /* @__PURE__ */ new Map();
1728
+ const enums = /* @__PURE__ */ new Set();
1729
+ if (schemas.length === 0) return {
1730
+ tables,
1731
+ enums
1732
+ };
1733
+ const inList = schemas.map((schema) => `'${assertSafeIdentifier(schema, "schema name")}'`).join(", ");
1734
+ const notNullColumns = /* @__PURE__ */ new Set();
1735
+ const { rows: columns } = await client.query(`SELECT table_schema, table_name, column_name, is_nullable
1736
+ FROM information_schema.columns
1737
+ WHERE table_schema IN (${inList})`);
1738
+ for (const row of columns) {
1739
+ const key = `${row.table_schema}.${row.table_name}`;
1740
+ if (!tables.has(key)) tables.set(key, /* @__PURE__ */ new Set());
1741
+ tables.get(key).add(row.column_name);
1742
+ if (row.is_nullable === "NO") notNullColumns.add(`${key}.${row.column_name}`);
1743
+ }
1744
+ const populatedTables = /* @__PURE__ */ new Set();
1745
+ const { rows: realTables } = await client.query(`SELECT n.nspname AS schema, c.relname AS name
1746
+ FROM pg_class c
1747
+ JOIN pg_namespace n ON c.relnamespace = n.oid
1748
+ WHERE c.relkind IN ('r', 'p') AND n.nspname IN (${inList})`);
1749
+ if (realTables.length > 0) {
1750
+ const probes = realTables.map((row) => {
1751
+ const schema = assertSafeIdentifier(row.schema, "schema name");
1752
+ const table = assertSafeIdentifier(row.name, "table name");
1753
+ return `SELECT ${quoteSqlLiteral(`${schema}.${table}`)} AS key, EXISTS(SELECT 1 FROM "${schema}"."${table}" LIMIT 1) AS populated`;
1754
+ });
1755
+ const { rows: populationRows } = await client.query(probes.join(" UNION ALL "));
1756
+ for (const row of populationRows) if (row.populated) populatedTables.add(row.key);
1757
+ }
1758
+ const enumValues = /* @__PURE__ */ new Map();
1759
+ const { rows: enumValueRows } = await client.query(`SELECT n.nspname AS schema, t.typname AS name, e.enumlabel AS value
1760
+ FROM pg_enum e
1761
+ JOIN pg_type t ON e.enumtypid = t.oid
1762
+ JOIN pg_namespace n ON t.typnamespace = n.oid
1763
+ WHERE n.nspname IN (${inList})
1764
+ ORDER BY t.typname, e.enumsortorder`);
1765
+ for (const row of enumValueRows) {
1766
+ const key = `${row.schema}.${row.name}`;
1767
+ if (!enumValues.has(key)) enumValues.set(key, []);
1768
+ enumValues.get(key).push(row.value);
1769
+ }
1770
+ const { rows: enumRows } = await client.query(`SELECT n.nspname AS schema, t.typname AS name
1771
+ FROM pg_type t
1772
+ JOIN pg_namespace n ON t.typnamespace = n.oid
1773
+ WHERE t.typtype = 'e' AND n.nspname IN (${inList})`);
1774
+ for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);
1775
+ const constraints = /* @__PURE__ */ new Set();
1776
+ const { rows: constraintRows } = await client.query(`SELECT n.nspname AS schema, c.relname AS table, con.conname AS name
1777
+ FROM pg_constraint con
1778
+ JOIN pg_class c ON con.conrelid = c.oid
1779
+ JOIN pg_namespace n ON c.relnamespace = n.oid
1780
+ WHERE n.nspname IN (${inList})`);
1781
+ for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);
1782
+ const columnComments = /* @__PURE__ */ new Map();
1783
+ const { rows: commentRows } = await client.query(`SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, d.description AS comment
1784
+ FROM pg_description d
1785
+ JOIN pg_class c ON d.objoid = c.oid
1786
+ JOIN pg_namespace n ON c.relnamespace = n.oid
1787
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid
1788
+ WHERE d.objsubid > 0 AND n.nspname IN (${inList})`);
1789
+ for (const row of commentRows) {
1790
+ if (row.comment == null) continue;
1791
+ columnComments.set(`${row.schema}.${row.table}.${row.column}`, row.comment);
1792
+ }
1793
+ return {
1794
+ tables,
1795
+ enums,
1796
+ constraints,
1797
+ columnComments,
1798
+ enumValues,
1799
+ notNullColumns,
1800
+ populatedTables
1801
+ };
1802
+ }
1803
+ /**
1804
+ * What to tell an operator whose `search` block no longer matches its column.
1805
+ *
1806
+ * Every line here is doing work: naming the collection is not enough, because
1807
+ * the symptom (a search that finds nothing) points at the data, not the schema;
1808
+ * and the remediation has to be exact, because it is a table rewrite the
1809
+ * operator is being asked to schedule rather than discover.
1810
+ */
1811
+ function searchDriftMessage(drift) {
1812
+ return "The `search` block changed after its generated column was created, and Postgres cannot alter a generated expression in place.\nRebase will not rebuild it for you: dropping and re-adding a STORED generated column rewrites the whole table under an ACCESS EXCLUSIVE lock and rebuilds its GIN index, which is an outage this unattended path may not schedule on your behalf.\nUntil it is rebuilt the column keeps indexing the previous fields, weights and language — searches for anything added since return nothing, which reads from outside as \"no such row\".\nRun these (or revert the block to what the column was built from), then boot again:\n" + drift.map((d) => ` "${d.table}"."${d.column}" was generated from a different \`search\` block (recorded ${d.found}, current ${d.expected}).\n` + d.rebuild.map((s) => ` ${s}`).join("\n")).join("\n") + "\n The GIN index is dropped with the column and recreated concurrently on the next boot.";
1813
+ }
1814
+ /**
1815
+ * The missing-pgvector explanation, appended to the error that reveals it.
1816
+ *
1817
+ * A `{ type: "vector" }` property compiles to `VECTOR(n)`, and nothing in the
1818
+ * OSS pipeline installs pgvector — not this ensure, not `db push`. Installing
1819
+ * an extension on someone's database is a decision with a deployment behind it
1820
+ * (image, superuser, cloud allow-list), so this path stays a refusal; what it
1821
+ * must not stay is a bare `type "vector" does not exist` on a crash-looping
1822
+ * pod, which names nothing the reader can act on.
1823
+ *
1824
+ * The scaffold now ships `pgvector/pgvector:pg18`, so this is reached by a
1825
+ * project pointed at a database someone else provisioned — which is exactly
1826
+ * the case where naming the extension and the image is worth the words.
1827
+ */
1828
+ function vectorExtensionHint(message) {
1829
+ if (!/type "(vector|halfvec|sparsevec)" does not exist/i.test(message)) return "";
1830
+ return "\n pgvector is not installed on this database, and Rebase does not install it: it is a server extension, so it needs an image that ships it (the scaffold's `pgvector/pgvector:pg18` does; a stock `postgres:18` does not) and a role allowed to run `CREATE EXTENSION vector;`. Install it once, then boot again. Rebase then creates an ANN index for the column automatically — see the `index` option on the property.";
1831
+ }
1832
+ /**
1833
+ * Read what the database looks like, for the schemas a set of collections
1834
+ * lives in.
1835
+ *
1836
+ * The same read `ensureCollectionTables` does at boot, exposed on its own for
1837
+ * the callers that want to *plan* against a real database without changing it —
1838
+ * the live schema editor, which has to tell somebody what a change would do
1839
+ * before they agree to it.
1840
+ */
1841
+ async function readSchemaFactsFor(client, collections) {
1842
+ const relational = relationalCollections(collections);
1843
+ return readExistingSchema(client, Array.from(/* @__PURE__ */ new Set([...relational.map(schemaOf), ...planJunctionTables(relational).map((junction) => junction.schema)])));
1844
+ }
1845
+ /**
1846
+ * Bring the database up to date. Returns what it did.
1847
+ *
1848
+ * Each statement runs on its own rather than in one transaction: they are all
1849
+ * independently safe and idempotent, and a single failure (an enum label that
1850
+ * cannot be added, say) should not roll back the tables that were created fine.
1851
+ * The error is surfaced with the statement that caused it.
1852
+ */
1853
+ async function ensureCollectionTables(client, collections, log) {
1854
+ const schemas = Array.from(/* @__PURE__ */ new Set([...collections.map(schemaOf), ...planJunctionTables(collections).map((j) => j.schema)]));
1855
+ for (const schema of schemas) {
1856
+ assertSafeIdentifier(schema, "schema name");
1857
+ if (schema !== "public") await client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}";`);
1858
+ }
1859
+ const plan = planCollectionSchemaEnsure(collections, await readExistingSchema(client, schemas));
1860
+ const failures = [];
1861
+ for (const legacy of plan.legacyForeignKeys) {
1862
+ const message = `Renaming "${legacy.table}"."${legacy.legacy}" to "${legacy.expected}". The old name is the one Rebase derived for this relation before it singularized properly; the column keeps its data, indexes and constraints. To keep the old name instead, set \`localKey: "${legacy.legacy}"\` on the relation and this will stop.`;
1863
+ logger.info(`[schema] ${message}`);
1864
+ log?.(message);
1865
+ }
1866
+ if (plan.searchDrift.length > 0) throw new Error(searchDriftMessage(plan.searchDrift));
1867
+ for (const adopted of plan.searchAdopted) {
1868
+ const message = `Adopting the existing generated column "${adopted.table}"."${adopted.column}" and recording what the current \`search\` block would generate. Any later change to that block will be detected and refused; a change made *before* this version was deployed cannot be, so if search has been missing content, rebuild the column once: ALTER TABLE "${adopted.table.split(".").join("\".\"")}" DROP COLUMN "${adopted.column}"; and boot again.`;
1869
+ logger.info(`[schema] ${message}`);
1870
+ log?.(message);
1871
+ }
1872
+ for (const skip of plan.vectorIndexSkipped) {
1873
+ const message = `No ANN index on "${skip.table}"."${skip.column}": ${skip.reason}`;
1874
+ logger.warn(`[schema] ${message}`);
1875
+ log?.(message);
1876
+ }
1877
+ for (const withheld of plan.withheldConstraints) {
1878
+ const message = `No NOT NULL on "${withheld.target}": ${withheld.reason} ${withheld.remedy}`;
1879
+ logger.warn(`[schema] ${message}`);
1880
+ log?.(message);
1881
+ }
1882
+ if (plan.actions.length === 0) {
1883
+ log?.("Schema is up to date; nothing to create.");
1884
+ return {
1885
+ ...plan,
1886
+ failures
1887
+ };
1888
+ }
1889
+ for (const action of plan.actions) try {
1890
+ if (await applyAction(client, action)) log?.(`${action.kind}: ${action.target}`);
1891
+ else log?.(`${action.kind}: ${action.target} (already created by a peer)`);
1892
+ } catch (err) {
1893
+ const message = err instanceof Error ? err.message : String(err);
1894
+ if (action.kind === "add-constraint" || action.kind === "comment-column") {
1895
+ failures.push({
1896
+ kind: action.kind,
1897
+ target: action.target,
1898
+ error: message
1899
+ });
1900
+ continue;
1901
+ }
1902
+ throw new Error(`Failed to ${action.kind} ${action.target}: ${message}${vectorExtensionHint(message)}\n ${action.sql}`);
1903
+ }
1904
+ return {
1905
+ ...plan,
1906
+ failures
1907
+ };
1908
+ }
1909
+ /** Attempts per action, including the first. Matches the server's bootstraps. */
1910
+ var DDL_ATTEMPTS = 4;
1911
+ /**
1912
+ * Run one planned statement, surviving a simultaneous boot.
1913
+ *
1914
+ * Every statement in a plan is written to be idempotent, and that is not the
1915
+ * same as being safe to run concurrently: `CREATE … IF NOT EXISTS` reads the
1916
+ * catalog and then writes to it as two steps, so peers starting together both
1917
+ * see "absent" and the loser gets a duplicate key on a *catalog* index. Measured
1918
+ * against Postgres 18: five instances, 8 of 10 calls lost. `CREATE TYPE` is
1919
+ * worse, because Postgres has no `IF NOT EXISTS` for it at all.
1920
+ *
1921
+ * What made that fatal here rather than merely noisy is the loop this sits in.
1922
+ * A losing statement threw, and the throw abandoned **every remaining action in
1923
+ * the plan** — so a replica that lost one race came up missing tables it never
1924
+ * attempted, and the boot log blamed the one statement that failed.
1925
+ *
1926
+ * @returns `true` if this process applied the statement, `false` if a peer had
1927
+ * already created the object. The distinction is only for the log; both mean
1928
+ * the object is now there.
1929
+ * @throws the original error for anything that is not a race — a syntax error, a
1930
+ * permission failure, a unique constraint the customer's own rows violate.
1931
+ */
1932
+ async function applyAction(client, action) {
1933
+ for (let attempt = 1;; attempt++) try {
1934
+ await client.query(action.sql);
1935
+ return true;
1936
+ } catch (err) {
1937
+ if (isDuplicateObjectRace(err)) {
1938
+ logger.debug(`[schema] ${action.kind} ${action.target}: already created by another instance`);
1939
+ return false;
1940
+ }
1941
+ if (isConcurrentDdlRace(err) && attempt < DDL_ATTEMPTS) {
1942
+ logger.debug(`[schema] ${action.kind} ${action.target}: lost a race with another instance (attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`);
1943
+ await new Promise((resolve) => setTimeout(resolve, 40 * attempt * (1 + Math.random())));
1944
+ continue;
1945
+ }
1946
+ throw err;
1947
+ }
1948
+ }
1949
+ //#endregion
1950
+ export { generatePostgresDdl as a, planCollectionPolicies as c, authUsersColumnSql as d, SEARCH_UNACCENT_FN as f, resolveStringColumnLength as g, visibleColumnProjection as h, readSchemaFactsFor as i, resolveColumnName as l, hiddenColumnsOption as m, planCollectionSchemaEnsure as n, generatePostgresPoliciesDdl as o, buildSearchColumnSpec as p, readExistingSchema as r, generatePostgresSearchDdl as s, ensure_collection_tables_exports as t, AUTH_USERS_COLUMNS as u };
1951
+
1952
+ //# sourceMappingURL=ensure-collection-tables-DMjOkeRy.js.map