@rebasepro/server-postgres 0.18.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BranchService-ByLfM_Tt.js +360 -0
- package/dist/BranchService-ByLfM_Tt.js.map +1 -0
- package/dist/__vite-browser-external-BnuHet1e.js +46 -0
- package/dist/__vite-browser-external-BnuHet1e.js.map +1 -0
- package/dist/arg-Dni7MzLB.js +87 -0
- package/dist/arg-Dni7MzLB.js.map +1 -0
- package/dist/auth-users-columns-D2LBFrMH.js +116 -0
- package/dist/auth-users-columns-D2LBFrMH.js.map +1 -0
- package/dist/backup-cli-oM9WQVlV.js +408 -0
- package/dist/backup-cli-oM9WQVlV.js.map +1 -0
- package/dist/backup-service-Br3tqwsy.js +715 -0
- package/dist/backup-service-Br3tqwsy.js.map +1 -0
- package/dist/cli-errors-DxN4yzdH.js +657 -0
- package/dist/cli-errors-DxN4yzdH.js.map +1 -0
- package/dist/cli-output-CNdMql-L.js +47 -0
- package/dist/cli-output-CNdMql-L.js.map +1 -0
- package/dist/cli.js +2020 -0
- package/dist/cli.js.map +1 -0
- package/dist/{collection-index-C7LopMyX.js → collection-index-BHgT_TKd.js} +32 -3
- package/dist/{collection-index-C7LopMyX.js.map → collection-index-BHgT_TKd.js.map} +1 -1
- package/dist/{collections-schema-version-BMeu3cgv.js → collections-schema-version-T6cGvrDi.js} +1 -2
- package/dist/{collections-schema-version-BMeu3cgv.js.map → collections-schema-version-T6cGvrDi.js.map} +1 -1
- package/dist/databasePoolManager-Bj5FbeAs.js +349 -0
- package/dist/databasePoolManager-Bj5FbeAs.js.map +1 -0
- package/dist/doctor-D7HWmGzs.js +974 -0
- package/dist/doctor-D7HWmGzs.js.map +1 -0
- package/dist/{ensure-collection-policies-CagOzEPS.js → ensure-collection-policies-2c2NV8zX.js} +5 -25
- package/dist/ensure-collection-policies-2c2NV8zX.js.map +1 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js +820 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js.map +1 -0
- package/dist/ensure-tables-CIojK-Rx.js +650 -0
- package/dist/ensure-tables-CIojK-Rx.js.map +1 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js +123 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js.map +1 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +528 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +1 -0
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js +1312 -0
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +1 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js +157 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js.map +1 -0
- package/dist/index.es.js +849 -10807
- package/dist/index.es.js.map +1 -1
- package/dist/introspect-db-logic-C6LQdTxj.js +1378 -0
- package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -0
- package/dist/policy-drift-kNJ6X2Uj.js +313 -0
- package/dist/policy-drift-kNJ6X2Uj.js.map +1 -0
- package/dist/rls-bootstrap-sql-DLDnUjtx.js +7092 -0
- package/dist/rls-bootstrap-sql-DLDnUjtx.js.map +1 -0
- package/dist/{rls-enforcement-ClJoTboT.js → rls-enforcement-DeYEjYLt.js} +14 -3
- package/dist/{rls-enforcement-ClJoTboT.js.map → rls-enforcement-DeYEjYLt.js.map} +1 -1
- package/dist/schema/bin/generate-drizzle-schema.d.ts +1 -0
- package/dist/schema/bin/generate-postgres-ddl.d.ts +1 -0
- package/dist/schema/doctor-cli.js +129 -0
- package/dist/schema/doctor-cli.js.map +1 -0
- package/dist/schema/generate-drizzle-schema.d.ts +1 -1
- package/dist/schema/generate-drizzle-schema.js +24 -0
- package/dist/schema/generate-drizzle-schema.js.map +1 -0
- package/dist/schema/generate-postgres-ddl.d.ts +1 -1
- package/dist/schema/generate-postgres-ddl.js +138 -0
- package/dist/schema/generate-postgres-ddl.js.map +1 -0
- package/dist/schema/introspect-db.js +866 -0
- package/dist/schema/introspect-db.js.map +1 -0
- package/dist/source-Br7L7GOI.js +410 -0
- package/dist/source-Br7L7GOI.js.map +1 -0
- package/dist/vector-index-DkWxm2de.js +309 -0
- package/dist/vector-index-DkWxm2de.js.map +1 -0
- package/package.json +7 -7
- package/dist/ensure-collection-policies-CagOzEPS.js.map +0 -1
- package/dist/ensure-collection-tables-DbAhrjnG.js +0 -2732
- package/dist/ensure-collection-tables-DbAhrjnG.js.map +0 -1
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "module";
|
|
2
|
+
__createRequire(import.meta.url);
|
|
3
|
+
import { r as __exportAll } from "./__vite-browser-external-BnuHet1e.js";
|
|
4
|
+
import { C as searchIndexStatements, S as searchHelperFunctions, _ as assertSearchIsPostgresOnly, b as searchColumnStamps, c as isIdProperty, d as planRelationalColumns, f as quoteSqlLiteral, g as SEARCH_UNACCENT_FN, h as SEARCH_TEXT_FN, p as resolveColumnName, s as getSqlColumnType, u as planJunctionTables, v as buildSearchColumnSpec, x as searchExtensionStatements } from "./generate-postgres-ddl-logic-CtnpIBVv.js";
|
|
5
|
+
import { l as extractCauseMessage, u as extractPgError } from "./cli-errors-DxN4yzdH.js";
|
|
6
|
+
import { i as isAuthCollection, n as authUsersColumnDefinition, r as authUsersColumnSql, t as AUTH_USERS_COLUMNS } from "./auth-users-columns-D2LBFrMH.js";
|
|
7
|
+
import { c as vectorExtensionStatement, l as vectorIndexStatement, n as buildVectorColumnSpecs, o as vectorExtensionDeclared, r as buildVectorIndexPlan, s as vectorExtensionHint } from "./vector-index-DkWxm2de.js";
|
|
8
|
+
import { r as collectionIndexStatement, t as buildCollectionIndexPlan } from "./collection-index-BHgT_TKd.js";
|
|
9
|
+
import { isConcurrentDdlRace, isDuplicateObjectRace, logger } from "@rebasepro/server";
|
|
10
|
+
import { declaredDatabaseExtensions, isPostgresCollectionConfig } from "@rebasepro/types";
|
|
11
|
+
import { getTableName, relationalCollections } from "@rebasepro/common";
|
|
12
|
+
//#region src/schema/column-type-drift.ts
|
|
13
|
+
/**
|
|
14
|
+
* Types that mean the same thing to everything above the driver.
|
|
15
|
+
*
|
|
16
|
+
* Keyed by every spelling either side can produce: `information_schema` reports
|
|
17
|
+
* `udt_name` (`int4`, `_numeric`, `bpchar`), while the generators emit SQL
|
|
18
|
+
* (`INTEGER`, `NUMERIC[]`, `CHAR(3)`). Both are normalised through here.
|
|
19
|
+
*/
|
|
20
|
+
var FAMILIES = {
|
|
21
|
+
int2: "number",
|
|
22
|
+
smallint: "number",
|
|
23
|
+
int4: "number",
|
|
24
|
+
int: "number",
|
|
25
|
+
integer: "number",
|
|
26
|
+
int8: "number",
|
|
27
|
+
bigint: "number",
|
|
28
|
+
numeric: "number",
|
|
29
|
+
decimal: "number",
|
|
30
|
+
float4: "number",
|
|
31
|
+
real: "number",
|
|
32
|
+
float8: "number",
|
|
33
|
+
"double precision": "number",
|
|
34
|
+
money: "number",
|
|
35
|
+
text: "text",
|
|
36
|
+
varchar: "text",
|
|
37
|
+
"character varying": "text",
|
|
38
|
+
bpchar: "text",
|
|
39
|
+
char: "text",
|
|
40
|
+
character: "text",
|
|
41
|
+
citext: "text",
|
|
42
|
+
bool: "boolean",
|
|
43
|
+
boolean: "boolean",
|
|
44
|
+
json: "json",
|
|
45
|
+
jsonb: "jsonb",
|
|
46
|
+
uuid: "uuid",
|
|
47
|
+
bytea: "bytea",
|
|
48
|
+
date: "date",
|
|
49
|
+
time: "time",
|
|
50
|
+
"time without time zone": "time",
|
|
51
|
+
timetz: "time",
|
|
52
|
+
"time with time zone": "time",
|
|
53
|
+
timestamp: "timestamp",
|
|
54
|
+
"timestamp without time zone": "timestamp",
|
|
55
|
+
timestamptz: "timestamptz",
|
|
56
|
+
"timestamp with time zone": "timestamptz",
|
|
57
|
+
interval: "interval",
|
|
58
|
+
tsvector: "tsvector",
|
|
59
|
+
vector: "vector",
|
|
60
|
+
halfvec: "halfvec",
|
|
61
|
+
sparsevec: "sparsevec"
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* One SQL or `udt_name` spelling reduced to its family, or `null` when this
|
|
65
|
+
* module has no opinion about it.
|
|
66
|
+
*
|
|
67
|
+
* `null` is not a failure. It is the answer for an enum type, a domain, a
|
|
68
|
+
* PostGIS column, a quoted qualified name — everything whose identity is a
|
|
69
|
+
* *name* rather than a shape, where two spellings being different says nothing
|
|
70
|
+
* about whether the values are compatible.
|
|
71
|
+
*/
|
|
72
|
+
function typeFamily(raw) {
|
|
73
|
+
if (!raw) return null;
|
|
74
|
+
let type = raw.trim().toLowerCase();
|
|
75
|
+
if (!type) return null;
|
|
76
|
+
if (type.startsWith("\"")) return null;
|
|
77
|
+
const generated = type.indexOf(" generated ");
|
|
78
|
+
if (generated > 0) type = type.slice(0, generated).trim();
|
|
79
|
+
if (type.endsWith("[]")) {
|
|
80
|
+
const element = typeFamily(type.slice(0, -2));
|
|
81
|
+
return element && `array:${element}`;
|
|
82
|
+
}
|
|
83
|
+
if (type.startsWith("_")) {
|
|
84
|
+
const element = typeFamily(type.slice(1));
|
|
85
|
+
return element && `array:${element}`;
|
|
86
|
+
}
|
|
87
|
+
const paren = type.indexOf("(");
|
|
88
|
+
if (paren > 0) type = type.slice(0, paren).trim();
|
|
89
|
+
return FAMILIES[type] ?? null;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Do these two spellings describe columns that hold the same kind of value?
|
|
93
|
+
*
|
|
94
|
+
* `true` whenever the answer is not confidently "no" — an unrecognised type on
|
|
95
|
+
* either side agrees with everything, because a report needs evidence and an
|
|
96
|
+
* unknown type is the absence of it.
|
|
97
|
+
*/
|
|
98
|
+
function typesAgree(declared, actual) {
|
|
99
|
+
const a = typeFamily(declared);
|
|
100
|
+
const b = typeFamily(actual);
|
|
101
|
+
if (a === null || b === null) return true;
|
|
102
|
+
return a === b;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The sentence a boot log says about one drifted column.
|
|
106
|
+
*
|
|
107
|
+
* Written to be actionable in the place it is read, which is a runtime log with
|
|
108
|
+
* no way to run a migration from it: it names both types, says which surface
|
|
109
|
+
* will break first, and gives the statement that resolves it.
|
|
110
|
+
*/
|
|
111
|
+
function columnTypeDriftMessage(drift) {
|
|
112
|
+
const [schema, table] = drift.table.split(".");
|
|
113
|
+
return `Column "${drift.table}"."${drift.column}" is ${drift.actual} in the database, but this collection declares ${drift.declared}. Boot does not change an existing column's type, so the database keeps what it has and writes that match the declaration will be rejected by Postgres. Change it deliberately, when you can watch it:
|
|
114
|
+
ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${drift.column}" TYPE ${drift.declared} USING "${drift.column}"::${drift.declared};`;
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/schema/ensure-collection-tables.ts
|
|
118
|
+
/**
|
|
119
|
+
* Bringing a database up to date with a bundle's collections, additively.
|
|
120
|
+
*
|
|
121
|
+
* ## Why this exists
|
|
122
|
+
*
|
|
123
|
+
* A managed runtime boots someone else's compiled project against a database it
|
|
124
|
+
* has never seen. Auth tables are ensured at boot already, but collection tables
|
|
125
|
+
* were not created by anything: the platform ran the app and every `/api/data/*`
|
|
126
|
+
* request answered 500 on a missing relation. `rebase db push` cannot help — it
|
|
127
|
+
* is an Atlas-driven CLI command, and the runtime image ships no CLI.
|
|
128
|
+
*
|
|
129
|
+
* ## Why additive-only, forever
|
|
130
|
+
*
|
|
131
|
+
* This runs unattended, against a database with customers' data in it, with no
|
|
132
|
+
* human reading a diff. So it may only ever do things that cannot lose data:
|
|
133
|
+
* create a missing table, add a missing column, create a missing enum type.
|
|
134
|
+
*
|
|
135
|
+
* It will **never** drop a table or a column, narrow a type, or alter a
|
|
136
|
+
* constraint. A removed field leaves its column behind; a renamed field looks
|
|
137
|
+
* like an addition and the old column stays. That is the correct trade for an
|
|
138
|
+
* automated path — the alternative is an unattended process that can silently
|
|
139
|
+
* destroy a column, which is precisely the failure `db push` was hardened
|
|
140
|
+
* against. Destructive changes stay a deliberate, human-reviewed migration.
|
|
141
|
+
*
|
|
142
|
+
* Because of that, this is safe to run on every boot, and re-running it is a
|
|
143
|
+
* no-op.
|
|
144
|
+
*/
|
|
145
|
+
var ensure_collection_tables_exports = /* @__PURE__ */ __exportAll({
|
|
146
|
+
describeDriverError: () => describeDriverError,
|
|
147
|
+
ensureCollectionTables: () => ensureCollectionTables,
|
|
148
|
+
planCollectionSchemaEnsure: () => planCollectionSchemaEnsure,
|
|
149
|
+
readExistingSchema: () => readExistingSchema,
|
|
150
|
+
readSchemaFactsFor: () => readSchemaFactsFor
|
|
151
|
+
});
|
|
152
|
+
/** Postgres identifiers this module is willing to interpolate. */
|
|
153
|
+
var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
|
154
|
+
function assertSafeIdentifier(value, what) {
|
|
155
|
+
if (!SAFE_IDENTIFIER.test(value)) throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);
|
|
156
|
+
return value;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* The schema a collection lives in — validated, because it is about to be
|
|
160
|
+
* interpolated into DDL.
|
|
161
|
+
*
|
|
162
|
+
* Validation used to run only on the names read back OUT of the catalogue,
|
|
163
|
+
* which is the direction that cannot hurt anyone: those came from Postgres. The
|
|
164
|
+
* names going IN — the schema and table a collection declares — were quoted and
|
|
165
|
+
* concatenated on trust, and quoting is not escaping. A table named
|
|
166
|
+
* `x" (id int); DROP TABLE users; --` closes the quote and the statement, and
|
|
167
|
+
* the whole thing runs on the owner connection, which is the one connection in
|
|
168
|
+
* the system that is exempt from every RLS policy.
|
|
169
|
+
*
|
|
170
|
+
* That is only a config file on a self-hosted project, where the person writing
|
|
171
|
+
* it could run the SQL directly anyway. It is not only a config file where a
|
|
172
|
+
* collection can be defined over the wire — the live-schema and source editors
|
|
173
|
+
* both do that — and there the caller is an admin on the app, not an operator
|
|
174
|
+
* of the database.
|
|
175
|
+
*/
|
|
176
|
+
function schemaOf(collection) {
|
|
177
|
+
return assertSafeIdentifier(isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public", "schema name");
|
|
178
|
+
}
|
|
179
|
+
/** A collection's table name, validated for the same reason as {@link schemaOf}. */
|
|
180
|
+
function tableOf(collection) {
|
|
181
|
+
return assertSafeIdentifier(getTableName(collection), "table name");
|
|
182
|
+
}
|
|
183
|
+
function qualified(collection) {
|
|
184
|
+
return `${schemaOf(collection)}.${tableOf(collection)}`;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Enum types a collection's properties require, as `schema.typename`.
|
|
188
|
+
*
|
|
189
|
+
* Named exactly as the DDL generator names them (`<table>_<column>`), because
|
|
190
|
+
* a column added here has to reference the same type the generator would have
|
|
191
|
+
* created — a second, differently-named type for the same field would be a
|
|
192
|
+
* silent schema fork.
|
|
193
|
+
*/
|
|
194
|
+
function requiredEnums(collection) {
|
|
195
|
+
const table = tableOf(collection);
|
|
196
|
+
const schema = schemaOf(collection);
|
|
197
|
+
const out = [];
|
|
198
|
+
for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
|
|
199
|
+
const p = prop;
|
|
200
|
+
if (!("enum" in p) || !p.enum) continue;
|
|
201
|
+
if (p.type !== "string" && p.type !== "number") continue;
|
|
202
|
+
const values = p.enum.map((entry) => entry && typeof entry === "object" && "id" in entry ? String(entry.id) : String(entry)).filter((v) => v.length > 0);
|
|
203
|
+
if (values.length === 0) continue;
|
|
204
|
+
out.push({
|
|
205
|
+
name: `${schema}.${table}_${resolveColumnName(propName, p)}`,
|
|
206
|
+
values
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
return out;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Decide what to add. Pure — the caller supplies what exists and runs the result.
|
|
213
|
+
*
|
|
214
|
+
* Ordering matters and is deliberate: enum types before the tables and columns
|
|
215
|
+
* that reference them, tables before the columns added to other tables (a new
|
|
216
|
+
* table may be the target of a relation), and nothing is emitted twice.
|
|
217
|
+
*/
|
|
218
|
+
function planCollectionSchemaEnsure(allCollections, existing, options = {}) {
|
|
219
|
+
const constraintPolicy = options.constraints ?? "additive";
|
|
220
|
+
const withheldConstraints = [];
|
|
221
|
+
const columnTypeDrift = [];
|
|
222
|
+
assertSearchIsPostgresOnly(allCollections);
|
|
223
|
+
const collections = relationalCollections(allCollections);
|
|
224
|
+
const actions = [];
|
|
225
|
+
const plannedEnums = /* @__PURE__ */ new Set();
|
|
226
|
+
for (const collection of collections) for (const { name, values } of requiredEnums(collection)) {
|
|
227
|
+
if (existing.enums.has(name) || plannedEnums.has(name)) {
|
|
228
|
+
const current = existing.enumValues?.get(name);
|
|
229
|
+
if (!current || plannedEnums.has(name)) continue;
|
|
230
|
+
const [schema, typeName] = name.split(".");
|
|
231
|
+
for (const value of values) {
|
|
232
|
+
if (current.includes(value)) continue;
|
|
233
|
+
actions.push({
|
|
234
|
+
kind: "add-enum-value",
|
|
235
|
+
target: `${name}.${value}`,
|
|
236
|
+
sql: `ALTER TYPE "${schema}"."${typeName}" ADD VALUE IF NOT EXISTS ${quoteSqlLiteral(value)};`
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
plannedEnums.add(name);
|
|
242
|
+
const [schema, typeName] = name.split(".");
|
|
243
|
+
actions.push({
|
|
244
|
+
kind: "create-enum",
|
|
245
|
+
target: name,
|
|
246
|
+
sql: `CREATE TYPE "${schema}"."${typeName}" AS ENUM (${values.map(quoteSqlLiteral).join(", ")});`
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
const searchSpecs = collections.map((c) => buildSearchColumnSpec(c)).filter((spec) => spec !== void 0);
|
|
250
|
+
const plannedExtensions = /* @__PURE__ */ new Set();
|
|
251
|
+
const planExtension = (statement) => {
|
|
252
|
+
if (plannedExtensions.has(statement)) return;
|
|
253
|
+
plannedExtensions.add(statement);
|
|
254
|
+
actions.push({
|
|
255
|
+
kind: "create-extension",
|
|
256
|
+
target: statement.replace(/^CREATE EXTENSION IF NOT EXISTS |;$/g, ""),
|
|
257
|
+
sql: statement
|
|
258
|
+
});
|
|
259
|
+
};
|
|
260
|
+
for (const spec of searchSpecs) for (const statement of searchExtensionStatements(spec)) planExtension(statement);
|
|
261
|
+
if (vectorExtensionDeclared(options.databaseExtensions) && collections.some((c) => buildVectorColumnSpecs(c, resolveColumnName).length > 0)) planExtension(vectorExtensionStatement());
|
|
262
|
+
const plannedFunctions = /* @__PURE__ */ new Set();
|
|
263
|
+
for (const spec of searchSpecs) for (const statement of searchHelperFunctions(spec)) {
|
|
264
|
+
if (plannedFunctions.has(statement)) continue;
|
|
265
|
+
plannedFunctions.add(statement);
|
|
266
|
+
actions.push({
|
|
267
|
+
kind: "create-function",
|
|
268
|
+
target: statement.includes("unaccent") ? SEARCH_UNACCENT_FN : SEARCH_TEXT_FN,
|
|
269
|
+
sql: statement
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
const created = /* @__PURE__ */ new Set();
|
|
273
|
+
for (const collection of collections) {
|
|
274
|
+
const key = qualified(collection);
|
|
275
|
+
if (existing.tables.has(key) || created.has(key)) continue;
|
|
276
|
+
created.add(key);
|
|
277
|
+
const schema = schemaOf(collection);
|
|
278
|
+
const table = tableOf(collection);
|
|
279
|
+
const idEntry = Object.entries(collection.properties ?? {}).find(([n, p]) => isIdProperty(n, p, collection));
|
|
280
|
+
const idName = idEntry ? resolveColumnName(idEntry[0], idEntry[1]) : "id";
|
|
281
|
+
const idProp = idEntry?.[1];
|
|
282
|
+
const idType = idProp ? getSqlColumnType(idEntry[0], idProp, collection, collections) : "TEXT";
|
|
283
|
+
let idDef = `"${assertSafeIdentifier(idName, "column name")}" ${idType} PRIMARY KEY`;
|
|
284
|
+
if (idProp?.type === "string" && idProp.isId === "uuid") idDef += " DEFAULT gen_random_uuid()";
|
|
285
|
+
actions.push({
|
|
286
|
+
kind: "create-table",
|
|
287
|
+
target: key,
|
|
288
|
+
sql: `CREATE TABLE IF NOT EXISTS "${schema}"."${table}" (${idDef});`
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
const junctions = planJunctionTables(collections);
|
|
292
|
+
for (const junction of junctions) {
|
|
293
|
+
const key = `${junction.schema}.${junction.table}`;
|
|
294
|
+
if (existing.tables.has(key) || created.has(key)) continue;
|
|
295
|
+
created.add(key);
|
|
296
|
+
actions.push({
|
|
297
|
+
kind: "create-table",
|
|
298
|
+
target: key,
|
|
299
|
+
sql: junction.createTable
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
const legacyForeignKeys = [];
|
|
303
|
+
/**
|
|
304
|
+
* Move a relation column that is only missing because it was renamed.
|
|
305
|
+
*
|
|
306
|
+
* Returns true when it handled the column, so the caller skips the ordinary
|
|
307
|
+
* ADD. Adding here would be the wrong move and a quiet one: the data is in
|
|
308
|
+
* the old column, `ADD COLUMN` creates the new one empty beside it, every
|
|
309
|
+
* statement succeeds, and the relation reads the empty one. A rename is
|
|
310
|
+
* metadata-only in Postgres, keeps the values, and carries the column's
|
|
311
|
+
* indexes and constraints with it.
|
|
312
|
+
*
|
|
313
|
+
* Only ever reached when the new name is absent and the old name is
|
|
314
|
+
* present, so there is nothing to overwrite and nothing to choose between.
|
|
315
|
+
*/
|
|
316
|
+
const renameLegacyColumn = (key, schema, table, column, legacyName) => {
|
|
317
|
+
const present = existing.tables.get(key);
|
|
318
|
+
if (!legacyName || !present) return false;
|
|
319
|
+
if (present.has(column) || !present.has(legacyName)) return false;
|
|
320
|
+
legacyForeignKeys.push({
|
|
321
|
+
table: key,
|
|
322
|
+
expected: column,
|
|
323
|
+
legacy: legacyName
|
|
324
|
+
});
|
|
325
|
+
actions.push({
|
|
326
|
+
kind: "rename-column",
|
|
327
|
+
target: `${key}.${column}`,
|
|
328
|
+
sql: `ALTER TABLE "${schema}"."${table}" RENAME COLUMN "${legacyName}" TO "${column}";`
|
|
329
|
+
});
|
|
330
|
+
return true;
|
|
331
|
+
};
|
|
332
|
+
const addColumn = (key, schema, table, column, definition) => {
|
|
333
|
+
if (existing.tables.get(key)?.has(column)) return;
|
|
334
|
+
assertSafeIdentifier(column, "column name");
|
|
335
|
+
actions.push({
|
|
336
|
+
kind: "add-column",
|
|
337
|
+
target: `${key}.${column}`,
|
|
338
|
+
sql: `ALTER TABLE "${schema}"."${table}" ADD COLUMN IF NOT EXISTS "${column}" ${definition};`
|
|
339
|
+
});
|
|
340
|
+
};
|
|
341
|
+
for (const collection of collections) {
|
|
342
|
+
const key = qualified(collection);
|
|
343
|
+
const schema = schemaOf(collection);
|
|
344
|
+
const table = tableOf(collection);
|
|
345
|
+
const fresh = created.has(key);
|
|
346
|
+
const auth = isAuthCollection(collection);
|
|
347
|
+
for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
|
|
348
|
+
const p = prop;
|
|
349
|
+
if (isIdProperty(propName, p, collection)) continue;
|
|
350
|
+
if (p.type === "reference" || p.type === "relation") continue;
|
|
351
|
+
const column = resolveColumnName(propName, p);
|
|
352
|
+
const authDefinition = auth ? authUsersColumnDefinition(column) : void 0;
|
|
353
|
+
if (authDefinition) {
|
|
354
|
+
addColumn(key, schema, table, column, authDefinition);
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
const declaredType = getSqlColumnType(propName, p, collection, collections);
|
|
358
|
+
let definition = declaredType;
|
|
359
|
+
if (fresh && p.validation?.unique) definition += " UNIQUE";
|
|
360
|
+
const autoValue = p.autoValue;
|
|
361
|
+
const hasDefault = p.type === "date" && (autoValue === "on_create" || autoValue === "on_update");
|
|
362
|
+
if (hasDefault) definition += " DEFAULT now()";
|
|
363
|
+
const required = p.validation?.required === true;
|
|
364
|
+
const columnKey = `${key}.${column}`;
|
|
365
|
+
const columnExists = existing.tables.get(key)?.has(column) === true;
|
|
366
|
+
const actualType = existing.columnTypes?.get(columnKey);
|
|
367
|
+
if (columnExists && actualType && !typesAgree(declaredType, actualType)) columnTypeDrift.push({
|
|
368
|
+
table: key,
|
|
369
|
+
column,
|
|
370
|
+
declared: declaredType,
|
|
371
|
+
actual: actualType
|
|
372
|
+
});
|
|
373
|
+
const tableIsEmpty = existing.populatedTables !== void 0 && existing.tables.has(key) && !existing.populatedTables.has(key);
|
|
374
|
+
const notNullIsSafe = fresh || tableIsEmpty || hasDefault;
|
|
375
|
+
if (required && !columnExists) if (notNullIsSafe) definition += " NOT NULL";
|
|
376
|
+
else withheldConstraints.push({
|
|
377
|
+
target: columnKey,
|
|
378
|
+
kind: "not-null",
|
|
379
|
+
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.`,
|
|
380
|
+
remedy: "Backfill the column, then add the constraint — or give the property a default so every existing row gets one."
|
|
381
|
+
});
|
|
382
|
+
addColumn(key, schema, table, column, definition);
|
|
383
|
+
if (columnExists && constraintPolicy === "converge") {
|
|
384
|
+
const isNotNull = existing.notNullColumns?.has(columnKey) === true;
|
|
385
|
+
if (required && !isNotNull) if (tableIsEmpty) actions.push({
|
|
386
|
+
kind: "set-not-null",
|
|
387
|
+
target: columnKey,
|
|
388
|
+
sql: `ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${column}" SET NOT NULL;`
|
|
389
|
+
});
|
|
390
|
+
else withheldConstraints.push({
|
|
391
|
+
target: columnKey,
|
|
392
|
+
kind: "not-null",
|
|
393
|
+
reason: `"${column}" became required, but "${key}" holds rows and any of them with no value would make SET NOT NULL fail.`,
|
|
394
|
+
remedy: "Backfill the column first — `UPDATE … SET \"" + column + "\" = … WHERE \"" + column + "\" IS NULL` — then apply this again."
|
|
395
|
+
});
|
|
396
|
+
if (!required && isNotNull) actions.push({
|
|
397
|
+
kind: "drop-not-null",
|
|
398
|
+
target: columnKey,
|
|
399
|
+
sql: `ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${column}" DROP NOT NULL;`
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (auth) {
|
|
404
|
+
const declared = new Set(Object.entries(collection.properties ?? {}).map(([name, prop]) => resolveColumnName(name, prop)));
|
|
405
|
+
for (const spec of AUTH_USERS_COLUMNS) {
|
|
406
|
+
if (declared.has(spec.column)) continue;
|
|
407
|
+
addColumn(key, schema, table, spec.column, authUsersColumnSql(spec));
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const searchDrift = [];
|
|
412
|
+
const searchAdopted = [];
|
|
413
|
+
for (const spec of searchSpecs) {
|
|
414
|
+
const key = `${spec.schema}.${spec.table}`;
|
|
415
|
+
const definitions = { [spec.column]: `tsvector GENERATED ALWAYS AS (${spec.expression}) STORED` };
|
|
416
|
+
if (spec.fuzzy) definitions[spec.fuzzy.column] = `text GENERATED ALWAYS AS (${spec.fuzzy.expression}) STORED`;
|
|
417
|
+
for (const stamp of searchColumnStamps(spec)) {
|
|
418
|
+
const definition = definitions[stamp.column];
|
|
419
|
+
const exists = existing.tables.get(key)?.has(stamp.column) === true;
|
|
420
|
+
const recorded = existing.columnComments?.get(`${key}.${stamp.column}`);
|
|
421
|
+
if (exists && recorded?.startsWith("rebase:search:v1:") && recorded !== stamp.fingerprint) {
|
|
422
|
+
searchDrift.push({
|
|
423
|
+
table: key,
|
|
424
|
+
column: stamp.column,
|
|
425
|
+
found: recorded,
|
|
426
|
+
expected: stamp.fingerprint,
|
|
427
|
+
rebuild: [
|
|
428
|
+
`ALTER TABLE "${spec.schema}"."${spec.table}" DROP COLUMN "${stamp.column}";`,
|
|
429
|
+
`ALTER TABLE "${spec.schema}"."${spec.table}" ADD COLUMN "${stamp.column}" ${definition};`,
|
|
430
|
+
stamp.sql
|
|
431
|
+
]
|
|
432
|
+
});
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
addColumn(key, spec.schema, spec.table, stamp.column, definition);
|
|
436
|
+
if (exists && recorded === void 0) searchAdopted.push({
|
|
437
|
+
table: key,
|
|
438
|
+
column: stamp.column
|
|
439
|
+
});
|
|
440
|
+
if (recorded !== stamp.fingerprint) actions.push({
|
|
441
|
+
kind: "comment-column",
|
|
442
|
+
target: `${key}.${stamp.column}`,
|
|
443
|
+
sql: stamp.sql
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
for (const junction of junctions) {
|
|
448
|
+
const key = `${junction.schema}.${junction.table}`;
|
|
449
|
+
if (created.has(key)) continue;
|
|
450
|
+
for (const column of junction.columns) {
|
|
451
|
+
if (renameLegacyColumn(key, junction.schema, junction.table, column.name, column.legacyName)) continue;
|
|
452
|
+
addColumn(key, junction.schema, junction.table, column.name, column.type);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const plannedRelationColumns = /* @__PURE__ */ new Map();
|
|
456
|
+
for (const relational of planRelationalColumns(collections)) {
|
|
457
|
+
const relKey = `${relational.schema}.${relational.table}`;
|
|
458
|
+
if (!plannedRelationColumns.has(relKey)) plannedRelationColumns.set(relKey, /* @__PURE__ */ new Set());
|
|
459
|
+
plannedRelationColumns.get(relKey).add(relational.column);
|
|
460
|
+
if (relational.legacyColumn) plannedRelationColumns.get(relKey).add(relational.legacyColumn);
|
|
461
|
+
if (renameLegacyColumn(relKey, relational.schema, relational.table, relational.column, relational.legacyColumn)) continue;
|
|
462
|
+
addColumn(relKey, relational.schema, relational.table, relational.column, relational.type);
|
|
463
|
+
}
|
|
464
|
+
const knownConstraints = existing.constraints ?? /* @__PURE__ */ new Set();
|
|
465
|
+
const plannedConstraints = /* @__PURE__ */ new Set();
|
|
466
|
+
const foreignKeys = [...planRelationalColumns(collections).map((r) => r.foreignKey), ...junctions.flatMap((j) => j.foreignKeys)];
|
|
467
|
+
for (const fk of foreignKeys) {
|
|
468
|
+
if (!fk) continue;
|
|
469
|
+
const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;
|
|
470
|
+
if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;
|
|
471
|
+
plannedConstraints.add(name);
|
|
472
|
+
actions.push({
|
|
473
|
+
kind: "add-constraint",
|
|
474
|
+
target: `${fk.schema}.${fk.table}.${fk.constraintName}`,
|
|
475
|
+
sql: fk.sql
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
const concurrentIndexing = (schema, table) => !created.has(`${schema}.${table}`);
|
|
479
|
+
for (const spec of searchSpecs) for (const statement of searchIndexStatements(spec)) actions.push({
|
|
480
|
+
kind: "create-index",
|
|
481
|
+
target: `${spec.schema}.${spec.table}`,
|
|
482
|
+
sql: concurrentIndexing(spec.schema, spec.table) ? statement.replace("CREATE INDEX IF NOT EXISTS", "CREATE INDEX CONCURRENTLY IF NOT EXISTS") : statement
|
|
483
|
+
});
|
|
484
|
+
const vectorIndexSkipped = [];
|
|
485
|
+
for (const collection of collections) {
|
|
486
|
+
const plan = buildVectorIndexPlan(collection, resolveColumnName);
|
|
487
|
+
for (const spec of plan.specs) actions.push({
|
|
488
|
+
kind: "create-index",
|
|
489
|
+
target: `${spec.schema}.${spec.table}`,
|
|
490
|
+
sql: concurrentIndexing(spec.schema, spec.table) ? vectorIndexStatement(spec).replace("CREATE INDEX IF NOT EXISTS", "CREATE INDEX CONCURRENTLY IF NOT EXISTS") : vectorIndexStatement(spec)
|
|
491
|
+
});
|
|
492
|
+
vectorIndexSkipped.push(...plan.skipped);
|
|
493
|
+
}
|
|
494
|
+
for (const spec of buildCollectionIndexPlan(collections, resolveColumnName)) actions.push({
|
|
495
|
+
kind: "create-index",
|
|
496
|
+
target: `${spec.schema}.${spec.table}`,
|
|
497
|
+
sql: collectionIndexStatement(spec, {
|
|
498
|
+
concurrently: concurrentIndexing(spec.schema, spec.table),
|
|
499
|
+
ifNotExists: true
|
|
500
|
+
})
|
|
501
|
+
});
|
|
502
|
+
const orphanedRequiredColumns = [];
|
|
503
|
+
if (existing.notNullColumns && existing.columnDefaults) for (const collection of collections) {
|
|
504
|
+
const key = qualified(collection);
|
|
505
|
+
const live = existing.tables.get(key);
|
|
506
|
+
if (!live || created.has(key)) continue;
|
|
507
|
+
const declared = /* @__PURE__ */ new Set();
|
|
508
|
+
for (const [propName, prop] of Object.entries(collection.properties ?? {})) declared.add(resolveColumnName(propName, prop));
|
|
509
|
+
for (const column of plannedRelationColumns.get(key) ?? []) declared.add(column);
|
|
510
|
+
for (const column of live) {
|
|
511
|
+
const columnKey = `${key}.${column}`;
|
|
512
|
+
if (declared.has(column)) continue;
|
|
513
|
+
if (!existing.notNullColumns.has(columnKey)) continue;
|
|
514
|
+
if (existing.columnDefaults.has(columnKey)) continue;
|
|
515
|
+
orphanedRequiredColumns.push({
|
|
516
|
+
table: key,
|
|
517
|
+
column,
|
|
518
|
+
slug: collection.slug
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return {
|
|
523
|
+
actions,
|
|
524
|
+
statements: actions.map((a) => a.sql),
|
|
525
|
+
legacyForeignKeys,
|
|
526
|
+
searchDrift,
|
|
527
|
+
searchAdopted,
|
|
528
|
+
vectorIndexSkipped,
|
|
529
|
+
withheldConstraints,
|
|
530
|
+
columnTypeDrift,
|
|
531
|
+
orphanedRequiredColumns
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
/** Read what the database has, for the schemas the collections live in. */
|
|
535
|
+
async function readExistingSchema(client, schemas) {
|
|
536
|
+
const tables = /* @__PURE__ */ new Map();
|
|
537
|
+
const enums = /* @__PURE__ */ new Set();
|
|
538
|
+
if (schemas.length === 0) return {
|
|
539
|
+
tables,
|
|
540
|
+
enums
|
|
541
|
+
};
|
|
542
|
+
const inList = schemas.map((schema) => `'${assertSafeIdentifier(schema, "schema name")}'`).join(", ");
|
|
543
|
+
const notNullColumns = /* @__PURE__ */ new Set();
|
|
544
|
+
const columnTypes = /* @__PURE__ */ new Map();
|
|
545
|
+
const columnDefaults = /* @__PURE__ */ new Set();
|
|
546
|
+
const { rows: columns } = await client.query(`SELECT table_schema, table_name, column_name, is_nullable, udt_name, column_default
|
|
547
|
+
FROM information_schema.columns
|
|
548
|
+
WHERE table_schema IN (${inList})`);
|
|
549
|
+
for (const row of columns) {
|
|
550
|
+
const key = `${row.table_schema}.${row.table_name}`;
|
|
551
|
+
if (!tables.has(key)) tables.set(key, /* @__PURE__ */ new Set());
|
|
552
|
+
tables.get(key).add(row.column_name);
|
|
553
|
+
if (row.is_nullable === "NO") notNullColumns.add(`${key}.${row.column_name}`);
|
|
554
|
+
if (row.udt_name) columnTypes.set(`${key}.${row.column_name}`, row.udt_name);
|
|
555
|
+
if (row.column_default !== null) columnDefaults.add(`${key}.${row.column_name}`);
|
|
556
|
+
}
|
|
557
|
+
const populatedTables = /* @__PURE__ */ new Set();
|
|
558
|
+
const { rows: realTables } = await client.query(`SELECT n.nspname AS schema, c.relname AS name
|
|
559
|
+
FROM pg_class c
|
|
560
|
+
JOIN pg_namespace n ON c.relnamespace = n.oid
|
|
561
|
+
WHERE c.relkind IN ('r', 'p') AND n.nspname IN (${inList})`);
|
|
562
|
+
if (realTables.length > 0) {
|
|
563
|
+
const probes = realTables.map((row) => {
|
|
564
|
+
const schema = assertSafeIdentifier(row.schema, "schema name");
|
|
565
|
+
const table = assertSafeIdentifier(row.name, "table name");
|
|
566
|
+
return `SELECT ${quoteSqlLiteral(`${schema}.${table}`)} AS key, EXISTS(SELECT 1 FROM "${schema}"."${table}" LIMIT 1) AS populated`;
|
|
567
|
+
});
|
|
568
|
+
const { rows: populationRows } = await client.query(probes.join(" UNION ALL "));
|
|
569
|
+
for (const row of populationRows) if (row.populated) populatedTables.add(row.key);
|
|
570
|
+
}
|
|
571
|
+
const enumValues = /* @__PURE__ */ new Map();
|
|
572
|
+
const { rows: enumValueRows } = await client.query(`SELECT n.nspname AS schema, t.typname AS name, e.enumlabel AS value
|
|
573
|
+
FROM pg_enum e
|
|
574
|
+
JOIN pg_type t ON e.enumtypid = t.oid
|
|
575
|
+
JOIN pg_namespace n ON t.typnamespace = n.oid
|
|
576
|
+
WHERE n.nspname IN (${inList})
|
|
577
|
+
ORDER BY t.typname, e.enumsortorder`);
|
|
578
|
+
for (const row of enumValueRows) {
|
|
579
|
+
const key = `${row.schema}.${row.name}`;
|
|
580
|
+
if (!enumValues.has(key)) enumValues.set(key, []);
|
|
581
|
+
enumValues.get(key).push(row.value);
|
|
582
|
+
}
|
|
583
|
+
const { rows: enumRows } = await client.query(`SELECT n.nspname AS schema, t.typname AS name
|
|
584
|
+
FROM pg_type t
|
|
585
|
+
JOIN pg_namespace n ON t.typnamespace = n.oid
|
|
586
|
+
WHERE t.typtype = 'e' AND n.nspname IN (${inList})`);
|
|
587
|
+
for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);
|
|
588
|
+
const constraints = /* @__PURE__ */ new Set();
|
|
589
|
+
const { rows: constraintRows } = await client.query(`SELECT n.nspname AS schema, c.relname AS table, con.conname AS name
|
|
590
|
+
FROM pg_constraint con
|
|
591
|
+
JOIN pg_class c ON con.conrelid = c.oid
|
|
592
|
+
JOIN pg_namespace n ON c.relnamespace = n.oid
|
|
593
|
+
WHERE n.nspname IN (${inList})`);
|
|
594
|
+
for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);
|
|
595
|
+
const columnComments = /* @__PURE__ */ new Map();
|
|
596
|
+
const { rows: commentRows } = await client.query(`SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, d.description AS comment
|
|
597
|
+
FROM pg_description d
|
|
598
|
+
JOIN pg_class c ON d.objoid = c.oid
|
|
599
|
+
JOIN pg_namespace n ON c.relnamespace = n.oid
|
|
600
|
+
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid
|
|
601
|
+
WHERE d.objsubid > 0 AND n.nspname IN (${inList})`);
|
|
602
|
+
for (const row of commentRows) {
|
|
603
|
+
if (row.comment == null) continue;
|
|
604
|
+
columnComments.set(`${row.schema}.${row.table}.${row.column}`, row.comment);
|
|
605
|
+
}
|
|
606
|
+
return {
|
|
607
|
+
tables,
|
|
608
|
+
enums,
|
|
609
|
+
constraints,
|
|
610
|
+
columnComments,
|
|
611
|
+
enumValues,
|
|
612
|
+
notNullColumns,
|
|
613
|
+
populatedTables,
|
|
614
|
+
columnTypes,
|
|
615
|
+
columnDefaults
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* What to tell an operator whose `search` block no longer matches its column.
|
|
620
|
+
*
|
|
621
|
+
* Every line here is doing work: naming the collection is not enough, because
|
|
622
|
+
* the symptom (a search that finds nothing) points at the data, not the schema;
|
|
623
|
+
* and the remediation has to be exact, because it is a table rewrite the
|
|
624
|
+
* operator is being asked to schedule rather than discover.
|
|
625
|
+
*/
|
|
626
|
+
function searchDriftMessage(drift) {
|
|
627
|
+
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.";
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Read what the database looks like, for the schemas a set of collections
|
|
631
|
+
* lives in.
|
|
632
|
+
*
|
|
633
|
+
* The same read `ensureCollectionTables` does at boot, exposed on its own for
|
|
634
|
+
* the callers that want to *plan* against a real database without changing it —
|
|
635
|
+
* the live schema editor, which has to tell somebody what a change would do
|
|
636
|
+
* before they agree to it.
|
|
637
|
+
*/
|
|
638
|
+
async function readSchemaFactsFor(client, collections) {
|
|
639
|
+
const relational = relationalCollections(collections);
|
|
640
|
+
return readExistingSchema(client, Array.from(/* @__PURE__ */ new Set([...relational.map(schemaOf), ...planJunctionTables(relational).map((junction) => junction.schema)])));
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Bring the database up to date. Returns what it did.
|
|
644
|
+
*
|
|
645
|
+
* Each statement runs on its own rather than in one transaction: they are all
|
|
646
|
+
* independently safe and idempotent, and a single failure (an enum label that
|
|
647
|
+
* cannot be added, say) should not roll back the tables that were created fine.
|
|
648
|
+
* The error is surfaced with the statement that caused it.
|
|
649
|
+
*/
|
|
650
|
+
async function ensureCollectionTables(client, collections, log, options = {}) {
|
|
651
|
+
const schemas = Array.from(/* @__PURE__ */ new Set([...collections.map(schemaOf), ...planJunctionTables(collections).map((j) => j.schema)]));
|
|
652
|
+
for (const schema of schemas) {
|
|
653
|
+
assertSafeIdentifier(schema, "schema name");
|
|
654
|
+
if (schema !== "public") await client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}";`);
|
|
655
|
+
}
|
|
656
|
+
const plan = planCollectionSchemaEnsure(collections, await readExistingSchema(client, schemas), {
|
|
657
|
+
...options,
|
|
658
|
+
databaseExtensions: options.databaseExtensions ?? declaredDatabaseExtensions()
|
|
659
|
+
});
|
|
660
|
+
const failures = [];
|
|
661
|
+
for (const legacy of plan.legacyForeignKeys) {
|
|
662
|
+
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.`;
|
|
663
|
+
logger.info(`[schema] ${message}`);
|
|
664
|
+
log?.(message);
|
|
665
|
+
}
|
|
666
|
+
if (plan.searchDrift.length > 0) throw new Error(searchDriftMessage(plan.searchDrift));
|
|
667
|
+
for (const adopted of plan.searchAdopted) {
|
|
668
|
+
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.`;
|
|
669
|
+
logger.info(`[schema] ${message}`);
|
|
670
|
+
log?.(message);
|
|
671
|
+
}
|
|
672
|
+
for (const skip of plan.vectorIndexSkipped) {
|
|
673
|
+
const message = `No ANN index on "${skip.table}"."${skip.column}": ${skip.reason}`;
|
|
674
|
+
logger.warn(`[schema] ${message}`);
|
|
675
|
+
log?.(message);
|
|
676
|
+
}
|
|
677
|
+
for (const withheld of plan.withheldConstraints) {
|
|
678
|
+
const message = `No NOT NULL on "${withheld.target}": ${withheld.reason} ${withheld.remedy}`;
|
|
679
|
+
logger.warn(`[schema] ${message}`);
|
|
680
|
+
log?.(message);
|
|
681
|
+
}
|
|
682
|
+
for (const drift of plan.columnTypeDrift) {
|
|
683
|
+
const message = columnTypeDriftMessage(drift);
|
|
684
|
+
logger.warn(`[schema] ${message}`);
|
|
685
|
+
log?.(message);
|
|
686
|
+
}
|
|
687
|
+
for (const orphan of plan.orphanedRequiredColumns) {
|
|
688
|
+
const [schema, table] = orphan.table.split(".");
|
|
689
|
+
const message = `"${orphan.table}"."${orphan.column}" is NOT NULL with no default, and the "${orphan.slug}" collection no longer declares it. Every insert will be rejected for a field you cannot set (PG_23502, naming "${orphan.column}"). This is what a renamed property looks like: the new column was added, and the old one cannot be dropped unattended. Fix it with ONE of:
|
|
690
|
+
ALTER TABLE "${schema}"."${table}" DROP COLUMN "${orphan.column}"; -- the rename is complete\n ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${orphan.column}" DROP NOT NULL; -- keep the data, stop requiring it\n ...or declare the property again, if the column is still wanted.`;
|
|
691
|
+
logger.warn(`[schema] ${message}`);
|
|
692
|
+
log?.(message);
|
|
693
|
+
}
|
|
694
|
+
if (plan.actions.length === 0) {
|
|
695
|
+
log?.("Schema is up to date; nothing to create.");
|
|
696
|
+
return {
|
|
697
|
+
...plan,
|
|
698
|
+
failures
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
for (const action of plan.actions) try {
|
|
702
|
+
if (await applyAction(client, action)) log?.(`${action.kind}: ${action.target}`);
|
|
703
|
+
else log?.(`${action.kind}: ${action.target} (already created by a peer)`);
|
|
704
|
+
} catch (err) {
|
|
705
|
+
const message = describeDriverError(err);
|
|
706
|
+
if (action.kind === "add-constraint" || action.kind === "comment-column" || action.kind === "create-index" && !/CREATE\s+UNIQUE\s+INDEX/i.test(action.sql)) {
|
|
707
|
+
failures.push({
|
|
708
|
+
kind: action.kind,
|
|
709
|
+
target: action.target,
|
|
710
|
+
error: message
|
|
711
|
+
});
|
|
712
|
+
continue;
|
|
713
|
+
}
|
|
714
|
+
throw new Error(`Failed to ${action.kind} ${action.target}: ${message}${vectorExtensionHint(message)}\n ${action.sql}`);
|
|
715
|
+
}
|
|
716
|
+
return {
|
|
717
|
+
...plan,
|
|
718
|
+
failures
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* What actually went wrong, rather than what the ORM said about it.
|
|
723
|
+
*
|
|
724
|
+
* Drizzle wraps every driver error, and its `message` is literally
|
|
725
|
+
* ``Failed query: ${sql}\nparams: ${params}`` — the statement we already know,
|
|
726
|
+
* and not one word of Postgres's answer. Reporting `err.message` therefore
|
|
727
|
+
* produced a failure that named the statement twice and the *reason* zero
|
|
728
|
+
* times, so four unrelated boot failures — a missing extension, a wrong
|
|
729
|
+
* privilege, a bad index method, a constraint the rows violate — all read
|
|
730
|
+
* identically to whoever had to fix them.
|
|
731
|
+
*
|
|
732
|
+
* Two consequences, both observed in the field before this existed:
|
|
733
|
+
*
|
|
734
|
+
* 1. On a managed deployment the reason never reaches anybody. Boot dies, the
|
|
735
|
+
* pod never goes ready, and the deploy reports a readiness timeout — so the
|
|
736
|
+
* one line that says why is the one line that was thrown away here.
|
|
737
|
+
* 2. {@link vectorExtensionHint} matches on the error text. Against the
|
|
738
|
+
* wrapper it matched nothing, so the hint written specifically to explain a
|
|
739
|
+
* missing pgvector never fired on the path that raises it.
|
|
740
|
+
*
|
|
741
|
+
* `detail` and `hint` come along because they are the fields Postgres uses to
|
|
742
|
+
* say which object it meant and what to do about it — `CREATE EXTENSION` names
|
|
743
|
+
* the missing library there, and a rejected constraint names the row. This
|
|
744
|
+
* writes into the tenant's own boot log, about the tenant's own database.
|
|
745
|
+
*/
|
|
746
|
+
function describeDriverError(err) {
|
|
747
|
+
const pg = extractPgError(err);
|
|
748
|
+
if (pg) {
|
|
749
|
+
const parts = [pg.code ? `${pg.message} [${pg.code}]` : pg.message];
|
|
750
|
+
if (pg.detail) parts.push(` detail: ${pg.detail}`);
|
|
751
|
+
if (pg.hint) parts.push(` hint: ${pg.hint}`);
|
|
752
|
+
return parts.join("\n");
|
|
753
|
+
}
|
|
754
|
+
const cause = extractCauseMessage(err);
|
|
755
|
+
if (cause) return cause;
|
|
756
|
+
return err instanceof Error ? err.message : String(err);
|
|
757
|
+
}
|
|
758
|
+
/** ` CONCURRENTLY ` as it appears in a rendered `CREATE [UNIQUE] INDEX`. */
|
|
759
|
+
var CONCURRENTLY_RE = /\sCONCURRENTLY\s/i;
|
|
760
|
+
/**
|
|
761
|
+
* `25001 active_sql_transaction` — "cannot run inside a transaction block".
|
|
762
|
+
*
|
|
763
|
+
* Only ever raised here by `CREATE INDEX CONCURRENTLY`, and only when the
|
|
764
|
+
* connection we were handed is inside a transaction. Deliberately narrow: it
|
|
765
|
+
* decides to retry a *different* statement, so it must not fire on anything it
|
|
766
|
+
* has not been reasoned about.
|
|
767
|
+
*/
|
|
768
|
+
function isTransactionBlockRefusal(err) {
|
|
769
|
+
return extractPgError(err)?.code === "25001";
|
|
770
|
+
}
|
|
771
|
+
/** Attempts per action, including the first. Matches the server's bootstraps. */
|
|
772
|
+
var DDL_ATTEMPTS = 4;
|
|
773
|
+
/**
|
|
774
|
+
* Run one planned statement, surviving a simultaneous boot.
|
|
775
|
+
*
|
|
776
|
+
* Every statement in a plan is written to be idempotent, and that is not the
|
|
777
|
+
* same as being safe to run concurrently: `CREATE … IF NOT EXISTS` reads the
|
|
778
|
+
* catalog and then writes to it as two steps, so peers starting together both
|
|
779
|
+
* see "absent" and the loser gets a duplicate key on a *catalog* index. Measured
|
|
780
|
+
* against Postgres 18: five instances, 8 of 10 calls lost. `CREATE TYPE` is
|
|
781
|
+
* worse, because Postgres has no `IF NOT EXISTS` for it at all.
|
|
782
|
+
*
|
|
783
|
+
* What made that fatal here rather than merely noisy is the loop this sits in.
|
|
784
|
+
* A losing statement threw, and the throw abandoned **every remaining action in
|
|
785
|
+
* the plan** — so a replica that lost one race came up missing tables it never
|
|
786
|
+
* attempted, and the boot log blamed the one statement that failed.
|
|
787
|
+
*
|
|
788
|
+
* @returns `true` if this process applied the statement, `false` if a peer had
|
|
789
|
+
* already created the object. The distinction is only for the log; both mean
|
|
790
|
+
* the object is now there.
|
|
791
|
+
* @throws the original error for anything that is not a race — a syntax error, a
|
|
792
|
+
* permission failure, a unique constraint the customer's own rows violate.
|
|
793
|
+
*/
|
|
794
|
+
async function applyAction(client, action) {
|
|
795
|
+
let sqlText = action.sql;
|
|
796
|
+
for (let attempt = 1;; attempt++) try {
|
|
797
|
+
await client.query(sqlText);
|
|
798
|
+
return true;
|
|
799
|
+
} catch (err) {
|
|
800
|
+
if (isTransactionBlockRefusal(err) && CONCURRENTLY_RE.test(sqlText)) {
|
|
801
|
+
sqlText = sqlText.replace(CONCURRENTLY_RE, " ");
|
|
802
|
+
logger.warn(`[schema] ${action.kind} ${action.target}: this connection is inside a transaction, so the index is being built with a write lock rather than concurrently. Writes to this table block until it finishes.`);
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
if (isDuplicateObjectRace(err)) {
|
|
806
|
+
logger.debug(`[schema] ${action.kind} ${action.target}: already created by another instance`);
|
|
807
|
+
return false;
|
|
808
|
+
}
|
|
809
|
+
if (isConcurrentDdlRace(err) && attempt < DDL_ATTEMPTS) {
|
|
810
|
+
logger.debug(`[schema] ${action.kind} ${action.target}: lost a race with another instance (attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`);
|
|
811
|
+
await new Promise((resolve) => setTimeout(resolve, 40 * attempt * (1 + Math.random())));
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
throw err;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
//#endregion
|
|
818
|
+
export { readSchemaFactsFor as a, readExistingSchema as i, ensure_collection_tables_exports as n, planCollectionSchemaEnsure as r, describeDriverError as t };
|
|
819
|
+
|
|
820
|
+
//# sourceMappingURL=ensure-collection-tables-D4wJzM4y.js.map
|