@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,359 @@
1
+ // Entity conformance · `updateMany([{ id, patch }])`: each row its own patch in one write, the count
2
+ // of rows it reached, all or nothing — tenant-scoped, soft-deleted rows unreachable, a JS-only rule
3
+ // judged on every row, an uneven batch refused, sealed values sealed, the change reported and one
4
+ // history version per row. Past the bind ceiling it is still one write.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Database } from '@ultimat3/entity';
8
+ import { entity, history, text } from '@ultimat3/entity';
9
+ import { remember } from './entity-conformance-entities';
10
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
11
+ import {
12
+ ledger,
13
+ logged,
14
+ loggedHistory,
15
+ notes,
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 } from './entity-driver-conformance';
22
+
23
+ /**
24
+ * Six hundred patched columns and a unique: 602 binds a row, so 200 rows are two statements. Wide
25
+ * rather than long: a `defineDriver` store sends one `update` per row, and a long batch is n² there.
26
+ */
27
+ const BROAD_COLUMNS = Array.from({ length: 600 }, (_, index) => `c${index}`);
28
+ const broad = remember(
29
+ entity('ec_um_broad', {
30
+ columns: {
31
+ id: text({ max: 20 }).primaryKey(),
32
+ u: text({ max: 20 }).unique(),
33
+ ...Object.fromEntries(BROAD_COLUMNS.map((name) => [name, text({ max: 20 })])),
34
+ },
35
+ }),
36
+ );
37
+
38
+ const uniques = remember(
39
+ entity('ec_um_uniques', {
40
+ columns: { id: text({ max: 20 }).primaryKey(), slug: text({ max: 20 }).unique() },
41
+ }),
42
+ );
43
+
44
+ const [ONE, TWO, THREE] = [idAt('d1'), idAt('d2'), idAt('d3')];
45
+ const ORG = idAt('da');
46
+ const OTHER_ORG = idAt('db');
47
+ const WHEN = new Date('2020-01-02T03:04:05.000Z');
48
+ /** Past 65,535 binds at 602 per row (key, `u`, six hundred columns): no one statement carries it. */
49
+ const PAST_CEILING = 200;
50
+
51
+ const broadRow = (id: string, value: string): Readonly<Record<string, string>> => ({
52
+ id,
53
+ u: id,
54
+ ...Object.fromEntries(BROAD_COLUMNS.map((name) => [name, value])),
55
+ });
56
+ const broadPatch = (u: string, value: string): Readonly<Record<string, string>> => ({
57
+ u,
58
+ ...Object.fromEntries(BROAD_COLUMNS.map((name) => [name, value])),
59
+ });
60
+
61
+ const seedNotes = async (db: Database<{ notes: typeof notes }>): Promise<void> => {
62
+ await db.notes.insertAll([
63
+ { id: ONE, kind: 'a', title: 'one', body: 'b1', updatedAt: WHEN },
64
+ { id: TWO, kind: 'a', title: 'two', body: 'b2', updatedAt: WHEN },
65
+ { id: THREE, kind: 'b', title: 'three', body: 'b3', updatedAt: WHEN },
66
+ ]);
67
+ };
68
+
69
+ const shape = async (db: Database<{ notes: typeof notes }>) =>
70
+ (await db.notes.orderBy('id').all()).map((row) => [row.id, row.title, row.body]);
71
+
72
+ const writes: readonly EntityDriverCheck[] = [
73
+ checkOver(
74
+ { notes },
75
+ 'updateMany writes each row its own patch, answers the count, keeps the rest',
76
+ async (db) => {
77
+ await seedNotes(db);
78
+ const written = await db.notes.updateMany([
79
+ { id: ONE, patch: { title: 'first', body: null } },
80
+ { id: THREE, patch: { title: 'third', body: 'x' } },
81
+ ]);
82
+ expect(written).toBe(2);
83
+ expect(await shape(db)).toEqual([
84
+ [ONE, 'first', null],
85
+ [TWO, 'two', 'b2'],
86
+ [THREE, 'third', 'x'],
87
+ ]);
88
+ },
89
+ ),
90
+ checkOver(
91
+ { notes },
92
+ 'updateMany counts only rows it reached; an empty batch writes nothing and answers 0',
93
+ async (db) => {
94
+ await seedNotes(db);
95
+ expect(
96
+ await db.notes.updateMany([
97
+ { id: ONE, patch: { title: 'first' } },
98
+ { id: idAt('dff'), patch: { title: 'ghost' } },
99
+ ]),
100
+ ).toBe(1);
101
+ expect(await db.notes.updateMany([])).toBe(0);
102
+ expect(await db.notes.count()).toBe(3);
103
+ expect((await shape(db)).map(([, title]) => title)).toEqual(['first', 'two', 'three']);
104
+ },
105
+ ),
106
+ checkOver(
107
+ { notes },
108
+ 'updateMany keeps a column a patch names as undefined, and stamps onUpdateNow',
109
+ async (db) => {
110
+ await seedNotes(db);
111
+ await db.notes.updateMany([
112
+ { id: ONE, patch: { title: 'first', body: undefined } },
113
+ { id: TWO, patch: { title: 'second' } },
114
+ ]);
115
+ const rows = await db.notes.orderBy('id').all();
116
+ expect(
117
+ rows.map((row) => [row.title, row.body, row.updatedAt.getTime() === WHEN.getTime()]),
118
+ ).toEqual([
119
+ ['first', 'b1', false],
120
+ ['second', 'b2', false],
121
+ ['three', 'b3', true],
122
+ ]);
123
+ },
124
+ ),
125
+ checkOver(
126
+ { notes },
127
+ 'an uneven batch, a repeated id or an empty patch is refused and writes nothing',
128
+ async (db) => {
129
+ await seedNotes(db);
130
+ const uneven = () =>
131
+ db.notes.updateMany([
132
+ { id: ONE, patch: { title: 'first' } },
133
+ { id: TWO, patch: { body: 'other' } },
134
+ ]);
135
+ expect(await codeOf(uneven)).toBe('X_INVARIANT_VIOLATED');
136
+ const twice = () =>
137
+ db.notes.updateMany([
138
+ { id: ONE, patch: { title: 'first' } },
139
+ { id: ONE, patch: { title: 'again' } },
140
+ ]);
141
+ expect(await codeOf(twice)).toBe('X_INVARIANT_VIOLATED');
142
+ expect(await codeOf(() => db.notes.updateMany([{ id: ONE, patch: {} }]))).toBe(
143
+ 'X_PATCH_EMPTY',
144
+ );
145
+ expect(await shape(db)).toEqual([
146
+ [ONE, 'one', 'b1'],
147
+ [TWO, 'two', 'b2'],
148
+ [THREE, 'three', 'b3'],
149
+ ]);
150
+ },
151
+ ),
152
+ checkOver(
153
+ { uniques },
154
+ 'two patches taking one unique value are refused; neither row moves',
155
+ async (db) => {
156
+ await db.uniques.insertAll([
157
+ { id: 'a', slug: 'one' },
158
+ { id: 'b', slug: 'two' },
159
+ ]);
160
+ const clash = () =>
161
+ db.uniques.updateMany([
162
+ { id: 'a', patch: { slug: 'same' } },
163
+ { id: 'b', patch: { slug: 'same' } },
164
+ ]);
165
+ expect(await codeOf(clash)).toBe('X_DB_UNIQUE_VIOLATION');
166
+ expect((await db.uniques.orderBy('id').all()).map((row) => row.slug)).toEqual(['one', 'two']);
167
+ },
168
+ ),
169
+ checkOver(
170
+ { uniques },
171
+ "a later patch taking an untouched row's unique value refuses the batch; no earlier row moves",
172
+ async (db) => {
173
+ await db.uniques.insertAll([
174
+ { id: 'a', slug: 'one' },
175
+ { id: 'b', slug: 'two' },
176
+ { id: 'c', slug: 'taken' },
177
+ ]);
178
+ const clash = () =>
179
+ db.uniques.updateMany([
180
+ { id: 'a', patch: { slug: 'moved' } },
181
+ { id: 'b', patch: { slug: 'taken' } },
182
+ ]);
183
+ expect(await codeOf(clash)).toBe('X_DB_UNIQUE_VIOLATION');
184
+ expect((await db.uniques.orderBy('id').all()).map((row) => row.slug)).toEqual([
185
+ 'one',
186
+ 'two',
187
+ 'taken',
188
+ ]);
189
+ },
190
+ ),
191
+ checkOver(
192
+ { broad },
193
+ 'a 200-row, 600-column updateMany past the bind ceiling lands every patch, or none of them',
194
+ async (db) => {
195
+ const ids = Array.from({ length: PAST_CEILING }, (_, index) => `r${index}`);
196
+ await db.broad.insertAll([...ids, 'z'].map((id) => broadRow(id, 'old')) as never[]);
197
+ // The LAST patch takes the stored `z`'s unique value: the refusal lands in the last statement.
198
+ const clash = ids.map((id, index) => ({
199
+ id,
200
+ patch: broadPatch(index === PAST_CEILING - 1 ? 'z' : `n${id}`, 'new'),
201
+ }));
202
+ expect(await codeOf(() => db.broad.updateMany(clash as never[]))).toBe(
203
+ 'X_DB_UNIQUE_VIOLATION',
204
+ );
205
+ expect(await db.broad.where({ c0: 'new' } as never).count()).toBe(0);
206
+ const all = ids.map((id) => ({ id, patch: broadPatch(`n${id}`, 'new') }));
207
+ expect(await db.broad.updateMany(all as never[])).toBe(PAST_CEILING);
208
+ const fresh = await db.broad.where({ c599: 'new' } as never).count();
209
+ const last = await db.broad.where({ id: `r${PAST_CEILING - 1}` }).one();
210
+ expect([fresh, (last as Record<string, unknown> | null)?.['u']]).toEqual([
211
+ PAST_CEILING,
212
+ `nr${PAST_CEILING - 1}`,
213
+ ]);
214
+ },
215
+ ),
216
+ ];
217
+
218
+ const held = async (db: Database<{ posts: typeof posts }>) =>
219
+ [
220
+ ...(await db.posts.where({ orgId: ORG }).all()),
221
+ ...(await db.posts.where({ orgId: OTHER_ORG }).all()),
222
+ ]
223
+ .map((row) => `${row.orgId === ORG ? 'ours' : 'theirs'}:${row.title}`)
224
+ .sort();
225
+
226
+ const semantics: readonly EntityDriverCheck[] = [
227
+ checkOver(
228
+ { posts },
229
+ 'updateMany reaches only the actor’s tenant: another tenant’s id is not reached',
230
+ async (db) => {
231
+ await db.posts.insertAll([
232
+ { id: ONE, orgId: ORG, title: 'same' },
233
+ { id: TWO, orgId: OTHER_ORG, title: 'same' },
234
+ ]);
235
+ const batch = [
236
+ { id: ONE, patch: { title: 'x' } },
237
+ { id: TWO, patch: { title: 'x' } },
238
+ ];
239
+ expect(await inOrg(ORG, () => db.posts.updateMany(batch))).toBe(1);
240
+ expect(await held(db)).toEqual(['ours:x', 'theirs:same']);
241
+ expect(await codeOf(() => db.posts.updateMany(batch))).toBe('X_TENANCY_UNSCOPED');
242
+ const handOver = () => db.posts.updateMany([{ id: ONE, patch: { orgId: OTHER_ORG } }]);
243
+ expect(await inOrg(ORG, () => codeOf(handOver))).toBe('X_TENANCY_ACTOR_MISMATCH');
244
+ expect(await held(db)).toEqual(['ours:x', 'theirs:same']);
245
+ },
246
+ ),
247
+ checkOver(
248
+ { swept },
249
+ 'updateMany cannot reach a soft-deleted row, and a JS-only rule refuses the batch whole',
250
+ async (db, { driver }) => {
251
+ await db.swept.insertAll([
252
+ { id: ONE, kind: 'k', reason: 'r', deletedAt: null },
253
+ { id: TWO, kind: 'k', reason: 'r', deletedAt: null },
254
+ { id: THREE, kind: 'k', reason: 'r', deletedAt: null },
255
+ ]);
256
+ await db.swept.delete(THREE);
257
+ // TWO's patch stamps it with no reason: the batch is judged whole, so ONE does not move.
258
+ const judged = () =>
259
+ db.swept.updateMany([
260
+ { id: ONE, patch: { reason: 'fine', deletedAt: null } },
261
+ { id: TWO, patch: { reason: null, deletedAt: WHEN } },
262
+ ]);
263
+ expect(await codeOf(judged)).toBe('X_INVARIANT_VIOLATED');
264
+ expect((await db.swept.orderBy('id').all()).map((row) => row.reason)).toEqual(['r', 'r']);
265
+ const revive = [
266
+ { id: ONE, patch: { reason: 'fine', deletedAt: null } },
267
+ { id: THREE, patch: { reason: 'back', deletedAt: null } },
268
+ ];
269
+ expect(await db.swept.updateMany(revive)).toBe(1);
270
+ const { rows } = await driver.repo(swept).findMany({
271
+ includeDeleted: true,
272
+ orderBy: [{ column: 'id', direction: 'asc' }],
273
+ });
274
+ expect(rows.map((row) => [row.reason, row.deletedAt === null])).toEqual([
275
+ ['fine', true],
276
+ ['r', true],
277
+ ['r', false],
278
+ ]);
279
+ },
280
+ ),
281
+ checkOver({ ledger }, 'an append-only table refuses updateMany', async (db) => {
282
+ await db.ledger.insert({ id: ONE, account: 'cash', note: 'n' });
283
+ expect(await codeOf(() => db.ledger.updateMany([{ id: ONE, patch: { note: 'x' } }]))).toBe(
284
+ 'X_ENTITY_APPEND_ONLY',
285
+ );
286
+ expect((await db.ledger.all()).map((row) => row.note)).toEqual(['n']);
287
+ }),
288
+ checkOver({ vault }, 'updateMany seals what it writes and reads back plaintext', async (db) => {
289
+ await db.vault.insertAll([
290
+ { id: ONE, label: 'a', secret: null, email: 'a@example.com' },
291
+ { id: TWO, label: 'b', secret: null, email: 'b@example.com' },
292
+ ]);
293
+ await db.vault.updateMany([
294
+ { id: ONE, patch: { secret: 's1', email: 'c@example.com' } },
295
+ { id: TWO, patch: { secret: 's2', email: 'd@example.com' } },
296
+ ]);
297
+ const rows = await db.vault.orderBy('id').all();
298
+ expect(rows.map((row) => [row.secret, row.email])).toEqual([
299
+ ['s1', 'c@example.com'],
300
+ ['s2', 'd@example.com'],
301
+ ]);
302
+ // A lookup column sealed deterministically still finds its row by the new value.
303
+ expect((await db.vault.where({ email: 'd@example.com' }).one())?.id).toBe(TWO);
304
+ }),
305
+ ];
306
+
307
+ const reported: readonly EntityDriverCheck[] = [
308
+ checkOver(
309
+ { notes },
310
+ 'updateMany is reported to the row observer for every row it wrote, never silence',
311
+ async (db) => {
312
+ await seedNotes(db);
313
+ const { answer, heard: told } = await heard('ec_wr_notes', () =>
314
+ db.notes.updateMany([
315
+ { id: ONE, patch: { title: 'x' } },
316
+ { id: TWO, patch: { title: 'y' } },
317
+ { id: idAt('dff'), patch: { title: 'ghost' } },
318
+ ]),
319
+ );
320
+ expect([answer, accountedFor(told)]).toEqual([2, 2]);
321
+ },
322
+ ),
323
+ checkOver(
324
+ { logged, loggedHistory },
325
+ 'updateMany writes one history version per row it reached',
326
+ async (db, raw) => {
327
+ if (!raw.history) return;
328
+ const versions = await inOrg(ORG, async () => {
329
+ await db.logged.insertAll([
330
+ { id: ONE, orgId: ORG, title: 'a' },
331
+ { id: TWO, orgId: ORG, title: 'b' },
332
+ ]);
333
+ await db.logged.updateMany([
334
+ { id: ONE, patch: { title: 'a2' } },
335
+ { id: TWO, patch: { title: 'b2' } },
336
+ ]);
337
+ return [await history(db.loggedHistory, ONE), await history(db.loggedHistory, TWO)];
338
+ });
339
+ const title = (image: unknown): string | null =>
340
+ (image as { title?: string } | null)?.title ?? null;
341
+ expect(versions.map((all) => all.map((v) => [v.version, v.op, title(v.after)]))).toEqual([
342
+ [
343
+ [1, 'insert', 'a'],
344
+ [2, 'update', 'a2'],
345
+ ],
346
+ [
347
+ [1, 'insert', 'b'],
348
+ [2, 'update', 'b2'],
349
+ ],
350
+ ]);
351
+ },
352
+ ),
353
+ ];
354
+
355
+ export const UPDATE_MANY_CHECKS: readonly EntityDriverCheck[] = [
356
+ ...writes,
357
+ ...semantics,
358
+ ...reported,
359
+ ];
@@ -0,0 +1,204 @@
1
+ // Entity conformance · the declared optimistic lock, `entity({ version: 'lockVersion' })`: an
2
+ // `update` naming the version it read writes only over that version and moves it, a stale one is
3
+ // `X_ENTITY_STALE` and writes nothing; a write that cannot condition on it is refused or moves it
4
+ // unconditioned, per the rule table — so no write path leaves a stale reader believing it is current.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Database, Driver } from '@ultimat3/entity';
8
+ import { entity, integer, text, timestamp, uuid } from '@ultimat3/entity';
9
+ import { remember } from './entity-conformance-entities';
10
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
11
+ import type { EntityDriverCheck } from './entity-driver-conformance';
12
+
13
+ const docs = remember(
14
+ entity('ec_vl_docs', {
15
+ columns: {
16
+ id: uuid().primaryKey(),
17
+ orgId: uuid().tenant(),
18
+ title: text({ max: 20 }),
19
+ lockVersion: integer().default(0),
20
+ deletedAt: timestamp().nullable(),
21
+ },
22
+ version: 'lockVersion',
23
+ }),
24
+ );
25
+
26
+ const SET = { docs };
27
+ type Db = Database<typeof SET>;
28
+ const [ORG, OTHER_ORG] = [idAt('7a'), idAt('7b')];
29
+ const [D1, D2, D3] = [idAt('71'), idAt('72'), idAt('73')];
30
+ const STALE = 'X_ENTITY_STALE';
31
+ const INVALID = 'X_ENTITY_VERSION_INVALID';
32
+ const RACERS = 8;
33
+
34
+ const seed = (db: Db) =>
35
+ db.docs.insertAll([
36
+ { id: D1, orgId: ORG, title: 'one' },
37
+ { id: D2, orgId: ORG, title: 'two' },
38
+ { id: D3, orgId: OTHER_ORG, title: 'theirs' },
39
+ ]);
40
+
41
+ /** Every row's `[title, version]` in id order, deleted rows included: each org read by the bare repo. */
42
+ const state = async (raw: { readonly driver: Driver }) => {
43
+ const read = (orgId: string) =>
44
+ raw.driver.repo(docs).findMany({
45
+ orgId,
46
+ includeDeleted: true,
47
+ orderBy: [{ column: 'id', direction: 'asc' }],
48
+ });
49
+ const rows = [...(await read(ORG)).rows, ...(await read(OTHER_ORG)).rows];
50
+ return rows.sort((a, b) => a.id.localeCompare(b.id)).map((row) => [row.title, row.lockVersion]);
51
+ };
52
+
53
+ const byId: readonly EntityDriverCheck[] = [
54
+ checkOver(
55
+ SET,
56
+ 'insert takes the declared default; update naming the version read moves it by one',
57
+ async (db, raw) => {
58
+ await seed(db);
59
+ await inOrg(ORG, () => db.docs.update(D1, { title: 'first', lockVersion: 0 }));
60
+ await inOrg(ORG, () => db.docs.update(D1, { title: 'second', lockVersion: 1 }));
61
+ expect(await state(raw)).toEqual([
62
+ ['second', 2],
63
+ ['two', 0],
64
+ ['theirs', 0],
65
+ ]);
66
+ },
67
+ ),
68
+ checkOver(
69
+ SET,
70
+ 'a stale version is X_ENTITY_STALE and writes nothing; an absent or foreign id is X_NOT_FOUND',
71
+ async (db, raw) => {
72
+ await seed(db);
73
+ await inOrg(ORG, () => db.docs.update(D1, { title: 'won', lockVersion: 0 }));
74
+ const answers = await inOrg(ORG, async () => [
75
+ await codeOf(() => db.docs.update(D1, { title: 'lost', lockVersion: 0 })),
76
+ await codeOf(() => db.docs.update(D1, { title: 'ahead', lockVersion: 5 })),
77
+ await codeOf(() => db.docs.update(idAt('7ff'), { title: 'ghost', lockVersion: 0 })),
78
+ await codeOf(() => db.docs.update(D3, { title: 'foreign', lockVersion: 0 })),
79
+ ]);
80
+ expect(answers).toEqual([STALE, STALE, 'X_NOT_FOUND', 'X_NOT_FOUND']);
81
+ expect(await state(raw)).toEqual([
82
+ ['won', 1],
83
+ ['two', 0],
84
+ ['theirs', 0],
85
+ ]);
86
+ },
87
+ ),
88
+ checkOver(
89
+ SET,
90
+ 'an update by id that omits the version is refused: the lock is the point',
91
+ async (db, raw) => {
92
+ await seed(db);
93
+ expect(await inOrg(ORG, () => codeOf(() => db.docs.update(D1, { title: 'blind' })))).toBe(
94
+ INVALID,
95
+ );
96
+ expect((await state(raw))[0]).toEqual(['one', 0]);
97
+ },
98
+ ),
99
+ checkOver(
100
+ SET,
101
+ `${RACERS} writers holding one version: exactly one wins, the rest are stale`,
102
+ async (db, raw) => {
103
+ await seed(db);
104
+ const answers = await inOrg(ORG, () =>
105
+ Promise.all(
106
+ Array.from({ length: RACERS }, (_, index) =>
107
+ codeOf(() => db.docs.update(D1, { title: `w${index}`, lockVersion: 0 })),
108
+ ),
109
+ ),
110
+ );
111
+ expect([...answers].sort()).toEqual([
112
+ ...Array.from({ length: RACERS - 1 }, () => STALE),
113
+ 'resolved',
114
+ ]);
115
+ const [title, version] = (await state(raw))[0] ?? [];
116
+ expect([answers[Number(String(title).slice(1))], version]).toEqual(['resolved', 1]);
117
+ },
118
+ ),
119
+ ];
120
+
121
+ const filtered: readonly EntityDriverCheck[] = [
122
+ checkOver(
123
+ SET,
124
+ 'updateWhere and chain updateAll move the version unconditioned; naming it is refused',
125
+ async (db, raw) => {
126
+ await seed(db);
127
+ await inOrg(ORG, async () => {
128
+ await db.docs.updateWhere({ id: D1 }, { title: 'a' });
129
+ await db.docs.where({ title: 'a' }).updateAll({ title: 'b' });
130
+ });
131
+ const named = await inOrg(ORG, async () => [
132
+ await codeOf(() => db.docs.updateWhere({ id: D1 }, { title: 'x', lockVersion: 9 })),
133
+ await codeOf(() => db.docs.where({ id: D1 }).updateAll({ title: 'x', lockVersion: 9 })),
134
+ ]);
135
+ expect(named).toEqual([INVALID, INVALID]);
136
+ expect(await state(raw)).toEqual([
137
+ ['b', 2],
138
+ ['two', 0],
139
+ ['theirs', 0],
140
+ ]);
141
+ },
142
+ ),
143
+ checkOver(
144
+ SET,
145
+ 'compare-and-set through the filter: a chain naming the version read writes once',
146
+ async (db, raw) => {
147
+ await seed(db);
148
+ const cas = () =>
149
+ inOrg(ORG, () => db.docs.where({ id: D1, lockVersion: 0 }).updateAll({ title: 'cas' }));
150
+ expect([await cas(), await cas()]).toEqual([1, 0]);
151
+ expect((await state(raw))[0]).toEqual(['cas', 1]);
152
+ },
153
+ ),
154
+ checkOver(SET, 'a soft delete moves the version too', async (db, raw) => {
155
+ await seed(db);
156
+ await inOrg(ORG, () => db.docs.delete(D2));
157
+ expect((await state(raw))[1]).toEqual(['two', 1]);
158
+ }),
159
+ checkOver(
160
+ SET,
161
+ 'updateMany conditions every row on its version: one stale row refuses the batch whole',
162
+ async (db, raw) => {
163
+ await seed(db);
164
+ await inOrg(ORG, () => db.docs.update(D2, { title: 'moved', lockVersion: 0 }));
165
+ const batch = (v2: number) => [
166
+ { id: D1, patch: { title: 'b1', lockVersion: 0 } },
167
+ { id: D2, patch: { title: 'b2', lockVersion: v2 } },
168
+ ];
169
+ const refusals = await inOrg(ORG, async () => [
170
+ await codeOf(() => db.docs.updateMany(batch(0))),
171
+ await codeOf(() => db.docs.updateMany([{ id: D1, patch: { title: 'blind' } }])),
172
+ ]);
173
+ expect(refusals).toEqual([STALE, INVALID]);
174
+ expect(await state(raw)).toEqual([
175
+ ['one', 0],
176
+ ['moved', 1],
177
+ ['theirs', 0],
178
+ ]);
179
+ expect(await inOrg(ORG, () => db.docs.updateMany(batch(1)))).toBe(2);
180
+ expect(await state(raw)).toEqual([
181
+ ['b1', 1],
182
+ ['b2', 2],
183
+ ['theirs', 0],
184
+ ]);
185
+ },
186
+ ),
187
+ checkOver(
188
+ SET,
189
+ 'upsertAll that would overwrite a match is refused; one that keeps it is not',
190
+ async (db, raw) => {
191
+ await seed(db);
192
+ const row = { id: D1, orgId: ORG, title: 'over', lockVersion: 0 };
193
+ const answers = await inOrg(ORG, async () => [
194
+ await codeOf(() => db.docs.upsertAll([row], { onConflict: ['id'] })),
195
+ await codeOf(() => db.docs.upsertAll([row], { onConflict: ['id'], onMatch: 'nothing' })),
196
+ ]);
197
+ expect(answers).toEqual([INVALID, 'resolved']);
198
+ expect((await state(raw))[0]).toEqual(['one', 0]);
199
+ },
200
+ ['upsert'],
201
+ ),
202
+ ];
203
+
204
+ export const VERSION_LOCK_CHECKS: readonly EntityDriverCheck[] = [...byId, ...filtered];
@@ -0,0 +1,71 @@
1
+ // The tables the many-row write checks share (chain writes, `updateMany`, the unreturned and COPY
2
+ // writes): one per concern — plain, tenant-scoped, soft-deleting under a JS-only rule, append-only,
3
+ // sealed, history-keeping. Each check re-creates the tables it names, so sharing them is free.
4
+
5
+ import { expect } from 'bun:test';
6
+ import { entity, invariant, text, timestamp, uuid } from '@ultimat3/entity';
7
+ import { remember } from './entity-conformance-entities';
8
+
9
+ export const notes = remember(
10
+ entity('ec_wr_notes', {
11
+ columns: {
12
+ id: uuid().primaryKey(),
13
+ kind: text({ max: 20 }),
14
+ title: text({ max: 40 }),
15
+ body: text({ max: 40 }).nullable(),
16
+ updatedAt: timestamp().defaultNow().onUpdateNow(),
17
+ },
18
+ }),
19
+ );
20
+
21
+ export const posts = remember(
22
+ entity('ec_wr_posts', {
23
+ columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), title: text({ max: 40 }) },
24
+ }),
25
+ );
26
+
27
+ const stampHasReason = (deletedAt: unknown, reason: unknown): boolean =>
28
+ deletedAt === null || reason !== null;
29
+
30
+ /** Soft-deleting, with a rule no CHECK can state: a stamp needs a reason. */
31
+ export const swept = remember(
32
+ entity('ec_wr_swept', {
33
+ columns: {
34
+ id: uuid().primaryKey(),
35
+ kind: text({ max: 20 }),
36
+ reason: text({ max: 40 }).nullable(),
37
+ deletedAt: timestamp().nullable(),
38
+ },
39
+ invariants: (c) => [
40
+ invariant('ec_wr_stamp_has_reason', c.satisfies(stampHasReason, ['deletedAt', 'reason'])),
41
+ ],
42
+ }),
43
+ );
44
+
45
+ export const ledger = remember(
46
+ entity('ec_wr_ledger', {
47
+ columns: { id: uuid().primaryKey(), account: text({ max: 20 }), note: text({ max: 20 }) },
48
+ appendOnly: true,
49
+ }),
50
+ );
51
+
52
+ export const vault = remember(
53
+ entity('ec_wr_vault', {
54
+ columns: {
55
+ id: uuid().primaryKey(),
56
+ label: text({ max: 20 }),
57
+ secret: text({ max: 40 }).nullable().sealed(),
58
+ email: text().sealed({ lookup: true }),
59
+ },
60
+ }),
61
+ );
62
+
63
+ export const logged = remember(
64
+ entity('ec_wr_logged', {
65
+ columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), title: text({ max: 40 }) },
66
+ history: true,
67
+ }),
68
+ );
69
+ export const loggedHistory = remember(
70
+ logged.$history ?? expect.unreachable('history: true declares a history entity'),
71
+ );
@@ -0,0 +1,40 @@
1
+ // What the many-row write checks share: the row observer heard through its two bus events, counted
2
+ // as one figure — so a write path that reports its rows as `entity.row`, as `entity.bulk` or as a
3
+ // mix is held to the one claim that matters, that none of them went unreported.
4
+
5
+ import type { EntityBulkEvent, EntityRowEvent } from '@ultimat3/core';
6
+ import { subscribe } from '@ultimat3/core';
7
+
8
+ export interface Heard {
9
+ readonly rows: readonly EntityRowEvent[];
10
+ readonly bulk: readonly EntityBulkEvent[];
11
+ }
12
+
13
+ /**
14
+ * `work`'s answer and every change the observer reported for `entity` while it ran. The two
15
+ * subscriptions are this call's own and are removed whatever `work` does — never a reset of the
16
+ * process-wide bus, which another suite in the process may be listening on.
17
+ */
18
+ export const heard = async <T>(
19
+ entity: string,
20
+ work: () => Promise<T>,
21
+ ): Promise<{ readonly answer: T; readonly heard: Heard }> => {
22
+ const rows: EntityRowEvent[] = [];
23
+ const bulk: EntityBulkEvent[] = [];
24
+ const offRow = subscribe('entity.row', (event) => {
25
+ if (event.payload.entity === entity) rows.push(event.payload);
26
+ });
27
+ const offBulk = subscribe('entity.bulk', (event) => {
28
+ if (event.payload.entity === entity) bulk.push(event.payload);
29
+ });
30
+ try {
31
+ return { answer: await work(), heard: { rows, bulk } };
32
+ } finally {
33
+ offRow();
34
+ offBulk();
35
+ }
36
+ };
37
+
38
+ /** How many written rows the observer accounted for: one per row event, `rows` per bulk event. */
39
+ export const accountedFor = ({ rows, bulk }: Heard): number =>
40
+ rows.length + bulk.reduce((sum, event) => sum + event.rows, 0);