@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.21

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.
Files changed (80) hide show
  1. package/package.json +35 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +229 -40
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
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 { type Container, type ForeignKey, modelOf, type TableModel, type TableModels, tableModels, type Tables } from './policy'
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
- /** A sample for a required column the test does not care about, by the types `@fabrika/db/codegen` accepts. */
157
- function sampleOf(table: string, column: CatalogColumn): Primitive {
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 [first] = column.enum_labels
160
- if (first !== undefined) {
161
- return first
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
- if (type === 'int2' || type === 'int4' || type === 'float4' || type === 'float8') return 1
168
- if (type === 'int8' || type === 'numeric') return '1'
169
- if (type === 'bool') return false
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 '12:00:00'
175
- if (type === 'interval') return '1 hour'
176
- throw new SeedLimitError(`the isolation fixture cannot fill ${table}.${column.column_name} (${type}); give the column a default or make it nullable`)
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 CHECK constraint of the schema, by the columns it names. */
189
- interface CheckConstraint {
190
- readonly name: string
191
- readonly table: string
192
- readonly columns: readonly string[]
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[]
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
- /** `CHECK ((status = ANY (ARRAY['open'::text, 'done'::text])))`, a one-column `IN` list as Postgres prints it. */
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
- /** The values of a one-column `IN` list, or none for any other CHECK. */
215
- function listedValues(definition: string, columns: readonly string[]): string[] {
216
- const listed = IN_LIST.exec(definition)
217
- if (listed === null || columns.length !== 1 || listed[1] !== columns[0]) return []
218
- return [...(listed[2] ?? '').matchAll(LITERAL)].map((match) => (match[1] ?? '').replaceAll("''", "'"))
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
- /** 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
- }
175
+ const typeRows = z.array(z.object({ table_name: z.string(), column_name: z.string(), type: z.string() }))
228
176
 
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
- }
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
- 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
- }
186
+ const nextRows = z.array(z.object({ next: z.union([z.number(), z.string(), z.bigint()]).nullable() }))
252
187
 
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
- }
188
+ /** SQLSTATE `numeric_value_out_of_range`: the column's type holds no such number. */
189
+ const OUT_OF_RANGE = '22003'
262
190
 
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')
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
- * 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.
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
- export const SEEDED_OBJECT_VERSION = '"seeded"'
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
- return new SeedLimitError(
280
- `the isolation fixture cannot satisfy the CHECK ${constraint} of ${table}: it writes a text marker or a sample of the type there; give the column an IN list, a default, or make it nullable`,
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 (a `test-isolation` run's), which only it administers.
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
- let checks: Promise<readonly CheckConstraint[]> | undefined
391
- const seededObjects: string[] = []
392
-
393
- /** The CHECK constraints that name `column` of `table`. */
394
- async function checksOn(table: string, column: string): Promise<readonly CheckConstraint[]> {
395
- checks ??= lock.unsafe(CHECK_QUERY, [schema]).then((rows: unknown) =>
396
- checkRows.parse(rows).map((row) => ({
397
- name: row.name,
398
- table: row.table_name,
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 column
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
- * Inserts one row: `assigned` as given, a file column a seeded file, a foreign key outside the chain `null` or referencing a row, a column a CHECK
507
- * names its `IN` list's first value or `null`, every other text column a marker and every other required column a
508
- * sample. Answers what the fixture wrote, and the row as stored (its database defaults filled). A CHECK or a foreign
509
- * key the values still fail is a `SeedLimitError` that names the constraint.
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 function insert(
512
- models: TableModels,
513
- table: string,
514
- assigned: ReadonlyMap<string, SampleValue>,
515
- markers: string[],
516
- depth = 0,
517
- ): Promise<{ readonly row: ReadonlyMap<string, SampleValue>; readonly stored: Readonly<Record<string, unknown>> }> {
518
- const model = modelOf(models, table)
519
- const columns = await columnsOf(table)
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 names = [...row.keys()]
553
- const placeholders = names.map((_, index) => `$${index + 1}`)
554
- const target = `${quoted(schema)}.${quoted(table)}`
555
- const statement = names.length === 0
556
- ? `INSERT INTO ${target} DEFAULT VALUES RETURNING *`
557
- : `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${placeholders.join(', ')}) RETURNING *`
558
- let stored: unknown
559
- try {
560
- stored = await seeder.unsafe(statement, names.map((name) => row.get(name) ?? null))
561
- } catch (error) {
562
- throw seedLimit(error, table) ?? error
563
- }
564
- const [returned] = z.array(z.record(z.string(), z.unknown())).parse(stored)
565
- return { row, stored: returned ?? {} }
566
- }
567
-
568
- /** The columns a model's row is placed by: its own key when it owns a dimension, and each link of its chain. */
569
- function placement(model: TableModel, values: ReadonlyMap<string, string>, key: string): Map<string, SampleValue> {
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 (model.version !== undefined) {
582
- assigned.set(model.version, 1)
583
- }
584
- if (model.createdBy !== undefined) {
585
- assigned.set(model.createdBy, 'isolation-fixture')
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
- async function seedWorld(models: TableModels, model: TableModel, world: string, seed: Readonly<Record<string, SampleValue>>): Promise<WorldRow> {
591
- const markers: string[] = []
592
- const values = new Map<string, string>()
593
- const links: readonly Container[] = model.chain
594
- for (const link of links) {
595
- values.set(link.dimension, await scopeValue(model.name, link.column, link.dimension, world))
596
- }
597
- const scope = model.scope
598
- if (scope.mode !== 'dimension' && scope.mode !== 'child') {
599
- throw new Error(`${model.name} is not a dimension or child table`)
600
- }
601
- const key = await scopeValue(model.name, scope.key, scope.mode === 'dimension' ? scope.dimension : model.name, world)
602
- if (scope.mode === 'dimension') {
603
- values.set(scope.dimension, key)
604
- }
605
- // Containers first, outermost first: a composite foreign key needs its target row.
606
- for (let index = links.length - 1; index >= 0; index--) {
607
- const link = links[index]
608
- const owner = link === undefined ? undefined : ownerOf(models, link.dimension)
609
- const value = link === undefined ? undefined : values.get(link.dimension)
610
- if (owner !== undefined && owner.name !== model.name && value !== undefined) {
611
- await insert(models, owner.name, placement(owner, values, value), markers)
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
- const assigned = placement(model, values, key)
615
- for (const [name, value] of Object.entries(seed)) {
616
- const column = await columnOf(model.name, name)
617
- if (assigned.has(name)) {
618
- throw new Error(`${model.name}.${name} places the row in its scope; a seed sets only the row's own state`)
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
- if (await holdsMarker(model, model.name, column)) {
621
- throw new Error(
622
- `${model.name}.${name} holds a text marker the leak cases look for; a seed sets a column of another type (an enum, a boolean, a number), a text column a CHECK lists the values of, or a foreign key`,
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
- assigned.set(name, value)
626
- }
627
- const { row } = await insert(models, model.name, assigned, markers)
628
- const updates: Record<string, SampleValue> = {}
629
- for (const name of namesOf(model.update)) {
630
- updates[name] = row.get(name) ?? await updateSample(model.name, name)
631
- }
632
- const dimension = grantDimension(models, model)
633
- const chain = [
634
- ...(scope.mode === 'dimension' ? [{ type: scope.dimension, value: key }] : []),
635
- ...links.flatMap((link) => {
636
- const value = values.get(link.dimension)
637
- return value === undefined ? [] : [{ type: link.dimension, value }]
638
- }),
639
- ]
640
- return {
641
- key,
642
- parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
643
- scope: values.get(dimension) ?? key,
644
- chain,
645
- updates,
646
- markers,
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 = Database.postgres({ url: runtimeUrl, schema, max: RUNTIME_CONNECTIONS })
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
- refuseInProduction(MODULE)
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
  }