@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.
- package/dist/PostgresAdapter.d.ts +1 -1
- package/dist/PostgresBackendDriver.d.ts +75 -12
- package/dist/PostgresBootstrapper.d.ts +6 -6
- package/dist/auth/services.d.ts +1 -1
- package/dist/backup/backup-cron.d.ts +1 -1
- package/dist/backup/backup-service.d.ts +2 -2
- package/dist/backup/index.d.ts +4 -4
- package/dist/{backup-service-BZoixhVl.js → backup-service-BtgHxfFm.js} +5 -4
- package/dist/{backup-service-BZoixhVl.js.map → backup-service-BtgHxfFm.js.map} +1 -1
- package/dist/cli-helpers.d.ts +41 -0
- package/dist/{auth-users-columns-CgyPWQ18.js → collection-index-DxJBvVTH.js} +486 -503
- package/dist/collection-index-DxJBvVTH.js.map +1 -0
- package/dist/collections/PostgresCollectionRegistry.d.ts +1 -1
- package/dist/collections/buildRegistry.d.ts +1 -1
- package/dist/collections/validate-relations.d.ts +1 -1
- package/dist/{connection-BuZ97wsr.js → connection-GOKU3Hu5.js} +34 -7
- package/dist/connection-GOKU3Hu5.js.map +1 -0
- package/dist/connection.d.ts +16 -0
- package/dist/data-transformer.d.ts +1 -1
- package/dist/{ensure-collection-policies-BVFb2olB.js → ensure-collection-policies-DFpOl8SM.js} +4 -4
- package/dist/{ensure-collection-policies-BVFb2olB.js.map → ensure-collection-policies-DFpOl8SM.js.map} +1 -1
- package/dist/ensure-collection-tables-DMjOkeRy.js +1952 -0
- package/dist/ensure-collection-tables-DMjOkeRy.js.map +1 -0
- package/dist/index.d.ts +16 -16
- package/dist/index.es.js +19 -7128
- package/dist/index.es.js.map +1 -1
- package/dist/{rls-bootstrap-sql-B5Sajku6.js → rls-bootstrap-sql-DNzaWd4C.js} +3 -3
- package/dist/{rls-bootstrap-sql-B5Sajku6.js.map → rls-bootstrap-sql-DNzaWd4C.js.map} +1 -1
- package/dist/{rls-enforcement-Ch0T6OwW.js → rls-enforcement-CInuYj1-.js} +14 -4
- package/dist/rls-enforcement-CInuYj1-.js.map +1 -0
- package/dist/schema/classify-change.d.ts +82 -0
- package/dist/schema/collection-index.d.ts +182 -0
- package/dist/schema/dynamic-tables.d.ts +1 -1
- package/dist/schema/ensure-collection-policies.d.ts +1 -1
- package/dist/schema/ensure-collection-tables.d.ts +93 -2
- package/dist/schema/generate-schema-commit.d.ts +136 -0
- package/dist/schema/generated-schema-staleness.d.ts +19 -0
- package/dist/schema/introspect-db-constraints.d.ts +1 -1
- package/dist/schema/introspect-db-logic.d.ts +3 -3
- package/dist/schema/introspect-db-project.d.ts +1 -1
- package/dist/schema/introspect-db-queries.d.ts +1 -1
- package/dist/schema/introspect-db-structure.d.ts +2 -2
- package/dist/schema/introspect-runtime.d.ts +1 -1
- package/dist/schema/vector-index.d.ts +88 -0
- package/dist/services/BranchService.d.ts +2 -2
- package/dist/services/FetchService.d.ts +4 -4
- package/dist/services/PersistService.d.ts +5 -5
- package/dist/services/RelationService.d.ts +3 -3
- package/dist/services/RelationWriteService.d.ts +3 -3
- package/dist/services/cdc/junction-tables.d.ts +1 -1
- package/dist/services/cdc/trigger-cdc.d.ts +1 -1
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -1
- package/dist/services/channel-bus/index.d.ts +2 -2
- package/dist/services/collection-helpers.d.ts +1 -1
- package/dist/services/dataService.d.ts +10 -10
- package/dist/services/index.d.ts +4 -4
- package/dist/services/junction-writes.d.ts +2 -2
- package/dist/services/nested-path.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +3 -3
- package/dist/services/row-pipeline.d.ts +1 -1
- package/dist/services/write-denial.d.ts +1 -1
- package/dist/{src-BBFsDaeA.js → src-DiDgtX8P.js} +97 -1
- package/dist/src-DiDgtX8P.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +2 -2
- package/dist/websocket-CUnpSe8v.js +8188 -0
- package/dist/websocket-CUnpSe8v.js.map +1 -0
- package/dist/websocket.d.ts +29 -2
- package/package.json +7 -7
- package/src/PostgresBackendDriver.ts +190 -59
- package/src/backup/backup-service.ts +1 -1
- package/src/cli-helpers.ts +117 -2
- package/src/cli.ts +22 -0
- package/src/connection.ts +37 -3
- package/src/databasePoolManager.ts +5 -2
- package/src/schema/classify-change.ts +436 -0
- package/src/schema/collection-index.ts +427 -0
- package/src/schema/ensure-collection-tables.test.ts +168 -1
- package/src/schema/ensure-collection-tables.ts +365 -14
- package/src/schema/generate-drizzle-schema-logic.ts +23 -11
- package/src/schema/generate-drizzle-schema.ts +13 -2
- package/src/schema/generate-postgres-ddl-logic.ts +33 -6
- package/src/schema/generate-postgres-ddl.ts +13 -2
- package/src/schema/generate-schema-commit.ts +242 -0
- package/src/schema/generated-schema-staleness.ts +114 -1
- package/src/schema/vector-index.ts +278 -0
- package/src/services/collection-helpers.ts +3 -2
- package/src/websocket.ts +47 -3
- package/dist/auth-users-columns-CgyPWQ18.js.map +0 -1
- package/dist/connection-BuZ97wsr.js.map +0 -1
- package/dist/data_driver-ULAyJEi9.js +0 -193
- package/dist/data_driver-ULAyJEi9.js.map +0 -1
- package/dist/ensure-collection-tables-BY1pHRD_.js +0 -840
- package/dist/ensure-collection-tables-BY1pHRD_.js.map +0 -1
- package/dist/rls-enforcement-Ch0T6OwW.js.map +0 -1
- package/dist/src-BBFsDaeA.js.map +0 -1
- package/dist/utils/table-classification.d.ts +0 -8
- package/dist/websocket-BVgDVO-V.js +0 -614
- package/dist/websocket-BVgDVO-V.js.map +0 -1
- package/src/utils/table-classification.ts +0 -16
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one place a collection's `indexes:` block becomes `CREATE INDEX`.
|
|
3
|
+
*
|
|
4
|
+
* Like `search-column.ts` and `vector-index.ts`, this module exists so the DDL
|
|
5
|
+
* generator and the boot-time ensure render the *same* specification rather
|
|
6
|
+
* than describing the same index twice, differently.
|
|
7
|
+
*
|
|
8
|
+
* ## Why every form here is core Postgres
|
|
9
|
+
*
|
|
10
|
+
* `rebase db push` runs `atlas schema apply`, which materialises the desired
|
|
11
|
+
* state in a bare scratch database to plan against. `--exclude` does not
|
|
12
|
+
* suppress that replay, and `CREATE EXTENSION` cannot go in the file. So an
|
|
13
|
+
* index wanting `gin_trgm_ops` or `vector_cosine_ops` would parse, plan, and
|
|
14
|
+
* then fail against a database the author has never heard of. Those are
|
|
15
|
+
* refused here instead, and redirected to the feature that owns them: trigram
|
|
16
|
+
* search is `search:`, ANN is a `vector` property.
|
|
17
|
+
*
|
|
18
|
+
* Verified against atlas v1.2.3 and Postgres 18 before this was written: plain,
|
|
19
|
+
* composite with `DESC NULLS LAST`, partial, unique, covering `INCLUDE`, `GIN`
|
|
20
|
+
* and expression indexes all parse, apply, and re-plan clean. The Atlas
|
|
21
|
+
* limitation that forced the search carve-out is that it will not parse a file
|
|
22
|
+
* containing a function *definition* — a function *call* inside an index is
|
|
23
|
+
* fine. That is why this module needs no carve-out and search did.
|
|
24
|
+
*
|
|
25
|
+
* ## Why the name carries a hash
|
|
26
|
+
*
|
|
27
|
+
* `CREATE INDEX IF NOT EXISTS` is a **name** check, not a definition check. A
|
|
28
|
+
* readable name means a changed declaration keeps the old index and reports
|
|
29
|
+
* success, forever. Hashing the index's *semantics* into its name makes a
|
|
30
|
+
* redefinition a different object: the new one is built before the old one is
|
|
31
|
+
* dropped, there is never a window with no index, and drift detection reduces
|
|
32
|
+
* to a set difference over names.
|
|
33
|
+
*/
|
|
34
|
+
import type { CollectionConfig, CollectionIndex, IndexPredicate, Property, ResolvedRelation } from "@rebasepro/types";
|
|
35
|
+
import { isPostgresCollectionConfig } from "@rebasepro/types";
|
|
36
|
+
import { getTableName, resolveCollectionRelations } from "@rebasepro/common";
|
|
37
|
+
import { sha1Hex, truncateToBytes } from "@rebasepro/utils";
|
|
38
|
+
|
|
39
|
+
/** Resolve a property key to its column name. Injected to avoid an import cycle. */
|
|
40
|
+
export type ResolveColumnName = (propName: string, prop?: Property | null) => string;
|
|
41
|
+
|
|
42
|
+
export type IndexMethod = "btree" | "gin" | "brin";
|
|
43
|
+
|
|
44
|
+
/** A key column, with the ordering Postgres will actually apply. */
|
|
45
|
+
export interface ResolvedIndexKey {
|
|
46
|
+
column: string;
|
|
47
|
+
/** Always concrete. `btree` defaults ascending; unordered methods report `asc`. */
|
|
48
|
+
direction: "asc" | "desc";
|
|
49
|
+
/** Postgres's own default: `last` under `asc`, `first` under `desc`. */
|
|
50
|
+
nulls: "first" | "last";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A predicate resolved onto column names, ready to render and to hash. */
|
|
54
|
+
export type ResolvedPredicate =
|
|
55
|
+
| { column: string; op: "=" | "!=" | "<" | "<=" | ">" | ">="; value: string | number | boolean }
|
|
56
|
+
| { column: string; op: "is null" | "is not null" }
|
|
57
|
+
| { column: string; op: "in"; value: readonly (string | number)[] }
|
|
58
|
+
| { and: readonly ResolvedPredicate[] };
|
|
59
|
+
|
|
60
|
+
/** One index, fully resolved. The only shape the renderers accept. */
|
|
61
|
+
export interface CollectionIndexSpec {
|
|
62
|
+
schema: string;
|
|
63
|
+
table: string;
|
|
64
|
+
method: IndexMethod;
|
|
65
|
+
unique: boolean;
|
|
66
|
+
keys: ResolvedIndexKey[];
|
|
67
|
+
include: string[];
|
|
68
|
+
predicate: ResolvedPredicate | null;
|
|
69
|
+
/** The author's one-line justification. Never enters the name. */
|
|
70
|
+
reason: string;
|
|
71
|
+
/** Derived by {@link deriveIndexName}. Frozen — see the module comment. */
|
|
72
|
+
indexName: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A declaration that cannot become an index.
|
|
77
|
+
*
|
|
78
|
+
* Thrown at build time, naming the collection and the array position, because
|
|
79
|
+
* the alternative is a `CREATE INDEX` that fails during a push with a Postgres
|
|
80
|
+
* error mentioning a column the author never wrote.
|
|
81
|
+
*/
|
|
82
|
+
export class CollectionIndexConfigError extends Error {
|
|
83
|
+
readonly collectionSlug: string;
|
|
84
|
+
readonly position: number;
|
|
85
|
+
|
|
86
|
+
constructor(collectionSlug: string, position: number, message: string) {
|
|
87
|
+
super(`${collectionSlug}.indexes[${position}]: ${message}`);
|
|
88
|
+
this.name = "CollectionIndexConfigError";
|
|
89
|
+
this.collectionSlug = collectionSlug;
|
|
90
|
+
this.position = position;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Postgres allows 32 key columns. See the doc comment on `on`. */
|
|
95
|
+
export const MAX_INDEX_KEYS = 5;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* `_ix`/`_ux` plus `_` plus 7 hex — the part of the name that must always
|
|
99
|
+
* survive truncation, and therefore is never inside the truncated portion.
|
|
100
|
+
*/
|
|
101
|
+
const NAME_SUFFIX_BYTES = 11;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Every Rebase-managed index name, and nothing else.
|
|
105
|
+
*
|
|
106
|
+
* The terminal `_ix_`/`_ux_` plus exactly seven lowercase hex characters is
|
|
107
|
+
* what separates this scheme from every other producer in the codebase —
|
|
108
|
+
* `_fkey`, `_gin`, `_trgm`, `_pkey`, `_key`, the vector distances, and the
|
|
109
|
+
* `idx_` prefix auth uses. `_idx` was rejected as a tail because it is already
|
|
110
|
+
* taken for real: `users_email_verification_token_idx` is byte-for-byte what a
|
|
111
|
+
* naive `<table>_<column>_idx` derives on an auth-enabled `users` collection.
|
|
112
|
+
*
|
|
113
|
+
* Load-bearing for safety, not just tidiness. An index that does NOT match this
|
|
114
|
+
* belongs to somebody else — a hand-written one, or one an introspected
|
|
115
|
+
* database arrived with — and is excluded from the Atlas diff so the push
|
|
116
|
+
* cannot drop it.
|
|
117
|
+
*/
|
|
118
|
+
export const isRebaseIndexName = (name: string): boolean => /_(?:ix|ux)_[0-9a-f]{7}$/.test(name);
|
|
119
|
+
|
|
120
|
+
const isOrderedMethod = (method: IndexMethod): boolean => method === "btree";
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The parts of an index that decide what it *is*.
|
|
124
|
+
*
|
|
125
|
+
* A semantic projection, not the rendered statement — the same arrangement as
|
|
126
|
+
* `getPolicyNameHash`, and for the same reason. A change to how this file
|
|
127
|
+
* formats SQL (eliding a default `USING btree`, quoting differently, emitting
|
|
128
|
+
* `NULLS LAST` explicitly) must not silently rename every index in every
|
|
129
|
+
* deployed database. Hashing generator output would make every cosmetic edit a
|
|
130
|
+
* fleet-wide DROP + CREATE.
|
|
131
|
+
*
|
|
132
|
+
* `reason` is deliberately absent: rewording a comment must not rebuild an
|
|
133
|
+
* index. `nulls` is the *effective* placement, so writing Postgres's own
|
|
134
|
+
* default down is a no-op rather than a redefinition.
|
|
135
|
+
*
|
|
136
|
+
* `v` is the only escape hatch, and it is expensive on purpose: bumping it
|
|
137
|
+
* renames every index in the field.
|
|
138
|
+
*/
|
|
139
|
+
export const indexFingerprint = (spec: Omit<CollectionIndexSpec, "indexName">): string => sha1Hex(JSON.stringify({
|
|
140
|
+
v: 1,
|
|
141
|
+
s: spec.schema,
|
|
142
|
+
t: spec.table,
|
|
143
|
+
m: spec.method,
|
|
144
|
+
u: spec.unique,
|
|
145
|
+
k: spec.keys.map(k => [k.column, k.direction, k.nulls]),
|
|
146
|
+
i: spec.include,
|
|
147
|
+
w: spec.predicate
|
|
148
|
+
})).substring(0, 7);
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* `<table>_<columns>_ix_<hash>`, or `_ux_` when unique.
|
|
152
|
+
*
|
|
153
|
+
* Truncation eats the readable head and never the hash. `toPostgresIdentifier`
|
|
154
|
+
* truncates the whole string at 63 bytes, which on a hashed name would cut off
|
|
155
|
+
* the one part that makes it unique — the failure already frozen into
|
|
156
|
+
* `contracts/derived-names.txt`, where a foreign key is recorded with its
|
|
157
|
+
* `_fkey` suffix truncated away, so a second foreign key on that table would
|
|
158
|
+
* derive a byte-identical name.
|
|
159
|
+
*/
|
|
160
|
+
export const deriveIndexName = (spec: Omit<CollectionIndexSpec, "indexName">): string => {
|
|
161
|
+
// Built suffix-first, so the two parts that carry meaning — the `_ix`/`_ux`
|
|
162
|
+
// tag that {@link isRebaseIndexName} matches on, and the fingerprint — are
|
|
163
|
+
// never in the string being truncated. Composing the whole name and then
|
|
164
|
+
// trimming it to 63 loses both, silently: an 80-byte table name yields
|
|
165
|
+
// `xxxx…xxx_610bb9e` with the tag gone, so the index stops being
|
|
166
|
+
// recognisable as Rebase's and `db push` treats it as foreign forever.
|
|
167
|
+
const tag = spec.unique ? "ux" : "ix";
|
|
168
|
+
const suffix = `_${tag}_${indexFingerprint(spec)}`;
|
|
169
|
+
const readable = `${spec.table}_${spec.keys.map(k => k.column).join("_")}`;
|
|
170
|
+
return `${truncateToBytes(readable, 63 - NAME_SUFFIX_BYTES)}${suffix}`;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const quoteLiteral = (value: string | number | boolean): string => {
|
|
174
|
+
if (typeof value === "number") return String(value);
|
|
175
|
+
if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
|
|
176
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** Render a resolved predicate as the body of a `WHERE` clause. */
|
|
180
|
+
export const renderPredicate = (predicate: ResolvedPredicate): string => {
|
|
181
|
+
if ("and" in predicate) {
|
|
182
|
+
// Always parenthesised. Postgres would apply the same precedence
|
|
183
|
+
// without it, but the rendered SQL is read by people diffing a plan.
|
|
184
|
+
return predicate.and.map(renderPredicate).join(" AND ");
|
|
185
|
+
}
|
|
186
|
+
switch (predicate.op) {
|
|
187
|
+
case "is null":
|
|
188
|
+
case "is not null":
|
|
189
|
+
return `"${predicate.column}" ${predicate.op.toUpperCase()}`;
|
|
190
|
+
case "in":
|
|
191
|
+
return `"${predicate.column}" IN (${predicate.value.map(quoteLiteral).join(", ")})`;
|
|
192
|
+
default:
|
|
193
|
+
return `"${predicate.column}" ${predicate.op} ${quoteLiteral(predicate.value)}`;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The `CREATE INDEX` for one spec.
|
|
199
|
+
*
|
|
200
|
+
* `concurrently` is a parameter rather than a string replacement on the way
|
|
201
|
+
* out. `search-column.ts` and `vector-index.ts` both reach for
|
|
202
|
+
* `.replace("CREATE INDEX IF NOT EXISTS", …)` instead, which silently does
|
|
203
|
+
* nothing for a UNIQUE index — the rendered text is `CREATE UNIQUE INDEX …`
|
|
204
|
+
* and the pattern never matches.
|
|
205
|
+
*/
|
|
206
|
+
export const collectionIndexStatement = (
|
|
207
|
+
spec: CollectionIndexSpec,
|
|
208
|
+
options: { concurrently?: boolean; ifNotExists?: boolean } = {}
|
|
209
|
+
): string => {
|
|
210
|
+
const unique = spec.unique ? "UNIQUE " : "";
|
|
211
|
+
const concurrently = options.concurrently ? "CONCURRENTLY " : "";
|
|
212
|
+
const ifNotExists = options.ifNotExists ? "IF NOT EXISTS " : "";
|
|
213
|
+
const using = spec.method === "btree" ? "" : ` USING ${spec.method}`;
|
|
214
|
+
|
|
215
|
+
const keys = spec.keys.map(k => {
|
|
216
|
+
if (!isOrderedMethod(spec.method)) return `"${k.column}"`;
|
|
217
|
+
const direction = k.direction === "desc" ? " DESC" : "";
|
|
218
|
+
// Emitted only when it is not what the direction already implies, so
|
|
219
|
+
// the rendered SQL matches what `pg_get_indexdef` reads back and a
|
|
220
|
+
// re-plan finds no difference.
|
|
221
|
+
const impliedNulls = k.direction === "desc" ? "first" : "last";
|
|
222
|
+
const nulls = k.nulls === impliedNulls ? "" : ` NULLS ${k.nulls.toUpperCase()}`;
|
|
223
|
+
return `"${k.column}"${direction}${nulls}`;
|
|
224
|
+
}).join(", ");
|
|
225
|
+
|
|
226
|
+
const include = spec.include.length > 0
|
|
227
|
+
? ` INCLUDE (${spec.include.map(c => `"${c}"`).join(", ")})`
|
|
228
|
+
: "";
|
|
229
|
+
const where = spec.predicate ? ` WHERE ${renderPredicate(spec.predicate)}` : "";
|
|
230
|
+
|
|
231
|
+
return `CREATE ${unique}INDEX ${concurrently}${ifNotExists}"${spec.indexName}" ` +
|
|
232
|
+
`ON "${spec.schema}"."${spec.table}"${using} (${keys})${include}${where};`;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
export const collectionIndexStatements = (
|
|
236
|
+
specs: readonly CollectionIndexSpec[],
|
|
237
|
+
options: { concurrently?: boolean; ifNotExists?: boolean } = {}
|
|
238
|
+
): string[] => specs.map(spec => collectionIndexStatement(spec, options));
|
|
239
|
+
|
|
240
|
+
const relationOf = (
|
|
241
|
+
collection: CollectionConfig,
|
|
242
|
+
propKey: string
|
|
243
|
+
): ResolvedRelation | undefined => resolveCollectionRelations(collection)[propKey];
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The column a property key indexes.
|
|
247
|
+
*
|
|
248
|
+
* A `belongsTo` resolves to its `localKey` — `primaryCategory` becomes
|
|
249
|
+
* `primary_category_id` — which is the case an index is most often wanted for
|
|
250
|
+
* and the case where the property key and the column differ. Everything else
|
|
251
|
+
* goes through `resolveColumnName`.
|
|
252
|
+
*
|
|
253
|
+
* The other relation kinds have no local column at all: the foreign key lives
|
|
254
|
+
* on the target's table, or in a junction. Indexing them here is refused
|
|
255
|
+
* rather than resolved to a column that does not exist.
|
|
256
|
+
*/
|
|
257
|
+
export const resolveIndexableColumn = (
|
|
258
|
+
collection: CollectionConfig,
|
|
259
|
+
propKey: string,
|
|
260
|
+
resolveColumnName: ResolveColumnName,
|
|
261
|
+
fail: (message: string) => never
|
|
262
|
+
): string => {
|
|
263
|
+
const relation = relationOf(collection, propKey);
|
|
264
|
+
if (relation) {
|
|
265
|
+
if (relation.kind === "belongsTo") return relation.localKey;
|
|
266
|
+
fail(
|
|
267
|
+
`"${propKey}" is a ${relation.kind} relation, which has no column on this table — ` +
|
|
268
|
+
`the foreign key lives on "${relation.targetSlug}". Declare the index there.`
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const property = collection.properties?.[propKey] as Property | undefined;
|
|
273
|
+
if (!property) {
|
|
274
|
+
fail(`"${propKey}" is not a property of this collection.`);
|
|
275
|
+
}
|
|
276
|
+
return resolveColumnName(propKey, property);
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
const resolvePredicate = (
|
|
280
|
+
collection: CollectionConfig,
|
|
281
|
+
predicate: IndexPredicate,
|
|
282
|
+
resolveColumnName: ResolveColumnName,
|
|
283
|
+
fail: (message: string) => never
|
|
284
|
+
): ResolvedPredicate => {
|
|
285
|
+
if ("and" in predicate) {
|
|
286
|
+
return { and: predicate.and.map(p => resolvePredicate(collection, p, resolveColumnName, fail)) };
|
|
287
|
+
}
|
|
288
|
+
const column = resolveIndexableColumn(collection, predicate.prop, resolveColumnName, fail);
|
|
289
|
+
switch (predicate.op) {
|
|
290
|
+
case "is null":
|
|
291
|
+
case "is not null":
|
|
292
|
+
return { column, op: predicate.op };
|
|
293
|
+
case "in": {
|
|
294
|
+
const seen = new Set(predicate.value);
|
|
295
|
+
if (seen.size !== predicate.value.length) {
|
|
296
|
+
fail(`the \`in\` list for "${predicate.prop}" repeats a value, which changes nothing.`);
|
|
297
|
+
}
|
|
298
|
+
return { column, op: "in", value: [...predicate.value] };
|
|
299
|
+
}
|
|
300
|
+
default:
|
|
301
|
+
return { column, op: predicate.op, value: predicate.value };
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
/** The primary key columns of a collection, for the "you already have this" refusal. */
|
|
306
|
+
const primaryKeyColumns = (collection: CollectionConfig, resolveColumnName: ResolveColumnName): string[] =>
|
|
307
|
+
Object.entries(collection.properties ?? {})
|
|
308
|
+
.filter(([, prop]) => prop && typeof prop === "object" && "isId" in prop && Boolean((prop as { isId?: unknown }).isId))
|
|
309
|
+
.map(([key, prop]) => resolveColumnName(key, prop as Property));
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Every index one collection declares, resolved and named.
|
|
313
|
+
*
|
|
314
|
+
* Throws {@link CollectionIndexConfigError} rather than dropping a bad entry:
|
|
315
|
+
* an index that silently does not exist is the failure mode this whole feature
|
|
316
|
+
* is here to remove.
|
|
317
|
+
*/
|
|
318
|
+
export const buildCollectionIndexSpecs = (
|
|
319
|
+
collection: CollectionConfig,
|
|
320
|
+
resolveColumnName: ResolveColumnName
|
|
321
|
+
): CollectionIndexSpec[] => {
|
|
322
|
+
if (!isPostgresCollectionConfig(collection)) return [];
|
|
323
|
+
const declared = collection.indexes;
|
|
324
|
+
if (!declared || declared.length === 0) return [];
|
|
325
|
+
|
|
326
|
+
const slug = collection.slug ?? getTableName(collection);
|
|
327
|
+
const schema = collection.schema ?? "public";
|
|
328
|
+
const table = getTableName(collection);
|
|
329
|
+
const pk = primaryKeyColumns(collection, resolveColumnName).sort().join(",");
|
|
330
|
+
|
|
331
|
+
const specs: CollectionIndexSpec[] = [];
|
|
332
|
+
const byName = new Map<string, number>();
|
|
333
|
+
|
|
334
|
+
declared.forEach((index: CollectionIndex, position: number) => {
|
|
335
|
+
const fail = (message: string): never => {
|
|
336
|
+
throw new CollectionIndexConfigError(slug, position, message);
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
if (typeof index.reason !== "string" || index.reason.trim() === "") {
|
|
340
|
+
fail("`reason` is required — see the doc comment. An index nobody can justify is one nobody can delete.");
|
|
341
|
+
}
|
|
342
|
+
if (!Array.isArray(index.on) || index.on.length === 0) {
|
|
343
|
+
fail("`on` must name at least one property.");
|
|
344
|
+
}
|
|
345
|
+
if (index.on.length > MAX_INDEX_KEYS) {
|
|
346
|
+
fail(`\`on\` has ${index.on.length} keys; the limit is ${MAX_INDEX_KEYS}. Payload columns belong in \`include\`.`);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const method: IndexMethod = index.using ?? "btree";
|
|
350
|
+
const unique = method === "btree" && Boolean((index as { unique?: boolean }).unique);
|
|
351
|
+
if (!isOrderedMethod(method)) {
|
|
352
|
+
for (const key of index.on) {
|
|
353
|
+
if (typeof key !== "string" && ("direction" in key || "nulls" in key)) {
|
|
354
|
+
fail(`access method "${method}" does not support ASC/DESC or NULLS options.`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const keys: ResolvedIndexKey[] = index.on.map(key => {
|
|
360
|
+
const propKey = typeof key === "string" ? key : key.prop;
|
|
361
|
+
const column = resolveIndexableColumn(collection, propKey, resolveColumnName, fail);
|
|
362
|
+
const direction = (typeof key === "string" ? undefined : (key as { direction?: "asc" | "desc" }).direction) ?? "asc";
|
|
363
|
+
const nulls = (typeof key === "string" ? undefined : (key as { nulls?: "first" | "last" }).nulls)
|
|
364
|
+
?? (direction === "desc" ? "first" : "last");
|
|
365
|
+
return { column, direction, nulls };
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
const duplicateKey = keys.map(k => k.column).find((c, i, all) => all.indexOf(c) !== i);
|
|
369
|
+
if (duplicateKey) fail(`"${duplicateKey}" appears twice in \`on\`.`);
|
|
370
|
+
|
|
371
|
+
if (keys.map(k => k.column).sort().join(",") === pk && pk !== "") {
|
|
372
|
+
fail(`this is the primary key — "${table}_pkey" already indexes exactly these columns.`);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const include = ((index as { include?: readonly string[] }).include ?? [])
|
|
376
|
+
.map(propKey => resolveIndexableColumn(collection, propKey, resolveColumnName, fail));
|
|
377
|
+
const overlap = include.find(c => keys.some(k => k.column === c));
|
|
378
|
+
if (overlap) fail(`"${overlap}" is in both \`on\` and \`include\`; Postgres rejects the overlap.`);
|
|
379
|
+
|
|
380
|
+
if (unique && keys.length === 1) {
|
|
381
|
+
const propKey = typeof index.on[0] === "string" ? index.on[0] as string : (index.on[0] as { prop: string }).prop;
|
|
382
|
+
const property = collection.properties?.[propKey] as { validation?: { unique?: boolean } } | undefined;
|
|
383
|
+
if (property?.validation?.unique) {
|
|
384
|
+
fail(
|
|
385
|
+
`"${propKey}" already declares \`validation.unique\`, which compiles to an inline UNIQUE. ` +
|
|
386
|
+
`Two declarations of one guarantee — remove one.`
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const predicate = index.where
|
|
392
|
+
? resolvePredicate(collection, index.where, resolveColumnName, fail)
|
|
393
|
+
: null;
|
|
394
|
+
|
|
395
|
+
const withoutName = { schema, table, method, unique, keys, include, predicate, reason: index.reason };
|
|
396
|
+
const indexName = deriveIndexName(withoutName);
|
|
397
|
+
|
|
398
|
+
const clash = byName.get(indexName);
|
|
399
|
+
if (clash !== undefined) {
|
|
400
|
+
fail(`derives the same name as indexes[${clash}] — they are the same index declared twice.`);
|
|
401
|
+
}
|
|
402
|
+
byName.set(indexName, position);
|
|
403
|
+
|
|
404
|
+
specs.push({ ...withoutName, indexName });
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
return specs;
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Every declared index across a set of collections, in a stable order.
|
|
412
|
+
*
|
|
413
|
+
* Sorted because the result reaches `schema.sql`, which `doctor` string-
|
|
414
|
+
* compares against a regenerated copy — `generatePostgresDdl` does not sort its
|
|
415
|
+
* collections, so leaving this in declaration order would make the artifact
|
|
416
|
+
* depend on the order files happened to load in.
|
|
417
|
+
*/
|
|
418
|
+
export const buildCollectionIndexPlan = (
|
|
419
|
+
collections: readonly CollectionConfig[],
|
|
420
|
+
resolveColumnName: ResolveColumnName
|
|
421
|
+
): CollectionIndexSpec[] =>
|
|
422
|
+
collections
|
|
423
|
+
.flatMap(collection => buildCollectionIndexSpecs(collection, resolveColumnName))
|
|
424
|
+
.sort((a, b) =>
|
|
425
|
+
a.schema.localeCompare(b.schema) ||
|
|
426
|
+
a.table.localeCompare(b.table) ||
|
|
427
|
+
a.indexName.localeCompare(b.indexName));
|
|
@@ -196,6 +196,124 @@ describe("planning an additive schema ensure", () => {
|
|
|
196
196
|
});
|
|
197
197
|
});
|
|
198
198
|
|
|
199
|
+
/**
|
|
200
|
+
* The three changes the ensure path used to apply *partly* while reporting
|
|
201
|
+
* success. Each one left a database that did not match its own configuration,
|
|
202
|
+
* and nothing anywhere said so — which is what made them worth more than the
|
|
203
|
+
* refusals beside them.
|
|
204
|
+
*/
|
|
205
|
+
describe("constraints the configuration asks for", () => {
|
|
206
|
+
const required = {
|
|
207
|
+
name: "Authors",
|
|
208
|
+
slug: "authors",
|
|
209
|
+
properties: {
|
|
210
|
+
id: { name: "ID", type: "string", isId: "uuid" },
|
|
211
|
+
name: { name: "Name", type: "string", validation: { required: true } }
|
|
212
|
+
}
|
|
213
|
+
} as unknown as CollectionConfig;
|
|
214
|
+
|
|
215
|
+
const optional = {
|
|
216
|
+
...required,
|
|
217
|
+
properties: {
|
|
218
|
+
...(required as unknown as { properties: Record<string, unknown> }).properties,
|
|
219
|
+
name: { name: "Name", type: "string" }
|
|
220
|
+
}
|
|
221
|
+
} as unknown as CollectionConfig;
|
|
222
|
+
|
|
223
|
+
it("adds NOT NULL when the existing table is empty", () => {
|
|
224
|
+
const plan = planCollectionSchemaEnsure([required], {
|
|
225
|
+
tables: new Map([["public.authors", new Set(["id"])]]),
|
|
226
|
+
enums: new Set(),
|
|
227
|
+
populatedTables: new Set()
|
|
228
|
+
});
|
|
229
|
+
const add = plan.actions.find(a => a.target === "public.authors.name");
|
|
230
|
+
expect(add!.sql).toContain("NOT NULL");
|
|
231
|
+
expect(plan.withheldConstraints).toEqual([]);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("withholds NOT NULL when the table holds rows, and says so", () => {
|
|
235
|
+
const plan = planCollectionSchemaEnsure([required], {
|
|
236
|
+
tables: new Map([["public.authors", new Set(["id"])]]),
|
|
237
|
+
enums: new Set(),
|
|
238
|
+
populatedTables: new Set(["public.authors"])
|
|
239
|
+
});
|
|
240
|
+
const add = plan.actions.find(a => a.target === "public.authors.name");
|
|
241
|
+
expect(add!.sql).not.toContain("NOT NULL");
|
|
242
|
+
// The whole point: withheld is no longer the same as unmentioned.
|
|
243
|
+
expect(plan.withheldConstraints).toHaveLength(1);
|
|
244
|
+
expect(plan.withheldConstraints[0]).toMatchObject({
|
|
245
|
+
target: "public.authors.name",
|
|
246
|
+
kind: "not-null"
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it("assumes rows when the caller does not know whether the table is empty", () => {
|
|
251
|
+
// A hand-built ExistingSchema carries no `populatedTables`. Reading that
|
|
252
|
+
// as "empty" would emit a NOT NULL checked against live data and abort
|
|
253
|
+
// the boot, so absent has to mean populated.
|
|
254
|
+
const plan = planCollectionSchemaEnsure([required], {
|
|
255
|
+
tables: new Map([["public.authors", new Set(["id"])]]),
|
|
256
|
+
enums: new Set()
|
|
257
|
+
});
|
|
258
|
+
expect(plan.actions.find(a => a.target === "public.authors.name")!.sql)
|
|
259
|
+
.not.toContain("NOT NULL");
|
|
260
|
+
expect(plan.withheldConstraints).toHaveLength(1);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("leaves an existing column's constraints alone at boot", () => {
|
|
264
|
+
// `additive` is the boot default. A database adopted by introspection
|
|
265
|
+
// carries NOT NULL on columns the generated collection leaves optional,
|
|
266
|
+
// and converging those unasked would drop constraints nobody edited.
|
|
267
|
+
const plan = planCollectionSchemaEnsure([optional], {
|
|
268
|
+
tables: new Map([["public.authors", new Set(["id", "name"])]]),
|
|
269
|
+
enums: new Set(),
|
|
270
|
+
notNullColumns: new Set(["public.authors.name"]),
|
|
271
|
+
populatedTables: new Set()
|
|
272
|
+
});
|
|
273
|
+
expect(plan.actions).toEqual([]);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("drops NOT NULL when a reviewed change relaxes the property", () => {
|
|
277
|
+
const plan = planCollectionSchemaEnsure([optional], {
|
|
278
|
+
tables: new Map([["public.authors", new Set(["id", "name"])]]),
|
|
279
|
+
enums: new Set(),
|
|
280
|
+
notNullColumns: new Set(["public.authors.name"]),
|
|
281
|
+
populatedTables: new Set(["public.authors"])
|
|
282
|
+
}, { constraints: "converge" });
|
|
283
|
+
expect(plan.actions).toEqual([{
|
|
284
|
+
kind: "drop-not-null",
|
|
285
|
+
target: "public.authors.name",
|
|
286
|
+
sql: `ALTER TABLE "public"."authors" ALTER COLUMN "name" DROP NOT NULL;`
|
|
287
|
+
}]);
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("sets NOT NULL on an existing empty column when the change is reviewed", () => {
|
|
291
|
+
const plan = planCollectionSchemaEnsure([required], {
|
|
292
|
+
tables: new Map([["public.authors", new Set(["id", "name"])]]),
|
|
293
|
+
enums: new Set(),
|
|
294
|
+
notNullColumns: new Set(),
|
|
295
|
+
populatedTables: new Set()
|
|
296
|
+
}, { constraints: "converge" });
|
|
297
|
+
expect(plan.actions).toEqual([{
|
|
298
|
+
kind: "set-not-null",
|
|
299
|
+
target: "public.authors.name",
|
|
300
|
+
sql: `ALTER TABLE "public"."authors" ALTER COLUMN "name" SET NOT NULL;`
|
|
301
|
+
}]);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it("refuses to set NOT NULL on a populated column, even when reviewed", () => {
|
|
305
|
+
const plan = planCollectionSchemaEnsure([required], {
|
|
306
|
+
tables: new Map([["public.authors", new Set(["id", "name"])]]),
|
|
307
|
+
enums: new Set(),
|
|
308
|
+
notNullColumns: new Set(),
|
|
309
|
+
populatedTables: new Set(["public.authors"])
|
|
310
|
+
}, { constraints: "converge" });
|
|
311
|
+
expect(plan.actions).toEqual([]);
|
|
312
|
+
expect(plan.withheldConstraints).toHaveLength(1);
|
|
313
|
+
expect(plan.withheldConstraints[0].remedy).toMatch(/Backfill/);
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
|
|
199
317
|
describe("applying the plan", () => {
|
|
200
318
|
function fakeClient(): { client: Queryable; executed: string[] } {
|
|
201
319
|
const executed: string[] = [];
|
|
@@ -236,7 +354,20 @@ describe("applying the plan", () => {
|
|
|
236
354
|
rows: ["id", "title", "views", "status"].map(c => ({
|
|
237
355
|
table_schema: "public",
|
|
238
356
|
table_name: "posts",
|
|
239
|
-
column_name: c
|
|
357
|
+
column_name: c,
|
|
358
|
+
is_nullable: "YES"
|
|
359
|
+
})) as unknown as T[]
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
// Before the `pg_type` arm: the enum *values* query joins
|
|
363
|
+
// pg_type too, and answering it with the type-name rows would
|
|
364
|
+
// describe a type whose only value is `undefined`.
|
|
365
|
+
if (sql.includes("pg_enum")) {
|
|
366
|
+
return {
|
|
367
|
+
rows: ["draft", "published"].map(value => ({
|
|
368
|
+
schema: "public",
|
|
369
|
+
name: "posts_status",
|
|
370
|
+
value
|
|
240
371
|
})) as unknown as T[]
|
|
241
372
|
};
|
|
242
373
|
}
|
|
@@ -249,6 +380,42 @@ describe("applying the plan", () => {
|
|
|
249
380
|
const plan = await ensureCollectionTables(client, [posts]);
|
|
250
381
|
expect(plan.actions).toEqual([]);
|
|
251
382
|
});
|
|
383
|
+
|
|
384
|
+
it("adds an enum value the existing type is missing", async () => {
|
|
385
|
+
// The bug this covers: the type exists, so the whole type was skipped by
|
|
386
|
+
// name, the boot reported success, and the first row using the new value
|
|
387
|
+
// was rejected by a type that had never heard of it.
|
|
388
|
+
const client: Queryable = {
|
|
389
|
+
async query<T>(sql: string): Promise<{ rows: T[] }> {
|
|
390
|
+
if (sql.includes("information_schema.columns")) {
|
|
391
|
+
return {
|
|
392
|
+
rows: ["id", "title", "views", "status"].map(c => ({
|
|
393
|
+
table_schema: "public",
|
|
394
|
+
table_name: "posts",
|
|
395
|
+
column_name: c,
|
|
396
|
+
is_nullable: "YES"
|
|
397
|
+
})) as unknown as T[]
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
if (sql.includes("pg_enum")) {
|
|
401
|
+
// "published" is missing from the type.
|
|
402
|
+
return {
|
|
403
|
+
rows: [{ schema: "public", name: "posts_status", value: "draft" }] as unknown as T[]
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
if (sql.includes("pg_type")) {
|
|
407
|
+
return { rows: [{ schema: "public", name: "posts_status" }] as unknown as T[] };
|
|
408
|
+
}
|
|
409
|
+
return { rows: [] as T[] };
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
const plan = await ensureCollectionTables(client, [posts]);
|
|
413
|
+
expect(plan.actions).toEqual([{
|
|
414
|
+
kind: "add-enum-value",
|
|
415
|
+
target: "public.posts_status.published",
|
|
416
|
+
sql: `ALTER TYPE "public"."posts_status" ADD VALUE IF NOT EXISTS 'published';`
|
|
417
|
+
}]);
|
|
418
|
+
});
|
|
252
419
|
});
|
|
253
420
|
|
|
254
421
|
/**
|