@fabrika/db 0.9.0-cloudflare.3 → 0.9.0-dev.10
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 +4 -4
- package/src/codegen-sqlite.ts +53 -8
- package/src/codegen.ts +120 -28
- package/src/description.ts +34 -8
- package/src/errors.ts +4 -2
- package/src/file-columns.ts +32 -8
- package/src/index.ts +1 -0
- package/src/json.ts +124 -0
- package/src/orm-types.ts +3 -3
- package/src/orm.ts +27 -3
- package/src/policy.ts +11 -2
- package/src/sql.ts +16 -6
- package/src/store.ts +22 -9
- package/src/temporal.ts +8 -1
- package/src/testing-shared.ts +185 -40
- package/src/testing-sqlite.ts +58 -1
- package/src/testing.ts +89 -4
- package/types/src/codegen-sqlite.d.ts +8 -1
- package/types/src/codegen.d.ts +40 -9
- package/types/src/description.d.ts +23 -8
- package/types/src/errors.d.ts +3 -2
- package/types/src/file-columns.d.ts +4 -2
- package/types/src/index.d.ts +1 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/orm-types.d.ts +4 -4
- package/types/src/orm.d.ts +5 -0
- package/types/src/policy.d.ts +4 -0
- package/types/src/store.d.ts +4 -4
- package/types/src/temporal.d.ts +4 -1
- package/types/src/testing-shared.d.ts +52 -3
package/src/testing-shared.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { type ApplicationRowRefusal, applicationRowRefusalText, type Application
|
|
|
7
7
|
import { inSet, namesOf } from './builtins'
|
|
8
8
|
import type { Database } from './database'
|
|
9
9
|
import type { Primitive } from './description'
|
|
10
|
+
import { jsonInput } from './json'
|
|
10
11
|
import { FILES_TABLE } from './migrations'
|
|
11
12
|
import { type Container, type ForeignKey, modelOf, type TableModel, type TableModels, tableModels, type Tables } from './policy'
|
|
12
13
|
import { refuseInProduction } from './production'
|
|
@@ -16,6 +17,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. */
|
|
17
18
|
export type SampleValue = Primitive | null
|
|
18
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 generated 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
|
+
|
|
19
29
|
/** One seeded row and where it lies. */
|
|
20
30
|
export interface WorldRow {
|
|
21
31
|
/** The row's key: the dimension value of a dimension table's row, a child's own key. */
|
|
@@ -128,8 +138,14 @@ export interface TestSeeding {
|
|
|
128
138
|
* the markers it holds.
|
|
129
139
|
*/
|
|
130
140
|
seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: WorldRow): Promise<SeededRow>
|
|
131
|
-
/**
|
|
132
|
-
|
|
141
|
+
/**
|
|
142
|
+
* Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file
|
|
143
|
+
* column a seeded file. `beside` is a row `seedWorlds` seeded that the inserted row will lie beside, in the same
|
|
144
|
+
* containers. A number column a unique index covers takes the next number above the largest the table holds now in the
|
|
145
|
+
* row's group (the index's other columns as the row will have them, its containers' from `beside`), so insert the
|
|
146
|
+
* values before taking the next sample, or the two share it.
|
|
147
|
+
*/
|
|
148
|
+
sampleInsert<DB, P>(tables: Tables<DB, P>, table: string, beside?: WorldRow): Promise<Readonly<Record<string, SampleValue>>>
|
|
133
149
|
/**
|
|
134
150
|
* The object key of every file the fixture seeded into a file column, oldest first. Each stands for an empty object,
|
|
135
151
|
* which a test's object store holds when a handler serves or opens the file.
|
|
@@ -159,6 +175,10 @@ export interface SeedColumn {
|
|
|
159
175
|
readonly text: boolean
|
|
160
176
|
/** A uuid type: a key or containment column of it holds a random uuid as its scope value. */
|
|
161
177
|
readonly uuid: boolean
|
|
178
|
+
/** A number type: where a unique index covers it, the fixture writes the next number of the row's group instead of its sample. */
|
|
179
|
+
readonly number: boolean
|
|
180
|
+
/** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
|
|
181
|
+
readonly json: boolean
|
|
162
182
|
/** A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it cannot fill. */
|
|
163
183
|
readonly sample: () => Primitive
|
|
164
184
|
}
|
|
@@ -172,6 +192,18 @@ export interface CheckConstraint {
|
|
|
172
192
|
readonly values: readonly string[]
|
|
173
193
|
}
|
|
174
194
|
|
|
195
|
+
/**
|
|
196
|
+
* A unique index of the schema (a primary key's or a UNIQUE constraint's included), by its key columns. Only an index of
|
|
197
|
+
* plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
|
|
198
|
+
*/
|
|
199
|
+
export interface UniqueIndex {
|
|
200
|
+
readonly name: string
|
|
201
|
+
readonly table: string
|
|
202
|
+
readonly columns: readonly string[]
|
|
203
|
+
/** `NULLS NOT DISTINCT`: a null in a key column collides with another row's null there. */
|
|
204
|
+
readonly nullsNotDistinct: boolean
|
|
205
|
+
}
|
|
206
|
+
|
|
175
207
|
/** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it. */
|
|
176
208
|
export interface SeededFile {
|
|
177
209
|
readonly id: string
|
|
@@ -200,7 +232,18 @@ export interface SeedingBackend {
|
|
|
200
232
|
readonly columns: readonly SeedColumn[]
|
|
201
233
|
/** Every CHECK constraint of the schema's tables; read once, on the first column that needs them. */
|
|
202
234
|
checks(): Promise<readonly CheckConstraint[]>
|
|
203
|
-
/**
|
|
235
|
+
/** Every unique index of plain columns and no predicate of the schema's tables; read once, on the first column that needs them. */
|
|
236
|
+
uniqueIndexes(): Promise<readonly UniqueIndex[]>
|
|
237
|
+
/**
|
|
238
|
+
* The smallest whole number above every value `column` holds in the rows of `table` that match one of `groups`
|
|
239
|
+
* (`groupsWhere`), and at least 1, as the column's type holds it; `undefined` when the type holds no such number, or
|
|
240
|
+
* the largest is no finite number.
|
|
241
|
+
*/
|
|
242
|
+
nextNumber(table: string, column: string, groups: readonly ReadonlyMap<string, SampleValue>[]): Promise<Primitive | undefined>
|
|
243
|
+
/**
|
|
244
|
+
* Inserts one row and answers it as stored; a CHECK, foreign key or unique index it fails is a `SeedLimitError`
|
|
245
|
+
* (`checkLimit`, `foreignKeyLimit`, `uniqueValueLimit`).
|
|
246
|
+
*/
|
|
204
247
|
insert(table: string, values: ReadonlyMap<string, SampleValue>): Promise<Readonly<Record<string, unknown>>>
|
|
205
248
|
/** One row of `table`, of `columns`, or `undefined` when it has none. */
|
|
206
249
|
firstRow(table: string, columns: readonly string[]): Promise<Readonly<Record<string, unknown>> | undefined>
|
|
@@ -225,11 +268,46 @@ export function foreignKeyLimit(constraint: string, table: string): SeedLimitErr
|
|
|
225
268
|
return new SeedLimitError(`the isolation fixture's row of ${table} breaks the foreign key ${constraint}`)
|
|
226
269
|
}
|
|
227
270
|
|
|
271
|
+
/** The seed limit of a number column a unique index covers whose type holds no number above the largest of the row's group. */
|
|
272
|
+
export function uniqueLimit(index: string, table: string, column: string): SeedLimitError {
|
|
273
|
+
return new SeedLimitError(
|
|
274
|
+
`the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value; give the column a default or make it nullable`,
|
|
275
|
+
)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The seed limit of a row whose values another row of the table already holds under a unique index. */
|
|
279
|
+
export function uniqueValueLimit(index: string, table: string): SeedLimitError {
|
|
280
|
+
return new SeedLimitError(
|
|
281
|
+
`the isolation fixture cannot satisfy the unique index ${index} of ${table}: it writes a sample of each column's type there, which another row holds; give a column of it a default, or make it nullable`,
|
|
282
|
+
)
|
|
283
|
+
}
|
|
284
|
+
|
|
228
285
|
/** The seed limit of a required column whose type the fixture has no sample of. */
|
|
229
286
|
export function typeLimit(table: string, column: string, type: string): SeedLimitError {
|
|
230
287
|
return new SeedLimitError(`the isolation fixture cannot fill ${table}.${column} (${type}); give the column a default or make it nullable`)
|
|
231
288
|
}
|
|
232
289
|
|
|
290
|
+
/**
|
|
291
|
+
* A condition that matches a row holding every value of one of `groups` (column → value, `null` matched by `IS NULL`; an
|
|
292
|
+
* empty group matches every row, no group none), in the dialect's quoting and placeholders, with the values it binds.
|
|
293
|
+
*/
|
|
294
|
+
export function groupsWhere(
|
|
295
|
+
groups: readonly ReadonlyMap<string, SampleValue>[],
|
|
296
|
+
quote: (identifier: string) => string,
|
|
297
|
+
placeholder: (position: number) => string,
|
|
298
|
+
): { where: string; values: SampleValue[] } {
|
|
299
|
+
const values: SampleValue[] = []
|
|
300
|
+
const each = groups.map((group) => {
|
|
301
|
+
const terms = [...group].map(([column, value]) => {
|
|
302
|
+
if (value === null) return `${quote(column)} IS NULL`
|
|
303
|
+
values.push(value)
|
|
304
|
+
return `${quote(column)} = ${placeholder(values.length)}`
|
|
305
|
+
})
|
|
306
|
+
return terms.length === 0 ? 'TRUE' : `(${terms.join(' AND ')})`
|
|
307
|
+
})
|
|
308
|
+
return { where: each.length === 0 ? 'FALSE' : each.join(' OR '), values }
|
|
309
|
+
}
|
|
310
|
+
|
|
233
311
|
export function randomHex(): string {
|
|
234
312
|
return crypto.randomUUID().replaceAll('-', '').slice(0, 8)
|
|
235
313
|
}
|
|
@@ -305,6 +383,7 @@ export const SEEDED_OBJECT_VERSION = '"seeded"'
|
|
|
305
383
|
/** The isolation fixtures over the schema `backend` describes. */
|
|
306
384
|
export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
307
385
|
let checks: Promise<readonly CheckConstraint[]> | undefined
|
|
386
|
+
let uniqueIndexes: Promise<readonly UniqueIndex[]> | undefined
|
|
308
387
|
const seededObjects: string[] = []
|
|
309
388
|
|
|
310
389
|
/** The CHECK constraints that name `column` of `table`. */
|
|
@@ -325,9 +404,65 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
325
404
|
return column.nullable ? null : undefined
|
|
326
405
|
}
|
|
327
406
|
|
|
328
|
-
|
|
407
|
+
async function uniqueIndexesOf(table: string): Promise<readonly UniqueIndex[]> {
|
|
408
|
+
uniqueIndexes ??= backend.uniqueIndexes()
|
|
409
|
+
return (await uniqueIndexes).filter((index) => index.table === table)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Whether the fixture numbers `column` (`nextNumberOf`) instead of writing its type's sample: a number a unique index covers. */
|
|
413
|
+
async function numbered(table: string, column: SeedColumn): Promise<boolean> {
|
|
414
|
+
return column.number && (await uniqueIndexesOf(table)).some((index) => index.columns.includes(column.name))
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* The number a column `numbered` names takes in `row` (column → value, as the row has them so far): the next above the
|
|
419
|
+
* largest of its group under every unique index that covers it, so the row collides with no row of the table, whoever
|
|
420
|
+
* wrote it. The group is the rows that hold the index's other columns as `row` does: under a fresh parent it is empty
|
|
421
|
+
* and the number 1, which a bounded CHECK passes as before. A key column `row` holds no value for yet is left out of
|
|
422
|
+
* the group, which only widens it; an index the row holds `null` in never conflicts, unless its nulls are not distinct.
|
|
423
|
+
*/
|
|
424
|
+
async function nextNumberOf(table: string, column: SeedColumn, row: ReadonlyMap<string, SampleValue>): Promise<SampleValue> {
|
|
425
|
+
const covering = (await uniqueIndexesOf(table)).filter((index) => index.columns.includes(column.name))
|
|
426
|
+
const groups: Map<string, SampleValue>[] = []
|
|
427
|
+
for (const index of covering) {
|
|
428
|
+
const group = new Map<string, SampleValue>()
|
|
429
|
+
for (const other of index.columns) {
|
|
430
|
+
if (other !== column.name && row.has(other)) group.set(other, row.get(other) ?? null)
|
|
431
|
+
}
|
|
432
|
+
if (index.nullsNotDistinct || ![...group.values()].includes(null)) groups.push(group)
|
|
433
|
+
}
|
|
434
|
+
if (groups.length === 0) return column.sample()
|
|
435
|
+
const next = await backend.nextNumber(table, column.name, groups)
|
|
436
|
+
if (next === undefined) throw uniqueLimit(covering.map((index) => index.name).join(', '), table, column.name)
|
|
437
|
+
return next
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** 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. */
|
|
329
441
|
async function requiredSample(table: string, column: SeedColumn): Promise<SampleValue> {
|
|
330
|
-
|
|
442
|
+
const checked = await checkedValue(table, column)
|
|
443
|
+
if (checked !== undefined) return checked
|
|
444
|
+
return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample()
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Writes into `row` a value for each of `columns`: `chosen`'s (a file, a CHECK's value, a marker, a null), else, for a
|
|
449
|
+
* number a unique index covers, its next number once every other column places the row in its group, else a sample
|
|
450
|
+
* of its type.
|
|
451
|
+
*/
|
|
452
|
+
async function fillRow(
|
|
453
|
+
table: string,
|
|
454
|
+
columns: readonly SeedColumn[],
|
|
455
|
+
row: Map<string, SampleValue>,
|
|
456
|
+
chosen: (column: SeedColumn) => Promise<SampleValue | undefined>,
|
|
457
|
+
): Promise<void> {
|
|
458
|
+
const later: SeedColumn[] = []
|
|
459
|
+
for (const column of columns) {
|
|
460
|
+
const value = await chosen(column)
|
|
461
|
+
if (value !== undefined) row.set(column.name, value)
|
|
462
|
+
else if (await numbered(table, column)) later.push(column)
|
|
463
|
+
else row.set(column.name, column.sample())
|
|
464
|
+
}
|
|
465
|
+
for (const column of later) row.set(column.name, await nextNumberOf(table, column, row))
|
|
331
466
|
}
|
|
332
467
|
|
|
333
468
|
function columnsOf(table: string): readonly SeedColumn[] {
|
|
@@ -447,29 +582,26 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
447
582
|
for (const [name, value] of await referencedKey(models, table, key, open, depth, inserted)) keyed.set(name, value)
|
|
448
583
|
}
|
|
449
584
|
const row = new Map<string, SampleValue>()
|
|
585
|
+
const open: SeedColumn[] = []
|
|
450
586
|
for (const column of columns) {
|
|
451
587
|
const name = column.name
|
|
452
588
|
// An assigned `null` is the fixture's value too, never a gap to fill.
|
|
453
589
|
const given = assigned.has(name) ? assigned : keyed.has(name) ? keyed : undefined
|
|
454
|
-
if (given !== undefined)
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
const checked =
|
|
461
|
-
if (
|
|
462
|
-
|
|
463
|
-
} else if (checked !== undefined) {
|
|
464
|
-
row.set(name, checked)
|
|
465
|
-
} else if (await holdsMarker(model, table, column)) {
|
|
590
|
+
if (given !== undefined) row.set(name, given.get(name) ?? null)
|
|
591
|
+
else if (!column.defaulted) open.push(column)
|
|
592
|
+
}
|
|
593
|
+
await fillRow(table, open, row, async (column) => {
|
|
594
|
+
const kind = model !== undefined && Object.hasOwn(model.files, column.name) ? model.files[column.name] : undefined
|
|
595
|
+
if (kind !== undefined) return seedFile(kind, inserted)
|
|
596
|
+
const checked = await checkedValue(table, column)
|
|
597
|
+
if (checked !== undefined) return checked
|
|
598
|
+
if (await holdsMarker(model, table, column)) {
|
|
466
599
|
const marker = `m${randomHex()}${randomHex()}`
|
|
467
600
|
markers.push(marker)
|
|
468
|
-
|
|
469
|
-
} else {
|
|
470
|
-
row.set(name, column.nullable ? null : column.sample())
|
|
601
|
+
return marker
|
|
471
602
|
}
|
|
472
|
-
|
|
603
|
+
return column.nullable ? null : undefined
|
|
604
|
+
})
|
|
473
605
|
return { row, stored: await backend.insert(table, row) }
|
|
474
606
|
}
|
|
475
607
|
|
|
@@ -548,7 +680,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
548
680
|
seed: Readonly<Record<string, SampleValue>>,
|
|
549
681
|
pins: Readonly<Record<string, string>>,
|
|
550
682
|
inserted: InsertedRow[],
|
|
551
|
-
): Promise<WorldRow> {
|
|
683
|
+
): Promise<{ readonly world: Omit<WorldRow, 'updates'>; readonly row: ReadonlyMap<string, SampleValue> }> {
|
|
552
684
|
const markers: string[] = []
|
|
553
685
|
const values = new Map<string, string>()
|
|
554
686
|
const links: readonly Container[] = model.chain
|
|
@@ -599,10 +731,6 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
599
731
|
}
|
|
600
732
|
const { row } = await insert(models, model.name, assigned, markers)
|
|
601
733
|
inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
|
|
602
|
-
const updates: Record<string, SampleValue> = {}
|
|
603
|
-
for (const name of namesOf(model.update)) {
|
|
604
|
-
updates[name] = row.get(name) ?? await updateSample(model.name, name)
|
|
605
|
-
}
|
|
606
734
|
const dimension = grantDimension(models, model)
|
|
607
735
|
const chain = [
|
|
608
736
|
...(scope.mode === 'dimension' ? [{ type: scope.dimension, value: key }] : []),
|
|
@@ -611,14 +739,23 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
611
739
|
return value === undefined ? [] : [{ type: link.dimension, value }]
|
|
612
740
|
}),
|
|
613
741
|
]
|
|
614
|
-
|
|
742
|
+
const seeded = {
|
|
615
743
|
key,
|
|
616
744
|
parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
|
|
617
745
|
scope: values.get(dimension) ?? key,
|
|
618
746
|
chain,
|
|
619
|
-
updates,
|
|
620
747
|
markers,
|
|
621
748
|
}
|
|
749
|
+
return { world: seeded, row }
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** A seeded row's values of the policy's update columns: as written, or a sample where the database filled the column. */
|
|
753
|
+
async function updatesOf(model: TableModel, row: ReadonlyMap<string, SampleValue>): Promise<Record<string, SampleValue>> {
|
|
754
|
+
const updates: Record<string, SampleValue> = {}
|
|
755
|
+
for (const name of namesOf(model.update)) {
|
|
756
|
+
updates[name] = row.get(name) ?? await updateSample(model.name, name)
|
|
757
|
+
}
|
|
758
|
+
return updates
|
|
622
759
|
}
|
|
623
760
|
|
|
624
761
|
return {
|
|
@@ -626,10 +763,13 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
626
763
|
const { models, model } = scopedModel(tables, table)
|
|
627
764
|
const dimension = grantDimension(models, model)
|
|
628
765
|
const inserted: InsertedRow[] = []
|
|
766
|
+
const own = await seedWorld(models, model, 'own', values, pins, inserted)
|
|
767
|
+
const other = await seedWorld(models, model, 'other', values, pins, inserted)
|
|
768
|
+
// Sampled once both rows are written: a number a unique index covers is the next above what the table holds.
|
|
629
769
|
return {
|
|
630
770
|
dimension,
|
|
631
|
-
own: await
|
|
632
|
-
other: await
|
|
771
|
+
own: { ...own.world, updates: await updatesOf(model, own.row) },
|
|
772
|
+
other: { ...other.world, updates: await updatesOf(model, other.row) },
|
|
633
773
|
remove: () => backend.remove(inserted),
|
|
634
774
|
}
|
|
635
775
|
},
|
|
@@ -638,11 +778,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
638
778
|
checkApplicationValues(models, { [table]: values })
|
|
639
779
|
const markers: string[] = []
|
|
640
780
|
const { key, row } = await seedApplicationRow(models, model, values, new Map(), markers)
|
|
641
|
-
|
|
642
|
-
for (const name of namesOf(model.update)) {
|
|
643
|
-
updates[name] = row.get(name) ?? await updateSample(table, name)
|
|
644
|
-
}
|
|
645
|
-
return { key, updates, markers }
|
|
781
|
+
return { key, updates: await updatesOf(model, row), markers }
|
|
646
782
|
},
|
|
647
783
|
async seedApplicationRows(tables, rows) {
|
|
648
784
|
const models = tableModels(tables)
|
|
@@ -697,7 +833,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
697
833
|
await insert(models, table, placement(model, values, key), markers)
|
|
698
834
|
return { key, markers }
|
|
699
835
|
},
|
|
700
|
-
async sampleInsert(tables, table) {
|
|
836
|
+
async sampleInsert(tables, table, beside) {
|
|
701
837
|
const { models, model } = scopedModel(tables, table)
|
|
702
838
|
const values: Record<string, SampleValue> = {}
|
|
703
839
|
const columns = columnsOf(table)
|
|
@@ -707,11 +843,20 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
707
843
|
if (open.length === 0) continue
|
|
708
844
|
for (const [name, value] of await referencedKey(models, table, key, open, 0)) values[name] = value
|
|
709
845
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
846
|
+
// The row as the insert will write it: in `beside`'s containers, which the handler places it in.
|
|
847
|
+
const containers = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
|
|
848
|
+
const row = new Map<string, SampleValue>()
|
|
849
|
+
for (const link of model.chain) {
|
|
850
|
+
const value = containers.get(link.dimension)
|
|
851
|
+
if (value !== undefined) row.set(link.column, value)
|
|
714
852
|
}
|
|
853
|
+
for (const [name, value] of Object.entries(values)) row.set(name, value)
|
|
854
|
+
const open = required.filter((column) => !(column.name in values))
|
|
855
|
+
await fillRow(table, open, row, async (column) => {
|
|
856
|
+
const kind = Object.hasOwn(model.files, column.name) ? model.files[column.name] : undefined
|
|
857
|
+
return kind === undefined ? checkedValue(table, column) : seedFile(kind)
|
|
858
|
+
})
|
|
859
|
+
for (const column of open) values[column.name] = row.get(column.name) ?? null
|
|
715
860
|
return values
|
|
716
861
|
},
|
|
717
862
|
seededObjects: () => [...seededObjects],
|
package/src/testing-sqlite.ts
CHANGED
|
@@ -22,18 +22,22 @@ import {
|
|
|
22
22
|
type CheckConstraint,
|
|
23
23
|
checkLimit,
|
|
24
24
|
foreignKeyLimit,
|
|
25
|
+
groupsWhere,
|
|
25
26
|
type InsertedRow,
|
|
26
27
|
MAX_REMOVED_ROWS,
|
|
27
28
|
probeTable,
|
|
28
29
|
randomHex,
|
|
29
30
|
removalLimit,
|
|
30
31
|
type SampleValue,
|
|
32
|
+
seedBinding,
|
|
31
33
|
type SeedColumn,
|
|
32
34
|
type SeedingBackend,
|
|
33
35
|
SeedLimitError,
|
|
34
36
|
type TestDatabase,
|
|
35
37
|
testSeeding,
|
|
36
38
|
typeLimit,
|
|
39
|
+
type UniqueIndex,
|
|
40
|
+
uniqueValueLimit,
|
|
37
41
|
} from './testing-shared'
|
|
38
42
|
|
|
39
43
|
export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store'
|
|
@@ -84,6 +88,8 @@ function sampleOf(table: string, column: string, declared: string): Primitive {
|
|
|
84
88
|
// A day is `YYYY-MM-DD` and a timestamp ISO text in UTC: the forms the layer writes and reads on SQLite.
|
|
85
89
|
if (type === 'DATE') return new Date().toISOString().slice(0, 10)
|
|
86
90
|
if (TIMESTAMP_TYPES.has(type)) return new Date().toISOString()
|
|
91
|
+
// A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
|
|
92
|
+
if (type === 'JSONB') return 'sample'
|
|
87
93
|
throw typeLimit(table, column, declared)
|
|
88
94
|
}
|
|
89
95
|
|
|
@@ -114,6 +120,8 @@ function readColumns(exec: Exec): SeedColumn[] {
|
|
|
114
120
|
defaulted: rowid || column.dflt_value !== null || column.hidden === 2 || column.hidden === 3,
|
|
115
121
|
text: TEXT_TYPES.has(type),
|
|
116
122
|
uuid: type === 'UUID',
|
|
123
|
+
number: NUMBER_TYPES.has(type),
|
|
124
|
+
json: type === 'JSONB',
|
|
117
125
|
sample: () => sampleOf(table.name, column.name, column.type),
|
|
118
126
|
})
|
|
119
127
|
}
|
|
@@ -298,6 +306,50 @@ function tableChecks(table: string, sql: string, columns: readonly string[]): Ch
|
|
|
298
306
|
return checks
|
|
299
307
|
}
|
|
300
308
|
|
|
309
|
+
const indexRows = z.array(z.object({ name: z.string(), partial: z.number(), column: z.string().nullable() }))
|
|
310
|
+
const maxRows = z.array(z.object({ largest: z.unknown() }))
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Every unique index of the tables (a primary key's and a UNIQUE constraint's are one) whose key columns are all plain
|
|
314
|
+
* columns and that has no predicate, with its key columns (`pragma_index_info` lists no others). An index on an
|
|
315
|
+
* expression (a key column with no name) or a partial one is left out. SQLite has no `NULLS NOT DISTINCT`.
|
|
316
|
+
*/
|
|
317
|
+
function readUniqueIndexes(exec: Exec, tables: readonly string[]): UniqueIndex[] {
|
|
318
|
+
const indexes: UniqueIndex[] = []
|
|
319
|
+
for (const table of tables) {
|
|
320
|
+
const covered = new Map<string, (string | null)[]>()
|
|
321
|
+
const rows = indexRows.parse(
|
|
322
|
+
exec(
|
|
323
|
+
'SELECT l.name AS name, l.partial AS partial, i.name AS "column" FROM pragma_index_list(?) l, pragma_index_info(l.name) i WHERE l."unique" = 1 ORDER BY l.name, i.seqno',
|
|
324
|
+
table,
|
|
325
|
+
),
|
|
326
|
+
)
|
|
327
|
+
for (const row of rows) {
|
|
328
|
+
if (row.partial === 0) covered.set(row.name, [...(covered.get(row.name) ?? []), row.column])
|
|
329
|
+
}
|
|
330
|
+
for (const [name, columns] of covered) {
|
|
331
|
+
const plain = columns.flatMap((column) => column ?? [])
|
|
332
|
+
if (plain.length === columns.length) indexes.push({ name, table, columns: plain, nullsNotDistinct: false })
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return indexes
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* The smallest whole number above every value of the column in the rows that match one of `groups`, and at least 1;
|
|
340
|
+
* `undefined` past the safe integers, or where the largest is no finite number.
|
|
341
|
+
*/
|
|
342
|
+
function readNextNumber(exec: Exec, table: string, column: string, groups: readonly ReadonlyMap<string, SampleValue>[]): number | undefined {
|
|
343
|
+
const { where, values } = groupsWhere(groups, quoted, () => '?')
|
|
344
|
+
const [found] = maxRows.parse(exec(`SELECT max(${quoted(column)}) AS largest FROM ${quoted(table)} WHERE ${where}`, ...values.map(binding)))
|
|
345
|
+
const largest = found?.largest ?? null
|
|
346
|
+
if (largest === null) return 1
|
|
347
|
+
const value = typeof largest === 'bigint' ? Number(largest) : largest
|
|
348
|
+
if (typeof value !== 'number') return undefined
|
|
349
|
+
const next = Math.max(Math.floor(value) + 1, 1)
|
|
350
|
+
return Number.isSafeInteger(next) ? next : undefined
|
|
351
|
+
}
|
|
352
|
+
|
|
301
353
|
const foreignKeyRows = z.array(z.object({ id: z.number(), seq: z.number(), table: z.string(), from: z.string(), to: z.string().nullable() }))
|
|
302
354
|
const keyRows = z.array(z.object({ name: z.string(), pk: z.number() }))
|
|
303
355
|
const rowidRows = z.array(z.object({ id: z.number() }))
|
|
@@ -363,6 +415,9 @@ function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
|
|
|
363
415
|
if (check !== null) return checkLimit(check[1] ?? 'unnamed', table)
|
|
364
416
|
// SQLite names no foreign key in its error.
|
|
365
417
|
if (message.startsWith('FOREIGN KEY constraint failed')) return foreignKeyLimit('unnamed', table)
|
|
418
|
+
// SQLite names a unique index by its columns in its error: `UNIQUE constraint failed: t.a, t.b`.
|
|
419
|
+
const unique = /^UNIQUE constraint failed: (.*)$/s.exec(message)
|
|
420
|
+
if (unique !== null) return uniqueValueLimit(`(${unique[1] ?? 'unnamed'})`, table)
|
|
366
421
|
return undefined
|
|
367
422
|
}
|
|
368
423
|
|
|
@@ -418,6 +473,8 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
418
473
|
const backend: SeedingBackend = {
|
|
419
474
|
columns,
|
|
420
475
|
checks: async () => readChecks(exec, columns),
|
|
476
|
+
uniqueIndexes: async () => readUniqueIndexes(exec, [...new Set(columns.map((column) => column.table))]),
|
|
477
|
+
nextNumber: async (table, column, groups) => readNextNumber(exec, table, column, groups),
|
|
421
478
|
async insert(table, row) {
|
|
422
479
|
const names = [...row.keys()]
|
|
423
480
|
const target = quoted(table)
|
|
@@ -425,7 +482,7 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
425
482
|
? `INSERT INTO ${target} DEFAULT VALUES RETURNING *`
|
|
426
483
|
: `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${names.map(() => '?').join(', ')}) RETURNING *`
|
|
427
484
|
try {
|
|
428
|
-
return exec(statement, ...names.map((name) => binding(row.get(name) ?? null)))[0] ?? {}
|
|
485
|
+
return exec(statement, ...names.map((name) => binding(seedBinding(columns, table, name, row.get(name) ?? null))))[0] ?? {}
|
|
429
486
|
} catch (error) {
|
|
430
487
|
throw seedLimit(error, table) ?? error
|
|
431
488
|
}
|
package/src/testing.ts
CHANGED
|
@@ -27,17 +27,20 @@ import {
|
|
|
27
27
|
type CheckConstraint,
|
|
28
28
|
checkLimit,
|
|
29
29
|
foreignKeyLimit,
|
|
30
|
+
groupsWhere,
|
|
30
31
|
type InsertedRow,
|
|
31
32
|
MAX_REMOVED_ROWS,
|
|
32
33
|
probeTable,
|
|
33
34
|
randomHex,
|
|
34
35
|
removalLimit,
|
|
36
|
+
seedBinding,
|
|
35
37
|
type SeedColumn,
|
|
36
38
|
type SeedingBackend,
|
|
37
39
|
type SeedLimitError,
|
|
38
40
|
type TestDatabase,
|
|
39
41
|
testSeeding,
|
|
40
42
|
typeLimit,
|
|
43
|
+
uniqueValueLimit,
|
|
41
44
|
} from './testing-shared'
|
|
42
45
|
|
|
43
46
|
export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store'
|
|
@@ -80,6 +83,7 @@ export interface TestDatabaseOptions {
|
|
|
80
83
|
let capacityExhausted: ConnectionCapacityError | undefined
|
|
81
84
|
|
|
82
85
|
const TEXT_TYPES: ReadonlySet<string> = new Set(['text', 'varchar', 'bpchar'])
|
|
86
|
+
const NUMBER_TYPES: ReadonlySet<string> = new Set(['int2', 'int4', 'int8', 'float4', 'float8', 'numeric'])
|
|
83
87
|
|
|
84
88
|
function quoted(identifier: string): string {
|
|
85
89
|
return `"${identifier}"`
|
|
@@ -96,8 +100,8 @@ function sampleOf(table: string, column: CatalogColumn): Primitive {
|
|
|
96
100
|
const type = column.type_name
|
|
97
101
|
if (type === 'uuid') return crypto.randomUUID()
|
|
98
102
|
if (TEXT_TYPES.has(type)) return `s${randomHex()}`
|
|
99
|
-
|
|
100
|
-
if (type === 'int8' || type === 'numeric'
|
|
103
|
+
// Bun.SQL reads an int8 and a numeric as text.
|
|
104
|
+
if (NUMBER_TYPES.has(type)) return type === 'int8' || type === 'numeric' ? '1' : 1
|
|
101
105
|
if (type === 'bool') return false
|
|
102
106
|
// ISO text, not a Date: the seed binds past the layer's compiler, where Bun.SQL would send Date#toString(). A day is
|
|
103
107
|
// `YYYY-MM-DD`, since the probe's insert sends it through the layer, which takes a `date` only so.
|
|
@@ -105,6 +109,8 @@ function sampleOf(table: string, column: CatalogColumn): Primitive {
|
|
|
105
109
|
if (type === 'timestamp' || type === 'timestamptz') return new Date().toISOString()
|
|
106
110
|
if (type === 'time' || type === 'timetz') return '12:00:00'
|
|
107
111
|
if (type === 'interval') return '1 hour'
|
|
112
|
+
// A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
|
|
113
|
+
if (type === 'jsonb') return 'sample'
|
|
108
114
|
throw typeLimit(table, column.column_name, type)
|
|
109
115
|
}
|
|
110
116
|
|
|
@@ -118,6 +124,8 @@ function seedColumn(column: CatalogColumn): SeedColumn {
|
|
|
118
124
|
defaulted: column.generated !== 'no',
|
|
119
125
|
text: column.type_type !== 'e' && TEXT_TYPES.has(column.type_name),
|
|
120
126
|
uuid: column.type_name === 'uuid',
|
|
127
|
+
number: column.type_type !== 'e' && NUMBER_TYPES.has(column.type_name),
|
|
128
|
+
json: column.type_type === 'b' && column.type_category !== 'A' && column.type_name === 'jsonb',
|
|
121
129
|
sample: () => sampleOf(column.table_name, column),
|
|
122
130
|
}
|
|
123
131
|
}
|
|
@@ -135,6 +143,44 @@ WHERE n.nspname = $1 AND c.contype = 'c'
|
|
|
135
143
|
ORDER BY r.relname, c.conname
|
|
136
144
|
`
|
|
137
145
|
|
|
146
|
+
const uniqueRows = z.array(z.object({ name: z.string(), table_name: z.string(), columns: z.array(z.string()), nulls_not_distinct: z.boolean() }))
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Every unique index of the schema's tables (a primary key's and a UNIQUE constraint's are one) whose key columns are all
|
|
150
|
+
* plain columns and that has no predicate, with its key columns: the first `indnkeyatts` of `indkey`, never an `INCLUDE`
|
|
151
|
+
* column. An index on an expression (`indexprs`) or a partial one (`indpred`) is left out.
|
|
152
|
+
*/
|
|
153
|
+
const UNIQUE_QUERY = `
|
|
154
|
+
SELECT i.relname::text AS name, r.relname::text AS table_name, x.indnullsnotdistinct AS nulls_not_distinct,
|
|
155
|
+
ARRAY(
|
|
156
|
+
SELECT a.attname::text FROM pg_attribute a
|
|
157
|
+
WHERE a.attrelid = x.indrelid AND a.attnum = ANY ((x.indkey::int2[])[0:x.indnkeyatts - 1])
|
|
158
|
+
ORDER BY a.attnum
|
|
159
|
+
) AS columns
|
|
160
|
+
FROM pg_index x
|
|
161
|
+
JOIN pg_class i ON i.oid = x.indexrelid
|
|
162
|
+
JOIN pg_class r ON r.oid = x.indrelid
|
|
163
|
+
JOIN pg_namespace n ON n.oid = r.relnamespace
|
|
164
|
+
WHERE n.nspname = $1 AND x.indisunique AND x.indexprs IS NULL AND x.indpred IS NULL
|
|
165
|
+
ORDER BY r.relname, i.relname
|
|
166
|
+
`
|
|
167
|
+
|
|
168
|
+
const typeRows = z.array(z.object({ table_name: z.string(), column_name: z.string(), type: z.string() }))
|
|
169
|
+
|
|
170
|
+
/** Every column of the schema's tables with its type as Postgres writes it (`smallint`, `numeric(3,0)`): a cast keeps its range and scale. */
|
|
171
|
+
const TYPE_QUERY = `
|
|
172
|
+
SELECT r.relname::text AS table_name, a.attname::text AS column_name, format_type(a.atttypid, a.atttypmod) AS type
|
|
173
|
+
FROM pg_attribute a
|
|
174
|
+
JOIN pg_class r ON r.oid = a.attrelid
|
|
175
|
+
JOIN pg_namespace n ON n.oid = r.relnamespace
|
|
176
|
+
WHERE n.nspname = $1 AND r.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped
|
|
177
|
+
`
|
|
178
|
+
|
|
179
|
+
const nextRows = z.array(z.object({ next: z.union([z.number(), z.string(), z.bigint()]).nullable() }))
|
|
180
|
+
|
|
181
|
+
/** SQLSTATE `numeric_value_out_of_range`: the column's type holds no such number. */
|
|
182
|
+
const OUT_OF_RANGE = '22003'
|
|
183
|
+
|
|
138
184
|
const referrerRows = z.array(z.object({ table_name: z.string(), columns: z.array(z.string()), refs: z.array(z.string()) }))
|
|
139
185
|
|
|
140
186
|
/** Every foreign key of the schema's tables that references the table `$2`, with its columns and the ones it references, in order. */
|
|
@@ -173,6 +219,7 @@ function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
|
|
|
173
219
|
const constraint = error.constraint ?? 'unnamed'
|
|
174
220
|
if (error.errno === '23514') return checkLimit(constraint, table)
|
|
175
221
|
if (error.errno === '23503') return foreignKeyLimit(constraint, table)
|
|
222
|
+
if (error.errno === '23505') return uniqueValueLimit(constraint, table)
|
|
176
223
|
return undefined
|
|
177
224
|
}
|
|
178
225
|
|
|
@@ -338,8 +385,10 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
338
385
|
)
|
|
339
386
|
await tx.unsafe(`WITH ${deletes.join(', ')} SELECT 1`, tables.map(([, ctids]) => tidArray(ctids)))
|
|
340
387
|
}
|
|
388
|
+
let types: Promise<ReadonlyMap<string, string>> | undefined
|
|
389
|
+
const seedColumns = catalog.map(seedColumn)
|
|
341
390
|
const backend: SeedingBackend = {
|
|
342
|
-
columns:
|
|
391
|
+
columns: seedColumns,
|
|
343
392
|
checks: async () =>
|
|
344
393
|
checkRows.parse(await lock.unsafe(CHECK_QUERY, [schema])).map((row): CheckConstraint => ({
|
|
345
394
|
name: row.name,
|
|
@@ -347,6 +396,42 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
347
396
|
columns: row.columns,
|
|
348
397
|
values: listedValues(row.definition, row.columns),
|
|
349
398
|
})),
|
|
399
|
+
uniqueIndexes: async () =>
|
|
400
|
+
uniqueRows.parse(await lock.unsafe(UNIQUE_QUERY, [schema])).map((row) => ({
|
|
401
|
+
name: row.name,
|
|
402
|
+
table: row.table_name,
|
|
403
|
+
columns: row.columns,
|
|
404
|
+
nullsNotDistinct: row.nulls_not_distinct,
|
|
405
|
+
})),
|
|
406
|
+
async nextNumber(table, column, groups) {
|
|
407
|
+
// A read that failed is read again on the next call, never answered from the cache.
|
|
408
|
+
types ??= lock.unsafe(TYPE_QUERY, [schema]).then(
|
|
409
|
+
(rows: unknown) => new Map(typeRows.parse(rows).map((row) => [`${row.table_name}.${row.column_name}`, row.type])),
|
|
410
|
+
(error: unknown) => {
|
|
411
|
+
types = undefined
|
|
412
|
+
throw error
|
|
413
|
+
},
|
|
414
|
+
)
|
|
415
|
+
const type = (await types).get(`${table}.${column}`)
|
|
416
|
+
if (type === undefined) {
|
|
417
|
+
throw new Error(`${table}.${column} is not a column of the migrated schema`)
|
|
418
|
+
}
|
|
419
|
+
const { where, values: bindings } = groupsWhere(groups, quoted, (position) => `$${position}`)
|
|
420
|
+
const largest = `(SELECT max(${quoted(column)}) FROM ${quoted(schema)}.${quoted(table)} WHERE ${where})`
|
|
421
|
+
// A float's NaN or Infinity has no next number; the cast refuses one the type cannot hold (22003).
|
|
422
|
+
const statement = `SELECT CASE WHEN largest IS NULL THEN 1::${type} WHEN largest::text IN ('NaN', 'Infinity', '-Infinity') THEN NULL
|
|
423
|
+
ELSE GREATEST(floor(largest::numeric) + 1, 1)::${type} END AS next FROM ${largest} AS m (largest)`
|
|
424
|
+
let next: unknown
|
|
425
|
+
try {
|
|
426
|
+
next = await seeder.unsafe(statement, bindings)
|
|
427
|
+
} catch (error) {
|
|
428
|
+
if (error instanceof SQL.PostgresError && error.errno === OUT_OF_RANGE) return undefined
|
|
429
|
+
throw error
|
|
430
|
+
}
|
|
431
|
+
const [found] = nextRows.parse(next)
|
|
432
|
+
if (found === undefined || found.next === null) return undefined
|
|
433
|
+
return typeof found.next === 'bigint' ? String(found.next) : found.next
|
|
434
|
+
},
|
|
350
435
|
async insert(table, row) {
|
|
351
436
|
const names = [...row.keys()]
|
|
352
437
|
const placeholders = names.map((_, index) => `$${index + 1}`)
|
|
@@ -356,7 +441,7 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
356
441
|
: `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${placeholders.join(', ')}) RETURNING *`
|
|
357
442
|
let stored: unknown
|
|
358
443
|
try {
|
|
359
|
-
stored = await seeder.unsafe(statement, names.map((name) => row.get(name) ?? null))
|
|
444
|
+
stored = await seeder.unsafe(statement, names.map((name) => seedBinding(seedColumns, table, name, row.get(name) ?? null)))
|
|
360
445
|
} catch (error) {
|
|
361
446
|
throw seedLimit(error, table) ?? error
|
|
362
447
|
}
|
|
@@ -1,6 +1,13 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import { type GeneratedModule } from './codegen';
|
|
1
3
|
import { type SqliteMigrationBundle } from './sqlite-migrate';
|
|
2
4
|
/**
|
|
3
5
|
* Applies `bundles` (the framework's `fabrika`, then the application's `app`) to a fresh in-memory database and renders
|
|
4
6
|
* the module for `SCHEMA_FILE` from its application tables. Deterministic for given migrations.
|
|
5
7
|
*/
|
|
6
|
-
export declare function generateSqliteSchema(bundles: readonly SqliteMigrationBundle[]): Promise<
|
|
8
|
+
export declare function generateSqliteSchema(bundles: readonly SqliteMigrationBundle[]): Promise<GeneratedModule>;
|
|
9
|
+
/**
|
|
10
|
+
* `read` of a fresh in-memory database with foreign keys enforced and `bundles` applied, as the Durable Object applies
|
|
11
|
+
* them; the database is closed after. `fabrika-check` plans the backup of an application's schema with it.
|
|
12
|
+
*/
|
|
13
|
+
export declare function withMigratedSqlite<T>(bundles: readonly SqliteMigrationBundle[], read: (db: Database) => T): Promise<T>;
|