@ultimat3/testing 31.8.0 → 31.10.0

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.
@@ -0,0 +1,355 @@
1
+ // Entity conformance · the writes that answer a COUNT: `insertAll(rows, { returning: false })`,
2
+ // `upsertAll(rows, { …, returning: false })` and `copyAll(rows)`. Each one is `insertAll` without the
3
+ // rows coming back — same defaults, tenancy, sealing and judging, all or nothing, reported and
4
+ // recorded in history — so every claim below is asked of all three writers alike.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Database } from '@ultimat3/entity';
8
+ import { entity, history, text, timestamp, uuid } from '@ultimat3/entity';
9
+ import type { DriverCapability } from '@ultimat3/entity/adapter';
10
+ import { remember } from './entity-conformance-entities';
11
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
12
+ import {
13
+ ledger,
14
+ logged,
15
+ loggedHistory,
16
+ posts,
17
+ swept,
18
+ vault,
19
+ } from './entity-conformance-write-entities';
20
+ import { accountedFor, heard } from './entity-conformance-write-support';
21
+ import type { EntityDriverCheck, EntityDriverRun } from './entity-driver-conformance';
22
+
23
+ /** Every kind of column `$parse` fills: a default, a nullable and a `defaultNow()`. */
24
+ const filled = remember(
25
+ entity('ec_nr_filled', {
26
+ columns: {
27
+ id: uuid().primaryKey(),
28
+ code: text({ max: 20 }).unique(),
29
+ title: text({ max: 40 }),
30
+ label: text({ max: 20 }).default('dflt'),
31
+ note: text({ max: 40 }).nullable(),
32
+ createdAt: timestamp().defaultNow(),
33
+ },
34
+ }),
35
+ );
36
+
37
+ /** Primary key only: memory's unique check is a scan per row, and this batch is 40,000 of them. */
38
+ const wide = remember(
39
+ entity('ec_nr_wide', {
40
+ columns: { id: text({ max: 20 }).primaryKey(), label: text({ max: 20 }) },
41
+ }),
42
+ );
43
+
44
+ type Batch = readonly Readonly<Record<string, unknown>>[];
45
+ interface UpsertCount {
46
+ readonly onConflict: readonly string[];
47
+ readonly onMatch?: 'update' | 'nothing';
48
+ readonly returning: false;
49
+ }
50
+ /** The three counting writers, row-agnostic: one claim, asked of each over any table. */
51
+ interface CountingTable {
52
+ insertAll(rows: Batch, options: { readonly returning: false }): Promise<number>;
53
+ upsertAll(rows: Batch, args: UpsertCount): Promise<number>;
54
+ copyAll(rows: Batch): Promise<number>;
55
+ }
56
+ const counting = (table: unknown): CountingTable => table as CountingTable;
57
+
58
+ interface Writer {
59
+ readonly name: string;
60
+ readonly needs: readonly DriverCapability[];
61
+ /** An upsert skips a row its target already holds, so a duplicate TARGET is not its refusal. */
62
+ readonly skipsTarget: boolean;
63
+ write(table: unknown, rows: Batch): Promise<number>;
64
+ }
65
+
66
+ const WRITERS: readonly Writer[] = [
67
+ {
68
+ name: 'insertAll({ returning: false })',
69
+ needs: [],
70
+ skipsTarget: false,
71
+ write: (table, rows) => counting(table).insertAll(rows, { returning: false }),
72
+ },
73
+ {
74
+ name: 'upsertAll({ returning: false })',
75
+ needs: ['upsert'],
76
+ skipsTarget: true,
77
+ write: (table, rows) =>
78
+ counting(table).upsertAll(rows, { onConflict: ['id'], onMatch: 'nothing', returning: false }),
79
+ },
80
+ {
81
+ name: 'copyAll',
82
+ needs: [],
83
+ skipsTarget: false,
84
+ write: (table, rows) => counting(table).copyAll(rows),
85
+ },
86
+ ];
87
+
88
+ const [ONE, TWO] = [idAt('e1'), idAt('e2')];
89
+ const ORG = idAt('ea');
90
+ const OTHER_ORG = idAt('eb');
91
+ const WHEN = new Date('2020-01-02T03:04:05.000Z');
92
+ const PAST_CEILING = 40_000;
93
+
94
+ /** One check per writer: the same claim, named for the writer it was asked of. */
95
+ const each = <E extends Parameters<typeof checkOver>[0]>(
96
+ entities: E,
97
+ claim: string,
98
+ run: (db: Database<E>, raw: EntityDriverRun, writer: Writer) => Promise<void>,
99
+ only: (writer: Writer) => boolean = () => true,
100
+ ): readonly EntityDriverCheck[] =>
101
+ WRITERS.filter(only).map((writer) =>
102
+ checkOver(
103
+ entities,
104
+ `${writer.name} ${claim}`,
105
+ (db, raw) => run(db as Database<E>, raw, writer),
106
+ writer.needs,
107
+ ),
108
+ );
109
+
110
+ const stores: readonly EntityDriverCheck[] = [
111
+ ...each(
112
+ { filled },
113
+ 'answers the count and stores every row, defaults filled',
114
+ async (db, _r, w) => {
115
+ const written = await w.write(db.filled, [
116
+ { id: ONE, code: 'a', title: 't' },
117
+ { id: TWO, code: 'b', title: 'u', label: 'set', note: 'n' },
118
+ ]);
119
+ const rows = await db.filled.orderBy('code').all();
120
+ expect([written, rows.map((row) => [row.id, row.label, row.note, row.createdAt])]).toEqual([
121
+ 2,
122
+ [
123
+ [ONE, 'dflt', null, new Date()],
124
+ [TWO, 'set', 'n', new Date()],
125
+ ],
126
+ ]);
127
+ },
128
+ ),
129
+ ...each({ filled }, 'writes nothing for an empty batch and answers 0', async (db, _r, w) => {
130
+ expect(await w.write(db.filled, [])).toBe(0);
131
+ expect(await db.filled.count()).toBe(0);
132
+ }),
133
+ ...each(
134
+ { filled },
135
+ 'refuses a duplicate unique value whole, in the batch or stored',
136
+ async (db, _r, w) => {
137
+ const inBatch = [
138
+ { id: ONE, code: 'a', title: 't' },
139
+ { id: TWO, code: 'a', title: 'u' },
140
+ ];
141
+ expect(await codeOf(() => w.write(db.filled, inBatch))).toBe('X_DB_UNIQUE_VIOLATION');
142
+ expect(await db.filled.count()).toBe(0);
143
+ await db.filled.insert({ id: ONE, code: 'a', title: 'stored' });
144
+ const clash = [
145
+ { id: idAt('e3'), code: 'b', title: 'fine' },
146
+ { id: TWO, code: 'a', title: 'clash' },
147
+ ];
148
+ expect(await codeOf(() => w.write(db.filled, clash))).toBe('X_DB_UNIQUE_VIOLATION');
149
+ expect((await db.filled.all()).map((row) => row.title)).toEqual(['stored']);
150
+ },
151
+ ),
152
+ ...each(
153
+ { wide },
154
+ 'refuses a 40,000-row batch with one duplicate key whole, past the bind ceiling',
155
+ async (db, _r, w) => {
156
+ const batch = Array.from({ length: PAST_CEILING }, (_, index) => ({
157
+ id: `r${index === 35_000 ? 0 : index}`,
158
+ label: 'l',
159
+ }));
160
+ expect(await codeOf(() => w.write(db.wide, batch))).toBe('X_DB_UNIQUE_VIOLATION');
161
+ expect(await db.wide.count()).toBe(0);
162
+ },
163
+ (writer) => !writer.skipsTarget,
164
+ ),
165
+ ...each({ wide }, 'lands a 40,000-row batch whole and counts it', async (db, _r, w) => {
166
+ const batch = Array.from({ length: PAST_CEILING }, (_, index) => ({
167
+ id: `r${index}`,
168
+ label: 'l',
169
+ }));
170
+ expect(await w.write(db.wide, batch)).toBe(PAST_CEILING);
171
+ expect(await db.wide.count()).toBe(PAST_CEILING);
172
+ }),
173
+ ];
174
+
175
+ const held = async (db: Database<{ posts: typeof posts }>) =>
176
+ [
177
+ ...(await db.posts.where({ orgId: ORG }).all()),
178
+ ...(await db.posts.where({ orgId: OTHER_ORG }).all()),
179
+ ]
180
+ .map((row) => `${row.orgId === ORG ? 'ours' : 'theirs'}:${row.title}`)
181
+ .sort();
182
+
183
+ const semantics: readonly EntityDriverCheck[] = [
184
+ ...each(
185
+ { posts },
186
+ 'refuses a row in another tenant whole; the actor’s own write',
187
+ async (db, _r, w) => {
188
+ const mixed = [
189
+ { id: ONE, orgId: ORG, title: 'mine' },
190
+ { id: TWO, orgId: OTHER_ORG, title: 'theirs' },
191
+ ];
192
+ expect(await inOrg(ORG, () => codeOf(() => w.write(db.posts, mixed)))).toBe(
193
+ 'X_TENANCY_ACTOR_MISMATCH',
194
+ );
195
+ expect(await held(db)).toEqual([]);
196
+ const own = [
197
+ { id: ONE, orgId: ORG, title: 'a' },
198
+ { id: TWO, orgId: ORG, title: 'b' },
199
+ ];
200
+ expect(await inOrg(ORG, () => w.write(db.posts, own))).toBe(2);
201
+ expect(await held(db)).toEqual(['ours:a', 'ours:b']);
202
+ },
203
+ ),
204
+ ...each(
205
+ { swept },
206
+ 'judges a JS-only rule on every row and refuses the batch whole',
207
+ async (db, _r, w) => {
208
+ const batch = [
209
+ { id: ONE, kind: 'k', reason: 'fine', deletedAt: null },
210
+ { id: TWO, kind: 'k', reason: null, deletedAt: WHEN },
211
+ ];
212
+ expect(await codeOf(() => w.write(db.swept, batch))).toBe('X_INVARIANT_VIOLATED');
213
+ expect(await db.swept.count()).toBe(0);
214
+ },
215
+ ),
216
+ ...each(
217
+ { vault },
218
+ 'seals what it writes: the row reads back plaintext, found by lookup',
219
+ async (db, _r, w) => {
220
+ await w.write(db.vault, [
221
+ { id: ONE, label: 'a', secret: 's1', email: 'a@example.com' },
222
+ { id: TWO, label: 'b', secret: null, email: 'b@example.com' },
223
+ ]);
224
+ const rows = await db.vault.orderBy('id').all();
225
+ expect(rows.map((row) => [row.secret, row.email])).toEqual([
226
+ ['s1', 'a@example.com'],
227
+ [null, 'b@example.com'],
228
+ ]);
229
+ expect((await db.vault.where({ email: 'b@example.com' }).one())?.id).toBe(TWO);
230
+ },
231
+ ),
232
+ ...each(
233
+ { filled },
234
+ 'is reported to the row observer for every row it wrote',
235
+ async (db, _r, w) => {
236
+ const { answer, heard: told } = await heard('ec_nr_filled', () =>
237
+ w.write(db.filled, [
238
+ { id: ONE, code: 'a', title: 't' },
239
+ { id: TWO, code: 'b', title: 'u' },
240
+ ]),
241
+ );
242
+ expect([answer, accountedFor(told)]).toEqual([2, 2]);
243
+ },
244
+ ),
245
+ ...each({ logged, loggedHistory }, 'writes one insert version per row', async (db, raw, w) => {
246
+ if (!raw.history) return;
247
+ const versions = await inOrg(ORG, async () => {
248
+ await w.write(db.logged, [
249
+ { id: ONE, orgId: ORG, title: 'a' },
250
+ { id: TWO, orgId: ORG, title: 'b' },
251
+ ]);
252
+ return [await history(db.loggedHistory, ONE), await history(db.loggedHistory, TWO)];
253
+ });
254
+ const title = (image: unknown): string | null =>
255
+ (image as { title?: string } | null)?.title ?? null;
256
+ expect(versions.map((all) => all.map((v) => [v.version, v.op, title(v.after)]))).toEqual([
257
+ [[1, 'insert', 'a']],
258
+ [[1, 'insert', 'b']],
259
+ ]);
260
+ }),
261
+ ...each({ ledger }, 'appends to an append-only table', async (db, _r, w) => {
262
+ expect(await w.write(db.ledger, [{ id: ONE, account: 'cash', note: 'n' }])).toBe(1);
263
+ expect((await db.ledger.all()).map((row) => row.note)).toEqual(['n']);
264
+ }),
265
+ ];
266
+
267
+ const STORED = {
268
+ id: ONE,
269
+ code: 'a',
270
+ label: 'kept',
271
+ note: 'kept note',
272
+ title: 'old',
273
+ createdAt: WHEN,
274
+ };
275
+
276
+ const upserts: readonly EntityDriverCheck[] = [
277
+ checkOver(
278
+ { filled },
279
+ 'upsertAll({ returning: false }) counts the rows it wrote, overwriting only what was named',
280
+ async (db) => {
281
+ await db.filled.insert(STORED);
282
+ const incoming = [
283
+ { code: 'a', title: 'new' },
284
+ { code: 'c', title: 'fresh' },
285
+ ];
286
+ const skipped: number = await db.filled.upsertAll(incoming, {
287
+ onConflict: ['code'],
288
+ onMatch: 'nothing',
289
+ returning: false,
290
+ });
291
+ expect(skipped).toBe(1);
292
+ expect((await db.filled.where({ code: 'a' }).one())?.title).toBe('old');
293
+ const merged: number = await db.filled.upsertAll(incoming, {
294
+ onConflict: ['code'],
295
+ returning: false,
296
+ });
297
+ expect(merged).toBe(2);
298
+ const rows = await db.filled.orderBy('code').all();
299
+ expect(rows.map((row) => [row.code, row.title, row.label, row.note, row.createdAt])).toEqual([
300
+ ['a', 'new', 'kept', 'kept note', WHEN],
301
+ ['c', 'fresh', 'dflt', null, new Date()],
302
+ ]);
303
+ },
304
+ ['upsert'],
305
+ ),
306
+ checkOver(
307
+ { swept },
308
+ 'upsertAll({ returning: false }) judges the merged row: a broken JS-only rule is refused',
309
+ async (db, { driver }) => {
310
+ await db.swept.insert({ id: ONE, kind: 'k', reason: 'because', deletedAt: null });
311
+ await db.swept.delete(ONE);
312
+ const merge = () =>
313
+ db.swept.upsertAll([{ id: ONE, kind: 'k', reason: null }], {
314
+ onConflict: ['id'],
315
+ returning: false,
316
+ });
317
+ expect(await codeOf(merge)).toBe('X_INVARIANT_VIOLATED');
318
+ const { rows } = await driver.repo(swept).findMany({ includeDeleted: true });
319
+ expect(rows.map((row) => [row.reason, row.deletedAt === null])).toEqual([['because', false]]);
320
+ },
321
+ ['upsert'],
322
+ ),
323
+ checkOver(
324
+ { ledger },
325
+ 'upsertAll({ returning: false }) on an append-only table is refused when it would update',
326
+ async (db) => {
327
+ await db.ledger.insert({ id: ONE, account: 'cash', note: 'n' });
328
+ const rewrite = () =>
329
+ db.ledger.upsertAll([{ id: ONE, account: 'cash', note: 'x' }], {
330
+ onConflict: ['id'],
331
+ returning: false,
332
+ });
333
+ expect(await codeOf(rewrite)).toBe('X_ENTITY_APPEND_ONLY');
334
+ expect((await db.ledger.all()).map((row) => row.note)).toEqual(['n']);
335
+ },
336
+ ['upsert'],
337
+ ),
338
+ checkOver(
339
+ { filled },
340
+ 'copyAll and insertAll({ returning: false }) answer a number, never rows',
341
+ async (db) => {
342
+ const inserted: number = await db.filled.insertAll([{ code: 'a', title: 't' }], {
343
+ returning: false,
344
+ });
345
+ const copied: number = await db.filled.copyAll([{ code: 'b', title: 'u' }]);
346
+ expect([inserted, copied, await db.filled.count()]).toEqual([1, 1, 2]);
347
+ },
348
+ ),
349
+ ];
350
+
351
+ export const UNRETURNED_CHECKS: readonly EntityDriverCheck[] = [
352
+ ...stores,
353
+ ...semantics,
354
+ ...upserts,
355
+ ];