@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.40
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/package.json +39 -4
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +56 -2
- package/src/codegen-sqlite.ts +194 -0
- package/src/codegen.ts +230 -41
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/database.ts +227 -61
- package/src/description.ts +37 -8
- package/src/errors.ts +10 -6
- package/src/file-columns.ts +56 -11
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +15 -5
- package/src/guard.ts +373 -15
- package/src/index.ts +17 -1
- package/src/job-leases.ts +228 -55
- package/src/job-wakes.ts +600 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +210 -0
- package/src/migrations.ts +73 -0
- package/src/nodes.ts +84 -14
- package/src/orm-types.ts +206 -71
- package/src/orm.ts +425 -170
- package/src/policy.ts +1979 -141
- package/src/postgres.ts +26 -0
- package/src/registry.ts +55 -3
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +247 -476
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +269 -0
- package/src/store.ts +2292 -239
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +172 -6
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +1351 -0
- package/src/testing-sqlite.ts +685 -0
- package/src/testing.ts +310 -494
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +55 -2
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +79 -5
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/description.d.ts +26 -8
- package/types/src/errors.d.ts +9 -6
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +12 -5
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +5 -4
- package/types/src/job-leases.d.ts +40 -5
- package/types/src/job-wakes.d.ts +124 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +4 -0
- package/types/src/nodes.d.ts +17 -2
- package/types/src/orm-types.d.ts +163 -71
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +351 -23
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +40 -3
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +29 -21
- package/types/src/sqlite-bun.d.ts +21 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +143 -34
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +18 -2
- package/types/src/temporal.d.ts +24 -0
- package/types/src/testing-shared.d.ts +290 -0
- package/types/src/testing-sqlite.d.ts +37 -0
- package/types/src/testing.d.ts +2 -93
- package/types/src/vocabulary-tables.d.ts +169 -22
|
@@ -0,0 +1,1351 @@
|
|
|
1
|
+
// The dialect-neutral half of the database test kits (`@fabrika/db/testing` on Postgres, `@fabrika/db/testing-sqlite`
|
|
2
|
+
// on SQLite): the isolation fixtures' shapes, the seeding plan over a migrated schema a kit describes, and the table
|
|
3
|
+
// probe. Not a subpath: each kit refuses a production process before it imports this module.
|
|
4
|
+
|
|
5
|
+
import { createHash } from 'node:crypto'
|
|
6
|
+
import { type ApplicationRowRefusal, applicationRowRefusalText, type ApplicationRowsPlan, planApplicationRows } from './application-rows'
|
|
7
|
+
import { inSet, namesOf } from './builtins'
|
|
8
|
+
import type { Database } from './database'
|
|
9
|
+
import type { Primitive } from './description'
|
|
10
|
+
import { jsonInput } from './json'
|
|
11
|
+
import { FILES_TABLE } from './migrations'
|
|
12
|
+
import { type Container, type ForeignKey, modelOf, type TableModel, type TableModels, tableModels, type Tables } from './policy'
|
|
13
|
+
import { refuseInProduction } from './production'
|
|
14
|
+
import { frameworkSideOf } from './registry'
|
|
15
|
+
import type { TableProbe } from './store'
|
|
16
|
+
|
|
17
|
+
/** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
|
|
18
|
+
export type SampleValue = Primitive | null
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A seeded value as a backend binds it: a JSON column's value as the JSON text the layer would write for it, so a
|
|
22
|
+
* seeded row and the kits' cases that write the same value through the layer hold the same JSON.
|
|
23
|
+
*/
|
|
24
|
+
export function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): SampleValue {
|
|
25
|
+
if (value === null || !columns.some((column) => column.table === table && column.name === name && column.json)) return value
|
|
26
|
+
return jsonInput(value, `${table}.${name}`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One seeded row and where it lies. */
|
|
30
|
+
export interface WorldRow {
|
|
31
|
+
/** The row's key: the dimension value of a dimension table's row, a child's own key. */
|
|
32
|
+
readonly key: string
|
|
33
|
+
/** A child row's parent key; `null` for a dimension table. */
|
|
34
|
+
readonly parent: string | null
|
|
35
|
+
/** The value of the grant dimension the row lies in (`IsolationWorlds.dimension`). */
|
|
36
|
+
readonly scope: string
|
|
37
|
+
/**
|
|
38
|
+
* Every dimension value the row lies in: a dimension table's own first, then each container, innermost first. A
|
|
39
|
+
* share link's chain is this list.
|
|
40
|
+
*/
|
|
41
|
+
readonly chain: readonly { readonly type: string; readonly value: string }[]
|
|
42
|
+
/** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
|
|
43
|
+
readonly updates: Readonly<Record<string, SampleValue>>
|
|
44
|
+
/**
|
|
45
|
+
* The distinct value written into every text column the fixture filled itself, in this row and in its containers.
|
|
46
|
+
* Each occurs in no other fixture, so one found in an answer to another scope is a leaked row.
|
|
47
|
+
*/
|
|
48
|
+
readonly markers: readonly string[]
|
|
49
|
+
/**
|
|
50
|
+
* The values of the text columns of a row the table already held under a known scope value (`seedWorlds`' `scopes`),
|
|
51
|
+
* which no fixture wrote and other rows may share; empty for a row the fixture inserted.
|
|
52
|
+
*/
|
|
53
|
+
readonly stored: readonly string[]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One seeded row of an application table, which lies in no dimension. */
|
|
57
|
+
export interface ApplicationRow {
|
|
58
|
+
readonly key: string
|
|
59
|
+
/** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
|
|
60
|
+
readonly updates: Readonly<Record<string, SampleValue>>
|
|
61
|
+
/** The distinct value written into every text column the fixture filled itself. */
|
|
62
|
+
readonly markers: readonly string[]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Rows of application tables seeded together for one case, and their removal once the case is over. */
|
|
66
|
+
export interface SeededApplicationRows {
|
|
67
|
+
/** Each table's row key, by table. */
|
|
68
|
+
readonly keys: Readonly<Record<string, string>>
|
|
69
|
+
/**
|
|
70
|
+
* Deletes the rows, the rows their required foreign keys and file columns made the fixture insert, and every row
|
|
71
|
+
* that refers to one of them, however deep (what the case's handler wrote about them), in one transaction, so rows
|
|
72
|
+
* that refer to each other go together. A row already gone is skipped.
|
|
73
|
+
*/
|
|
74
|
+
remove(): Promise<void>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A row seeded under another: its key, and the distinct value written into every text column the fixture filled. */
|
|
78
|
+
export interface SeededRow {
|
|
79
|
+
readonly key: string
|
|
80
|
+
readonly markers: readonly string[]
|
|
81
|
+
/** Deletes the row, the rows its foreign keys made the fixture insert, and every row that refers to them. */
|
|
82
|
+
readonly remove: () => Promise<void>
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* What the isolation fixture cannot seed for a schema: a CHECK or a unique index no row it tries passes, a required
|
|
87
|
+
* foreign key whose referenced row it cannot seed. It is a limit of the generator, named with the constraint or the
|
|
88
|
+
* column, never a failure of the handler or the policy a case is about.
|
|
89
|
+
*/
|
|
90
|
+
export class SeedLimitError extends Error {
|
|
91
|
+
override readonly name = 'SeedLimitError'
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The constraint a seeded row failed, as a backend reads it off the database's error. */
|
|
95
|
+
export interface Violation {
|
|
96
|
+
readonly kind: 'check' | 'unique' | 'foreign'
|
|
97
|
+
/** The constraint's name, or for an unnamed CHECK on SQLite its expression, as the database reports it. */
|
|
98
|
+
readonly name: string
|
|
99
|
+
/** The columns the database names (SQLite's unique error); `undefined` where the seeding looks them up by `name`. */
|
|
100
|
+
readonly columns?: readonly string[]
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A seed limit of a row the database refused, with the constraint it failed: the seeding tries another row. */
|
|
104
|
+
export class ConstraintLimitError extends SeedLimitError {
|
|
105
|
+
readonly violation: Violation
|
|
106
|
+
|
|
107
|
+
constructor(message: string, violation: Violation) {
|
|
108
|
+
super(message)
|
|
109
|
+
this.violation = violation
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** One row of a table in each of two containment chains that share no value. */
|
|
114
|
+
export interface IsolationWorlds {
|
|
115
|
+
/**
|
|
116
|
+
* The dimension a caller's grants are scoped by: a dimension table's container, or its own dimension when it has
|
|
117
|
+
* none; a child table's parent's.
|
|
118
|
+
*/
|
|
119
|
+
readonly dimension: string
|
|
120
|
+
readonly own: WorldRow
|
|
121
|
+
readonly other: WorldRow
|
|
122
|
+
/**
|
|
123
|
+
* Deletes both rows of the table it inserted, every container row it inserted when it was given known scope values,
|
|
124
|
+
* and every row that refers to them, however deep; the other containers stay. A case whose rows hold pinned values or
|
|
125
|
+
* known scope values removes them, so the next case can seed the same values again under a unique index.
|
|
126
|
+
*/
|
|
127
|
+
readonly remove: () => Promise<void>
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Known values of dimensions, by dimension: the own world's and the other world's, which differ. A dimension whose values
|
|
132
|
+
* are a fixed set (an enum the input names it by) takes these instead of fresh ones.
|
|
133
|
+
*/
|
|
134
|
+
export type ScopeValues = Readonly<Record<string, { readonly own: string; readonly other: string }>>
|
|
135
|
+
|
|
136
|
+
/** What a test kit seeds through, over its migrated schema. */
|
|
137
|
+
export interface TestSeeding {
|
|
138
|
+
/**
|
|
139
|
+
* Seeds one row of `table` in each of two fresh chains, with every container row a table owns. `values` (column →
|
|
140
|
+
* value) are written into both rows of `table`: the state an endpoint's precondition needs. A text column keeps its
|
|
141
|
+
* marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
|
|
142
|
+
* `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
|
|
143
|
+
* counts among the other row's markers, so a leak of it is still found. A pin of a column that places the row, or of
|
|
144
|
+
* no text column, throws. `scopes` place each world in known values of a dimension instead of fresh ones: a row of
|
|
145
|
+
* the table that owns it with that key is used as it is stored (a migration wrote it), its containers' values with it,
|
|
146
|
+
* and is inserted otherwise. A stored row of `table` itself takes no `values` or `pins`: they throw. A seed that throws
|
|
147
|
+
* removes what it inserted.
|
|
148
|
+
*/
|
|
149
|
+
seedWorlds<DB, P>(
|
|
150
|
+
tables: Tables<DB, P>,
|
|
151
|
+
table: string,
|
|
152
|
+
values?: Readonly<Record<string, SampleValue>>,
|
|
153
|
+
pins?: Readonly<Record<string, string>>,
|
|
154
|
+
scopes?: ScopeValues,
|
|
155
|
+
): Promise<IsolationWorlds>
|
|
156
|
+
/**
|
|
157
|
+
* Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
|
|
158
|
+
* as given, a text column too, every other column sampled. A value for a stamped column or a file column throws.
|
|
159
|
+
*/
|
|
160
|
+
seedRow<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>): Promise<ApplicationRow>
|
|
161
|
+
/**
|
|
162
|
+
* Seeds one row of each application table `rows` names (table → column → value), as `seedRow` does, in foreign-key
|
|
163
|
+
* order: a foreign key from one of them to another holds that row's key unless the values give it. Every table's
|
|
164
|
+
* values are checked before the first insert, and a table that fails removes the rows seeded before it. `remove`
|
|
165
|
+
* deletes them, the rows a required foreign key of theirs made it insert, and every row that refers to any of them,
|
|
166
|
+
* so the next case starts without them.
|
|
167
|
+
*/
|
|
168
|
+
seedApplicationRows<DB, P>(
|
|
169
|
+
tables: Tables<DB, P>,
|
|
170
|
+
rows: Readonly<Record<string, Readonly<Record<string, SampleValue>>>>,
|
|
171
|
+
): Promise<SeededApplicationRows>
|
|
172
|
+
/**
|
|
173
|
+
* Seeds one row of `table`, a child or dimension table that lies in the object `under`'s chain starts at (a row
|
|
174
|
+
* `seedWorlds` seeded, or a value of its chain with the values outside it), placed in that chain: the row a fixture
|
|
175
|
+
* names by id, such as a note's comment. Answers its key and the markers it holds.
|
|
176
|
+
*/
|
|
177
|
+
seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: Pick<WorldRow, 'chain'>): Promise<SeededRow>
|
|
178
|
+
/**
|
|
179
|
+
* Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file
|
|
180
|
+
* column a seeded file. `beside` is a row `seedWorlds` seeded that the inserted row will lie beside, in the same
|
|
181
|
+
* containers. A number column a unique index covers takes the next number above the largest the table holds now in the
|
|
182
|
+
* row's group (the index's other columns as the row will have them, its containers' from `beside`), so insert the
|
|
183
|
+
* values before taking the next sample, or the two share it.
|
|
184
|
+
*/
|
|
185
|
+
sampleInsert<DB, P>(tables: Tables<DB, P>, table: string, beside?: WorldRow): Promise<Readonly<Record<string, SampleValue>>>
|
|
186
|
+
/**
|
|
187
|
+
* The object key of every file the fixture seeded into a file column, oldest first. Each stands for an empty object,
|
|
188
|
+
* which a test's object store holds when a handler serves or opens the file.
|
|
189
|
+
*/
|
|
190
|
+
seededObjects(): readonly string[]
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface TestDatabase extends TestSeeding {
|
|
194
|
+
/** The connection `boot` binds the data layer to: on Postgres the runtime role on the migrated schema; on SQLite the database itself. */
|
|
195
|
+
readonly database: Database
|
|
196
|
+
/** The migrated schema: `app_test_<hex>` on Postgres, `main` on SQLite. */
|
|
197
|
+
readonly schema: string
|
|
198
|
+
/** Closes the connections and drops the schema and its roles (on SQLite: closes the in-memory database). */
|
|
199
|
+
close(): Promise<void>
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A column of the migrated schema, as the seeding reads it. */
|
|
203
|
+
export interface SeedColumn {
|
|
204
|
+
readonly table: string
|
|
205
|
+
readonly name: string
|
|
206
|
+
/** The type as the database names it, for a message. */
|
|
207
|
+
readonly type: string
|
|
208
|
+
readonly nullable: boolean
|
|
209
|
+
/** The database fills it when an insert leaves it out: a default, an identity, a generated column. */
|
|
210
|
+
readonly defaulted: boolean
|
|
211
|
+
/** A text type that is no enum: where nothing else fills it, the fixture writes a marker into it. */
|
|
212
|
+
readonly text: boolean
|
|
213
|
+
/** A uuid type: a key or containment column of it holds a random uuid as its scope value. */
|
|
214
|
+
readonly uuid: boolean
|
|
215
|
+
/** A number type: where a unique index covers it, the fixture writes the next number of the row's group instead of its sample. */
|
|
216
|
+
readonly number: boolean
|
|
217
|
+
/** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
|
|
218
|
+
readonly json: boolean
|
|
219
|
+
/**
|
|
220
|
+
* A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it
|
|
221
|
+
* cannot fill. `variant` 0 is the plain sample; a higher one differs from the lower ones where the type allows (another
|
|
222
|
+
* day, the other boolean, a larger number), for a unique index whose other columns the row cannot vary.
|
|
223
|
+
*/
|
|
224
|
+
readonly sample: (variant: number) => Primitive
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** A CHECK constraint of the schema, by the columns it names. */
|
|
228
|
+
export interface CheckConstraint {
|
|
229
|
+
readonly name: string
|
|
230
|
+
readonly table: string
|
|
231
|
+
readonly columns: readonly string[]
|
|
232
|
+
/** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
|
|
233
|
+
readonly values: readonly CheckLiteral[]
|
|
234
|
+
/** Every text and number literal of the expression: what the fixture tries in the columns it names when a row fails it. */
|
|
235
|
+
readonly literals: readonly CheckLiteral[]
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** A literal of a CHECK expression. */
|
|
239
|
+
export type CheckLiteral = string | number
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* A unique index of the schema (a primary key's or a UNIQUE constraint's included), by its key columns. Only an index of
|
|
243
|
+
* plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
|
|
244
|
+
*/
|
|
245
|
+
export interface UniqueIndex {
|
|
246
|
+
readonly name: string
|
|
247
|
+
readonly table: string
|
|
248
|
+
readonly columns: readonly string[]
|
|
249
|
+
/** `NULLS NOT DISTINCT`: a null in a key column collides with another row's null there. */
|
|
250
|
+
readonly nullsNotDistinct: boolean
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it. */
|
|
254
|
+
export interface SeededFile {
|
|
255
|
+
readonly id: string
|
|
256
|
+
readonly kind: string
|
|
257
|
+
readonly objectKey: string
|
|
258
|
+
readonly sha256: string
|
|
259
|
+
readonly objectVersion: string
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** A row the fixture inserted, found again by `match` (column → value): what a removal deletes. */
|
|
263
|
+
export interface InsertedRow {
|
|
264
|
+
readonly table: string
|
|
265
|
+
readonly match: ReadonlyMap<string, SampleValue>
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** How many rows one removal deletes, referring rows included, before it gives up. */
|
|
269
|
+
export const MAX_REMOVED_ROWS = 10_000
|
|
270
|
+
|
|
271
|
+
/** The seed limit of a removal that reaches more than `MAX_REMOVED_ROWS` rows. */
|
|
272
|
+
export function removalLimit(): SeedLimitError {
|
|
273
|
+
return new SeedLimitError(`the isolation fixture cannot remove the application rows: more than ${MAX_REMOVED_ROWS} rows refer to them`)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** What a kit gives the seeding: its schema's columns and CHECK constraints, and the statements it runs. */
|
|
277
|
+
export interface SeedingBackend {
|
|
278
|
+
readonly columns: readonly SeedColumn[]
|
|
279
|
+
/** Every CHECK constraint of the schema's tables; read once, on the first column that needs them. */
|
|
280
|
+
checks(): Promise<readonly CheckConstraint[]>
|
|
281
|
+
/** Every unique index of plain columns and no predicate of the schema's tables; read once, on the first column that needs them. */
|
|
282
|
+
uniqueIndexes(): Promise<readonly UniqueIndex[]>
|
|
283
|
+
/**
|
|
284
|
+
* The smallest whole number above every value `column` holds in the rows of `table` that match one of `groups`
|
|
285
|
+
* (`groupsWhere`), and at least 1, as the column's type holds it; `undefined` when the type holds no such number, or
|
|
286
|
+
* the largest is no finite number.
|
|
287
|
+
*/
|
|
288
|
+
nextNumber(table: string, column: string, groups: readonly ReadonlyMap<string, SampleValue>[]): Promise<Primitive | undefined>
|
|
289
|
+
/**
|
|
290
|
+
* Inserts one row and answers it as stored; a CHECK, foreign key or unique index it fails is a `SeedLimitError`
|
|
291
|
+
* (`checkLimit`, `foreignKeyLimit`, `uniqueValueLimit`).
|
|
292
|
+
*/
|
|
293
|
+
insert(table: string, values: ReadonlyMap<string, SampleValue>): Promise<Readonly<Record<string, unknown>>>
|
|
294
|
+
/** One row of `table` that holds `where` (column → value; every row when empty), of `columns`, or `undefined` when none does. */
|
|
295
|
+
firstRow(
|
|
296
|
+
table: string,
|
|
297
|
+
columns: readonly string[],
|
|
298
|
+
where?: ReadonlyMap<string, SampleValue>,
|
|
299
|
+
): Promise<Readonly<Record<string, unknown>> | undefined>
|
|
300
|
+
insertFile(file: SeededFile): Promise<void>
|
|
301
|
+
/**
|
|
302
|
+
* Deletes `rows` (each found by its `match`; one already gone is skipped) and every row that refers to one of them,
|
|
303
|
+
* however deep, in one transaction whose foreign keys are checked once all are gone, so rows that refer to each other
|
|
304
|
+
* go together. No write moves or adds a referring row between finding the rows and deleting them.
|
|
305
|
+
*/
|
|
306
|
+
remove(rows: readonly InsertedRow[]): Promise<void>
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The seed limit of a CHECK a seeded row fails. */
|
|
310
|
+
export function checkLimit(constraint: string, table: string): ConstraintLimitError {
|
|
311
|
+
return new ConstraintLimitError(
|
|
312
|
+
`the isolation fixture cannot satisfy the CHECK ${constraint} of ${table}: no row it tried passes it (the values the CHECK names, null where a column admits it, samples of each type, fresh referenced rows)`,
|
|
313
|
+
{ kind: 'check', name: constraint },
|
|
314
|
+
)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** The seed limit of a foreign key a seeded row breaks. */
|
|
318
|
+
export function foreignKeyLimit(constraint: string, table: string): ConstraintLimitError {
|
|
319
|
+
return new ConstraintLimitError(`the isolation fixture's row of ${table} breaks the foreign key ${constraint}`, {
|
|
320
|
+
kind: 'foreign',
|
|
321
|
+
name: constraint,
|
|
322
|
+
})
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The seed limit of a number column a unique index covers whose type holds no number above the largest of the row's group. */
|
|
326
|
+
export function uniqueLimit(index: string, table: string, column: string): SeedLimitError {
|
|
327
|
+
return new SeedLimitError(
|
|
328
|
+
`the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value`,
|
|
329
|
+
)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** The seed limit of a row whose values another row of the table already holds under a unique index. */
|
|
333
|
+
export function uniqueValueLimit(index: string, table: string, columns?: readonly string[]): ConstraintLimitError {
|
|
334
|
+
return new ConstraintLimitError(
|
|
335
|
+
`the isolation fixture cannot satisfy the unique index ${index} of ${table}: every row it tried holds values another row holds there (samples of each type, the values a CHECK names, fresh referenced rows)`,
|
|
336
|
+
columns === undefined ? { kind: 'unique', name: index } : { kind: 'unique', name: index, columns },
|
|
337
|
+
)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The seed limit of a required column whose type the fixture has no sample of. */
|
|
341
|
+
export function typeLimit(table: string, column: string, type: string): SeedLimitError {
|
|
342
|
+
return new SeedLimitError(`the isolation fixture cannot fill ${table}.${column} (${type}): it has no sample of that type`)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* A condition that matches a row holding every value of one of `groups` (column → value, `null` matched by `IS NULL`; an
|
|
347
|
+
* empty group matches every row, no group none), in the dialect's quoting and placeholders, with the values it binds.
|
|
348
|
+
*/
|
|
349
|
+
export function groupsWhere(
|
|
350
|
+
groups: readonly ReadonlyMap<string, SampleValue>[],
|
|
351
|
+
quote: (identifier: string) => string,
|
|
352
|
+
placeholder: (position: number) => string,
|
|
353
|
+
): { where: string; values: SampleValue[] } {
|
|
354
|
+
const values: SampleValue[] = []
|
|
355
|
+
const each = groups.map((group) => {
|
|
356
|
+
const terms = [...group].map(([column, value]) => {
|
|
357
|
+
if (value === null) return `${quote(column)} IS NULL`
|
|
358
|
+
values.push(value)
|
|
359
|
+
return `${quote(column)} = ${placeholder(values.length)}`
|
|
360
|
+
})
|
|
361
|
+
return terms.length === 0 ? 'TRUE' : `(${terms.join(' AND ')})`
|
|
362
|
+
})
|
|
363
|
+
return { where: each.length === 0 ? 'FALSE' : each.join(' OR '), values }
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export function randomHex(): string {
|
|
367
|
+
return crypto.randomUUID().replaceAll('-', '').slice(0, 8)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The error a refusal of `planApplicationRows` throws when a test seeds the rows anyway. */
|
|
371
|
+
function applicationRowError(refusal: ApplicationRowRefusal): Error {
|
|
372
|
+
const text = applicationRowRefusalText(refusal)
|
|
373
|
+
return refusal.kind === 'cycle' ? new SeedLimitError(`the isolation fixture cannot order the application rows: ${text}`) : new Error(text)
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** A key value as the database returned it, for the foreign key that references it. */
|
|
377
|
+
/** `value` as the fixture can write it back, or `undefined` when it is none it writes (a JSON object, bytes). */
|
|
378
|
+
function plainValue(value: unknown): SampleValue | undefined {
|
|
379
|
+
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
380
|
+
return value
|
|
381
|
+
}
|
|
382
|
+
return value instanceof Date ? value : undefined
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function keyValue(value: unknown, where: string): SampleValue {
|
|
386
|
+
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
387
|
+
return value
|
|
388
|
+
}
|
|
389
|
+
throw new SeedLimitError(`the isolation fixture cannot reference ${where}: its key is no text, number or boolean`)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function isRequired(column: SeedColumn): boolean {
|
|
393
|
+
return !column.nullable && !column.defaulted
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** A text column the fixture writes a marker into, nullable or not, so that a leaked value is recognised anywhere. */
|
|
397
|
+
function isMarkable(column: SeedColumn): boolean {
|
|
398
|
+
return column.text && !column.defaulted
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** The dimension a caller's grants are scoped by, as `IsolationWorlds.dimension` describes. */
|
|
402
|
+
function grantDimension(models: TableModels, model: TableModel): string {
|
|
403
|
+
const scope = model.scope
|
|
404
|
+
if (scope.mode === 'dimension') {
|
|
405
|
+
return scope.container?.dimension ?? scope.dimension
|
|
406
|
+
}
|
|
407
|
+
if (scope.mode === 'child') {
|
|
408
|
+
const parent = modelOf(models, scope.parent)
|
|
409
|
+
if (parent?.scope.mode === 'dimension') {
|
|
410
|
+
return parent.scope.container?.dimension ?? parent.scope.dimension
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
throw new Error(`${model.name} is not a dimension or child table; no store reaches it, so it has no isolation tests`)
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function scopedModel<DB, P>(tables: Tables<DB, P>, table: string): { readonly models: TableModels; readonly model: TableModel } {
|
|
417
|
+
const models = tableModels(tables)
|
|
418
|
+
const model = modelOf(models, table)
|
|
419
|
+
if (model === undefined) {
|
|
420
|
+
throw new Error(`${table} is not a table of the policies`)
|
|
421
|
+
}
|
|
422
|
+
if (model.view) {
|
|
423
|
+
throw new Error(`${table} is a view, whose rows come from the tables it reads: seed those instead`)
|
|
424
|
+
}
|
|
425
|
+
return { models, model }
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function ownerOf(models: TableModels, dimension: string): TableModel | undefined {
|
|
429
|
+
for (const name of Object.keys(models)) {
|
|
430
|
+
const model = modelOf(models, name)
|
|
431
|
+
if (model?.scope.mode === 'dimension' && model.scope.dimension === dimension) {
|
|
432
|
+
return model
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return undefined
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** How many referenced rows deep the fixture follows required foreign keys outside the chain before it gives up. */
|
|
439
|
+
const MAX_REFERENCE_DEPTH = 16
|
|
440
|
+
/** How many rows the fixture tries for one insert before it reports the last constraint they failed. */
|
|
441
|
+
const MAX_ROW_ATTEMPTS = 64
|
|
442
|
+
/** How many samples of its type the fixture tries in a column whose values a constraint may refuse. */
|
|
443
|
+
const SAMPLE_VARIANTS = 4
|
|
444
|
+
|
|
445
|
+
/** One way to fill a slot of a row: its values, given the row so far; a `SeedLimitError` when it has none. */
|
|
446
|
+
interface SlotOption {
|
|
447
|
+
/** It reads the row's other values (a number a unique index numbers within its group), so it is taken last and never kept. */
|
|
448
|
+
readonly grouped: boolean
|
|
449
|
+
readonly values: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Columns the fixture fills together (one column, or a foreign key's open columns) and the ways it may fill them, first
|
|
454
|
+
* first. `reads` are the columns of the row its options read, which other slots fill first.
|
|
455
|
+
*/
|
|
456
|
+
interface Slot {
|
|
457
|
+
readonly columns: readonly string[]
|
|
458
|
+
readonly options: readonly SlotOption[]
|
|
459
|
+
readonly reads?: readonly string[]
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* An option computed once for each value of `reads` in the row: a fresh referenced row is inserted once for the values
|
|
464
|
+
* it shares with the row, and again only when they change.
|
|
465
|
+
*/
|
|
466
|
+
function keptOption(
|
|
467
|
+
compute: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>,
|
|
468
|
+
reads: readonly string[] = [],
|
|
469
|
+
): SlotOption {
|
|
470
|
+
const computed = new Map<string, Promise<ReadonlyMap<string, SampleValue>>>()
|
|
471
|
+
return {
|
|
472
|
+
grouped: false,
|
|
473
|
+
values: (row) => {
|
|
474
|
+
const key = reads.map((name) => valueKey(row.get(name) ?? null)).join('\u0000')
|
|
475
|
+
const values = computed.get(key) ?? compute(row)
|
|
476
|
+
computed.set(key, values)
|
|
477
|
+
return values
|
|
478
|
+
},
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function valueKey(value: SampleValue): string {
|
|
483
|
+
if (value === null) return 'null'
|
|
484
|
+
return `${typeof value}:${value instanceof Date ? value.toISOString() : String(value)}`
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* The order the fixture fills `slots` in: a slot after the slots that fill the columns it reads, and a slot that numbers
|
|
489
|
+
* within the row's group last, once every other slot placed the row. A cycle keeps the declared order.
|
|
490
|
+
*/
|
|
491
|
+
function slotOrder(slots: readonly Slot[]): number[] {
|
|
492
|
+
const filledBy = new Map<string, number>()
|
|
493
|
+
slots.forEach((slot, index) => {
|
|
494
|
+
for (const name of slot.columns) filledBy.set(name, index)
|
|
495
|
+
})
|
|
496
|
+
const grouped = (index: number): boolean => slots[index]?.options.some((option) => option.grouped) ?? false
|
|
497
|
+
const pending = [...slots.keys()].sort((left, right) => Number(grouped(left)) - Number(grouped(right)))
|
|
498
|
+
const order: number[] = []
|
|
499
|
+
while (pending.length > 0) {
|
|
500
|
+
const ready = pending.findIndex((index) =>
|
|
501
|
+
(slots[index]?.reads ?? []).every((name) => {
|
|
502
|
+
const filler = filledBy.get(name)
|
|
503
|
+
return filler === undefined || filler === index || order.includes(filler)
|
|
504
|
+
})
|
|
505
|
+
)
|
|
506
|
+
const [next] = pending.splice(Math.max(ready, 0), 1)
|
|
507
|
+
if (next !== undefined) order.push(next)
|
|
508
|
+
}
|
|
509
|
+
return order
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function valueOption(name: string, value: SampleValue): SlotOption {
|
|
513
|
+
return { grouped: false, values: async () => new Map([[name, value]]) }
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** The values a literal of a CHECK suggests for `column`: a number and its neighbours in a number column, a text in a text column. */
|
|
517
|
+
function literalValues(column: SeedColumn, literal: CheckLiteral): SampleValue[] {
|
|
518
|
+
if (column.number) return typeof literal === 'number' && Number.isSafeInteger(literal) ? [literal, literal + 1, literal - 1] : []
|
|
519
|
+
return column.text && typeof literal === 'string' ? [literal] : []
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** The first usable option of `slot` from `choice[index]` on, which `choice` then records; `undefined` when none is. */
|
|
523
|
+
async function pickOption(
|
|
524
|
+
slot: Slot,
|
|
525
|
+
choice: number[],
|
|
526
|
+
index: number,
|
|
527
|
+
row: ReadonlyMap<string, SampleValue>,
|
|
528
|
+
): Promise<{ readonly values: ReadonlyMap<string, SampleValue> } | { readonly error: SeedLimitError }> {
|
|
529
|
+
let refused: SeedLimitError | undefined
|
|
530
|
+
for (let at = choice[index] ?? 0; at < slot.options.length; at++) {
|
|
531
|
+
const option = slot.options[at]
|
|
532
|
+
if (option === undefined) continue
|
|
533
|
+
try {
|
|
534
|
+
const values = await option.values(row)
|
|
535
|
+
choice[index] = at
|
|
536
|
+
return { values }
|
|
537
|
+
} catch (error) {
|
|
538
|
+
if (!(error instanceof SeedLimitError)) throw error
|
|
539
|
+
refused = error
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return { error: refused ?? new SeedLimitError('the isolation fixture has no value to try') }
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** The next combination of the `involved` slots' options, the first involved changing first; `false` once all were tried. */
|
|
546
|
+
function advanceChoice(slots: readonly Slot[], choice: number[], involved: readonly number[]): boolean {
|
|
547
|
+
for (const index of involved) {
|
|
548
|
+
const at = choice[index] ?? 0
|
|
549
|
+
if (at + 1 < (slots[index]?.options.length ?? 0)) {
|
|
550
|
+
choice[index] = at + 1
|
|
551
|
+
return true
|
|
552
|
+
}
|
|
553
|
+
choice[index] = 0
|
|
554
|
+
}
|
|
555
|
+
return false
|
|
556
|
+
}
|
|
557
|
+
/** The digest of the empty object a seeded file stands for. */
|
|
558
|
+
const EMPTY_SHA256 = createHash('sha256').digest('hex')
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* The object version a seeded file was scanned at: whoever stocks its empty object (`seededObjects`) stores it under
|
|
562
|
+
* this version, so a file of a scanning kind is served as a live one is, by its scanned version.
|
|
563
|
+
*/
|
|
564
|
+
export const SEEDED_OBJECT_VERSION = '"seeded"'
|
|
565
|
+
|
|
566
|
+
/** The isolation fixtures over the schema `backend` describes. */
|
|
567
|
+
export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
568
|
+
let checks: Promise<readonly CheckConstraint[]> | undefined
|
|
569
|
+
let uniqueIndexes: Promise<readonly UniqueIndex[]> | undefined
|
|
570
|
+
const seededObjects: string[] = []
|
|
571
|
+
|
|
572
|
+
/** The CHECK constraints that name `column` of `table`. */
|
|
573
|
+
async function checksOn(table: string, column: string): Promise<readonly CheckConstraint[]> {
|
|
574
|
+
checks ??= backend.checks()
|
|
575
|
+
return (await checks).filter((check) => check.table === table && check.columns.includes(column))
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* What the fixture writes into a column a CHECK names: the first value of a one-column `IN` list, `null` where the
|
|
580
|
+
* column admits it (a CHECK passes on null); `undefined` when no CHECK names it or none of those applies.
|
|
581
|
+
*/
|
|
582
|
+
async function checkedValue(table: string, column: SeedColumn): Promise<SampleValue | undefined> {
|
|
583
|
+
const named = await checksOn(table, column.name)
|
|
584
|
+
if (named.length === 0) return undefined
|
|
585
|
+
const [listed] = named.flatMap((check) => check.values)
|
|
586
|
+
if (listed !== undefined && named.every((check) => check.values.includes(listed))) return listed
|
|
587
|
+
return column.nullable ? null : undefined
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async function uniqueIndexesOf(table: string): Promise<readonly UniqueIndex[]> {
|
|
591
|
+
uniqueIndexes ??= backend.uniqueIndexes()
|
|
592
|
+
return (await uniqueIndexes).filter((index) => index.table === table)
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/** Whether the fixture numbers `column` (`nextNumberOf`) instead of writing its type's sample: a number a unique index covers. */
|
|
596
|
+
async function numbered(table: string, column: SeedColumn): Promise<boolean> {
|
|
597
|
+
return column.number && (await uniqueIndexesOf(table)).some((index) => index.columns.includes(column.name))
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* The number a column `numbered` names takes in `row` (column → value, as the row has them so far): the next above the
|
|
602
|
+
* largest of its group under every unique index that covers it, so the row collides with no row of the table, whoever
|
|
603
|
+
* wrote it. The group is the rows that hold the index's other columns as `row` does: under a fresh parent it is empty
|
|
604
|
+
* and the number 1, which a bounded CHECK passes as before. A key column `row` holds no value for yet is left out of
|
|
605
|
+
* the group, which only widens it; an index the row holds `null` in never conflicts, unless its nulls are not distinct.
|
|
606
|
+
*/
|
|
607
|
+
async function nextNumberOf(
|
|
608
|
+
table: string,
|
|
609
|
+
column: SeedColumn,
|
|
610
|
+
row: ReadonlyMap<string, SampleValue>,
|
|
611
|
+
ungrouped: ReadonlySet<string> = new Set(),
|
|
612
|
+
): Promise<SampleValue> {
|
|
613
|
+
const covering = (await uniqueIndexesOf(table)).filter((index) => index.columns.includes(column.name))
|
|
614
|
+
const groups: Map<string, SampleValue>[] = []
|
|
615
|
+
for (const index of covering) {
|
|
616
|
+
const group = new Map<string, SampleValue>()
|
|
617
|
+
for (const other of index.columns) {
|
|
618
|
+
if (other !== column.name && row.has(other) && !ungrouped.has(other)) group.set(other, row.get(other) ?? null)
|
|
619
|
+
}
|
|
620
|
+
if (index.nullsNotDistinct || ![...group.values()].includes(null)) groups.push(group)
|
|
621
|
+
}
|
|
622
|
+
if (groups.length === 0) return column.sample(0)
|
|
623
|
+
const next = await backend.nextNumber(table, column.name, groups)
|
|
624
|
+
if (next === undefined) throw uniqueLimit(covering.map((index) => index.name).join(', '), table, column.name)
|
|
625
|
+
return next
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/** A required column's sample where the row is not at hand: an `IN` list's first value where a CHECK names one, else a sample of its type. */
|
|
629
|
+
async function requiredSample(table: string, column: SeedColumn): Promise<SampleValue> {
|
|
630
|
+
const checked = await checkedValue(table, column)
|
|
631
|
+
if (checked !== undefined) return checked
|
|
632
|
+
return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample(0)
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function columnsOf(table: string): readonly SeedColumn[] {
|
|
636
|
+
const columns = backend.columns.filter((column) => column.table === table)
|
|
637
|
+
if (columns.length === 0) {
|
|
638
|
+
throw new Error(`${table} is not a table of the migrated schema; write its migration first`)
|
|
639
|
+
}
|
|
640
|
+
return columns
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function columnOf(table: string, name: string): SeedColumn {
|
|
644
|
+
const column = columnsOf(table).find((candidate) => candidate.name === name)
|
|
645
|
+
if (column === undefined) {
|
|
646
|
+
throw new Error(`${table}.${name} is not a column of the migrated schema`)
|
|
647
|
+
}
|
|
648
|
+
return column
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** A column the seeded row left to its default: null only where the column admits it. */
|
|
652
|
+
async function updateSample(table: string, name: string): Promise<SampleValue> {
|
|
653
|
+
const column = columnOf(table, name)
|
|
654
|
+
return column.nullable ? null : requiredSample(table, column)
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** Whether the fixture writes a marker into `column`: text that holds no foreign key and that no CHECK names. */
|
|
658
|
+
async function holdsMarker(model: TableModel | undefined, table: string, column: SeedColumn): Promise<boolean> {
|
|
659
|
+
const keyed = (model?.foreignKeys ?? []).some((key) => key.columns.includes(column.name))
|
|
660
|
+
return isMarkable(column) && !keyed && (await checksOn(table, column.name)).length === 0
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** The open columns of `key` as the referenced row holds them. */
|
|
664
|
+
function keyValues(key: ForeignKey, open: readonly string[], row: Readonly<Record<string, unknown>>): Map<string, SampleValue> {
|
|
665
|
+
const values = new Map<string, SampleValue>()
|
|
666
|
+
key.columns.forEach((name, index) => {
|
|
667
|
+
const referenced = key.references[index] ?? ''
|
|
668
|
+
if (open.includes(name)) values.set(name, keyValue(row[referenced], `${key.table}.${referenced}`))
|
|
669
|
+
})
|
|
670
|
+
return values
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* The ways to fill a foreign key outside the containment chain: `null` where every open column admits it, an existing
|
|
675
|
+
* row of an unscoped table (a reference table's rows come from a migration), and a row the fixture inserts, which
|
|
676
|
+
* `inserted` records when given. A row of a dimension or child table is always a fresh one: an existing one lies in
|
|
677
|
+
* another chain. The key's columns the row already holds (a tenant-holding key's ancestors) the referenced row holds too.
|
|
678
|
+
*/
|
|
679
|
+
async function referenceSlot(
|
|
680
|
+
models: TableModels,
|
|
681
|
+
table: string,
|
|
682
|
+
key: ForeignKey,
|
|
683
|
+
open: readonly string[],
|
|
684
|
+
assigned: ReadonlyMap<string, SampleValue>,
|
|
685
|
+
depth: number,
|
|
686
|
+
inserted?: InsertedRow[],
|
|
687
|
+
): Promise<Slot> {
|
|
688
|
+
const columns = columnsOf(table)
|
|
689
|
+
const options: SlotOption[] = []
|
|
690
|
+
if (open.every((name) => columns.find((column) => column.name === name)?.nullable === true)) {
|
|
691
|
+
options.push({ grouped: false, values: async () => new Map(open.map((name) => [name, null])) })
|
|
692
|
+
}
|
|
693
|
+
// The key's columns the row holds already, or another slot fills first (a column two keys share), as the referenced
|
|
694
|
+
// row names them.
|
|
695
|
+
const shared = key.columns.filter((name) => !open.includes(name))
|
|
696
|
+
const fixedOf = (row: ReadonlyMap<string, SampleValue>): Map<string, SampleValue> => {
|
|
697
|
+
const fixed = new Map<string, SampleValue>()
|
|
698
|
+
key.columns.forEach((name, index) => {
|
|
699
|
+
if (shared.includes(name)) fixed.set(key.references[index] ?? '', row.get(name) ?? null)
|
|
700
|
+
})
|
|
701
|
+
return fixed
|
|
702
|
+
}
|
|
703
|
+
const target = modelOf(models, key.table)
|
|
704
|
+
const scoped = target?.scope.mode === 'dimension' || target?.scope.mode === 'child'
|
|
705
|
+
const refused = key.table === table
|
|
706
|
+
? 'which references its own table'
|
|
707
|
+
: depth >= MAX_REFERENCE_DEPTH
|
|
708
|
+
? `whose referenced rows nest deeper than ${MAX_REFERENCE_DEPTH}`
|
|
709
|
+
: undefined
|
|
710
|
+
if (refused === undefined) {
|
|
711
|
+
if (!scoped) {
|
|
712
|
+
options.push(keptOption(async (row) => {
|
|
713
|
+
const existing = await backend.firstRow(key.table, key.references, fixedOf(row))
|
|
714
|
+
if (existing === undefined) throw new SeedLimitError(`the isolation fixture finds no row of ${key.table} to reference`)
|
|
715
|
+
return keyValues(key, open, existing)
|
|
716
|
+
}, shared))
|
|
717
|
+
}
|
|
718
|
+
options.push(keptOption(async (row) => keyValues(key, open, await freshRow(models, key, fixedOf(row), depth + 1, inserted)), shared))
|
|
719
|
+
}
|
|
720
|
+
if (options.length === 0) {
|
|
721
|
+
throw new SeedLimitError(
|
|
722
|
+
`the isolation fixture cannot fill ${table}.${open.join(', ')}: a required foreign key to ${key.table} outside the containment chain, ${refused}`,
|
|
723
|
+
)
|
|
724
|
+
}
|
|
725
|
+
return { columns: open, options, reads: shared.filter((name) => !assigned.has(name)) }
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Gives each dimension of `model`'s chain that `values` lacks a fresh value, and inserts the row of each such
|
|
730
|
+
* container a table owns, outermost first; `inserted` records them when given.
|
|
731
|
+
*/
|
|
732
|
+
async function placeContainers(
|
|
733
|
+
models: TableModels,
|
|
734
|
+
model: TableModel,
|
|
735
|
+
values: Map<string, string>,
|
|
736
|
+
world: string,
|
|
737
|
+
depth: number,
|
|
738
|
+
inserted?: InsertedRow[],
|
|
739
|
+
): Promise<void> {
|
|
740
|
+
for (let index = model.chain.length - 1; index >= 0; index--) {
|
|
741
|
+
const link = model.chain[index]
|
|
742
|
+
if (link === undefined || values.has(link.dimension)) continue
|
|
743
|
+
const value = scopeValue(model.name, link.column, link.dimension, world)
|
|
744
|
+
values.set(link.dimension, value)
|
|
745
|
+
const owner = ownerOf(models, link.dimension)
|
|
746
|
+
if (owner === undefined || owner.name === model.name || owner.scope.mode !== 'dimension') continue
|
|
747
|
+
await insert(models, owner.name, placement(owner, values, value), [], depth, inserted)
|
|
748
|
+
inserted?.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* A fresh row of the table `key` references, holding `fixed` (referenced column → value), as stored. A row of a dimension
|
|
754
|
+
* or child table lies in the chain `fixed` holds of it, else in fresh values with containers of its own.
|
|
755
|
+
*/
|
|
756
|
+
async function freshRow(
|
|
757
|
+
models: TableModels,
|
|
758
|
+
key: ForeignKey,
|
|
759
|
+
fixed: ReadonlyMap<string, SampleValue>,
|
|
760
|
+
depth: number,
|
|
761
|
+
inserted?: InsertedRow[],
|
|
762
|
+
): Promise<Readonly<Record<string, unknown>>> {
|
|
763
|
+
const target = modelOf(models, key.table)
|
|
764
|
+
const scope = target?.scope
|
|
765
|
+
if (target === undefined || scope === undefined || (scope.mode !== 'dimension' && scope.mode !== 'child')) {
|
|
766
|
+
const { stored } = await insert(models, key.table, fixed, [], depth, inserted)
|
|
767
|
+
inserted?.push({
|
|
768
|
+
table: key.table,
|
|
769
|
+
match: new Map(key.references.map((name) => [name, keyValue(stored[name], `${key.table}.${name}`)])),
|
|
770
|
+
})
|
|
771
|
+
return stored
|
|
772
|
+
}
|
|
773
|
+
if (fixed.has(scope.key)) {
|
|
774
|
+
throw new SeedLimitError(`the isolation fixture cannot insert a row of ${key.table} whose key the referencing row fixes`)
|
|
775
|
+
}
|
|
776
|
+
const values = new Map<string, string>()
|
|
777
|
+
for (const link of target.chain) {
|
|
778
|
+
const value = fixed.get(link.column)
|
|
779
|
+
if (value !== undefined && value !== null) values.set(link.dimension, String(value))
|
|
780
|
+
}
|
|
781
|
+
await placeContainers(models, target, values, 'referenced', depth, inserted)
|
|
782
|
+
const rowKey = scopeValue(target.name, scope.key, scope.mode === 'dimension' ? scope.dimension : target.name, 'referenced')
|
|
783
|
+
const assigned = placement(target, values, rowKey)
|
|
784
|
+
for (const [name, value] of fixed) {
|
|
785
|
+
if (!assigned.has(name)) assigned.set(name, value)
|
|
786
|
+
}
|
|
787
|
+
const { stored } = await insert(models, target.name, assigned, [], depth, inserted)
|
|
788
|
+
inserted?.push({ table: target.name, match: new Map([[scope.key, rowKey]]) })
|
|
789
|
+
return stored
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/**
|
|
793
|
+
* A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. Either
|
|
794
|
+
* holds a random v4 uuid's 122 bits, so a large seed never collides on a key.
|
|
795
|
+
*/
|
|
796
|
+
function scopeValue(table: string, name: string, dimension: string, world: string): string {
|
|
797
|
+
const column = columnOf(table, name)
|
|
798
|
+
if (column.uuid) return crypto.randomUUID()
|
|
799
|
+
if (column.text) return `${dimension}-${world}-${crypto.randomUUID()}`
|
|
800
|
+
throw new Error(`${table}.${name} holds a ${dimension} as ${column.type}; a key or containment column holds its scope value as text or uuid`)
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* A live, empty file of `kind`, as the framework's put leaves one once a reference claims it: what a seeded file column
|
|
805
|
+
* holds. `inserted` records it when given.
|
|
806
|
+
*/
|
|
807
|
+
async function seedFile(kind: string, inserted?: InsertedRow[]): Promise<string> {
|
|
808
|
+
const id = crypto.randomUUID()
|
|
809
|
+
const objectKey = `${kind}/${id}`
|
|
810
|
+
seededObjects.push(objectKey)
|
|
811
|
+
await backend.insertFile({ id, kind, objectKey, sha256: EMPTY_SHA256, objectVersion: SEEDED_OBJECT_VERSION })
|
|
812
|
+
inserted?.push({ table: FILES_TABLE, match: new Map([['id', id]]) })
|
|
813
|
+
return id
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* The ways to fill `column`: a file column a seeded file; a column a CHECK names the `IN` list's first value or `null`,
|
|
818
|
+
* then every value the CHECKs naming it list or compare with, and samples of its type; a text column a marker; any other
|
|
819
|
+
* nullable column `null`; a number a unique index covers its next number in the row's group; else samples of its type.
|
|
820
|
+
*/
|
|
821
|
+
async function columnSlot(
|
|
822
|
+
model: TableModel | undefined,
|
|
823
|
+
table: string,
|
|
824
|
+
column: SeedColumn,
|
|
825
|
+
markers: string[],
|
|
826
|
+
inserted: InsertedRow[] | undefined,
|
|
827
|
+
ungrouped: ReadonlySet<string>,
|
|
828
|
+
): Promise<Slot> {
|
|
829
|
+
const name = column.name
|
|
830
|
+
const single = (value: SampleValue): ReadonlyMap<string, SampleValue> => new Map([[name, value]])
|
|
831
|
+
const sampled = (variant: number): SlotOption => ({ grouped: false, values: async () => single(column.sample(variant)) })
|
|
832
|
+
const samples = Array.from({ length: SAMPLE_VARIANTS }, (_, variant) => sampled(variant))
|
|
833
|
+
const next: SlotOption = { grouped: true, values: async (row) => single(await nextNumberOf(table, column, row, ungrouped)) }
|
|
834
|
+
const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
|
|
835
|
+
if (kind !== undefined) {
|
|
836
|
+
return {
|
|
837
|
+
columns: [name],
|
|
838
|
+
options: [keptOption(async () => single(await seedFile(kind, inserted))), ...(column.nullable ? [valueOption(name, null)] : [])],
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
const named = await checksOn(table, name)
|
|
842
|
+
const isNumbered = await numbered(table, column)
|
|
843
|
+
if (named.length > 0) {
|
|
844
|
+
const checked = await checkedValue(table, column)
|
|
845
|
+
const first = checked === undefined ? (isNumbered ? next : sampled(0)) : valueOption(name, checked)
|
|
846
|
+
const tried: SampleValue[] = column.nullable ? [null] : []
|
|
847
|
+
for (const check of named) {
|
|
848
|
+
for (const literal of [...check.values, ...check.literals]) tried.push(...literalValues(column, literal))
|
|
849
|
+
}
|
|
850
|
+
const listed = [...new Set(tried)].filter((value) => value !== checked).map((value) => valueOption(name, value))
|
|
851
|
+
return { columns: [name], options: [first, ...listed, ...(isNumbered ? [next] : []), ...samples] }
|
|
852
|
+
}
|
|
853
|
+
if (await holdsMarker(model, table, column)) {
|
|
854
|
+
return {
|
|
855
|
+
columns: [name],
|
|
856
|
+
options: [keptOption(async () => {
|
|
857
|
+
const marker = `m${randomHex()}${randomHex()}`
|
|
858
|
+
markers.push(marker)
|
|
859
|
+
return single(marker)
|
|
860
|
+
})],
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
if (column.nullable) return { columns: [name], options: [valueOption(name, null)] }
|
|
864
|
+
return { columns: [name], options: isNumbered ? [next] : samples }
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** The columns of the constraint a row failed, or `undefined` when the seeding cannot tell (an index on an expression). */
|
|
868
|
+
async function violatedColumns(table: string, violation: Violation): Promise<readonly string[] | undefined> {
|
|
869
|
+
if (violation.columns !== undefined) return violation.columns
|
|
870
|
+
if (violation.kind === 'check') {
|
|
871
|
+
checks ??= backend.checks()
|
|
872
|
+
return (await checks).find((check) => check.table === table && check.name === violation.name)?.columns
|
|
873
|
+
}
|
|
874
|
+
return (await uniqueIndexesOf(table)).find((index) => index.name === violation.name)?.columns
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/**
|
|
878
|
+
* Inserts one row: `assigned` as given, every other column a database default leaves open filled by its slot
|
|
879
|
+
* (`columnSlot`, `referenceSlot`), each slot's first option first. When the database refuses the row for a CHECK or
|
|
880
|
+
* a unique index, the fixture tries the next combination of the options of the slots that constraint names (all of
|
|
881
|
+
* them when it names none it can read), up to `MAX_ROW_ATTEMPTS` rows; the last refusal is the `SeedLimitError`.
|
|
882
|
+
* Answers what the fixture wrote, and the row as stored (its database defaults filled). `inserted` records every row
|
|
883
|
+
* a foreign key or a file column made it insert, not the row itself. A number a unique index covers is numbered within
|
|
884
|
+
* its group without the columns in `ungrouped` (a container the row will not lie in).
|
|
885
|
+
*/
|
|
886
|
+
async function insert(
|
|
887
|
+
models: TableModels,
|
|
888
|
+
table: string,
|
|
889
|
+
assigned: ReadonlyMap<string, SampleValue>,
|
|
890
|
+
markers: string[],
|
|
891
|
+
depth = 0,
|
|
892
|
+
inserted?: InsertedRow[],
|
|
893
|
+
ungrouped: ReadonlySet<string> = new Set(),
|
|
894
|
+
): Promise<{ readonly row: ReadonlyMap<string, SampleValue>; readonly stored: Readonly<Record<string, unknown>> }> {
|
|
895
|
+
const model = modelOf(models, table)
|
|
896
|
+
const columns = columnsOf(table)
|
|
897
|
+
// A column with a database default keeps it unless the fixture assigned it or fills a foreign key over it.
|
|
898
|
+
const defaulted = new Set(columns.filter((column) => column.defaulted).map((column) => column.name))
|
|
899
|
+
const slots: Slot[] = []
|
|
900
|
+
const slotted = new Set<string>()
|
|
901
|
+
for (const key of model?.foreignKeys ?? []) {
|
|
902
|
+
const open = key.columns.filter((column) => !assigned.has(column) && !slotted.has(column))
|
|
903
|
+
// A key whose columns all have defaults keeps them; one the fixture fills fills its defaulted columns too, which
|
|
904
|
+
// alone may name no row the key's other columns pick.
|
|
905
|
+
if (open.every((column) => defaulted.has(column))) continue
|
|
906
|
+
slots.push(await referenceSlot(models, table, key, open, assigned, depth, inserted))
|
|
907
|
+
for (const name of open) slotted.add(name)
|
|
908
|
+
}
|
|
909
|
+
for (const column of columns) {
|
|
910
|
+
// An assigned `null` is the fixture's value too, never a gap to fill.
|
|
911
|
+
if (assigned.has(column.name) || column.defaulted || slotted.has(column.name)) continue
|
|
912
|
+
slots.push(await columnSlot(model, table, column, markers, inserted, ungrouped))
|
|
913
|
+
}
|
|
914
|
+
const order = slotOrder(slots)
|
|
915
|
+
const choice = slots.map(() => 0)
|
|
916
|
+
const involved: number[] = []
|
|
917
|
+
// The refusal of the row the fixture prefers, which the error names once no other row passes.
|
|
918
|
+
let refused: SeedLimitError | undefined
|
|
919
|
+
for (let attempt = 0; attempt < MAX_ROW_ATTEMPTS; attempt++) {
|
|
920
|
+
const row = new Map(assigned)
|
|
921
|
+
let complete = true
|
|
922
|
+
for (const index of order) {
|
|
923
|
+
const slot = slots[index]
|
|
924
|
+
if (slot === undefined) continue
|
|
925
|
+
const picked = await pickOption(slot, choice, index, row)
|
|
926
|
+
if ('error' in picked) {
|
|
927
|
+
// No option of the slot is usable from its current one on: the next combination, or the reason.
|
|
928
|
+
if ((choice[index] ?? 0) === 0 || !involved.includes(index)) throw picked.error
|
|
929
|
+
refused ??= picked.error
|
|
930
|
+
complete = false
|
|
931
|
+
break
|
|
932
|
+
}
|
|
933
|
+
for (const [name, value] of picked.values) row.set(name, value)
|
|
934
|
+
}
|
|
935
|
+
if (complete) {
|
|
936
|
+
try {
|
|
937
|
+
return { row, stored: await backend.insert(table, row) }
|
|
938
|
+
} catch (error) {
|
|
939
|
+
if (!(error instanceof ConstraintLimitError) || error.violation.kind === 'foreign') throw error
|
|
940
|
+
refused ??= error
|
|
941
|
+
const named = await violatedColumns(table, error.violation)
|
|
942
|
+
const touched = [...slots.keys()].filter((index) => named === undefined || (slots[index]?.columns ?? []).some((name) => named.includes(name)))
|
|
943
|
+
// A constraint over the assigned columns only has nothing to try.
|
|
944
|
+
if (touched.length === 0) throw error
|
|
945
|
+
for (const index of touched) {
|
|
946
|
+
if (!involved.includes(index)) involved.push(index)
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (!advanceChoice(slots, choice, involved)) break
|
|
951
|
+
}
|
|
952
|
+
throw refused ?? new SeedLimitError(`the isolation fixture tried ${MAX_ROW_ATTEMPTS} rows of ${table}`)
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/** The columns a model's row is placed by: its own key when it owns a dimension, and each link of its chain. */
|
|
956
|
+
function placement(model: TableModel, values: ReadonlyMap<string, string>, key: string): Map<string, SampleValue> {
|
|
957
|
+
const assigned = new Map<string, SampleValue>()
|
|
958
|
+
const scope = model.scope
|
|
959
|
+
if (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app') {
|
|
960
|
+
assigned.set(scope.key, key)
|
|
961
|
+
}
|
|
962
|
+
for (const link of model.chain) {
|
|
963
|
+
const value = values.get(link.dimension)
|
|
964
|
+
if (value !== undefined) {
|
|
965
|
+
assigned.set(link.column, value)
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
if (model.version !== undefined) {
|
|
969
|
+
assigned.set(model.version, 1)
|
|
970
|
+
}
|
|
971
|
+
if (model.createdBy !== undefined) {
|
|
972
|
+
assigned.set(model.createdBy, 'isolation-fixture')
|
|
973
|
+
}
|
|
974
|
+
return assigned
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/**
|
|
978
|
+
* The plan of seeding `rows` (table → column → value), after `planApplicationRows`, the rule `@fabrika/check` reports
|
|
979
|
+
* from source, and the migrated schema passed it: each given column is a column of the database too. Throws the first
|
|
980
|
+
* refusal; inserts nothing, so a seed of several tables checks them all first.
|
|
981
|
+
*/
|
|
982
|
+
function checkApplicationValues(models: TableModels, rows: Readonly<Record<string, Readonly<Record<string, SampleValue>>>>): ApplicationRowsPlan {
|
|
983
|
+
const plan = planApplicationRows(models, rows)
|
|
984
|
+
const [refusal] = plan.refusals
|
|
985
|
+
if (refusal !== undefined) throw applicationRowError(refusal)
|
|
986
|
+
for (const table of plan.order) {
|
|
987
|
+
for (const name of Object.keys(rows[table] ?? {})) columnOf(table, name)
|
|
988
|
+
}
|
|
989
|
+
return plan
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* One row of the application table `model`, whose values `checkApplicationValues` passed: its key, version and
|
|
994
|
+
* creator stamped, `linked` (a foreign key to a row seeded beside it) and `values` as given, a text column too, every
|
|
995
|
+
* other column sampled. A key `linked` gives (a table that shares its referenced row's key) is the row's key.
|
|
996
|
+
* `inserted` records the row and each row a foreign key or a file column made it insert, referenced rows first.
|
|
997
|
+
*/
|
|
998
|
+
async function seedApplicationRow(
|
|
999
|
+
models: TableModels,
|
|
1000
|
+
model: TableModel,
|
|
1001
|
+
values: Readonly<Record<string, SampleValue>>,
|
|
1002
|
+
linked: ReadonlyMap<string, SampleValue>,
|
|
1003
|
+
markers: string[],
|
|
1004
|
+
inserted?: InsertedRow[],
|
|
1005
|
+
) {
|
|
1006
|
+
const table = model.name
|
|
1007
|
+
const scope = model.scope
|
|
1008
|
+
if (scope.mode !== 'app') throw new Error(`${table} is a ${scope.mode} table, not an application table`)
|
|
1009
|
+
const shared = linked.get(scope.key)
|
|
1010
|
+
const key = shared === undefined || shared === null ? scopeValue(table, scope.key, table, 'app') : String(shared)
|
|
1011
|
+
const assigned = placement(model, new Map(), key)
|
|
1012
|
+
for (const [name, value] of linked) assigned.set(name, value)
|
|
1013
|
+
// A given text column holds no marker: no leak case counts an application row's values as another scope's.
|
|
1014
|
+
for (const [name, value] of Object.entries(values)) assigned.set(name, value)
|
|
1015
|
+
const seeded = await insert(models, table, assigned, markers, 0, inserted)
|
|
1016
|
+
inserted?.push({ table, match: new Map([[scope.key, key]]) })
|
|
1017
|
+
return { key, ...seeded }
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/** The value a pin gives the row of `world`: as written in the own row, distinct in the other. */
|
|
1021
|
+
const pinnedValue = (value: string, world: string): string => (world === 'own' ? value : `${value}-${world}`)
|
|
1022
|
+
|
|
1023
|
+
/**
|
|
1024
|
+
* The dimension values the row of `owner` keyed `key` lies in, as the table stores it: its own, then each container's;
|
|
1025
|
+
* `undefined` when the table holds no such row.
|
|
1026
|
+
*/
|
|
1027
|
+
async function storedChain(owner: TableModel, key: string): Promise<ReadonlyMap<string, string> | undefined> {
|
|
1028
|
+
const scope = owner.scope
|
|
1029
|
+
if (scope.mode !== 'dimension') return undefined
|
|
1030
|
+
const row = await backend.firstRow(owner.name, [scope.key, ...owner.chain.map((link) => link.column)], new Map([[scope.key, key]]))
|
|
1031
|
+
if (row === undefined) return undefined
|
|
1032
|
+
const chain = new Map([[scope.dimension, key]])
|
|
1033
|
+
for (const link of owner.chain) chain.set(link.dimension, String(keyValue(row[link.column], `${owner.name}.${link.column}`)))
|
|
1034
|
+
return chain
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/**
|
|
1038
|
+
* The dimension values a row of `model` lies in for `world`, as far as `scopes` know them: each known value, and every
|
|
1039
|
+
* value a stored row of a known one holds. `stored` are the dimensions whose row a table holds already.
|
|
1040
|
+
*/
|
|
1041
|
+
async function knownValues(
|
|
1042
|
+
models: TableModels,
|
|
1043
|
+
model: TableModel,
|
|
1044
|
+
world: 'own' | 'other',
|
|
1045
|
+
scopes: ScopeValues,
|
|
1046
|
+
): Promise<{ readonly values: Map<string, string>; readonly stored: ReadonlySet<string> }> {
|
|
1047
|
+
const own = model.scope.mode === 'dimension' ? [model.scope.dimension] : []
|
|
1048
|
+
const dimensions = [...own, ...model.chain.map((link) => link.dimension)].filter((dimension) => Object.hasOwn(scopes, dimension))
|
|
1049
|
+
const values = new Map<string, string>()
|
|
1050
|
+
for (const dimension of dimensions) {
|
|
1051
|
+
const known = scopes[dimension]
|
|
1052
|
+
if (known !== undefined) values.set(dimension, world === 'own' ? known.own : known.other)
|
|
1053
|
+
}
|
|
1054
|
+
const stored = new Set<string>()
|
|
1055
|
+
for (const dimension of dimensions) {
|
|
1056
|
+
const owner = ownerOf(models, dimension)
|
|
1057
|
+
const value = values.get(dimension)
|
|
1058
|
+
const chain = owner === undefined || value === undefined ? undefined : await storedChain(owner, value)
|
|
1059
|
+
for (const [type, found] of chain ?? []) {
|
|
1060
|
+
const expected = values.get(type)
|
|
1061
|
+
if (expected !== undefined && expected !== found) {
|
|
1062
|
+
throw new Error(`the stored ${dimension} '${value}' lies in the ${type} '${found}', not in the known '${expected}'`)
|
|
1063
|
+
}
|
|
1064
|
+
values.set(type, found)
|
|
1065
|
+
stored.add(type)
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
return { values, stored }
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/** The values of the text columns that would hold a marker in the stored row of `model` keyed `key`. */
|
|
1072
|
+
async function storedTexts(model: TableModel, key: string): Promise<string[]> {
|
|
1073
|
+
const scope = model.scope
|
|
1074
|
+
if (scope.mode !== 'dimension') return []
|
|
1075
|
+
const names: string[] = []
|
|
1076
|
+
for (const column of columnsOf(model.name)) {
|
|
1077
|
+
if (await holdsMarker(model, model.name, column)) names.push(column.name)
|
|
1078
|
+
}
|
|
1079
|
+
if (names.length === 0) return []
|
|
1080
|
+
const row = await backend.firstRow(model.name, names, new Map([[scope.key, key]]))
|
|
1081
|
+
return names.flatMap((name) => {
|
|
1082
|
+
const value = row?.[name]
|
|
1083
|
+
return typeof value === 'string' && value !== '' ? [value] : []
|
|
1084
|
+
})
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
async function seedWorld(
|
|
1088
|
+
models: TableModels,
|
|
1089
|
+
model: TableModel,
|
|
1090
|
+
world: 'own' | 'other',
|
|
1091
|
+
seed: Readonly<Record<string, SampleValue>>,
|
|
1092
|
+
pins: Readonly<Record<string, string>>,
|
|
1093
|
+
scopes: ScopeValues,
|
|
1094
|
+
inserted: InsertedRow[],
|
|
1095
|
+
): Promise<{
|
|
1096
|
+
readonly world: Omit<WorldRow, 'updates'>
|
|
1097
|
+
readonly row: ReadonlyMap<string, SampleValue>
|
|
1098
|
+
/** The row as stored, its defaults filled. */
|
|
1099
|
+
readonly holds: Readonly<Record<string, unknown>>
|
|
1100
|
+
}> {
|
|
1101
|
+
const markers: string[] = []
|
|
1102
|
+
const scope = model.scope
|
|
1103
|
+
if (scope.mode !== 'dimension' && scope.mode !== 'child') {
|
|
1104
|
+
throw new Error(`${model.name} is not a dimension or child table`)
|
|
1105
|
+
}
|
|
1106
|
+
const { values, stored } = await knownValues(models, model, world, scopes)
|
|
1107
|
+
const links: readonly Container[] = model.chain
|
|
1108
|
+
for (const link of links) {
|
|
1109
|
+
if (!values.has(link.dimension)) values.set(link.dimension, scopeValue(model.name, link.column, link.dimension, world))
|
|
1110
|
+
}
|
|
1111
|
+
const own = scope.mode === 'dimension' ? scope.dimension : undefined
|
|
1112
|
+
const key = (own === undefined ? undefined : values.get(own)) ?? scopeValue(model.name, scope.key, own ?? model.name, world)
|
|
1113
|
+
if (own !== undefined) {
|
|
1114
|
+
values.set(own, key)
|
|
1115
|
+
}
|
|
1116
|
+
const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[], holds: Readonly<Record<string, unknown>> = {}) => {
|
|
1117
|
+
const chain = [
|
|
1118
|
+
...(own === undefined ? [] : [{ type: own, value: key }]),
|
|
1119
|
+
...links.flatMap((link) => {
|
|
1120
|
+
const value = values.get(link.dimension)
|
|
1121
|
+
return value === undefined ? [] : [{ type: link.dimension, value }]
|
|
1122
|
+
}),
|
|
1123
|
+
]
|
|
1124
|
+
const seeded = {
|
|
1125
|
+
key,
|
|
1126
|
+
parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
|
|
1127
|
+
scope: values.get(grantDimension(models, model)) ?? key,
|
|
1128
|
+
chain,
|
|
1129
|
+
markers,
|
|
1130
|
+
stored,
|
|
1131
|
+
}
|
|
1132
|
+
return { world: seeded, row, holds }
|
|
1133
|
+
}
|
|
1134
|
+
if (own !== undefined && stored.has(own)) {
|
|
1135
|
+
if (Object.keys(seed).length > 0 || Object.keys(pins).length > 0) {
|
|
1136
|
+
throw new Error(
|
|
1137
|
+
`${model.name} already holds the ${own} '${key}' (a migration wrote it), so a case writes no seed or pin into it; seed the state of a row the case inserts`,
|
|
1138
|
+
)
|
|
1139
|
+
}
|
|
1140
|
+
return worldRow(new Map(), await storedTexts(model, key))
|
|
1141
|
+
}
|
|
1142
|
+
// Containers first, outermost first: a composite foreign key needs its target row. A stored one is used as it is.
|
|
1143
|
+
for (let index = links.length - 1; index >= 0; index--) {
|
|
1144
|
+
const link = links[index]
|
|
1145
|
+
const owner = link === undefined ? undefined : ownerOf(models, link.dimension)
|
|
1146
|
+
const value = link === undefined ? undefined : values.get(link.dimension)
|
|
1147
|
+
if (link === undefined || owner === undefined || owner.name === model.name || value === undefined || stored.has(link.dimension)) continue
|
|
1148
|
+
// With known values, every container goes with the worlds: one of a known value, so the next case can insert it
|
|
1149
|
+
// again, and one inside a stored row, which no removal of that row reaches.
|
|
1150
|
+
const tracked = Object.keys(scopes).length > 0 ? inserted : undefined
|
|
1151
|
+
await insert(models, owner.name, placement(owner, values, value), markers, 0, tracked)
|
|
1152
|
+
if (tracked !== undefined && owner.scope.mode === 'dimension') {
|
|
1153
|
+
tracked.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
const assigned = placement(model, values, key)
|
|
1157
|
+
for (const [name, value] of Object.entries(seed)) {
|
|
1158
|
+
const column = columnOf(model.name, name)
|
|
1159
|
+
if (assigned.has(name)) {
|
|
1160
|
+
throw new Error(`${model.name}.${name} places the row in its scope; a seed sets only the row's own state`)
|
|
1161
|
+
}
|
|
1162
|
+
if (await holdsMarker(model, model.name, column)) {
|
|
1163
|
+
throw new Error(
|
|
1164
|
+
`${model.name}.${name} holds a text marker the leak cases look for; a seed sets a column of another type (an enum, a boolean, a number), a text column a CHECK lists the values of, or a foreign key`,
|
|
1165
|
+
)
|
|
1166
|
+
}
|
|
1167
|
+
assigned.set(name, value)
|
|
1168
|
+
}
|
|
1169
|
+
for (const [name, value] of Object.entries(pins)) {
|
|
1170
|
+
const column = columnOf(model.name, name)
|
|
1171
|
+
if (assigned.has(name)) {
|
|
1172
|
+
throw new Error(`${model.name}.${name} places the row in its scope or is seeded; a pin gives a text column of the row's own state a known value`)
|
|
1173
|
+
}
|
|
1174
|
+
if (!(await holdsMarker(model, model.name, column))) {
|
|
1175
|
+
throw new Error(`${model.name}.${name} holds no text marker; a pin gives a text column a known value, a seed every other column`)
|
|
1176
|
+
}
|
|
1177
|
+
const pinned = pinnedValue(value, world)
|
|
1178
|
+
assigned.set(name, pinned)
|
|
1179
|
+
markers.push(pinned)
|
|
1180
|
+
}
|
|
1181
|
+
const { row, stored: holds } = await insert(models, model.name, assigned, markers, 0, inserted)
|
|
1182
|
+
inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
|
|
1183
|
+
return worldRow(row, [], holds)
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/** `work`, after which a failure removes the rows it recorded in `inserted` before it rethrows. */
|
|
1187
|
+
async function removedOnFailure<T>(inserted: readonly InsertedRow[], what: string, work: () => Promise<T>): Promise<T> {
|
|
1188
|
+
try {
|
|
1189
|
+
return await work()
|
|
1190
|
+
} catch (error) {
|
|
1191
|
+
try {
|
|
1192
|
+
await backend.remove(inserted)
|
|
1193
|
+
} catch (cleanup) {
|
|
1194
|
+
throw new AggregateError([error, cleanup], `the isolation fixture could not ${what}, nor remove what it had seeded`)
|
|
1195
|
+
}
|
|
1196
|
+
throw error
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
/**
|
|
1201
|
+
* A seeded row's values of the policy's update columns, which its CHECKs accepted: as written, as stored where the
|
|
1202
|
+
* database filled the column (a default), or a sample where the stored value is no plain value.
|
|
1203
|
+
*/
|
|
1204
|
+
async function updatesOf(
|
|
1205
|
+
model: TableModel,
|
|
1206
|
+
row: ReadonlyMap<string, SampleValue>,
|
|
1207
|
+
stored: Readonly<Record<string, unknown>> = {},
|
|
1208
|
+
): Promise<Record<string, SampleValue>> {
|
|
1209
|
+
const updates: Record<string, SampleValue> = {}
|
|
1210
|
+
for (const name of namesOf(model.update)) {
|
|
1211
|
+
const written = row.get(name)
|
|
1212
|
+
const kept = written === undefined ? plainValue(stored[name]) : written
|
|
1213
|
+
updates[name] = kept === undefined ? await updateSample(model.name, name) : kept
|
|
1214
|
+
}
|
|
1215
|
+
return updates
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
return {
|
|
1219
|
+
async seedWorlds(tables, table, values = {}, pins = {}, scopes = {}) {
|
|
1220
|
+
const { models, model } = scopedModel(tables, table)
|
|
1221
|
+
const dimension = grantDimension(models, model)
|
|
1222
|
+
for (const [name, known] of Object.entries(scopes)) {
|
|
1223
|
+
if (known.own === known.other) throw new Error(`the two worlds share the ${name} '${known.own}'; each needs a value of its own`)
|
|
1224
|
+
}
|
|
1225
|
+
const inserted: InsertedRow[] = []
|
|
1226
|
+
let own: Awaited<ReturnType<typeof seedWorld>>
|
|
1227
|
+
let other: Awaited<ReturnType<typeof seedWorld>>
|
|
1228
|
+
try {
|
|
1229
|
+
own = await seedWorld(models, model, 'own', values, pins, scopes, inserted)
|
|
1230
|
+
other = await seedWorld(models, model, 'other', values, pins, scopes, inserted)
|
|
1231
|
+
} catch (error) {
|
|
1232
|
+
// A row of a known value left behind would pass for one a migration wrote in every later case.
|
|
1233
|
+
try {
|
|
1234
|
+
await backend.remove(inserted)
|
|
1235
|
+
} catch (cleanup) {
|
|
1236
|
+
throw new AggregateError([error, cleanup], 'the isolation fixture could not seed the worlds, nor remove what it had seeded')
|
|
1237
|
+
}
|
|
1238
|
+
throw error
|
|
1239
|
+
}
|
|
1240
|
+
// Sampled once both rows are written: a number a unique index covers is the next above what the table holds.
|
|
1241
|
+
return {
|
|
1242
|
+
dimension,
|
|
1243
|
+
own: { ...own.world, updates: await updatesOf(model, own.row, own.holds) },
|
|
1244
|
+
other: { ...other.world, updates: await updatesOf(model, other.row, other.holds) },
|
|
1245
|
+
remove: () => backend.remove(inserted),
|
|
1246
|
+
}
|
|
1247
|
+
},
|
|
1248
|
+
async seedRow(tables, table, values = {}) {
|
|
1249
|
+
const { models, model } = scopedModel(tables, table)
|
|
1250
|
+
checkApplicationValues(models, { [table]: values })
|
|
1251
|
+
const markers: string[] = []
|
|
1252
|
+
const { key, row, stored } = await seedApplicationRow(models, model, values, new Map(), markers)
|
|
1253
|
+
return { key, updates: await updatesOf(model, row, stored), markers }
|
|
1254
|
+
},
|
|
1255
|
+
async seedApplicationRows(tables, rows) {
|
|
1256
|
+
const models = tableModels(tables)
|
|
1257
|
+
const plan = checkApplicationValues(models, rows)
|
|
1258
|
+
const order = plan.order.flatMap((table) => modelOf(models, table) ?? [])
|
|
1259
|
+
const inserted: InsertedRow[] = []
|
|
1260
|
+
// Every row the fixture inserted: the given rows, the rows a foreign key or a file column of theirs made it
|
|
1261
|
+
// insert, and every row that refers to one of them.
|
|
1262
|
+
const remove = (): Promise<void> => backend.remove(inserted)
|
|
1263
|
+
const stored = new Map<string, Readonly<Record<string, unknown>>>()
|
|
1264
|
+
const keys: Record<string, string> = {}
|
|
1265
|
+
try {
|
|
1266
|
+
for (const model of order) {
|
|
1267
|
+
const values = rows[model.name] ?? {}
|
|
1268
|
+
const linked = new Map<string, SampleValue>()
|
|
1269
|
+
for (const key of plan.links[model.name] ?? []) {
|
|
1270
|
+
const referenced = stored.get(key.table)
|
|
1271
|
+
if (referenced === undefined) continue
|
|
1272
|
+
key.columns.forEach((column, index) => {
|
|
1273
|
+
const name = key.references[index] ?? ''
|
|
1274
|
+
linked.set(column, keyValue(referenced[name], `${key.table}.${name}`))
|
|
1275
|
+
})
|
|
1276
|
+
}
|
|
1277
|
+
const seeded = await seedApplicationRow(models, model, values, linked, [], inserted)
|
|
1278
|
+
stored.set(model.name, seeded.stored)
|
|
1279
|
+
keys[model.name] = seeded.key
|
|
1280
|
+
}
|
|
1281
|
+
} catch (error) {
|
|
1282
|
+
// A table that fails leaves none of the rows seeded before it for the next case.
|
|
1283
|
+
try {
|
|
1284
|
+
await remove()
|
|
1285
|
+
} catch (cleanup) {
|
|
1286
|
+
throw new AggregateError([error, cleanup], 'the isolation fixture could not seed the application rows, nor remove those it had seeded')
|
|
1287
|
+
}
|
|
1288
|
+
throw error
|
|
1289
|
+
}
|
|
1290
|
+
return { keys, remove }
|
|
1291
|
+
},
|
|
1292
|
+
async seedUnder(tables, table, under) {
|
|
1293
|
+
const { models, model } = scopedModel(tables, table)
|
|
1294
|
+
const scope = model.scope
|
|
1295
|
+
const [object] = under.chain
|
|
1296
|
+
if ((scope.mode !== 'dimension' && scope.mode !== 'child') || object === undefined) {
|
|
1297
|
+
throw new Error(`${table} is a ${scope.mode} table; a row seeded under another lies in its chain`)
|
|
1298
|
+
}
|
|
1299
|
+
const values = new Map(under.chain.map((link) => [link.type, link.value]))
|
|
1300
|
+
if (!model.chain.some((link) => link.dimension === object.type) || model.chain.some((link) => !values.has(link.dimension))) {
|
|
1301
|
+
throw new Error(`${table} does not lie in a ${object.type}, so no row of it is seeded under one`)
|
|
1302
|
+
}
|
|
1303
|
+
const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
|
|
1304
|
+
const markers: string[] = []
|
|
1305
|
+
const inserted: InsertedRow[] = []
|
|
1306
|
+
await removedOnFailure(inserted, 'seed the row', () => insert(models, table, placement(model, values, key), markers, 0, inserted))
|
|
1307
|
+
inserted.push({ table, match: new Map([[scope.key, key]]) })
|
|
1308
|
+
return { key, markers, remove: () => backend.remove(inserted) }
|
|
1309
|
+
},
|
|
1310
|
+
async sampleInsert(tables, table, beside) {
|
|
1311
|
+
const { models, model } = scopedModel(tables, table)
|
|
1312
|
+
const scope = model.scope
|
|
1313
|
+
if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
|
|
1314
|
+
throw new Error(`${table} is a ${scope.mode} table; no store inserts into it`)
|
|
1315
|
+
}
|
|
1316
|
+
// A probe row the database judges, placed as the insert will place it (in `beside`'s containers, else in fresh
|
|
1317
|
+
// ones it removes with the probe), numbered within the containers known; its values are the sample.
|
|
1318
|
+
const values = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
|
|
1319
|
+
const ungrouped = new Set(model.chain.filter((link) => !values.has(link.dimension)).map((link) => link.column))
|
|
1320
|
+
const placed: InsertedRow[] = []
|
|
1321
|
+
const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'probe')
|
|
1322
|
+
const { row } = await removedOnFailure(placed, 'insert a probe row', async () => {
|
|
1323
|
+
await placeContainers(models, model, values, 'probe', 0, placed)
|
|
1324
|
+
return insert(models, table, placement(model, values, key), [], 0, undefined, ungrouped)
|
|
1325
|
+
})
|
|
1326
|
+
await backend.remove([{ table, match: new Map([[scope.key, key]]) }, ...placed])
|
|
1327
|
+
const sample: Record<string, SampleValue> = {}
|
|
1328
|
+
for (const column of columnsOf(table)) {
|
|
1329
|
+
if (!inSet(model.insert, column.name) || !row.has(column.name)) continue
|
|
1330
|
+
// A nullable column a CHECK ties to another is written as the probe held it; any other is left to the insert.
|
|
1331
|
+
if (isRequired(column) || (await checksOn(table, column.name)).length > 0) sample[column.name] = row.get(column.name) ?? null
|
|
1332
|
+
}
|
|
1333
|
+
return sample
|
|
1334
|
+
},
|
|
1335
|
+
seededObjects: () => [...seededObjects],
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/**
|
|
1340
|
+
* The untyped handle over one table of the data layer `scoped(tables)` created; it reaches the database once `boot`
|
|
1341
|
+
* has bound that layer. Every runtime check of a store applies: kind, dimension, action and the request's authority.
|
|
1342
|
+
* `module` is the kit's, which refuses a production process.
|
|
1343
|
+
*/
|
|
1344
|
+
export function probeTable(module: string, layer: unknown, table: string): TableProbe {
|
|
1345
|
+
refuseInProduction(module)
|
|
1346
|
+
const side = frameworkSideOf(layer)
|
|
1347
|
+
if (side === undefined) {
|
|
1348
|
+
throw new TypeError('not a data layer scoped(tables) created')
|
|
1349
|
+
}
|
|
1350
|
+
return side.probe(table)
|
|
1351
|
+
}
|