@rebasepro/server-postgres 0.12.1-canary.gf5f1d39 → 0.13.1-canary.g18cfeb7

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 (112) hide show
  1. package/dist/PostgresBackendDriver.d.ts +49 -2
  2. package/dist/PostgresBootstrapper.d.ts +25 -1
  3. package/dist/auth/services.d.ts +21 -0
  4. package/dist/{src-BbFOPJ1S.js → auth-users-columns-Do9mw5Y5.js} +602 -200
  5. package/dist/auth-users-columns-Do9mw5Y5.js.map +1 -0
  6. package/dist/backup/backup-service.d.ts +10 -1
  7. package/dist/backup/pg-tools.d.ts +47 -0
  8. package/dist/backup-service-Bww-Lg0s.js +8999 -0
  9. package/dist/backup-service-Bww-Lg0s.js.map +1 -0
  10. package/dist/cli-helpers.d.ts +40 -1
  11. package/dist/connection-BuZ97wsr.js +250 -0
  12. package/dist/connection-BuZ97wsr.js.map +1 -0
  13. package/dist/connection.d.ts +42 -0
  14. package/dist/ensure-collection-policies-DMUdRQdM.js +57 -0
  15. package/dist/ensure-collection-policies-DMUdRQdM.js.map +1 -0
  16. package/dist/ensure-collection-tables-DSIxvLLD.js +694 -0
  17. package/dist/ensure-collection-tables-DSIxvLLD.js.map +1 -0
  18. package/dist/index.es.js +1701 -10167
  19. package/dist/index.es.js.map +1 -1
  20. package/dist/policy-CPkCqVTz.js +105 -0
  21. package/dist/policy-CPkCqVTz.js.map +1 -0
  22. package/dist/rls-bootstrap-sql-Bpv3nUZo.js +244 -0
  23. package/dist/rls-bootstrap-sql-Bpv3nUZo.js.map +1 -0
  24. package/dist/schema/auth-schema.d.ts +83 -144
  25. package/dist/schema/auth-users-columns.d.ts +97 -0
  26. package/dist/schema/ensure-collection-policies.d.ts +60 -0
  27. package/dist/schema/ensure-collection-tables.d.ts +45 -3
  28. package/dist/schema/generate-drizzle-schema-logic.d.ts +1 -1
  29. package/dist/schema/generate-postgres-ddl-logic.d.ts +137 -3
  30. package/dist/schema/generated-schema-staleness.d.ts +39 -0
  31. package/dist/schema/introspect-db-constraints.d.ts +57 -0
  32. package/dist/schema/introspect-db-logic.d.ts +94 -5
  33. package/dist/schema/introspect-db-queries.d.ts +119 -0
  34. package/dist/schema/introspect-db-structure.d.ts +263 -0
  35. package/dist/schema/introspect-db-types.d.ts +11 -0
  36. package/dist/schema/rls-bootstrap-sql.d.ts +135 -0
  37. package/dist/security/rls-enforcement.d.ts +53 -2
  38. package/dist/services/FetchService.d.ts +14 -8
  39. package/dist/services/RelationService.d.ts +24 -1
  40. package/dist/services/channel-bus/index.d.ts +1 -7
  41. package/dist/services/collection-helpers.d.ts +36 -2
  42. package/dist/services/dataService.d.ts +5 -1
  43. package/dist/services/realtimeService.d.ts +25 -21
  44. package/dist/services/row-pipeline.d.ts +1 -1
  45. package/dist/{src-Zqwaw3P5.js → src-C_wvdMnl.js} +78 -145
  46. package/dist/src-C_wvdMnl.js.map +1 -0
  47. package/dist/utils/connection-string.d.ts +29 -0
  48. package/dist/utils/drizzle-conditions.d.ts +5 -4
  49. package/dist/utils/pg-error-utils.d.ts +35 -0
  50. package/dist/websocket-D0TBU3ia.js +530 -0
  51. package/dist/websocket-D0TBU3ia.js.map +1 -0
  52. package/package.json +17 -16
  53. package/src/PostgresAdapter.ts +21 -2
  54. package/src/PostgresBackendDriver.ts +169 -3
  55. package/src/PostgresBootstrapper.ts +233 -35
  56. package/src/auth/ensure-tables.ts +335 -81
  57. package/src/auth/services.ts +24 -2
  58. package/src/backup/backup-cli.ts +41 -2
  59. package/src/backup/backup-service.ts +38 -5
  60. package/src/backup/pg-tools.ts +96 -3
  61. package/src/cli-helpers.ts +92 -9
  62. package/src/cli.ts +219 -56
  63. package/src/collections/validate-relations.ts +136 -14
  64. package/src/connection.ts +73 -0
  65. package/src/data-transformer.ts +22 -6
  66. package/src/databasePoolManager.ts +5 -2
  67. package/src/history/ensure-history-table.ts +7 -0
  68. package/src/schema/auth-schema.ts +30 -19
  69. package/src/schema/auth-users-columns.ts +131 -0
  70. package/src/schema/doctor.ts +7 -5
  71. package/src/schema/ensure-collection-policies.ts +105 -0
  72. package/src/schema/ensure-collection-tables.test.ts +105 -9
  73. package/src/schema/ensure-collection-tables.ts +301 -44
  74. package/src/schema/generate-drizzle-schema-logic.ts +49 -7
  75. package/src/schema/generate-postgres-ddl-logic.ts +474 -27
  76. package/src/schema/generated-schema-staleness.ts +169 -0
  77. package/src/schema/introspect-db-constraints.ts +385 -0
  78. package/src/schema/introspect-db-inference.ts +18 -8
  79. package/src/schema/introspect-db-logic.ts +385 -71
  80. package/src/schema/introspect-db-queries.ts +326 -0
  81. package/src/schema/introspect-db-structure.ts +670 -0
  82. package/src/schema/introspect-db-types.ts +56 -0
  83. package/src/schema/introspect-db.ts +37 -80
  84. package/src/schema/introspect-runtime.test.ts +56 -8
  85. package/src/schema/introspect-runtime.ts +31 -9
  86. package/src/schema/non-sql-collections.test.ts +131 -0
  87. package/src/schema/rls-bootstrap-sql.ts +288 -0
  88. package/src/security/anonymous-grants.test.ts +4 -2
  89. package/src/security/policy-drift.test.ts +11 -3
  90. package/src/security/rls-enforcement.ts +141 -3
  91. package/src/services/BranchService.ts +71 -28
  92. package/src/services/FetchService.ts +100 -107
  93. package/src/services/PersistService.ts +34 -7
  94. package/src/services/RelationService.ts +249 -48
  95. package/src/services/channel-bus/index.ts +0 -9
  96. package/src/services/channel-history.ts +8 -0
  97. package/src/services/channel-presence.ts +6 -0
  98. package/src/services/collection-helpers.ts +69 -3
  99. package/src/services/dataService.ts +5 -1
  100. package/src/services/realtimeService.ts +38 -35
  101. package/src/services/row-pipeline.ts +1 -1
  102. package/src/utils/connection-string.ts +58 -0
  103. package/src/utils/drizzle-conditions.ts +31 -6
  104. package/src/utils/pg-error-utils.ts +65 -0
  105. package/src/websocket.ts +18 -9
  106. package/dist/chunk-DSJWtz9O.js +0 -40
  107. package/dist/ensure-collection-tables-CNTcZGvn.js +0 -304
  108. package/dist/ensure-collection-tables-CNTcZGvn.js.map +0 -1
  109. package/dist/schema/auth-bootstrap-sql.d.ts +0 -24
  110. package/dist/src-BbFOPJ1S.js.map +0 -1
  111. package/dist/src-Zqwaw3P5.js.map +0 -1
  112. package/src/schema/auth-bootstrap-sql.ts +0 -47
