@fabrika/db 0.9.0-dev.1 → 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 +44 -12
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/capability.ts +5 -0
- package/src/codegen-sqlite.ts +191 -0
- package/src/codegen.ts +170 -28
- package/src/database.ts +227 -61
- package/src/description.ts +34 -8
- package/src/errors.ts +6 -4
- package/src/file-columns.ts +36 -9
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +14 -5
- package/src/guard.ts +8 -0
- package/src/index.ts +10 -1
- package/src/job-leases.ts +210 -54
- package/src/job-wakes.ts +450 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/migrations-sqlite.ts +163 -0
- package/src/migrations.ts +25 -0
- package/src/nodes.ts +64 -9
- package/src/orm-types.ts +5 -5
- package/src/orm.ts +94 -37
- package/src/policy.ts +17 -2
- package/src/postgres.ts +26 -0
- package/src/registry.ts +11 -2
- package/src/sql.ts +230 -477
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +224 -0
- package/src/store.ts +385 -103
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +16 -0
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +878 -0
- package/src/testing-sqlite.ts +570 -0
- package/src/testing.ts +255 -482
- package/types/src/admissions.d.ts +21 -0
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/builtins.d.ts +42 -0
- package/types/src/capability.d.ts +119 -0
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +113 -0
- package/types/src/database.d.ts +185 -0
- package/types/src/description.d.ts +124 -0
- package/types/src/errors.d.ts +98 -0
- package/types/src/file-columns.d.ts +39 -0
- package/types/src/file-references.d.ts +27 -0
- package/types/src/framework-tables.d.ts +59 -0
- package/types/src/framework.d.ts +38 -0
- package/types/src/guard.d.ts +23 -0
- package/types/src/identifier.d.ts +4 -0
- package/types/src/index.d.ts +11 -0
- package/types/src/job-leases.d.ts +112 -0
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/links.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +26 -0
- package/types/src/nodes.d.ts +73 -0
- package/types/src/orm-types.d.ts +638 -0
- package/types/src/orm.d.ts +82 -0
- package/types/src/policy.d.ts +358 -0
- package/types/src/postgres.d.ts +12 -0
- package/types/src/production.d.ts +5 -0
- package/types/src/registry.d.ts +43 -0
- package/types/src/sql.d.ts +67 -0
- 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 +351 -0
- package/types/src/stored-files.d.ts +102 -0
- package/types/src/tables.d.ts +21 -0
- package/types/src/temporal.d.ts +36 -0
- package/types/src/testing-shared.d.ts +250 -0
- package/types/src/testing-sqlite.d.ts +22 -0
- package/types/src/testing.d.ts +35 -0
- package/types/src/vocabulary-tables.d.ts +225 -0
package/src/testing.ts
CHANGED
|
@@ -16,17 +16,45 @@ import { type ReservedSQL, SQL } from 'bun'
|
|
|
16
16
|
import { createHash } from 'node:crypto'
|
|
17
17
|
import { fileURLToPath } from 'node:url'
|
|
18
18
|
import { z } from 'zod/v4'
|
|
19
|
-
import { inSet, namesOf } from './builtins'
|
|
20
19
|
import { type CatalogColumn, introspectSchema } from './codegen'
|
|
21
20
|
import { applicationSchema, Database, openFirstConnection } from './database'
|
|
22
21
|
import type { Primitive } from './description'
|
|
23
22
|
import { FILES_TABLE, FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from './migrations'
|
|
24
|
-
import {
|
|
23
|
+
import { openPostgres } from './postgres'
|
|
25
24
|
import { refuseInProduction } from './production'
|
|
26
|
-
import { frameworkSideOf } from './registry'
|
|
27
25
|
import type { TableProbe } from './store'
|
|
26
|
+
import {
|
|
27
|
+
type CheckConstraint,
|
|
28
|
+
checkLimit,
|
|
29
|
+
foreignKeyLimit,
|
|
30
|
+
groupsWhere,
|
|
31
|
+
type InsertedRow,
|
|
32
|
+
MAX_REMOVED_ROWS,
|
|
33
|
+
probeTable,
|
|
34
|
+
randomHex,
|
|
35
|
+
removalLimit,
|
|
36
|
+
seedBinding,
|
|
37
|
+
type SeedColumn,
|
|
38
|
+
type SeedingBackend,
|
|
39
|
+
type SeedLimitError,
|
|
40
|
+
type TestDatabase,
|
|
41
|
+
testSeeding,
|
|
42
|
+
typeLimit,
|
|
43
|
+
uniqueValueLimit,
|
|
44
|
+
} from './testing-shared'
|
|
28
45
|
|
|
29
46
|
export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store'
|
|
47
|
+
export {
|
|
48
|
+
type ApplicationRow,
|
|
49
|
+
type IsolationWorlds,
|
|
50
|
+
type SampleValue,
|
|
51
|
+
SEEDED_OBJECT_VERSION,
|
|
52
|
+
type SeededApplicationRows,
|
|
53
|
+
type SeededRow,
|
|
54
|
+
SeedLimitError,
|
|
55
|
+
type TestDatabase,
|
|
56
|
+
type WorldRow,
|
|
57
|
+
} from './testing-shared'
|
|
30
58
|
|
|
31
59
|
const MODULE = '@fabrika/db/testing'
|
|
32
60
|
refuseInProduction(MODULE)
|
|
@@ -54,100 +82,8 @@ export interface TestDatabaseOptions {
|
|
|
54
82
|
/** Set once a test database of this process gave up waiting for a connection slot. */
|
|
55
83
|
let capacityExhausted: ConnectionCapacityError | undefined
|
|
56
84
|
|
|
57
|
-
/** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
|
|
58
|
-
export type SampleValue = Primitive | null
|
|
59
|
-
|
|
60
|
-
/** One seeded row and where it lies. */
|
|
61
|
-
export interface WorldRow {
|
|
62
|
-
/** The row's key: the dimension value of a dimension table's row, a child's own key. */
|
|
63
|
-
readonly key: string
|
|
64
|
-
/** A child row's parent key; `null` for a dimension table. */
|
|
65
|
-
readonly parent: string | null
|
|
66
|
-
/** The value of the grant dimension the row lies in (`IsolationWorlds.dimension`). */
|
|
67
|
-
readonly scope: string
|
|
68
|
-
/**
|
|
69
|
-
* Every dimension value the row lies in: a dimension table's own first, then each container, innermost first. A
|
|
70
|
-
* share link's chain is this list.
|
|
71
|
-
*/
|
|
72
|
-
readonly chain: readonly { readonly type: string; readonly value: string }[]
|
|
73
|
-
/** The row's values of the policy's update columns, as seeded. */
|
|
74
|
-
readonly updates: Readonly<Record<string, SampleValue>>
|
|
75
|
-
/**
|
|
76
|
-
* The distinct value written into every text column the fixture filled itself, in this row and in its containers.
|
|
77
|
-
* Each occurs in no other fixture, so one found in an answer to another scope is a leaked row.
|
|
78
|
-
*/
|
|
79
|
-
readonly markers: readonly string[]
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** One seeded row of an application table, which lies in no dimension. */
|
|
83
|
-
export interface ApplicationRow {
|
|
84
|
-
readonly key: string
|
|
85
|
-
/** The row's values of the policy's update columns, as seeded. */
|
|
86
|
-
readonly updates: Readonly<Record<string, SampleValue>>
|
|
87
|
-
/** The distinct value written into every text column the fixture filled itself. */
|
|
88
|
-
readonly markers: readonly string[]
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/** A row seeded under another: its key, and the distinct value written into every text column the fixture filled. */
|
|
92
|
-
export interface SeededRow {
|
|
93
|
-
readonly key: string
|
|
94
|
-
readonly markers: readonly string[]
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* What the isolation fixture cannot seed for a schema: a CHECK its values fail, a required foreign key to a scoped table
|
|
99
|
-
* outside the containment chain. It is a limit of the generator, named with the constraint or the column, never a
|
|
100
|
-
* failure of the handler or the policy a case is about.
|
|
101
|
-
*/
|
|
102
|
-
export class SeedLimitError extends Error {
|
|
103
|
-
override readonly name = 'SeedLimitError'
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** One row of a table in each of two containment chains that share no value. */
|
|
107
|
-
export interface IsolationWorlds {
|
|
108
|
-
/**
|
|
109
|
-
* The dimension a caller's grants are scoped by: a dimension table's container, or its own dimension when it has
|
|
110
|
-
* none; a child table's parent's.
|
|
111
|
-
*/
|
|
112
|
-
readonly dimension: string
|
|
113
|
-
readonly own: WorldRow
|
|
114
|
-
readonly other: WorldRow
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export interface TestDatabase {
|
|
118
|
-
/** The connection `boot` binds the data layer to: the runtime role, on the migrated schema. */
|
|
119
|
-
readonly database: Database
|
|
120
|
-
readonly schema: string
|
|
121
|
-
/**
|
|
122
|
-
* Seeds one row of `table` in each of two fresh chains, with every container row a table owns. `values` (column →
|
|
123
|
-
* value) are written into both rows of `table`: the state an endpoint's precondition needs. A text column keeps its
|
|
124
|
-
* marker, so a seed of one, or of a column that places the row, throws.
|
|
125
|
-
*/
|
|
126
|
-
seedWorlds<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>): Promise<IsolationWorlds>
|
|
127
|
-
/** Seeds one row of the application table `table`: its key, version and creator stamped, every other column sampled. */
|
|
128
|
-
seedRow<DB, P>(tables: Tables<DB, P>, table: string): Promise<ApplicationRow>
|
|
129
|
-
/**
|
|
130
|
-
* Seeds one row of `table`, a child or dimension table that lies in the object of `under` (a row `seedWorlds`
|
|
131
|
-
* seeded), placed in that row's chain: the row a fixture names by id, such as a note's comment. Answers its key and
|
|
132
|
-
* the markers it holds.
|
|
133
|
-
*/
|
|
134
|
-
seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: WorldRow): Promise<SeededRow>
|
|
135
|
-
/** Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file column a seeded file. */
|
|
136
|
-
sampleInsert<DB, P>(tables: Tables<DB, P>, table: string): Promise<Readonly<Record<string, SampleValue>>>
|
|
137
|
-
/**
|
|
138
|
-
* The object key of every file the fixture seeded into a file column, oldest first. Each stands for an empty object,
|
|
139
|
-
* which a test's object store holds when a handler serves or opens the file.
|
|
140
|
-
*/
|
|
141
|
-
seededObjects(): readonly string[]
|
|
142
|
-
/** Closes the connections and drops the schema and its roles. */
|
|
143
|
-
close(): Promise<void>
|
|
144
|
-
}
|
|
145
|
-
|
|
146
85
|
const TEXT_TYPES: ReadonlySet<string> = new Set(['text', 'varchar', 'bpchar'])
|
|
147
|
-
|
|
148
|
-
function randomHex(): string {
|
|
149
|
-
return crypto.randomUUID().replaceAll('-', '').slice(0, 8)
|
|
150
|
-
}
|
|
86
|
+
const NUMBER_TYPES: ReadonlySet<string> = new Set(['int2', 'int4', 'int8', 'float4', 'float8', 'numeric'])
|
|
151
87
|
|
|
152
88
|
function quoted(identifier: string): string {
|
|
153
89
|
return `"${identifier}"`
|
|
@@ -164,8 +100,8 @@ function sampleOf(table: string, column: CatalogColumn): Primitive {
|
|
|
164
100
|
const type = column.type_name
|
|
165
101
|
if (type === 'uuid') return crypto.randomUUID()
|
|
166
102
|
if (TEXT_TYPES.has(type)) return `s${randomHex()}`
|
|
167
|
-
|
|
168
|
-
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
|
|
169
105
|
if (type === 'bool') return false
|
|
170
106
|
// ISO text, not a Date: the seed binds past the layer's compiler, where Bun.SQL would send Date#toString(). A day is
|
|
171
107
|
// `YYYY-MM-DD`, since the probe's insert sends it through the layer, which takes a `date` only so.
|
|
@@ -173,25 +109,25 @@ function sampleOf(table: string, column: CatalogColumn): Primitive {
|
|
|
173
109
|
if (type === 'timestamp' || type === 'timestamptz') return new Date().toISOString()
|
|
174
110
|
if (type === 'time' || type === 'timetz') return '12:00:00'
|
|
175
111
|
if (type === 'interval') return '1 hour'
|
|
176
|
-
|
|
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'
|
|
114
|
+
throw typeLimit(table, column.column_name, type)
|
|
177
115
|
}
|
|
178
116
|
|
|
179
|
-
/** A
|
|
180
|
-
function
|
|
181
|
-
return
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
/** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
|
|
194
|
-
readonly values: readonly string[]
|
|
117
|
+
/** A catalog column as the seeding reads it. */
|
|
118
|
+
function seedColumn(column: CatalogColumn): SeedColumn {
|
|
119
|
+
return {
|
|
120
|
+
table: column.table_name,
|
|
121
|
+
name: column.column_name,
|
|
122
|
+
type: column.type_name,
|
|
123
|
+
nullable: column.nullable,
|
|
124
|
+
defaulted: column.generated !== 'no',
|
|
125
|
+
text: column.type_type !== 'e' && TEXT_TYPES.has(column.type_name),
|
|
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',
|
|
129
|
+
sample: () => sampleOf(column.table_name, column),
|
|
130
|
+
}
|
|
195
131
|
}
|
|
196
132
|
|
|
197
133
|
const checkRows = z.array(z.object({ name: z.string(), table_name: z.string(), definition: z.string(), columns: z.array(z.string()) }))
|
|
@@ -207,6 +143,65 @@ WHERE n.nspname = $1 AND c.contype = 'c'
|
|
|
207
143
|
ORDER BY r.relname, c.conname
|
|
208
144
|
`
|
|
209
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
|
+
|
|
184
|
+
const referrerRows = z.array(z.object({ table_name: z.string(), columns: z.array(z.string()), refs: z.array(z.string()) }))
|
|
185
|
+
|
|
186
|
+
/** Every foreign key of the schema's tables that references the table `$2`, with its columns and the ones it references, in order. */
|
|
187
|
+
const REFERRER_QUERY = `
|
|
188
|
+
SELECT r.relname::text AS table_name,
|
|
189
|
+
ARRAY(SELECT a.attname::text FROM unnest(c.conkey) WITH ORDINALITY k(attnum, ord) JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum ORDER BY k.ord) AS columns,
|
|
190
|
+
ARRAY(SELECT a.attname::text FROM unnest(c.confkey) WITH ORDINALITY k(attnum, ord) JOIN pg_attribute a ON a.attrelid = c.confrelid AND a.attnum = k.attnum ORDER BY k.ord) AS refs
|
|
191
|
+
FROM pg_constraint c
|
|
192
|
+
JOIN pg_class r ON r.oid = c.conrelid
|
|
193
|
+
JOIN pg_namespace n ON n.oid = r.relnamespace
|
|
194
|
+
JOIN pg_class t ON t.oid = c.confrelid
|
|
195
|
+
WHERE n.nspname = $1 AND t.relnamespace = n.oid AND t.relname = $2 AND c.contype = 'f'
|
|
196
|
+
ORDER BY r.relname, c.conname
|
|
197
|
+
`
|
|
198
|
+
|
|
199
|
+
// A row's ctid is its place, unique in a table: an application migration creates no partitioned table (ADR-0017).
|
|
200
|
+
const ctidRows = z.array(z.object({ ctid: z.string() }))
|
|
201
|
+
|
|
202
|
+
/** Ctids as one array literal parameter, `{"(0,1)","(0,2)"}`: the driver mis-binds a JS array. */
|
|
203
|
+
const tidArray = (ctids: Iterable<string>): string => `{${[...ctids].map((ctid) => `"${ctid}"`).join(',')}}`
|
|
204
|
+
|
|
210
205
|
/** `CHECK ((status = ANY (ARRAY['open'::text, 'done'::text])))`, a one-column `IN` list as Postgres prints it. */
|
|
211
206
|
const IN_LIST = /^CHECK \(\(\(?"?([^"()\s]+)"?\)?(?:::[a-z ]+)? = ANY \(\(?ARRAY\[(.+)\]\)?(?:::[a-z ]+\[\])?\)\)\)$/
|
|
212
207
|
const LITERAL = /'((?:[^']|'')*)'::/g
|
|
@@ -218,71 +213,13 @@ function listedValues(definition: string, columns: readonly string[]): string[]
|
|
|
218
213
|
return [...(listed[2] ?? '').matchAll(LITERAL)].map((match) => (match[1] ?? '').replaceAll("''", "'"))
|
|
219
214
|
}
|
|
220
215
|
|
|
221
|
-
/** A key value as the database returned it, for the foreign key that references it. */
|
|
222
|
-
function keyValue(value: unknown, where: string): SampleValue {
|
|
223
|
-
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
224
|
-
return value
|
|
225
|
-
}
|
|
226
|
-
throw new SeedLimitError(`the isolation fixture cannot reference ${where}: its key is no text, number or boolean`)
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/** The dimension a caller's grants are scoped by, as `IsolationWorlds.dimension` describes. */
|
|
230
|
-
function grantDimension(models: TableModels, model: TableModel): string {
|
|
231
|
-
const scope = model.scope
|
|
232
|
-
if (scope.mode === 'dimension') {
|
|
233
|
-
return scope.container?.dimension ?? scope.dimension
|
|
234
|
-
}
|
|
235
|
-
if (scope.mode === 'child') {
|
|
236
|
-
const parent = modelOf(models, scope.parent)
|
|
237
|
-
if (parent?.scope.mode === 'dimension') {
|
|
238
|
-
return parent.scope.container?.dimension ?? parent.scope.dimension
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
throw new Error(`${model.name} is not a dimension or child table; no store reaches it, so it has no isolation tests`)
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
function scopedModel<DB, P>(tables: Tables<DB, P>, table: string): { readonly models: TableModels; readonly model: TableModel } {
|
|
245
|
-
const models = tableModels(tables)
|
|
246
|
-
const model = modelOf(models, table)
|
|
247
|
-
if (model === undefined) {
|
|
248
|
-
throw new Error(`${table} is not a table of the policies`)
|
|
249
|
-
}
|
|
250
|
-
return { models, model }
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
function ownerOf(models: TableModels, dimension: string): TableModel | undefined {
|
|
254
|
-
for (const name of Object.keys(models)) {
|
|
255
|
-
const model = modelOf(models, name)
|
|
256
|
-
if (model?.scope.mode === 'dimension' && model.scope.dimension === dimension) {
|
|
257
|
-
return model
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
return undefined
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/** How many referenced rows deep the fixture follows required foreign keys outside the chain before it gives up. */
|
|
264
|
-
const MAX_REFERENCE_DEPTH = 4
|
|
265
|
-
/** The digest of the empty object a seeded file stands for. */
|
|
266
|
-
const EMPTY_SHA256 = createHash('sha256').digest('hex')
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* The object version a seeded file was scanned at: whoever stocks its empty object (`seededObjects`) stores it under
|
|
270
|
-
* this version, so a file of a scanning kind is served as a live one is, by its scanned version.
|
|
271
|
-
*/
|
|
272
|
-
export const SEEDED_OBJECT_VERSION = '"seeded"'
|
|
273
|
-
|
|
274
216
|
/** A CHECK or foreign key violation of a seeded row, as the generator limit it is; `undefined` for any other failure. */
|
|
275
217
|
function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
|
|
276
218
|
if (!(error instanceof SQL.PostgresError)) return undefined
|
|
277
219
|
const constraint = error.constraint ?? 'unnamed'
|
|
278
|
-
if (error.errno === '23514')
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
)
|
|
282
|
-
}
|
|
283
|
-
if (error.errno === '23503') {
|
|
284
|
-
return new SeedLimitError(`the isolation fixture's row of ${table} breaks the foreign key ${constraint}`)
|
|
285
|
-
}
|
|
220
|
+
if (error.errno === '23514') return checkLimit(constraint, table)
|
|
221
|
+
if (error.errno === '23503') return foreignKeyLimit(constraint, table)
|
|
222
|
+
if (error.errno === '23505') return uniqueValueLimit(constraint, table)
|
|
286
223
|
return undefined
|
|
287
224
|
}
|
|
288
225
|
|
|
@@ -371,6 +308,7 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
371
308
|
if (process.env[TEST_POSTGRES_REQUIRED] === '1') {
|
|
372
309
|
throw new Error(`${options.label}: ${TEST_POSTGRES_REQUIRED}=1, but ${TEST_POSTGRES_URL} is unset`)
|
|
373
310
|
}
|
|
311
|
+
// The Zerops build counts this line's text in every framework release's output: never reword it.
|
|
374
312
|
console.warn(`${options.label} skipped: set ${TEST_POSTGRES_URL} to run the Postgres-backed tests`)
|
|
375
313
|
return null
|
|
376
314
|
}
|
|
@@ -386,322 +324,162 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
386
324
|
throw new Error(`${options.label}: ${error.message}; its cases did not run`)
|
|
387
325
|
}
|
|
388
326
|
const { schema, lock, seeder, catalog } = opened
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
columns: row.columns,
|
|
399
|
-
values: listedValues(row.definition, row.columns),
|
|
400
|
-
}))
|
|
401
|
-
)
|
|
402
|
-
return (await checks).filter((check) => check.table === table && check.columns.includes(column))
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* What the fixture writes into a column a CHECK names: the first value of a one-column `IN` list, `null` where the
|
|
407
|
-
* column admits it (a CHECK passes on null); `undefined` when no CHECK names it or none of those applies.
|
|
408
|
-
*/
|
|
409
|
-
async function checkedValue(table: string, column: CatalogColumn): Promise<SampleValue | undefined> {
|
|
410
|
-
const named = await checksOn(table, column.column_name)
|
|
411
|
-
if (named.length === 0) return undefined
|
|
412
|
-
const [listed] = named.flatMap((check) => check.values)
|
|
413
|
-
if (listed !== undefined && named.every((check) => check.values.includes(listed))) return listed
|
|
414
|
-
return column.nullable ? null : undefined
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
/** A required column's sample: an `IN` list's first value where a CHECK names one, else a sample of its type. */
|
|
418
|
-
async function requiredSample(table: string, column: CatalogColumn): Promise<SampleValue> {
|
|
419
|
-
return (await checkedValue(table, column)) ?? sampleOf(table, column)
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
async function columnsOf(table: string): Promise<readonly CatalogColumn[]> {
|
|
423
|
-
const columns = catalog.filter((column) => column.table_name === table)
|
|
424
|
-
if (columns.length === 0) {
|
|
425
|
-
throw new Error(`${table} is not a table of the migrated schema; write its migration first`)
|
|
426
|
-
}
|
|
427
|
-
return columns
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
async function columnOf(table: string, name: string): Promise<CatalogColumn> {
|
|
431
|
-
const column = (await columnsOf(table)).find((candidate) => candidate.column_name === name)
|
|
432
|
-
if (column === undefined) {
|
|
433
|
-
throw new Error(`${table}.${name} is not a column of the migrated schema`)
|
|
434
|
-
}
|
|
435
|
-
return column
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/** A column the seeded row left to its default: null only where the column admits it. */
|
|
439
|
-
async function updateSample(table: string, name: string): Promise<SampleValue> {
|
|
440
|
-
const column = await columnOf(table, name)
|
|
441
|
-
return column.nullable ? null : requiredSample(table, column)
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
/** Whether the fixture writes a marker into `column`: text that holds no foreign key and that no CHECK names. */
|
|
445
|
-
async function holdsMarker(model: TableModel | undefined, table: string, column: CatalogColumn): Promise<boolean> {
|
|
446
|
-
const keyed = (model?.foreignKeys ?? []).some((key) => key.columns.includes(column.column_name))
|
|
447
|
-
return isMarkable(column) && !keyed && (await checksOn(table, column.column_name)).length === 0
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
/**
|
|
451
|
-
* The values of a foreign key outside the containment chain: `null` where every open column admits it, else the
|
|
452
|
-
* key of a row of the referenced table, an existing one (a reference table's rows come from a migration) or one the
|
|
453
|
-
* fixture inserts. A required key to a dimension or child table is refused: its row would lie in another chain.
|
|
454
|
-
*/
|
|
455
|
-
async function referencedKey(models: TableModels, table: string, key: ForeignKey, open: readonly string[], depth: number) {
|
|
456
|
-
const columns = await columnsOf(table)
|
|
457
|
-
const values = new Map<string, SampleValue>()
|
|
458
|
-
if (open.every((name) => columns.find((column) => column.column_name === name)?.nullable === true)) {
|
|
459
|
-
for (const name of open) values.set(name, null)
|
|
460
|
-
return values
|
|
461
|
-
}
|
|
462
|
-
const target = modelOf(models, key.table)
|
|
463
|
-
const scoped = target?.scope.mode === 'dimension' || target?.scope.mode === 'child'
|
|
464
|
-
if (scoped || open.length !== key.columns.length || key.table === table || depth >= MAX_REFERENCE_DEPTH) {
|
|
465
|
-
throw new SeedLimitError(
|
|
466
|
-
`the isolation fixture cannot fill ${table}.${
|
|
467
|
-
open.join(', ')
|
|
468
|
-
}: a required foreign key to ${key.table} outside the containment chain; give the column a default or make it nullable`,
|
|
469
|
-
)
|
|
327
|
+
const referrers = new Map<string, Promise<z.infer<typeof referrerRows>>>()
|
|
328
|
+
/** The foreign keys that reference `table`, read from the catalog once. */
|
|
329
|
+
const referrersOf = (table: string): Promise<z.infer<typeof referrerRows>> => {
|
|
330
|
+
let known = referrers.get(table)
|
|
331
|
+
if (known === undefined) {
|
|
332
|
+
known = lock.unsafe(REFERRER_QUERY, [schema, table]).then((rows: unknown) => referrerRows.parse(rows))
|
|
333
|
+
referrers.set(table, known)
|
|
334
|
+
// A failed read is not kept: the next removal reads the catalog again.
|
|
335
|
+
known.catch(() => referrers.delete(table))
|
|
470
336
|
}
|
|
471
|
-
|
|
472
|
-
`SELECT ${key.references.map(quoted).join(', ')} FROM ${quoted(schema)}.${quoted(key.table)} LIMIT 1`,
|
|
473
|
-
)
|
|
474
|
-
const existing = z.array(z.record(z.string(), z.unknown())).parse(selected)[0]
|
|
475
|
-
const row = existing ?? (await insert(models, key.table, new Map(), [], depth + 1)).stored
|
|
476
|
-
key.columns.forEach((name, index) => {
|
|
477
|
-
const referenced = key.references[index] ?? ''
|
|
478
|
-
values.set(name, keyValue(row[referenced], `${key.table}.${referenced}`))
|
|
479
|
-
})
|
|
480
|
-
return values
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
/** A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. */
|
|
484
|
-
async function scopeValue(table: string, column: string, dimension: string, world: string): Promise<string> {
|
|
485
|
-
const type = (await columnOf(table, column)).type_name
|
|
486
|
-
if (type === 'uuid') return crypto.randomUUID()
|
|
487
|
-
if (TEXT_TYPES.has(type)) return `${dimension}-${world}-${randomHex()}`
|
|
488
|
-
throw new Error(`${table}.${column} holds a ${dimension} as ${type}; a key or containment column holds its scope value as text or uuid`)
|
|
337
|
+
return known
|
|
489
338
|
}
|
|
490
|
-
|
|
491
|
-
/** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it: what a seeded file column holds. */
|
|
492
|
-
async function seedFile(kind: string): Promise<string> {
|
|
493
|
-
const id = crypto.randomUUID()
|
|
494
|
-
const objectKey = `${kind}/${id}`
|
|
495
|
-
seededObjects.push(objectKey)
|
|
496
|
-
await seeder.unsafe(
|
|
497
|
-
`INSERT INTO ${quoted(schema)}.${quoted(FILES_TABLE)} (id, kind, status, object_key, size, sha256, content_type, name, created_at, object_version)
|
|
498
|
-
VALUES ($1, $2, 'live', $3, 0, $4, 'application/octet-stream', 'seeded', now(), $5)`,
|
|
499
|
-
[id, kind, objectKey, EMPTY_SHA256, SEEDED_OBJECT_VERSION],
|
|
500
|
-
)
|
|
501
|
-
return id
|
|
502
|
-
}
|
|
503
|
-
|
|
504
339
|
/**
|
|
505
|
-
*
|
|
506
|
-
*
|
|
507
|
-
*
|
|
508
|
-
*
|
|
340
|
+
* Deletes the rows `start` names (table → ctids) and every row that refers to one of them, however deep. Rows are
|
|
341
|
+
* found a level at a time, one statement per table and foreign key, by joining on the key's columns, so no value
|
|
342
|
+
* leaves the database and comes back as a parameter. Each found row is locked (`FOR UPDATE`) until the transaction
|
|
343
|
+
* ends: no write moves it to another ctid, and no new row refers to it, before the delete. All go in one statement,
|
|
344
|
+
* so rows that refer to each other (a reply its notice pins) go together: a foreign key is checked at its end.
|
|
509
345
|
*/
|
|
510
|
-
async
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
// A column with a database default keeps it unless the fixture assigned it, a foreign key's included.
|
|
520
|
-
const defaulted = new Set(columns.filter((column) => column.generated !== 'no').map((column) => column.column_name))
|
|
521
|
-
const keyed = new Map<string, SampleValue>()
|
|
522
|
-
for (const key of model?.foreignKeys ?? []) {
|
|
523
|
-
const open = key.columns.filter((column) => !assigned.has(column) && !defaulted.has(column))
|
|
524
|
-
if (open.length === 0) continue
|
|
525
|
-
for (const [name, value] of await referencedKey(models, table, key, open, depth)) keyed.set(name, value)
|
|
526
|
-
}
|
|
527
|
-
const row = new Map<string, SampleValue>()
|
|
528
|
-
for (const column of columns) {
|
|
529
|
-
const name = column.column_name
|
|
530
|
-
// An assigned `null` is the fixture's value too, never a gap to fill.
|
|
531
|
-
const given = assigned.has(name) ? assigned : keyed.has(name) ? keyed : undefined
|
|
532
|
-
if (given !== undefined) {
|
|
533
|
-
row.set(name, given.get(name) ?? null)
|
|
534
|
-
continue
|
|
535
|
-
}
|
|
536
|
-
if (column.generated !== 'no') continue
|
|
537
|
-
const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
|
|
538
|
-
const checked = kind === undefined ? await checkedValue(table, column) : undefined
|
|
539
|
-
if (kind !== undefined) {
|
|
540
|
-
row.set(name, await seedFile(kind))
|
|
541
|
-
} else if (checked !== undefined) {
|
|
542
|
-
row.set(name, checked)
|
|
543
|
-
} else if (await holdsMarker(model, table, column)) {
|
|
544
|
-
const marker = `m${randomHex()}${randomHex()}`
|
|
545
|
-
markers.push(marker)
|
|
546
|
-
row.set(name, marker)
|
|
547
|
-
} else {
|
|
548
|
-
row.set(name, column.nullable ? null : sampleOf(table, column))
|
|
346
|
+
const removeRows = async (tx: SQL, start: ReadonlyMap<string, readonly string[]>): Promise<void> => {
|
|
347
|
+
const found = new Map<string, Set<string>>()
|
|
348
|
+
let count = 0
|
|
349
|
+
let level = new Map<string, string[]>()
|
|
350
|
+
const add = (table: string, ctid: string): void => {
|
|
351
|
+
let ctids = found.get(table)
|
|
352
|
+
if (ctids === undefined) {
|
|
353
|
+
ctids = new Set()
|
|
354
|
+
found.set(table, ctids)
|
|
549
355
|
}
|
|
356
|
+
if (ctids.has(ctid)) return
|
|
357
|
+
if (++count > MAX_REMOVED_ROWS) throw removalLimit()
|
|
358
|
+
ctids.add(ctid)
|
|
359
|
+
level.set(table, [...(level.get(table) ?? []), ctid])
|
|
550
360
|
}
|
|
551
|
-
const
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
const assigned = new Map<string, SampleValue>()
|
|
570
|
-
const scope = model.scope
|
|
571
|
-
if (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app') {
|
|
572
|
-
assigned.set(scope.key, key)
|
|
573
|
-
}
|
|
574
|
-
for (const link of model.chain) {
|
|
575
|
-
const value = values.get(link.dimension)
|
|
576
|
-
if (value !== undefined) {
|
|
577
|
-
assigned.set(link.column, value)
|
|
361
|
+
for (const [table, ctids] of start) for (const ctid of ctids) add(table, ctid)
|
|
362
|
+
while (level.size > 0) {
|
|
363
|
+
const current = level
|
|
364
|
+
level = new Map()
|
|
365
|
+
for (const [table, ctids] of current) {
|
|
366
|
+
const target = `${quoted(schema)}.${quoted(table)}`
|
|
367
|
+
for (const key of await referrersOf(table)) {
|
|
368
|
+
const on = key.columns.map((column, position) => `r.${quoted(column)} = t.${quoted(key.refs[position] ?? '')}`).join(' AND ')
|
|
369
|
+
const referring = ctidRows.parse(
|
|
370
|
+
await tx.unsafe(
|
|
371
|
+
`SELECT r.ctid::text AS ctid FROM ${quoted(schema)}.${
|
|
372
|
+
quoted(key.table_name)
|
|
373
|
+
} r JOIN ${target} t ON ${on} WHERE t.ctid = ANY($1::tid[]) FOR UPDATE OF r`,
|
|
374
|
+
[tidArray(ctids)],
|
|
375
|
+
),
|
|
376
|
+
)
|
|
377
|
+
for (const referrer of referring) add(key.table_name, referrer.ctid)
|
|
378
|
+
}
|
|
578
379
|
}
|
|
579
380
|
}
|
|
580
|
-
if (
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
}
|
|
586
|
-
return assigned
|
|
381
|
+
if (found.size === 0) return
|
|
382
|
+
const tables = [...found]
|
|
383
|
+
const deletes = tables.map(([table], index) =>
|
|
384
|
+
`d${index} AS (DELETE FROM ${quoted(schema)}.${quoted(table)} WHERE ctid = ANY($${index + 1}::tid[]))`
|
|
385
|
+
)
|
|
386
|
+
await tx.unsafe(`WITH ${deletes.join(', ')} SELECT 1`, tables.map(([, ctids]) => tidArray(ctids)))
|
|
587
387
|
}
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
388
|
+
let types: Promise<ReadonlyMap<string, string>> | undefined
|
|
389
|
+
const seedColumns = catalog.map(seedColumn)
|
|
390
|
+
const backend: SeedingBackend = {
|
|
391
|
+
columns: seedColumns,
|
|
392
|
+
checks: async () =>
|
|
393
|
+
checkRows.parse(await lock.unsafe(CHECK_QUERY, [schema])).map((row): CheckConstraint => ({
|
|
394
|
+
name: row.name,
|
|
395
|
+
table: row.table_name,
|
|
396
|
+
columns: row.columns,
|
|
397
|
+
values: listedValues(row.definition, row.columns),
|
|
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`)
|
|
611
418
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
const
|
|
616
|
-
|
|
617
|
-
|
|
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
|
|
618
430
|
}
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
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
|
+
},
|
|
435
|
+
async insert(table, row) {
|
|
436
|
+
const names = [...row.keys()]
|
|
437
|
+
const placeholders = names.map((_, index) => `$${index + 1}`)
|
|
438
|
+
const target = `${quoted(schema)}.${quoted(table)}`
|
|
439
|
+
const statement = names.length === 0
|
|
440
|
+
? `INSERT INTO ${target} DEFAULT VALUES RETURNING *`
|
|
441
|
+
: `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${placeholders.join(', ')}) RETURNING *`
|
|
442
|
+
let stored: unknown
|
|
443
|
+
try {
|
|
444
|
+
stored = await seeder.unsafe(statement, names.map((name) => seedBinding(seedColumns, table, name, row.get(name) ?? null)))
|
|
445
|
+
} catch (error) {
|
|
446
|
+
throw seedLimit(error, table) ?? error
|
|
623
447
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
]
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
448
|
+
const [returned] = z.array(z.record(z.string(), z.unknown())).parse(stored)
|
|
449
|
+
return returned ?? {}
|
|
450
|
+
},
|
|
451
|
+
async firstRow(table, columns) {
|
|
452
|
+
const selected: unknown = await seeder.unsafe(`SELECT ${columns.map(quoted).join(', ')} FROM ${quoted(schema)}.${quoted(table)} LIMIT 1`)
|
|
453
|
+
return z.array(z.record(z.string(), z.unknown())).parse(selected)[0]
|
|
454
|
+
},
|
|
455
|
+
async insertFile(file) {
|
|
456
|
+
await seeder.unsafe(
|
|
457
|
+
`INSERT INTO ${quoted(schema)}.${quoted(FILES_TABLE)} (id, kind, status, object_key, size, sha256, content_type, name, created_at, object_version)
|
|
458
|
+
VALUES ($1, $2, 'live', $3, 0, $4, 'application/octet-stream', 'seeded', now(), $5)`,
|
|
459
|
+
[file.id, file.kind, file.objectKey, file.sha256, file.objectVersion],
|
|
460
|
+
)
|
|
461
|
+
},
|
|
462
|
+
async remove(rows: readonly InsertedRow[]) {
|
|
463
|
+
await seeder.begin(async (tx) => {
|
|
464
|
+
const start = new Map<string, string[]>()
|
|
465
|
+
for (const row of rows) {
|
|
466
|
+
const where = [...row.match.keys()].map((column, index) => `${quoted(column)} = $${index + 1}`).join(' AND ')
|
|
467
|
+
const located = ctidRows.parse(
|
|
468
|
+
await tx.unsafe(`SELECT ctid::text AS ctid FROM ${quoted(schema)}.${quoted(row.table)} WHERE ${where} FOR UPDATE`, [
|
|
469
|
+
...row.match.values(),
|
|
470
|
+
]),
|
|
471
|
+
)
|
|
472
|
+
start.set(row.table, [...(start.get(row.table) ?? []), ...located.map((found) => found.ctid)])
|
|
473
|
+
}
|
|
474
|
+
await removeRows(tx, start)
|
|
475
|
+
})
|
|
476
|
+
},
|
|
647
477
|
}
|
|
648
478
|
|
|
649
479
|
return {
|
|
480
|
+
...testSeeding(backend),
|
|
650
481
|
database: opened.database,
|
|
651
482
|
schema,
|
|
652
|
-
async seedWorlds(tables, table, values = {}) {
|
|
653
|
-
const { models, model } = scopedModel(tables, table)
|
|
654
|
-
const dimension = grantDimension(models, model)
|
|
655
|
-
return { dimension, own: await seedWorld(models, model, 'own', values), other: await seedWorld(models, model, 'other', values) }
|
|
656
|
-
},
|
|
657
|
-
async seedRow(tables, table) {
|
|
658
|
-
const { models, model } = scopedModel(tables, table)
|
|
659
|
-
if (model.scope.mode !== 'app') {
|
|
660
|
-
throw new Error(`${table} is a ${model.scope.mode} table; seedWorlds seeds a dimension or child table`)
|
|
661
|
-
}
|
|
662
|
-
const markers: string[] = []
|
|
663
|
-
const key = await scopeValue(table, model.scope.key, table, 'app')
|
|
664
|
-
const { row } = await insert(models, table, placement(model, new Map(), key), markers)
|
|
665
|
-
const updates: Record<string, SampleValue> = {}
|
|
666
|
-
for (const name of namesOf(model.update)) {
|
|
667
|
-
updates[name] = row.get(name) ?? await updateSample(table, name)
|
|
668
|
-
}
|
|
669
|
-
return { key, updates, markers }
|
|
670
|
-
},
|
|
671
|
-
async seedUnder(tables, table, under) {
|
|
672
|
-
const { models, model } = scopedModel(tables, table)
|
|
673
|
-
const scope = model.scope
|
|
674
|
-
const [object] = under.chain
|
|
675
|
-
if ((scope.mode !== 'dimension' && scope.mode !== 'child') || object === undefined) {
|
|
676
|
-
throw new Error(`${table} is a ${scope.mode} table; a row seeded under another lies in its chain`)
|
|
677
|
-
}
|
|
678
|
-
const values = new Map(under.chain.map((link) => [link.type, link.value]))
|
|
679
|
-
if (!model.chain.some((link) => link.dimension === object.type) || model.chain.some((link) => !values.has(link.dimension))) {
|
|
680
|
-
throw new Error(`${table} does not lie in a ${object.type}, so no row of it is seeded under one`)
|
|
681
|
-
}
|
|
682
|
-
const key = await scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
|
|
683
|
-
const markers: string[] = []
|
|
684
|
-
await insert(models, table, placement(model, values, key), markers)
|
|
685
|
-
return { key, markers }
|
|
686
|
-
},
|
|
687
|
-
async sampleInsert(tables, table) {
|
|
688
|
-
const { models, model } = scopedModel(tables, table)
|
|
689
|
-
const values: Record<string, SampleValue> = {}
|
|
690
|
-
const columns = await columnsOf(table)
|
|
691
|
-
const required = columns.filter((column) => inSet(model.insert, column.column_name) && isRequired(column))
|
|
692
|
-
for (const key of model.foreignKeys) {
|
|
693
|
-
const open = key.columns.filter((name) => required.some((column) => column.column_name === name))
|
|
694
|
-
if (open.length === 0) continue
|
|
695
|
-
for (const [name, value] of await referencedKey(models, table, key, open, 0)) values[name] = value
|
|
696
|
-
}
|
|
697
|
-
for (const column of required) {
|
|
698
|
-
const name = column.column_name
|
|
699
|
-
const kind = Object.hasOwn(model.files, name) ? model.files[name] : undefined
|
|
700
|
-
if (!(name in values)) values[name] = kind === undefined ? await requiredSample(table, column) : await seedFile(kind)
|
|
701
|
-
}
|
|
702
|
-
return values
|
|
703
|
-
},
|
|
704
|
-
seededObjects: () => [...seededObjects],
|
|
705
483
|
// Its own connections end first, so the drop finds a slot even in a database at its limit.
|
|
706
484
|
close: () => closeTestDatabase(url, opened, (drop) => withConnectionCapacity(drop, { waitMs })),
|
|
707
485
|
}
|
|
@@ -750,7 +528,7 @@ async function openTestDatabase(url: string, directory: string): Promise<OpenedT
|
|
|
750
528
|
const runtimeUrl = applicationRuntimeUrl(url, appId)
|
|
751
529
|
const admin = new SQL({ url, adapter: 'postgres', max: 1, prepare: false })
|
|
752
530
|
const seeder = new SQL({ url: runtimeUrl, adapter: 'postgres', max: 1, prepare: false })
|
|
753
|
-
const database =
|
|
531
|
+
const database = openPostgres({ url: runtimeUrl, schema, max: RUNTIME_CONNECTIONS })
|
|
754
532
|
let lock: ReservedSQL | undefined
|
|
755
533
|
try {
|
|
756
534
|
lock = await admin.reserve()
|
|
@@ -799,10 +577,5 @@ function closeTestDatabase(url: string, connections: TestConnections, dropping:
|
|
|
799
577
|
* has bound that layer. Every runtime check of a store applies: kind, dimension, action and the request's authority.
|
|
800
578
|
*/
|
|
801
579
|
export function tableProbe(layer: unknown, table: string): TableProbe {
|
|
802
|
-
|
|
803
|
-
const side = frameworkSideOf(layer)
|
|
804
|
-
if (side === undefined) {
|
|
805
|
-
throw new TypeError('not a data layer scoped(tables) created')
|
|
806
|
-
}
|
|
807
|
-
return side.probe(table)
|
|
580
|
+
return probeTable(MODULE, layer, table)
|
|
808
581
|
}
|