@fabrika/db 0.9.0-dev.3 → 0.9.0-dev.30
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 +8 -5
- 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 +212 -55
- package/src/job-wakes.ts +450 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/migrations-sqlite.ts +181 -0
- package/src/migrations.ts +43 -0
- package/src/nodes.ts +84 -14
- package/src/orm-types.ts +198 -67
- package/src/orm.ts +383 -133
- package/src/policy.ts +1933 -122
- 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 +171 -5
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +1348 -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 +7 -5
- 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 +34 -5
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +2 -0
- package/types/src/nodes.d.ts +17 -2
- package/types/src/orm-types.d.ts +155 -63
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +344 -16
- 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
package/src/testing.ts
CHANGED
|
@@ -16,17 +16,47 @@ 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
|
+
type CheckLiteral,
|
|
30
|
+
foreignKeyLimit,
|
|
31
|
+
groupsWhere,
|
|
32
|
+
type InsertedRow,
|
|
33
|
+
MAX_REMOVED_ROWS,
|
|
34
|
+
probeTable,
|
|
35
|
+
randomHex,
|
|
36
|
+
removalLimit,
|
|
37
|
+
seedBinding,
|
|
38
|
+
type SeedColumn,
|
|
39
|
+
type SeedingBackend,
|
|
40
|
+
type SeedLimitError,
|
|
41
|
+
type TestDatabase,
|
|
42
|
+
testSeeding,
|
|
43
|
+
typeLimit,
|
|
44
|
+
uniqueValueLimit,
|
|
45
|
+
} from './testing-shared'
|
|
28
46
|
|
|
29
47
|
export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store'
|
|
48
|
+
export {
|
|
49
|
+
type ApplicationRow,
|
|
50
|
+
type IsolationWorlds,
|
|
51
|
+
type SampleValue,
|
|
52
|
+
type ScopeValues,
|
|
53
|
+
SEEDED_OBJECT_VERSION,
|
|
54
|
+
type SeededApplicationRows,
|
|
55
|
+
type SeededRow,
|
|
56
|
+
SeedLimitError,
|
|
57
|
+
type TestDatabase,
|
|
58
|
+
type WorldRow,
|
|
59
|
+
} from './testing-shared'
|
|
30
60
|
|
|
31
61
|
const MODULE = '@fabrika/db/testing'
|
|
32
62
|
refuseInProduction(MODULE)
|
|
@@ -54,144 +84,57 @@ export interface TestDatabaseOptions {
|
|
|
54
84
|
/** Set once a test database of this process gave up waiting for a connection slot. */
|
|
55
85
|
let capacityExhausted: ConnectionCapacityError | undefined
|
|
56
86
|
|
|
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
87
|
const TEXT_TYPES: ReadonlySet<string> = new Set(['text', 'varchar', 'bpchar'])
|
|
147
|
-
|
|
148
|
-
function randomHex(): string {
|
|
149
|
-
return crypto.randomUUID().replaceAll('-', '').slice(0, 8)
|
|
150
|
-
}
|
|
88
|
+
const NUMBER_TYPES: ReadonlySet<string> = new Set(['int2', 'int4', 'int8', 'float4', 'float8', 'numeric'])
|
|
151
89
|
|
|
152
90
|
function quoted(identifier: string): string {
|
|
153
91
|
return `"${identifier}"`
|
|
154
92
|
}
|
|
155
93
|
|
|
156
|
-
|
|
157
|
-
|
|
94
|
+
const DAY_MS = 86_400_000
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A sample for a required column the test does not care about, by the types `@fabrika/db/codegen` accepts; `variant`
|
|
98
|
+
* above 0 is another value of the type (`SeedColumn.sample`).
|
|
99
|
+
*/
|
|
100
|
+
function sampleOf(table: string, column: CatalogColumn, variant: number): Primitive {
|
|
158
101
|
if (column.type_type === 'e') {
|
|
159
|
-
const
|
|
160
|
-
if (
|
|
161
|
-
return
|
|
102
|
+
const label = column.enum_labels[variant % Math.max(column.enum_labels.length, 1)]
|
|
103
|
+
if (label !== undefined) {
|
|
104
|
+
return label
|
|
162
105
|
}
|
|
163
106
|
}
|
|
164
107
|
const type = column.type_name
|
|
165
108
|
if (type === 'uuid') return crypto.randomUUID()
|
|
166
109
|
if (TEXT_TYPES.has(type)) return `s${randomHex()}`
|
|
167
|
-
|
|
168
|
-
if (type === 'int8' || type === 'numeric')
|
|
169
|
-
if (type === 'bool') return
|
|
110
|
+
// Bun.SQL reads an int8 and a numeric as text.
|
|
111
|
+
if (NUMBER_TYPES.has(type)) return type === 'int8' || type === 'numeric' ? String(1 + variant) : 1 + variant
|
|
112
|
+
if (type === 'bool') return variant % 2 === 1
|
|
170
113
|
// ISO text, not a Date: the seed binds past the layer's compiler, where Bun.SQL would send Date#toString(). A day is
|
|
171
114
|
// `YYYY-MM-DD`, since the probe's insert sends it through the layer, which takes a `date` only so.
|
|
172
|
-
if (type === 'date') return new Date().toISOString().slice(0, 10)
|
|
173
|
-
if (type === 'timestamp' || type === 'timestamptz') return new Date().toISOString()
|
|
174
|
-
if (type === 'time' || type === 'timetz') return
|
|
175
|
-
if (type === 'interval') return
|
|
176
|
-
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/** A text column the fixture writes a marker into, nullable or not, so that a leaked value is recognised anywhere. */
|
|
180
|
-
function isMarkable(column: CatalogColumn): boolean {
|
|
181
|
-
return column.type_type !== 'e' && TEXT_TYPES.has(column.type_name) && column.generated === 'no'
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function isRequired(column: CatalogColumn): boolean {
|
|
185
|
-
return !column.nullable && column.generated === 'no'
|
|
115
|
+
if (type === 'date') return new Date(Date.now() + variant * DAY_MS).toISOString().slice(0, 10)
|
|
116
|
+
if (type === 'timestamp' || type === 'timestamptz') return new Date(Date.now() + variant * 1000).toISOString()
|
|
117
|
+
if (type === 'time' || type === 'timetz') return `12:00:${String(variant % 60).padStart(2, '0')}`
|
|
118
|
+
if (type === 'interval') return `${1 + variant} hour`
|
|
119
|
+
// A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
|
|
120
|
+
if (type === 'jsonb') return variant === 0 ? 'sample' : `sample-${variant}`
|
|
121
|
+
throw typeLimit(table, column.column_name, type)
|
|
186
122
|
}
|
|
187
123
|
|
|
188
|
-
/** A
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
124
|
+
/** A catalog column as the seeding reads it. */
|
|
125
|
+
function seedColumn(column: CatalogColumn): SeedColumn {
|
|
126
|
+
return {
|
|
127
|
+
table: column.table_name,
|
|
128
|
+
name: column.column_name,
|
|
129
|
+
type: column.type_name,
|
|
130
|
+
nullable: column.nullable,
|
|
131
|
+
defaulted: column.generated !== 'no',
|
|
132
|
+
text: column.type_type !== 'e' && TEXT_TYPES.has(column.type_name),
|
|
133
|
+
uuid: column.type_name === 'uuid',
|
|
134
|
+
number: column.type_type !== 'e' && NUMBER_TYPES.has(column.type_name),
|
|
135
|
+
json: column.type_type === 'b' && column.type_category !== 'A' && column.type_name === 'jsonb',
|
|
136
|
+
sample: (variant) => sampleOf(column.table_name, column, variant),
|
|
137
|
+
}
|
|
195
138
|
}
|
|
196
139
|
|
|
197
140
|
const checkRows = z.array(z.object({ name: z.string(), table_name: z.string(), definition: z.string(), columns: z.array(z.string()) }))
|
|
@@ -207,82 +150,114 @@ WHERE n.nspname = $1 AND c.contype = 'c'
|
|
|
207
150
|
ORDER BY r.relname, c.conname
|
|
208
151
|
`
|
|
209
152
|
|
|
210
|
-
|
|
211
|
-
const IN_LIST = /^CHECK \(\(\(?"?([^"()\s]+)"?\)?(?:::[a-z ]+)? = ANY \(\(?ARRAY\[(.+)\]\)?(?:::[a-z ]+\[\])?\)\)\)$/
|
|
212
|
-
const LITERAL = /'((?:[^']|'')*)'::/g
|
|
153
|
+
const uniqueRows = z.array(z.object({ name: z.string(), table_name: z.string(), columns: z.array(z.string()), nulls_not_distinct: z.boolean() }))
|
|
213
154
|
|
|
214
|
-
/**
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
155
|
+
/**
|
|
156
|
+
* Every unique index of the schema's tables (a primary key's and a UNIQUE constraint's are one) whose key columns are all
|
|
157
|
+
* plain columns and that has no predicate, with its key columns: the first `indnkeyatts` of `indkey`, never an `INCLUDE`
|
|
158
|
+
* column. An index on an expression (`indexprs`) or a partial one (`indpred`) is left out.
|
|
159
|
+
*/
|
|
160
|
+
const UNIQUE_QUERY = `
|
|
161
|
+
SELECT i.relname::text AS name, r.relname::text AS table_name, x.indnullsnotdistinct AS nulls_not_distinct,
|
|
162
|
+
ARRAY(
|
|
163
|
+
SELECT a.attname::text FROM pg_attribute a
|
|
164
|
+
WHERE a.attrelid = x.indrelid AND a.attnum = ANY ((x.indkey::int2[])[0:x.indnkeyatts - 1])
|
|
165
|
+
ORDER BY a.attnum
|
|
166
|
+
) AS columns
|
|
167
|
+
FROM pg_index x
|
|
168
|
+
JOIN pg_class i ON i.oid = x.indexrelid
|
|
169
|
+
JOIN pg_class r ON r.oid = x.indrelid
|
|
170
|
+
JOIN pg_namespace n ON n.oid = r.relnamespace
|
|
171
|
+
WHERE n.nspname = $1 AND x.indisunique AND x.indexprs IS NULL AND x.indpred IS NULL
|
|
172
|
+
ORDER BY r.relname, i.relname
|
|
173
|
+
`
|
|
220
174
|
|
|
221
|
-
|
|
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
|
-
}
|
|
175
|
+
const typeRows = z.array(z.object({ table_name: z.string(), column_name: z.string(), type: z.string() }))
|
|
228
176
|
|
|
229
|
-
/**
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
-
}
|
|
177
|
+
/** 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. */
|
|
178
|
+
const TYPE_QUERY = `
|
|
179
|
+
SELECT r.relname::text AS table_name, a.attname::text AS column_name, format_type(a.atttypid, a.atttypmod) AS type
|
|
180
|
+
FROM pg_attribute a
|
|
181
|
+
JOIN pg_class r ON r.oid = a.attrelid
|
|
182
|
+
JOIN pg_namespace n ON n.oid = r.relnamespace
|
|
183
|
+
WHERE n.nspname = $1 AND r.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped
|
|
184
|
+
`
|
|
243
185
|
|
|
244
|
-
|
|
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
|
-
}
|
|
186
|
+
const nextRows = z.array(z.object({ next: z.union([z.number(), z.string(), z.bigint()]).nullable() }))
|
|
252
187
|
|
|
253
|
-
|
|
254
|
-
|
|
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
|
-
}
|
|
188
|
+
/** SQLSTATE `numeric_value_out_of_range`: the column's type holds no such number. */
|
|
189
|
+
const OUT_OF_RANGE = '22003'
|
|
262
190
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
const
|
|
191
|
+
const referrerRows = z.array(z.object({ table_name: z.string(), columns: z.array(z.string()), refs: z.array(z.string()) }))
|
|
192
|
+
|
|
193
|
+
/** Every foreign key of the schema's tables that references the table `$2`, with its columns and the ones it references, in order. */
|
|
194
|
+
const REFERRER_QUERY = `
|
|
195
|
+
SELECT r.relname::text AS table_name,
|
|
196
|
+
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,
|
|
197
|
+
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
|
|
198
|
+
FROM pg_constraint c
|
|
199
|
+
JOIN pg_class r ON r.oid = c.conrelid
|
|
200
|
+
JOIN pg_namespace n ON n.oid = r.relnamespace
|
|
201
|
+
JOIN pg_class t ON t.oid = c.confrelid
|
|
202
|
+
WHERE n.nspname = $1 AND t.relnamespace = n.oid AND t.relname = $2 AND c.contype = 'f'
|
|
203
|
+
ORDER BY r.relname, c.conname
|
|
204
|
+
`
|
|
205
|
+
|
|
206
|
+
// A row's ctid is its place, unique in a table: an application migration creates no partitioned table (ADR-0017).
|
|
207
|
+
const ctidRows = z.array(z.object({ ctid: z.string() }))
|
|
208
|
+
|
|
209
|
+
/** Ctids as one array literal parameter, `{"(0,1)","(0,2)"}`: the driver mis-binds a JS array. */
|
|
210
|
+
const tidArray = (ctids: Iterable<string>): string => `{${[...ctids].map((ctid) => `"${ctid}"`).join(',')}}`
|
|
267
211
|
|
|
268
212
|
/**
|
|
269
|
-
*
|
|
270
|
-
*
|
|
213
|
+
* `CHECK ((status = ANY (ARRAY['open'::text, 'done'::text])))` or `CHECK ((rate = ANY (ARRAY[0, 12])))`, a one-column
|
|
214
|
+
* `IN` list as Postgres prints it.
|
|
271
215
|
*/
|
|
272
|
-
|
|
216
|
+
const IN_LIST = /^CHECK \(\(\(?"?([^"()\s]+)"?\)?(?:::[a-z ]+)? = ANY \(\(?ARRAY\[(.+)\]\)?(?:::[a-z ]+\[\])?\)\)\)$/
|
|
217
|
+
const LITERAL = /'((?:[^']|'')*)'::([a-z ]+)/g
|
|
218
|
+
const QUOTED_ITEM = /^\(?'((?:[^']|'')*)'::([a-z ]+)\)?$/
|
|
219
|
+
const LIST_NUMBER = /^\(?(-?[0-9]+(?:\.[0-9]+)?)\)?(?:::[a-z ]+)?$/
|
|
220
|
+
/** A string literal of a printed definition, or a number outside one that no name or other number touches. */
|
|
221
|
+
const DEFINITION_LITERAL = /'((?:[^']|'')*)'(?:::([a-z ]+))?|(?<![\w$."])(-?[0-9]+(?:\.[0-9]+)?)(?![\w$.])/g
|
|
222
|
+
/** Postgres prints a negative number constant quoted and cast, `'-5'::integer`. */
|
|
223
|
+
const NUMBER_CAST = /^(?:smallint|integer|bigint|numeric|real|double precision)$/
|
|
224
|
+
const NUMBER_TEXT = /^-?[0-9]+(?:\.[0-9]+)?$/
|
|
225
|
+
|
|
226
|
+
/** A quoted constant of a printed definition: a number where it is cast to a number type, else its text. */
|
|
227
|
+
function quotedValue(quoted: string, cast: string | undefined): CheckLiteral {
|
|
228
|
+
const text = quoted.replaceAll("''", "'")
|
|
229
|
+
return cast !== undefined && NUMBER_CAST.test(cast.trim()) && NUMBER_TEXT.test(text) ? Number(text) : text
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** The values of a one-column `IN` list, or none for any other CHECK. */
|
|
233
|
+
function listedValues(definition: string, columns: readonly string[]): CheckLiteral[] {
|
|
234
|
+
const listed = IN_LIST.exec(definition)
|
|
235
|
+
if (listed === null || columns.length !== 1 || listed[1] !== columns[0]) return []
|
|
236
|
+
const items = listed[2] ?? ''
|
|
237
|
+
const quoted = [...items.matchAll(LITERAL)]
|
|
238
|
+
// A text list is read by its literals, which may hold the separator; a number list item by item.
|
|
239
|
+
if (quoted.some((match) => !NUMBER_CAST.test((match[2] ?? '').trim()))) return quoted.map((match) => quotedValue(match[1] ?? '', match[2]))
|
|
240
|
+
const numbers = items.split(', ').map((item) => {
|
|
241
|
+
const constant = QUOTED_ITEM.exec(item)
|
|
242
|
+
if (constant !== null) return quotedValue(constant[1] ?? '', constant[2])
|
|
243
|
+
const number = LIST_NUMBER.exec(item)?.[1]
|
|
244
|
+
return number === undefined ? undefined : Number(number)
|
|
245
|
+
})
|
|
246
|
+
return numbers.every((number) => typeof number === 'number') ? numbers.filter((number) => typeof number === 'number') : []
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Every text and number literal of a CHECK as Postgres prints it. */
|
|
250
|
+
function definitionLiterals(definition: string): CheckLiteral[] {
|
|
251
|
+
return [...definition.matchAll(DEFINITION_LITERAL)].map((match) => match[1] === undefined ? Number(match[3]) : quotedValue(match[1], match[2]))
|
|
252
|
+
}
|
|
273
253
|
|
|
274
254
|
/** A CHECK or foreign key violation of a seeded row, as the generator limit it is; `undefined` for any other failure. */
|
|
275
255
|
function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
|
|
276
256
|
if (!(error instanceof SQL.PostgresError)) return undefined
|
|
277
257
|
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
|
-
}
|
|
258
|
+
if (error.errno === '23514') return checkLimit(constraint, table)
|
|
259
|
+
if (error.errno === '23503') return foreignKeyLimit(constraint, table)
|
|
260
|
+
if (error.errno === '23505') return uniqueValueLimit(constraint, table)
|
|
286
261
|
return undefined
|
|
287
262
|
}
|
|
288
263
|
|
|
@@ -291,7 +266,7 @@ const TEST_SCHEMA = /^app_test_[0-9a-f]{16}$/
|
|
|
291
266
|
const TEST_ROLE = /^(?:app|run)_(test_[0-9a-f]{16})$/
|
|
292
267
|
/**
|
|
293
268
|
* Why an abandoned family is left alone: `DROP ROLE` of a role that still owns something in another database of the
|
|
294
|
-
* cluster, and a family another provisioner created
|
|
269
|
+
* cluster, and a family another provisioner created, which only it administers.
|
|
295
270
|
*/
|
|
296
271
|
const LEFT_TO_ITS_OWNER: ReadonlySet<unknown> = new Set(['2BP01', '42501'])
|
|
297
272
|
|
|
@@ -387,322 +362,168 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
387
362
|
throw new Error(`${options.label}: ${error.message}; its cases did not run`)
|
|
388
363
|
}
|
|
389
364
|
const { schema, lock, seeder, catalog } = opened
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
columns: row.columns,
|
|
400
|
-
values: listedValues(row.definition, row.columns),
|
|
401
|
-
}))
|
|
402
|
-
)
|
|
403
|
-
return (await checks).filter((check) => check.table === table && check.columns.includes(column))
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
/**
|
|
407
|
-
* What the fixture writes into a column a CHECK names: the first value of a one-column `IN` list, `null` where the
|
|
408
|
-
* column admits it (a CHECK passes on null); `undefined` when no CHECK names it or none of those applies.
|
|
409
|
-
*/
|
|
410
|
-
async function checkedValue(table: string, column: CatalogColumn): Promise<SampleValue | undefined> {
|
|
411
|
-
const named = await checksOn(table, column.column_name)
|
|
412
|
-
if (named.length === 0) return undefined
|
|
413
|
-
const [listed] = named.flatMap((check) => check.values)
|
|
414
|
-
if (listed !== undefined && named.every((check) => check.values.includes(listed))) return listed
|
|
415
|
-
return column.nullable ? null : undefined
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
/** A required column's sample: an `IN` list's first value where a CHECK names one, else a sample of its type. */
|
|
419
|
-
async function requiredSample(table: string, column: CatalogColumn): Promise<SampleValue> {
|
|
420
|
-
return (await checkedValue(table, column)) ?? sampleOf(table, column)
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
async function columnsOf(table: string): Promise<readonly CatalogColumn[]> {
|
|
424
|
-
const columns = catalog.filter((column) => column.table_name === table)
|
|
425
|
-
if (columns.length === 0) {
|
|
426
|
-
throw new Error(`${table} is not a table of the migrated schema; write its migration first`)
|
|
427
|
-
}
|
|
428
|
-
return columns
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
async function columnOf(table: string, name: string): Promise<CatalogColumn> {
|
|
432
|
-
const column = (await columnsOf(table)).find((candidate) => candidate.column_name === name)
|
|
433
|
-
if (column === undefined) {
|
|
434
|
-
throw new Error(`${table}.${name} is not a column of the migrated schema`)
|
|
365
|
+
const referrers = new Map<string, Promise<z.infer<typeof referrerRows>>>()
|
|
366
|
+
/** The foreign keys that reference `table`, read from the catalog once. */
|
|
367
|
+
const referrersOf = (table: string): Promise<z.infer<typeof referrerRows>> => {
|
|
368
|
+
let known = referrers.get(table)
|
|
369
|
+
if (known === undefined) {
|
|
370
|
+
known = lock.unsafe(REFERRER_QUERY, [schema, table]).then((rows: unknown) => referrerRows.parse(rows))
|
|
371
|
+
referrers.set(table, known)
|
|
372
|
+
// A failed read is not kept: the next removal reads the catalog again.
|
|
373
|
+
known.catch(() => referrers.delete(table))
|
|
435
374
|
}
|
|
436
|
-
return
|
|
375
|
+
return known
|
|
437
376
|
}
|
|
438
|
-
|
|
439
|
-
/** A column the seeded row left to its default: null only where the column admits it. */
|
|
440
|
-
async function updateSample(table: string, name: string): Promise<SampleValue> {
|
|
441
|
-
const column = await columnOf(table, name)
|
|
442
|
-
return column.nullable ? null : requiredSample(table, column)
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
/** Whether the fixture writes a marker into `column`: text that holds no foreign key and that no CHECK names. */
|
|
446
|
-
async function holdsMarker(model: TableModel | undefined, table: string, column: CatalogColumn): Promise<boolean> {
|
|
447
|
-
const keyed = (model?.foreignKeys ?? []).some((key) => key.columns.includes(column.column_name))
|
|
448
|
-
return isMarkable(column) && !keyed && (await checksOn(table, column.column_name)).length === 0
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
/**
|
|
452
|
-
* The values of a foreign key outside the containment chain: `null` where every open column admits it, else the
|
|
453
|
-
* key of a row of the referenced table, an existing one (a reference table's rows come from a migration) or one the
|
|
454
|
-
* fixture inserts. A required key to a dimension or child table is refused: its row would lie in another chain.
|
|
455
|
-
*/
|
|
456
|
-
async function referencedKey(models: TableModels, table: string, key: ForeignKey, open: readonly string[], depth: number) {
|
|
457
|
-
const columns = await columnsOf(table)
|
|
458
|
-
const values = new Map<string, SampleValue>()
|
|
459
|
-
if (open.every((name) => columns.find((column) => column.column_name === name)?.nullable === true)) {
|
|
460
|
-
for (const name of open) values.set(name, null)
|
|
461
|
-
return values
|
|
462
|
-
}
|
|
463
|
-
const target = modelOf(models, key.table)
|
|
464
|
-
const scoped = target?.scope.mode === 'dimension' || target?.scope.mode === 'child'
|
|
465
|
-
if (scoped || open.length !== key.columns.length || key.table === table || depth >= MAX_REFERENCE_DEPTH) {
|
|
466
|
-
throw new SeedLimitError(
|
|
467
|
-
`the isolation fixture cannot fill ${table}.${
|
|
468
|
-
open.join(', ')
|
|
469
|
-
}: a required foreign key to ${key.table} outside the containment chain; give the column a default or make it nullable`,
|
|
470
|
-
)
|
|
471
|
-
}
|
|
472
|
-
const selected: unknown = await seeder.unsafe(
|
|
473
|
-
`SELECT ${key.references.map(quoted).join(', ')} FROM ${quoted(schema)}.${quoted(key.table)} LIMIT 1`,
|
|
474
|
-
)
|
|
475
|
-
const existing = z.array(z.record(z.string(), z.unknown())).parse(selected)[0]
|
|
476
|
-
const row = existing ?? (await insert(models, key.table, new Map(), [], depth + 1)).stored
|
|
477
|
-
key.columns.forEach((name, index) => {
|
|
478
|
-
const referenced = key.references[index] ?? ''
|
|
479
|
-
values.set(name, keyValue(row[referenced], `${key.table}.${referenced}`))
|
|
480
|
-
})
|
|
481
|
-
return values
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
/** A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. */
|
|
485
|
-
async function scopeValue(table: string, column: string, dimension: string, world: string): Promise<string> {
|
|
486
|
-
const type = (await columnOf(table, column)).type_name
|
|
487
|
-
if (type === 'uuid') return crypto.randomUUID()
|
|
488
|
-
if (TEXT_TYPES.has(type)) return `${dimension}-${world}-${randomHex()}`
|
|
489
|
-
throw new Error(`${table}.${column} holds a ${dimension} as ${type}; a key or containment column holds its scope value as text or uuid`)
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
/** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it: what a seeded file column holds. */
|
|
493
|
-
async function seedFile(kind: string): Promise<string> {
|
|
494
|
-
const id = crypto.randomUUID()
|
|
495
|
-
const objectKey = `${kind}/${id}`
|
|
496
|
-
seededObjects.push(objectKey)
|
|
497
|
-
await seeder.unsafe(
|
|
498
|
-
`INSERT INTO ${quoted(schema)}.${quoted(FILES_TABLE)} (id, kind, status, object_key, size, sha256, content_type, name, created_at, object_version)
|
|
499
|
-
VALUES ($1, $2, 'live', $3, 0, $4, 'application/octet-stream', 'seeded', now(), $5)`,
|
|
500
|
-
[id, kind, objectKey, EMPTY_SHA256, SEEDED_OBJECT_VERSION],
|
|
501
|
-
)
|
|
502
|
-
return id
|
|
503
|
-
}
|
|
504
|
-
|
|
505
377
|
/**
|
|
506
|
-
*
|
|
507
|
-
*
|
|
508
|
-
*
|
|
509
|
-
*
|
|
378
|
+
* Deletes the rows `start` names (table → ctids) and every row that refers to one of them, however deep. Rows are
|
|
379
|
+
* found a level at a time, one statement per table and foreign key, by joining on the key's columns, so no value
|
|
380
|
+
* leaves the database and comes back as a parameter. Each found row is locked (`FOR UPDATE`) until the transaction
|
|
381
|
+
* ends: no write moves it to another ctid, and no new row refers to it, before the delete. All go in one statement,
|
|
382
|
+
* so rows that refer to each other (a reply its notice pins) go together: a foreign key is checked at its end.
|
|
510
383
|
*/
|
|
511
|
-
async
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
// A column with a database default keeps it unless the fixture assigned it, a foreign key's included.
|
|
521
|
-
const defaulted = new Set(columns.filter((column) => column.generated !== 'no').map((column) => column.column_name))
|
|
522
|
-
const keyed = new Map<string, SampleValue>()
|
|
523
|
-
for (const key of model?.foreignKeys ?? []) {
|
|
524
|
-
const open = key.columns.filter((column) => !assigned.has(column) && !defaulted.has(column))
|
|
525
|
-
if (open.length === 0) continue
|
|
526
|
-
for (const [name, value] of await referencedKey(models, table, key, open, depth)) keyed.set(name, value)
|
|
527
|
-
}
|
|
528
|
-
const row = new Map<string, SampleValue>()
|
|
529
|
-
for (const column of columns) {
|
|
530
|
-
const name = column.column_name
|
|
531
|
-
// An assigned `null` is the fixture's value too, never a gap to fill.
|
|
532
|
-
const given = assigned.has(name) ? assigned : keyed.has(name) ? keyed : undefined
|
|
533
|
-
if (given !== undefined) {
|
|
534
|
-
row.set(name, given.get(name) ?? null)
|
|
535
|
-
continue
|
|
536
|
-
}
|
|
537
|
-
if (column.generated !== 'no') continue
|
|
538
|
-
const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
|
|
539
|
-
const checked = kind === undefined ? await checkedValue(table, column) : undefined
|
|
540
|
-
if (kind !== undefined) {
|
|
541
|
-
row.set(name, await seedFile(kind))
|
|
542
|
-
} else if (checked !== undefined) {
|
|
543
|
-
row.set(name, checked)
|
|
544
|
-
} else if (await holdsMarker(model, table, column)) {
|
|
545
|
-
const marker = `m${randomHex()}${randomHex()}`
|
|
546
|
-
markers.push(marker)
|
|
547
|
-
row.set(name, marker)
|
|
548
|
-
} else {
|
|
549
|
-
row.set(name, column.nullable ? null : sampleOf(table, column))
|
|
384
|
+
const removeRows = async (tx: SQL, start: ReadonlyMap<string, readonly string[]>): Promise<void> => {
|
|
385
|
+
const found = new Map<string, Set<string>>()
|
|
386
|
+
let count = 0
|
|
387
|
+
let level = new Map<string, string[]>()
|
|
388
|
+
const add = (table: string, ctid: string): void => {
|
|
389
|
+
let ctids = found.get(table)
|
|
390
|
+
if (ctids === undefined) {
|
|
391
|
+
ctids = new Set()
|
|
392
|
+
found.set(table, ctids)
|
|
550
393
|
}
|
|
394
|
+
if (ctids.has(ctid)) return
|
|
395
|
+
if (++count > MAX_REMOVED_ROWS) throw removalLimit()
|
|
396
|
+
ctids.add(ctid)
|
|
397
|
+
level.set(table, [...(level.get(table) ?? []), ctid])
|
|
551
398
|
}
|
|
552
|
-
const
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
const assigned = new Map<string, SampleValue>()
|
|
571
|
-
const scope = model.scope
|
|
572
|
-
if (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app') {
|
|
573
|
-
assigned.set(scope.key, key)
|
|
574
|
-
}
|
|
575
|
-
for (const link of model.chain) {
|
|
576
|
-
const value = values.get(link.dimension)
|
|
577
|
-
if (value !== undefined) {
|
|
578
|
-
assigned.set(link.column, value)
|
|
399
|
+
for (const [table, ctids] of start) for (const ctid of ctids) add(table, ctid)
|
|
400
|
+
while (level.size > 0) {
|
|
401
|
+
const current = level
|
|
402
|
+
level = new Map()
|
|
403
|
+
for (const [table, ctids] of current) {
|
|
404
|
+
const target = `${quoted(schema)}.${quoted(table)}`
|
|
405
|
+
for (const key of await referrersOf(table)) {
|
|
406
|
+
const on = key.columns.map((column, position) => `r.${quoted(column)} = t.${quoted(key.refs[position] ?? '')}`).join(' AND ')
|
|
407
|
+
const referring = ctidRows.parse(
|
|
408
|
+
await tx.unsafe(
|
|
409
|
+
`SELECT r.ctid::text AS ctid FROM ${quoted(schema)}.${
|
|
410
|
+
quoted(key.table_name)
|
|
411
|
+
} r JOIN ${target} t ON ${on} WHERE t.ctid = ANY($1::tid[]) FOR UPDATE OF r`,
|
|
412
|
+
[tidArray(ctids)],
|
|
413
|
+
),
|
|
414
|
+
)
|
|
415
|
+
for (const referrer of referring) add(key.table_name, referrer.ctid)
|
|
416
|
+
}
|
|
579
417
|
}
|
|
580
418
|
}
|
|
581
|
-
if (
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
}
|
|
587
|
-
return assigned
|
|
419
|
+
if (found.size === 0) return
|
|
420
|
+
const tables = [...found]
|
|
421
|
+
const deletes = tables.map(([table], index) =>
|
|
422
|
+
`d${index} AS (DELETE FROM ${quoted(schema)}.${quoted(table)} WHERE ctid = ANY($${index + 1}::tid[]))`
|
|
423
|
+
)
|
|
424
|
+
await tx.unsafe(`WITH ${deletes.join(', ')} SELECT 1`, tables.map(([, ctids]) => tidArray(ctids)))
|
|
588
425
|
}
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
426
|
+
let types: Promise<ReadonlyMap<string, string>> | undefined
|
|
427
|
+
const seedColumns = catalog.map(seedColumn)
|
|
428
|
+
const backend: SeedingBackend = {
|
|
429
|
+
columns: seedColumns,
|
|
430
|
+
checks: async () =>
|
|
431
|
+
checkRows.parse(await lock.unsafe(CHECK_QUERY, [schema])).map((row): CheckConstraint => ({
|
|
432
|
+
name: row.name,
|
|
433
|
+
table: row.table_name,
|
|
434
|
+
columns: row.columns,
|
|
435
|
+
values: listedValues(row.definition, row.columns),
|
|
436
|
+
literals: definitionLiterals(row.definition),
|
|
437
|
+
})),
|
|
438
|
+
uniqueIndexes: async () =>
|
|
439
|
+
uniqueRows.parse(await lock.unsafe(UNIQUE_QUERY, [schema])).map((row) => ({
|
|
440
|
+
name: row.name,
|
|
441
|
+
table: row.table_name,
|
|
442
|
+
columns: row.columns,
|
|
443
|
+
nullsNotDistinct: row.nulls_not_distinct,
|
|
444
|
+
})),
|
|
445
|
+
async nextNumber(table, column, groups) {
|
|
446
|
+
// A read that failed is read again on the next call, never answered from the cache.
|
|
447
|
+
types ??= lock.unsafe(TYPE_QUERY, [schema]).then(
|
|
448
|
+
(rows: unknown) => new Map(typeRows.parse(rows).map((row) => [`${row.table_name}.${row.column_name}`, row.type])),
|
|
449
|
+
(error: unknown) => {
|
|
450
|
+
types = undefined
|
|
451
|
+
throw error
|
|
452
|
+
},
|
|
453
|
+
)
|
|
454
|
+
const type = (await types).get(`${table}.${column}`)
|
|
455
|
+
if (type === undefined) {
|
|
456
|
+
throw new Error(`${table}.${column} is not a column of the migrated schema`)
|
|
612
457
|
}
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
const
|
|
617
|
-
|
|
618
|
-
|
|
458
|
+
const { where, values: bindings } = groupsWhere(groups, quoted, (position) => `$${position}`)
|
|
459
|
+
const largest = `(SELECT max(${quoted(column)}) FROM ${quoted(schema)}.${quoted(table)} WHERE ${where})`
|
|
460
|
+
// A float's NaN or Infinity has no next number; the cast refuses one the type cannot hold (22003).
|
|
461
|
+
const statement = `SELECT CASE WHEN largest IS NULL THEN 1::${type} WHEN largest::text IN ('NaN', 'Infinity', '-Infinity') THEN NULL
|
|
462
|
+
ELSE GREATEST(floor(largest::numeric) + 1, 1)::${type} END AS next FROM ${largest} AS m (largest)`
|
|
463
|
+
let next: unknown
|
|
464
|
+
try {
|
|
465
|
+
next = await seeder.unsafe(statement, bindings)
|
|
466
|
+
} catch (error) {
|
|
467
|
+
if (error instanceof SQL.PostgresError && error.errno === OUT_OF_RANGE) return undefined
|
|
468
|
+
throw error
|
|
619
469
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
470
|
+
const [found] = nextRows.parse(next)
|
|
471
|
+
if (found === undefined || found.next === null) return undefined
|
|
472
|
+
return typeof found.next === 'bigint' ? String(found.next) : found.next
|
|
473
|
+
},
|
|
474
|
+
async insert(table, row) {
|
|
475
|
+
const names = [...row.keys()]
|
|
476
|
+
const placeholders = names.map((_, index) => `$${index + 1}`)
|
|
477
|
+
const target = `${quoted(schema)}.${quoted(table)}`
|
|
478
|
+
const statement = names.length === 0
|
|
479
|
+
? `INSERT INTO ${target} DEFAULT VALUES RETURNING *`
|
|
480
|
+
: `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${placeholders.join(', ')}) RETURNING *`
|
|
481
|
+
let stored: unknown
|
|
482
|
+
try {
|
|
483
|
+
stored = await seeder.unsafe(statement, names.map((name) => seedBinding(seedColumns, table, name, row.get(name) ?? null)))
|
|
484
|
+
} catch (error) {
|
|
485
|
+
throw seedLimit(error, table) ?? error
|
|
624
486
|
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
487
|
+
const [returned] = z.array(z.record(z.string(), z.unknown())).parse(stored)
|
|
488
|
+
return returned ?? {}
|
|
489
|
+
},
|
|
490
|
+
async firstRow(table, columns, where = new Map()) {
|
|
491
|
+
const names = [...where.keys()]
|
|
492
|
+
const condition = names.length === 0 ? '' : ` WHERE ${names.map((name, index) => `${quoted(name)} = $${index + 1}`).join(' AND ')}`
|
|
493
|
+
const selected: unknown = await seeder.unsafe(
|
|
494
|
+
`SELECT ${columns.map(quoted).join(', ')} FROM ${quoted(schema)}.${quoted(table)}${condition} LIMIT 1`,
|
|
495
|
+
names.map((name) => where.get(name) ?? null),
|
|
496
|
+
)
|
|
497
|
+
return z.array(z.record(z.string(), z.unknown())).parse(selected)[0]
|
|
498
|
+
},
|
|
499
|
+
async insertFile(file) {
|
|
500
|
+
await seeder.unsafe(
|
|
501
|
+
`INSERT INTO ${quoted(schema)}.${quoted(FILES_TABLE)} (id, kind, status, object_key, size, sha256, content_type, name, created_at, object_version)
|
|
502
|
+
VALUES ($1, $2, 'live', $3, 0, $4, 'application/octet-stream', 'seeded', now(), $5)`,
|
|
503
|
+
[file.id, file.kind, file.objectKey, file.sha256, file.objectVersion],
|
|
504
|
+
)
|
|
505
|
+
},
|
|
506
|
+
async remove(rows: readonly InsertedRow[]) {
|
|
507
|
+
await seeder.begin(async (tx) => {
|
|
508
|
+
const start = new Map<string, string[]>()
|
|
509
|
+
for (const row of rows) {
|
|
510
|
+
const where = [...row.match.keys()].map((column, index) => `${quoted(column)} = $${index + 1}`).join(' AND ')
|
|
511
|
+
const located = ctidRows.parse(
|
|
512
|
+
await tx.unsafe(`SELECT ctid::text AS ctid FROM ${quoted(schema)}.${quoted(row.table)} WHERE ${where} FOR UPDATE`, [
|
|
513
|
+
...row.match.values(),
|
|
514
|
+
]),
|
|
515
|
+
)
|
|
516
|
+
start.set(row.table, [...(start.get(row.table) ?? []), ...located.map((found) => found.ctid)])
|
|
517
|
+
}
|
|
518
|
+
await removeRows(tx, start)
|
|
519
|
+
})
|
|
520
|
+
},
|
|
648
521
|
}
|
|
649
522
|
|
|
650
523
|
return {
|
|
524
|
+
...testSeeding(backend),
|
|
651
525
|
database: opened.database,
|
|
652
526
|
schema,
|
|
653
|
-
async seedWorlds(tables, table, values = {}) {
|
|
654
|
-
const { models, model } = scopedModel(tables, table)
|
|
655
|
-
const dimension = grantDimension(models, model)
|
|
656
|
-
return { dimension, own: await seedWorld(models, model, 'own', values), other: await seedWorld(models, model, 'other', values) }
|
|
657
|
-
},
|
|
658
|
-
async seedRow(tables, table) {
|
|
659
|
-
const { models, model } = scopedModel(tables, table)
|
|
660
|
-
if (model.scope.mode !== 'app') {
|
|
661
|
-
throw new Error(`${table} is a ${model.scope.mode} table; seedWorlds seeds a dimension or child table`)
|
|
662
|
-
}
|
|
663
|
-
const markers: string[] = []
|
|
664
|
-
const key = await scopeValue(table, model.scope.key, table, 'app')
|
|
665
|
-
const { row } = await insert(models, table, placement(model, new Map(), key), markers)
|
|
666
|
-
const updates: Record<string, SampleValue> = {}
|
|
667
|
-
for (const name of namesOf(model.update)) {
|
|
668
|
-
updates[name] = row.get(name) ?? await updateSample(table, name)
|
|
669
|
-
}
|
|
670
|
-
return { key, updates, markers }
|
|
671
|
-
},
|
|
672
|
-
async seedUnder(tables, table, under) {
|
|
673
|
-
const { models, model } = scopedModel(tables, table)
|
|
674
|
-
const scope = model.scope
|
|
675
|
-
const [object] = under.chain
|
|
676
|
-
if ((scope.mode !== 'dimension' && scope.mode !== 'child') || object === undefined) {
|
|
677
|
-
throw new Error(`${table} is a ${scope.mode} table; a row seeded under another lies in its chain`)
|
|
678
|
-
}
|
|
679
|
-
const values = new Map(under.chain.map((link) => [link.type, link.value]))
|
|
680
|
-
if (!model.chain.some((link) => link.dimension === object.type) || model.chain.some((link) => !values.has(link.dimension))) {
|
|
681
|
-
throw new Error(`${table} does not lie in a ${object.type}, so no row of it is seeded under one`)
|
|
682
|
-
}
|
|
683
|
-
const key = await scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
|
|
684
|
-
const markers: string[] = []
|
|
685
|
-
await insert(models, table, placement(model, values, key), markers)
|
|
686
|
-
return { key, markers }
|
|
687
|
-
},
|
|
688
|
-
async sampleInsert(tables, table) {
|
|
689
|
-
const { models, model } = scopedModel(tables, table)
|
|
690
|
-
const values: Record<string, SampleValue> = {}
|
|
691
|
-
const columns = await columnsOf(table)
|
|
692
|
-
const required = columns.filter((column) => inSet(model.insert, column.column_name) && isRequired(column))
|
|
693
|
-
for (const key of model.foreignKeys) {
|
|
694
|
-
const open = key.columns.filter((name) => required.some((column) => column.column_name === name))
|
|
695
|
-
if (open.length === 0) continue
|
|
696
|
-
for (const [name, value] of await referencedKey(models, table, key, open, 0)) values[name] = value
|
|
697
|
-
}
|
|
698
|
-
for (const column of required) {
|
|
699
|
-
const name = column.column_name
|
|
700
|
-
const kind = Object.hasOwn(model.files, name) ? model.files[name] : undefined
|
|
701
|
-
if (!(name in values)) values[name] = kind === undefined ? await requiredSample(table, column) : await seedFile(kind)
|
|
702
|
-
}
|
|
703
|
-
return values
|
|
704
|
-
},
|
|
705
|
-
seededObjects: () => [...seededObjects],
|
|
706
527
|
// Its own connections end first, so the drop finds a slot even in a database at its limit.
|
|
707
528
|
close: () => closeTestDatabase(url, opened, (drop) => withConnectionCapacity(drop, { waitMs })),
|
|
708
529
|
}
|
|
@@ -751,7 +572,7 @@ async function openTestDatabase(url: string, directory: string): Promise<OpenedT
|
|
|
751
572
|
const runtimeUrl = applicationRuntimeUrl(url, appId)
|
|
752
573
|
const admin = new SQL({ url, adapter: 'postgres', max: 1, prepare: false })
|
|
753
574
|
const seeder = new SQL({ url: runtimeUrl, adapter: 'postgres', max: 1, prepare: false })
|
|
754
|
-
const database =
|
|
575
|
+
const database = openPostgres({ url: runtimeUrl, schema, max: RUNTIME_CONNECTIONS })
|
|
755
576
|
let lock: ReservedSQL | undefined
|
|
756
577
|
try {
|
|
757
578
|
lock = await admin.reserve()
|
|
@@ -800,10 +621,5 @@ function closeTestDatabase(url: string, connections: TestConnections, dropping:
|
|
|
800
621
|
* has bound that layer. Every runtime check of a store applies: kind, dimension, action and the request's authority.
|
|
801
622
|
*/
|
|
802
623
|
export function tableProbe(layer: unknown, table: string): TableProbe {
|
|
803
|
-
|
|
804
|
-
const side = frameworkSideOf(layer)
|
|
805
|
-
if (side === undefined) {
|
|
806
|
-
throw new TypeError('not a data layer scoped(tables) created')
|
|
807
|
-
}
|
|
808
|
-
return side.probe(table)
|
|
624
|
+
return probeTable(MODULE, layer, table)
|
|
809
625
|
}
|