@@ -0,0 +1,694 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import "process";
3
+ __createRequire(import.meta.url);
4
+ import { A as generateForeignKeyName, I as toSnakeCase, M as getPolicyNamesForRule, c as resolveStringColumnLength, d as resolveJunctionSpecs, f as getEffectiveSecurityRules, g as findRelation, i as isAuthCollection, j as legacyForeignKeyName, l as getJunctionCollectionConfig, m as securityRuleToConditions, n as authUsersColumnDefinition, p as policyToPostgres, r as authUsersColumnSql, s as relationalCollections, t as AUTH_USERS_COLUMNS, u as getJunctionSecurityRules, x as resolveCollectionRelations, y as getTableName } from "./auth-users-columns-Do9mw5Y5.js";
5
+ import { c as isPostgresCollectionConfig } from "./src-C_wvdMnl.js";
6
+ import { logger } from "@rebasepro/server";
7
+ //#region src/schema/generate-postgres-ddl-logic.ts
8
+ var resolveColumnName = (propName, prop) => {
9
+ if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
10
+ return toSnakeCase(propName);
11
+ };
12
+ var getPrimaryKeyProp = (collection) => {
13
+ if (collection.properties) {
14
+ const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => "isId" in prop && Boolean(prop.isId));
15
+ if (idPropEntry) {
16
+ const prop = idPropEntry[1];
17
+ const isUuid = prop.type === "string" && "isId" in prop && prop.isId === "uuid";
18
+ return {
19
+ name: idPropEntry[0],
20
+ type: prop.type === "number" ? "number" : "string",
21
+ isUuid
22
+ };
23
+ }
24
+ }
25
+ const idProp = collection.properties?.["id"];
26
+ if (idProp?.type === "number") return {
27
+ name: "id",
28
+ type: "number",
29
+ isUuid: false
30
+ };
31
+ return {
32
+ name: "id",
33
+ type: "string",
34
+ isUuid: idProp?.type === "string" && "isId" in idProp && idProp.isId === "uuid"
35
+ };
36
+ };
37
+ var isNumericId = (collection) => {
38
+ return getPrimaryKeyProp(collection).type === "number";
39
+ };
40
+ var getPrimaryKeyName = (collection) => {
41
+ return getPrimaryKeyProp(collection).name;
42
+ };
43
+ /** The column type a junction holds for one endpoint's primary key. */
44
+ var junctionKeyType = (collection) => isNumericId(collection) ? "INTEGER" : getPrimaryKeyProp(collection).isUuid ? "UUID" : "TEXT";
45
+ var isIdProperty = (propName, prop, collection) => {
46
+ if ("isId" in prop && Boolean(prop.isId)) return true;
47
+ return !Object.values(collection.properties ?? {}).some((p) => "isId" in p && Boolean(p.isId)) && propName === "id";
48
+ };
49
+ /**
50
+ * The individual SQL statements a single security rule compiles to: a
51
+ * `DROP POLICY IF EXISTS` / `CREATE POLICY` pair per operation, each a complete
52
+ * statement (terminated by `;`, no trailing newline).
53
+ *
54
+ * This is the primitive the boot-time RLS applier runs one statement at a time
55
+ * (the runtime's DB handle speaks the extended query protocol, which forbids
56
+ * multiple commands in one execute), while `db push` writes the joined string.
57
+ */
58
+ var generatePolicyStatements = (collection, rule, resolveCollection) => {
59
+ const tableName = getTableName(collection);
60
+ const ops = rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? "all"];
61
+ const policyNames = getPolicyNamesForRule(rule, tableName);
62
+ return ops.flatMap((op, opIdx) => {
63
+ return generateSinglePolicyStatements(collection, rule, op, policyNames[opIdx], resolveCollection);
64
+ });
65
+ };
66
+ var generateSinglePolicyStatements = (collection, rule, operation, policyName, resolveCollection) => {
67
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
68
+ const tableName = getTableName(collection);
69
+ const mode = (rule.mode ?? "permissive").toUpperCase();
70
+ const operationUpper = operation.toUpperCase();
71
+ const pgRoles = rule.pgRoles ? [...rule.pgRoles].sort() : ["public"];
72
+ const needsUsing = operation !== "insert";
73
+ const needsWithCheck = operation !== "select" && operation !== "delete";
74
+ const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
75
+ let usingClause = needsUsing && usingExpr ? policyToPostgres(usingExpr, collection, { resolveCollection }) : null;
76
+ let withCheckClause = needsWithCheck && withCheckExpr ? policyToPostgres(withCheckExpr, collection, { resolveCollection }) : null;
77
+ if (!usingClause && needsUsing) usingClause = "false";
78
+ if (!withCheckClause && needsWithCheck) withCheckClause = "false";
79
+ const drop = `DROP POLICY IF EXISTS "${policyName}" ON "${schema}"."${tableName}";`;
80
+ let create = `CREATE POLICY "${policyName}" ON "${schema}"."${tableName}" AS ${mode} FOR ${operationUpper} TO ${pgRoles.map((r) => `"${r}"`).join(", ")}`;
81
+ if (usingClause) create += ` USING (${usingClause})`;
82
+ if (withCheckClause) create += ` WITH CHECK (${withCheckClause})`;
83
+ create += ";";
84
+ return [drop, create];
85
+ };
86
+ /**
87
+ * Single-quote escaping for a SQL string literal (PostgreSQL doubles the
88
+ * quote). Enum labels come straight from user-authored collection config, so a
89
+ * label like `it's` closes the literal early and the whole generated file stops
90
+ * parsing at the `CREATE TYPE`. Lives here rather than next to its other caller
91
+ * because ensure-collection-tables already imports from this module — the
92
+ * reverse would be a cycle.
93
+ */
94
+ var quoteSqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
95
+ var getSqlColumnType = (propName, prop, collection, collections) => {
96
+ switch (prop.type) {
97
+ case "string": {
98
+ const stringProp = prop;
99
+ if (stringProp.enum) {
100
+ const tableName = getTableName(collection);
101
+ const colName = resolveColumnName(propName, prop);
102
+ return `"${isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public"}"."${tableName}_${colName}"`;
103
+ }
104
+ if (stringProp.isId === "uuid" || stringProp.columnType === "uuid") return "UUID";
105
+ if (stringProp.columnType === "char") return `CHAR(${resolveStringColumnLength(stringProp)})`;
106
+ if (stringProp.columnType === "varchar") return `VARCHAR(${resolveStringColumnLength(stringProp)})`;
107
+ return "TEXT";
108
+ }
109
+ case "number": {
110
+ const numProp = prop;
111
+ const isId = isIdProperty(propName, prop, collection);
112
+ if ("isId" in numProp && numProp.isId === "increment") return "INTEGER GENERATED BY DEFAULT AS IDENTITY";
113
+ if (numProp.columnType) {
114
+ if (numProp.columnType === "double precision") return "DOUBLE PRECISION";
115
+ return numProp.columnType.toUpperCase();
116
+ }
117
+ return numProp.validation?.integer || isId ? "INTEGER" : "NUMERIC";
118
+ }
119
+ case "boolean": return "BOOLEAN";
120
+ case "date": {
121
+ const dateProp = prop;
122
+ if (dateProp.columnType === "date") return "DATE";
123
+ if (dateProp.columnType === "time") return "TIME";
124
+ return "TIMESTAMP WITH TIME ZONE";
125
+ }
126
+ case "map": return prop.columnType === "json" ? "JSON" : "JSONB";
127
+ case "array": {
128
+ const arrayProp = prop;
129
+ let colType = arrayProp.columnType;
130
+ if (!colType && arrayProp.of && !Array.isArray(arrayProp.of)) {
131
+ const ofProp = arrayProp.of;
132
+ if (ofProp.type === "string") colType = "text[]";
133
+ else if (ofProp.type === "number") colType = ofProp.validation?.integer ? "integer[]" : "numeric[]";
134
+ else if (ofProp.type === "boolean") colType = "boolean[]";
135
+ }
136
+ if (colType === "json") return "JSON";
137
+ if (colType === "text[]") return "TEXT[]";
138
+ if (colType === "integer[]") return "INTEGER[]";
139
+ if (colType === "boolean[]") return "BOOLEAN[]";
140
+ if (colType === "numeric[]") return "NUMERIC[]";
141
+ return "JSONB";
142
+ }
143
+ case "vector": return `VECTOR(${prop.dimensions})`;
144
+ case "binary": return "BYTEA";
145
+ case "relation": {
146
+ const refProp = prop;
147
+ const relation = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
148
+ if (relation?.kind !== "belongsTo") throw new Error(`Relation ${propName} does not put a column on this table (only \`belongsTo\` does)`);
149
+ let targetCollection;
150
+ try {
151
+ targetCollection = relation.target();
152
+ } catch {
153
+ return "TEXT";
154
+ }
155
+ const pkProp = getPrimaryKeyProp(targetCollection);
156
+ return pkProp.type === "number" ? "INTEGER" : pkProp.isUuid ? "UUID" : "TEXT";
157
+ }
158
+ case "reference": {
159
+ const refProp = prop;
160
+ const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
161
+ if (!targetCollection) return "TEXT";
162
+ const pkProp = getPrimaryKeyProp(targetCollection);
163
+ return pkProp.type === "number" ? "INTEGER" : pkProp.isUuid ? "UUID" : "TEXT";
164
+ }
165
+ default: return "TEXT";
166
+ }
167
+ };
168
+ var schemaOfCollection = (collection) => isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
169
+ var bareTableName = (name) => name.includes(".") ? name.split(".").pop() : name;
170
+ /**
171
+ * Truncate a derived identifier the way Postgres does: to 63 bytes, silently.
172
+ *
173
+ * This is not cosmetic, and not really a naming choice at all — it is agreeing
174
+ * with the name the database ALREADY stored. `ADD CONSTRAINT` on a longer name
175
+ * succeeds and records the truncated form, so the untruncated name this used to
176
+ * derive matched nothing in the catalogue. Boot-ensure compares its planned
177
+ * constraints against `readExistingSchema`, which reads catalogue names, so the
178
+ * comparison could never hit: every boot re-issued `ADD CONSTRAINT` for the same
179
+ * constraint, forever, and got "already exists" every time. Non-fatal (foreign
180
+ * keys are the one action allowed to fail) and therefore permanent — an error in
181
+ * the log on every restart of a project whose table and column names happened to
182
+ * be long.
183
+ *
184
+ * Byte length, not string length: NAMEDATALEN is 64 bytes, and a multi-byte
185
+ * character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.
186
+ */
187
+ var toPostgresIdentifier = (name) => {
188
+ const bytes = Buffer.from(name, "utf8");
189
+ if (bytes.byteLength <= 63) return name;
190
+ return bytes.subarray(0, 63).toString("utf8").replace(/�+$/, "");
191
+ };
192
+ var foreignKeyPlan = (args) => {
193
+ const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);
194
+ const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : "";
195
+ return {
196
+ constraintName,
197
+ schema: args.schema,
198
+ table: args.table,
199
+ column: args.column,
200
+ targetSchema: args.targetSchema,
201
+ targetTable: args.targetTable,
202
+ targetColumn: args.targetColumn,
203
+ 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};`
204
+ };
205
+ };
206
+ /**
207
+ * The FK columns the declared collections own — one entry per `relation`
208
+ * (`belongsTo` side) or `reference` property.
209
+ *
210
+ * Split out of {@link generatePostgresDdl} so the boot-time schema ensure can
211
+ * create the same columns with the same names, types and constraints. Before
212
+ * this it skipped them outright, which was survivable only because `db push`
213
+ * always followed; on a managed tenant nothing follows, so a table arrived
214
+ * without the column its own collection reads and wrote 400 on every insert.
215
+ *
216
+ * A relation whose target is not in the bundle yields no column at all (the
217
+ * generator returns early on an unresolvable target); a `reference` whose target
218
+ * is unknown yields the column without a constraint. Both mirror the generator
219
+ * exactly — a divergence here is a schema fork between boot and `db push`.
220
+ */
221
+ var planRelationalColumns = (allCollections) => {
222
+ const collections = relationalCollections(allCollections);
223
+ const plans = [];
224
+ for (const collection of collections) {
225
+ const tableName = getTableName(collection);
226
+ if (!tableName) continue;
227
+ const schema = schemaOfCollection(collection);
228
+ const table = bareTableName(tableName);
229
+ for (const [propName, rawProp] of Object.entries(collection.properties ?? {})) {
230
+ const prop = rawProp;
231
+ if (prop.type === "relation") {
232
+ const refProp = prop;
233
+ const relInfo = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
234
+ if (relInfo?.kind !== "belongsTo") continue;
235
+ if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) continue;
236
+ let targetCollection;
237
+ try {
238
+ targetCollection = relInfo.target();
239
+ } catch {
240
+ continue;
241
+ }
242
+ if (!targetCollection) continue;
243
+ const required = prop.validation?.required;
244
+ const relationName = refProp.relation?.relationName ?? propName;
245
+ const legacyKey = legacyForeignKeyName(relationName);
246
+ const derived = relInfo.localKey === generateForeignKeyName(relationName);
247
+ plans.push({
248
+ schema,
249
+ table,
250
+ column: relInfo.localKey,
251
+ legacyColumn: derived && legacyKey !== relInfo.localKey ? legacyKey : void 0,
252
+ type: getSqlColumnType(propName, prop, collection, collections),
253
+ foreignKey: foreignKeyPlan({
254
+ schema,
255
+ table,
256
+ column: relInfo.localKey,
257
+ targetSchema: schemaOfCollection(targetCollection),
258
+ targetTable: bareTableName(getTableName(targetCollection)),
259
+ targetColumn: getPrimaryKeyName(targetCollection),
260
+ onDelete: relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL"),
261
+ onUpdate: relInfo.onUpdate
262
+ })
263
+ });
264
+ } else if (prop.type === "reference") {
265
+ const refProp = prop;
266
+ const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
267
+ const column = resolveColumnName(propName, prop);
268
+ const type = getSqlColumnType(propName, prop, collection, collections);
269
+ const required = prop.validation?.required;
270
+ plans.push({
271
+ schema,
272
+ table,
273
+ column,
274
+ type,
275
+ foreignKey: targetCollection ? foreignKeyPlan({
276
+ schema,
277
+ table,
278
+ column,
279
+ targetSchema: schemaOfCollection(targetCollection),
280
+ targetTable: bareTableName(getTableName(targetCollection)),
281
+ targetColumn: getPrimaryKeyName(targetCollection),
282
+ onDelete: required ? "CASCADE" : "SET NULL"
283
+ }) : void 0
284
+ });
285
+ }
286
+ }
287
+ }
288
+ return plans;
289
+ };
290
+ /**
291
+ * The junction tables a bundle's many-to-many relations imply.
292
+ *
293
+ * Derived from {@link resolveJunctionSpecs}, the same source the junction RLS
294
+ * comes from, so a table created here always has policies planned for it — a
295
+ * junction with row-level security left off is readable and writable by every
296
+ * signed-in user, which is why the two must ship together.
297
+ */
298
+ var planJunctionTables = (allCollections) => {
299
+ const collections = relationalCollections(allCollections);
300
+ const plans = [];
301
+ for (const spec of resolveJunctionSpecs(collections).values()) {
302
+ const [source, target] = spec.endpoints;
303
+ const legacyFor = (endpoint) => {
304
+ const slug = toSnakeCase(endpoint.collection.slug ?? endpoint.collection.name ?? "");
305
+ const legacy = legacyForeignKeyName(slug);
306
+ return endpoint.junctionColumn === generateForeignKeyName(slug) && legacy !== endpoint.junctionColumn ? legacy : void 0;
307
+ };
308
+ const columns = [{
309
+ name: source.junctionColumn,
310
+ type: junctionKeyType(source.collection),
311
+ legacyName: legacyFor(source)
312
+ }, {
313
+ name: target.junctionColumn,
314
+ type: junctionKeyType(target.collection),
315
+ legacyName: legacyFor(target)
316
+ }];
317
+ const onDelete = spec.declaringSides[0]?.relation.onDelete ?? "CASCADE";
318
+ plans.push({
319
+ schema: spec.schema,
320
+ table: spec.table,
321
+ columns,
322
+ 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(", ")}));`,
323
+ foreignKeys: [source, target].map((endpoint, i) => foreignKeyPlan({
324
+ schema: spec.schema,
325
+ table: spec.table,
326
+ column: columns[i].name,
327
+ targetSchema: schemaOfCollection(endpoint.collection),
328
+ targetTable: bareTableName(getTableName(endpoint.collection)),
329
+ targetColumn: getPrimaryKeyName(endpoint.collection),
330
+ onDelete
331
+ }))
332
+ });
333
+ }
334
+ return plans;
335
+ };
336
+ /**
337
+ * The per-table RLS plan for the *declared* collections, as executable
338
+ * statements — what the managed runtime applies at boot so a freshly
339
+ * provisioned tenant database serves data instead of 401ing every read.
340
+ *
341
+ * Mirrors {@link generatePostgresPoliciesDdl} exactly (same
342
+ * `generatePolicyStatements`, same enable-RLS, same effective rules, same
343
+ * derived junction rules), so boot and `db push` produce identical policies from
344
+ * identical collections.
345
+ *
346
+ * Junction tables are included, and have to be: boot creates them now
347
+ * ({@link planJunctionTables}), and a junction with RLS left off is readable and
348
+ * writable by every signed-in user. A junction whose table is still absent is
349
+ * skipped by the applier, not planned away here.
350
+ */
351
+ var planCollectionPolicies = (allCollections) => {
352
+ const collections = relationalCollections(allCollections);
353
+ const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
354
+ const plans = [];
355
+ const seen = /* @__PURE__ */ new Set();
356
+ for (const collection of collections) {
357
+ const tableName = getTableName(collection);
358
+ if (!tableName) continue;
359
+ const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
360
+ const baseTableName = tableName.includes(".") ? tableName.split(".").pop() : tableName;
361
+ const qualified = `${schema}.${baseTableName}`;
362
+ if (seen.has(qualified)) continue;
363
+ seen.add(qualified);
364
+ const policyStatements = [];
365
+ for (const rule of getEffectiveSecurityRules(collection)) policyStatements.push(...generatePolicyStatements(collection, rule, resolveCollection));
366
+ plans.push({
367
+ schema,
368
+ table: baseTableName,
369
+ qualified,
370
+ enableRls: `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;`,
371
+ policyStatements
372
+ });
373
+ }
374
+ for (const spec of resolveJunctionSpecs(collections).values()) {
375
+ const qualified = `${spec.schema}.${spec.table}`;
376
+ if (seen.has(qualified)) continue;
377
+ seen.add(qualified);
378
+ const junctionCollection = getJunctionCollectionConfig(spec);
379
+ const policyStatements = [];
380
+ for (const rule of getJunctionSecurityRules(spec)) policyStatements.push(...generatePolicyStatements(junctionCollection, rule, resolveCollection));
381
+ plans.push({
382
+ schema: spec.schema,
383
+ table: spec.table,
384
+ qualified,
385
+ enableRls: `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;`,
386
+ policyStatements
387
+ });
388
+ }
389
+ return plans;
390
+ };
391
+ //#endregion
392
+ //#region src/schema/ensure-collection-tables.ts
393
+ /**
394
+ * Bringing a database up to date with a bundle's collections, additively.
395
+ *
396
+ * ## Why this exists
397
+ *
398
+ * A managed runtime boots someone else's compiled project against a database it
399
+ * has never seen. Auth tables are ensured at boot already, but collection tables
400
+ * were not created by anything: the platform ran the app and every `/api/data/*`
401
+ * request answered 500 on a missing relation. `rebase db push` cannot help — it
402
+ * is an Atlas-driven CLI command, and the runtime image ships no CLI.
403
+ *
404
+ * ## Why additive-only, forever
405
+ *
406
+ * This runs unattended, against a database with customers' data in it, with no
407
+ * human reading a diff. So it may only ever do things that cannot lose data:
408
+ * create a missing table, add a missing column, create a missing enum type.
409
+ *
410
+ * It will **never** drop a table or a column, narrow a type, or alter a
411
+ * constraint. A removed field leaves its column behind; a renamed field looks
412
+ * like an addition and the old column stays. That is the correct trade for an
413
+ * automated path — the alternative is an unattended process that can silently
414
+ * destroy a column, which is precisely the failure `db push` was hardened
415
+ * against. Destructive changes stay a deliberate, human-reviewed migration.
416
+ *
417
+ * Because of that, this is safe to run on every boot, and re-running it is a
418
+ * no-op.
419
+ */
420
+ /** Postgres identifiers this module is willing to interpolate. */
421
+ var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
422
+ function assertSafeIdentifier(value, what) {
423
+ if (!SAFE_IDENTIFIER.test(value)) throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);
424
+ return value;
425
+ }
426
+ function schemaOf(collection) {
427
+ return isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
428
+ }
429
+ function qualified(collection) {
430
+ return `${schemaOf(collection)}.${getTableName(collection)}`;
431
+ }
432
+ /**
433
+ * Enum types a collection's properties require, as `schema.typename`.
434
+ *
435
+ * Named exactly as the DDL generator names them (`<table>_<column>`), because
436
+ * a column added here has to reference the same type the generator would have
437
+ * created — a second, differently-named type for the same field would be a
438
+ * silent schema fork.
439
+ */
440
+ function requiredEnums(collection) {
441
+ const table = getTableName(collection);
442
+ const schema = schemaOf(collection);
443
+ const out = [];
444
+ for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
445
+ const p = prop;
446
+ if (!("enum" in p) || !p.enum) continue;
447
+ if (p.type !== "string" && p.type !== "number") continue;
448
+ const values = p.enum.map((entry) => entry && typeof entry === "object" && "id" in entry ? String(entry.id) : String(entry)).filter((v) => v.length > 0);
449
+ if (values.length === 0) continue;
450
+ out.push({
451
+ name: `${schema}.${table}_${resolveColumnName(propName, p)}`,
452
+ values
453
+ });
454
+ }
455
+ return out;
456
+ }
457
+ /**
458
+ * Decide what to add. Pure — the caller supplies what exists and runs the result.
459
+ *
460
+ * Ordering matters and is deliberate: enum types before the tables and columns
461
+ * that reference them, tables before the columns added to other tables (a new
462
+ * table may be the target of a relation), and nothing is emitted twice.
463
+ */
464
+ function planCollectionSchemaEnsure(allCollections, existing) {
465
+ const collections = relationalCollections(allCollections);
466
+ const actions = [];
467
+ const plannedEnums = /* @__PURE__ */ new Set();
468
+ for (const collection of collections) for (const { name, values } of requiredEnums(collection)) {
469
+ if (existing.enums.has(name) || plannedEnums.has(name)) continue;
470
+ plannedEnums.add(name);
471
+ const [schema, typeName] = name.split(".");
472
+ actions.push({
473
+ kind: "create-enum",
474
+ target: name,
475
+ sql: `CREATE TYPE "${schema}"."${typeName}" AS ENUM (${values.map(quoteSqlLiteral).join(", ")});`
476
+ });
477
+ }
478
+ const created = /* @__PURE__ */ new Set();
479
+ for (const collection of collections) {
480
+ const key = qualified(collection);
481
+ if (existing.tables.has(key) || created.has(key)) continue;
482
+ created.add(key);
483
+ const schema = schemaOf(collection);
484
+ const table = getTableName(collection);
485
+ const idEntry = Object.entries(collection.properties ?? {}).find(([n, p]) => isIdProperty(n, p, collection));
486
+ const idName = idEntry ? resolveColumnName(idEntry[0], idEntry[1]) : "id";
487
+ const idProp = idEntry?.[1];
488
+ let idDef = `"${idName}" ${idProp ? getSqlColumnType(idEntry[0], idProp, collection, collections) : "TEXT"} PRIMARY KEY`;
489
+ if (idProp?.type === "string" && idProp.isId === "uuid") idDef += " DEFAULT gen_random_uuid()";
490
+ actions.push({
491
+ kind: "create-table",
492
+ target: key,
493
+ sql: `CREATE TABLE IF NOT EXISTS "${schema}"."${table}" (${idDef});`
494
+ });
495
+ }
496
+ const junctions = planJunctionTables(collections);
497
+ for (const junction of junctions) {
498
+ const key = `${junction.schema}.${junction.table}`;
499
+ if (existing.tables.has(key) || created.has(key)) continue;
500
+ created.add(key);
501
+ actions.push({
502
+ kind: "create-table",
503
+ target: key,
504
+ sql: junction.createTable
505
+ });
506
+ }
507
+ const legacyForeignKeys = [];
508
+ /**
509
+ * Move a relation column that is only missing because it was renamed.
510
+ *
511
+ * Returns true when it handled the column, so the caller skips the ordinary
512
+ * ADD. Adding here would be the wrong move and a quiet one: the data is in
513
+ * the old column, `ADD COLUMN` creates the new one empty beside it, every
514
+ * statement succeeds, and the relation reads the empty one. A rename is
515
+ * metadata-only in Postgres, keeps the values, and carries the column's
516
+ * indexes and constraints with it.
517
+ *
518
+ * Only ever reached when the new name is absent and the old name is
519
+ * present, so there is nothing to overwrite and nothing to choose between.
520
+ */
521
+ const renameLegacyColumn = (key, schema, table, column, legacyName) => {
522
+ const present = existing.tables.get(key);
523
+ if (!legacyName || !present) return false;
524
+ if (present.has(column) || !present.has(legacyName)) return false;
525
+ legacyForeignKeys.push({
526
+ table: key,
527
+ expected: column,
528
+ legacy: legacyName
529
+ });
530
+ actions.push({
531
+ kind: "rename-column",
532
+ target: `${key}.${column}`,
533
+ sql: `ALTER TABLE "${schema}"."${table}" RENAME COLUMN "${legacyName}" TO "${column}";`
534
+ });
535
+ return true;
536
+ };
537
+ const addColumn = (key, schema, table, column, definition) => {
538
+ if (existing.tables.get(key)?.has(column)) return;
539
+ actions.push({
540
+ kind: "add-column",
541
+ target: `${key}.${column}`,
542
+ sql: `ALTER TABLE "${schema}"."${table}" ADD COLUMN IF NOT EXISTS "${column}" ${definition};`
543
+ });
544
+ };
545
+ for (const collection of collections) {
546
+ const key = qualified(collection);
547
+ const schema = schemaOf(collection);
548
+ const table = getTableName(collection);
549
+ const fresh = created.has(key);
550
+ const auth = isAuthCollection(collection);
551
+ for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
552
+ const p = prop;
553
+ if (isIdProperty(propName, p, collection)) continue;
554
+ if (p.type === "reference" || p.type === "relation") continue;
555
+ const column = resolveColumnName(propName, p);
556
+ const authDefinition = auth ? authUsersColumnDefinition(column) : void 0;
557
+ if (authDefinition) {
558
+ addColumn(key, schema, table, column, authDefinition);
559
+ continue;
560
+ }
561
+ let definition = getSqlColumnType(propName, p, collection, collections);
562
+ if (fresh && p.validation?.unique) definition += " UNIQUE";
563
+ const autoValue = p.autoValue;
564
+ if (p.type === "date" && (autoValue === "on_create" || autoValue === "on_update")) definition += " DEFAULT now()";
565
+ if (fresh && p.validation?.required) definition += " NOT NULL";
566
+ addColumn(key, schema, table, column, definition);
567
+ }
568
+ if (auth) {
569
+ const declared = new Set(Object.entries(collection.properties ?? {}).map(([name, prop]) => resolveColumnName(name, prop)));
570
+ for (const spec of AUTH_USERS_COLUMNS) {
571
+ if (declared.has(spec.column)) continue;
572
+ addColumn(key, schema, table, spec.column, authUsersColumnSql(spec));
573
+ }
574
+ }
575
+ }
576
+ for (const junction of junctions) {
577
+ const key = `${junction.schema}.${junction.table}`;
578
+ if (created.has(key)) continue;
579
+ for (const column of junction.columns) {
580
+ if (renameLegacyColumn(key, junction.schema, junction.table, column.name, column.legacyName)) continue;
581
+ addColumn(key, junction.schema, junction.table, column.name, column.type);
582
+ }
583
+ }
584
+ for (const relational of planRelationalColumns(collections)) {
585
+ const relKey = `${relational.schema}.${relational.table}`;
586
+ if (renameLegacyColumn(relKey, relational.schema, relational.table, relational.column, relational.legacyColumn)) continue;
587
+ addColumn(relKey, relational.schema, relational.table, relational.column, relational.type);
588
+ }
589
+ const knownConstraints = existing.constraints ?? /* @__PURE__ */ new Set();
590
+ const plannedConstraints = /* @__PURE__ */ new Set();
591
+ const foreignKeys = [...planRelationalColumns(collections).map((r) => r.foreignKey), ...junctions.flatMap((j) => j.foreignKeys)];
592
+ for (const fk of foreignKeys) {
593
+ if (!fk) continue;
594
+ const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;
595
+ if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;
596
+ plannedConstraints.add(name);
597
+ actions.push({
598
+ kind: "add-constraint",
599
+ target: `${fk.schema}.${fk.table}.${fk.constraintName}`,
600
+ sql: fk.sql
601
+ });
602
+ }
603
+ return {
604
+ actions,
605
+ statements: actions.map((a) => a.sql),
606
+ legacyForeignKeys
607
+ };
608
+ }
609
+ /** Read what the database has, for the schemas the collections live in. */
610
+ async function readExistingSchema(client, schemas) {
611
+ const tables = /* @__PURE__ */ new Map();
612
+ const enums = /* @__PURE__ */ new Set();
613
+ if (schemas.length === 0) return {
614
+ tables,
615
+ enums
616
+ };
617
+ const inList = schemas.map((schema) => `'${assertSafeIdentifier(schema, "schema name")}'`).join(", ");
618
+ const { rows: columns } = await client.query(`SELECT table_schema, table_name, column_name
619
+ FROM information_schema.columns
620
+ WHERE table_schema IN (${inList})`);
621
+ for (const row of columns) {
622
+ const key = `${row.table_schema}.${row.table_name}`;
623
+ if (!tables.has(key)) tables.set(key, /* @__PURE__ */ new Set());
624
+ tables.get(key).add(row.column_name);
625
+ }
626
+ const { rows: enumRows } = await client.query(`SELECT n.nspname AS schema, t.typname AS name
627
+ FROM pg_type t
628
+ JOIN pg_namespace n ON t.typnamespace = n.oid
629
+ WHERE t.typtype = 'e' AND n.nspname IN (${inList})`);
630
+ for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);
631
+ const constraints = /* @__PURE__ */ new Set();
632
+ const { rows: constraintRows } = await client.query(`SELECT n.nspname AS schema, c.relname AS table, con.conname AS name
633
+ FROM pg_constraint con
634
+ JOIN pg_class c ON con.conrelid = c.oid
635
+ JOIN pg_namespace n ON c.relnamespace = n.oid
636
+ WHERE n.nspname IN (${inList})`);
637
+ for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);
638
+ return {
639
+ tables,
640
+ enums,
641
+ constraints
642
+ };
643
+ }
644
+ /**
645
+ * Bring the database up to date. Returns what it did.
646
+ *
647
+ * Each statement runs on its own rather than in one transaction: they are all
648
+ * independently safe and idempotent, and a single failure (an enum label that
649
+ * cannot be added, say) should not roll back the tables that were created fine.
650
+ * The error is surfaced with the statement that caused it.
651
+ */
652
+ async function ensureCollectionTables(client, collections, log) {
653
+ const schemas = Array.from(/* @__PURE__ */ new Set([...collections.map(schemaOf), ...planJunctionTables(collections).map((j) => j.schema)]));
654
+ for (const schema of schemas) {
655
+ assertSafeIdentifier(schema, "schema name");
656
+ if (schema !== "public") await client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}";`);
657
+ }
658
+ const plan = planCollectionSchemaEnsure(collections, await readExistingSchema(client, schemas));
659
+ const failures = [];
660
+ for (const legacy of plan.legacyForeignKeys) {
661
+ 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.`;
662
+ logger.info(`[schema] ${message}`);
663
+ log?.(message);
664
+ }
665
+ if (plan.actions.length === 0) {
666
+ log?.("Schema is up to date; nothing to create.");
667
+ return {
668
+ ...plan,
669
+ failures
670
+ };
671
+ }
672
+ for (const action of plan.actions) try {
673
+ await client.query(action.sql);
674
+ log?.(`${action.kind}: ${action.target}`);
675
+ } catch (err) {
676
+ const message = err instanceof Error ? err.message : String(err);
677
+ if (action.kind === "add-constraint") {
678
+ failures.push({
679
+ target: action.target,
680
+ error: message
681
+ });
682
+ continue;
683
+ }
684
+ throw new Error(`Failed to ${action.kind} ${action.target}: ${message}\n ${action.sql}`);
685
+ }
686
+ return {
687
+ ...plan,
688
+ failures
689
+ };
690
+ }
691
+ //#endregion
692
+ export { ensureCollectionTables, readExistingSchema, planCollectionPolicies as t };
693
+
694
+ //# sourceMappingURL=ensure-collection-tables-DSIxvLLD.js.map