@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,75 @@
1
+ // Entity conformance · the column matrix through the WRITE PATHS that bind rows their own way:
2
+ // `copyAll` (COPY's text format on Postgres — a tab, a newline, a backslash and the word NULL are
3
+ // its own syntax), `insertAll({ returning: false })` and `updateMany`. Every row of the matrix,
4
+ // written each way, reads back exactly what the reference `memoryDriver()` reads after `insert`.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Driver } from '@ultimat3/entity';
8
+ import { memoryDriver } from '@ultimat3/entity';
9
+ import {
10
+ idFor,
11
+ MATRIX_ROWS,
12
+ type MatrixWrite,
13
+ matrix,
14
+ matrixDb,
15
+ } from './entity-conformance-matrix';
16
+ import { checkOver } from './entity-conformance-support';
17
+ import type { EntityDriverCheck } from './entity-driver-conformance';
18
+
19
+ /** The row a keyed read answers after `insert`, on memory: what every path must read back. */
20
+ const reference = async (write: MatrixWrite) => {
21
+ const db = matrixDb(memoryDriver());
22
+ await db.rows.insert(write);
23
+ return db.rows.where({ id: write.id as string }).one();
24
+ };
25
+
26
+ /** A row naming every scalar and no array: what `updateMany` starts from. */
27
+ const base = (id: string, write: MatrixWrite): MatrixWrite => ({
28
+ id,
29
+ label: 'base',
30
+ mood: 'sad',
31
+ count: 0,
32
+ flag: false,
33
+ at: new Date('2000-01-01T00:00:00.000Z'),
34
+ rate: '0',
35
+ day: write.day,
36
+ big: '0',
37
+ data: { plan: 'base', seats: 0 },
38
+ });
39
+
40
+ type Path = (driver: Driver, write: MatrixWrite) => Promise<number>;
41
+
42
+ const PATHS: Readonly<Record<string, Path>> = {
43
+ copyAll: (driver, write) => matrixDb(driver).rows.copyAll([write]),
44
+ 'insertAll({ returning: false })': (driver, write) =>
45
+ matrixDb(driver).rows.insertAll([write], { returning: false }),
46
+ updateMany: async (driver, write) => {
47
+ const db = matrixDb(driver);
48
+ const { id, ...patch } = write;
49
+ if (id === undefined) return expect.unreachable('every matrix row is written with its id');
50
+ await db.rows.insert(base(id, write));
51
+ return db.rows.updateMany([{ id, patch }]);
52
+ },
53
+ };
54
+
55
+ const checks: readonly EntityDriverCheck[] = Object.entries(PATHS).flatMap(([path, run]) =>
56
+ Object.entries(MATRIX_ROWS).map(([name, row], index) =>
57
+ checkOver(
58
+ { matrix },
59
+ `column matrix · ${path} · ${name}: reads back what memory reads back`,
60
+ async (_db, { driver }) => {
61
+ const write = { ...row, id: idFor(index) };
62
+ const expected = await reference(write);
63
+ expect(await run(driver, write)).toBe(1);
64
+ const read = await matrixDb(driver)
65
+ .rows.where({ id: idFor(index) })
66
+ .one();
67
+ expect(read).toEqual(expected);
68
+ // Not two wrong answers agreeing: the reference holds the row as written.
69
+ expect(expected?.label).toBe(write.label);
70
+ },
71
+ ),
72
+ ),
73
+ );
74
+
75
+ export const MATRIX_WRITE_CHECKS: readonly EntityDriverCheck[] = checks;
@@ -38,7 +38,7 @@ const MOODS = ['sad', 'ok', 'happy'] as const;
38
38
  * NULL inside a row value, the one shape a driver's binary array reader has to carry a null bitmap
39
39
  * for. Every array column is nullable so one row can hold `null` for the whole column.
40
40
  */
41
- const matrix = remember(
41
+ export const matrix = remember(
42
42
  entity('ec_m_rows', {
43
43
  columns: {
44
44
  id: uuid().primaryKey(),
@@ -76,9 +76,9 @@ const matrix = remember(
76
76
  }),
77
77
  );
78
78
 
79
- type MatrixWrite = Parameters<ReturnType<typeof matrixDb>['rows']['insert']>[0];
79
+ export type MatrixWrite = Parameters<ReturnType<typeof matrixDb>['rows']['insert']>[0];
80
80
 
81
- const matrixDb = (driver: Driver) => database({ rows: matrix }, { driver });
81
+ export const matrixDb = (driver: Driver) => database({ rows: matrix }, { driver });
82
82
 
83
83
  const A = '01a12719-28e5-735e-b5bb-000000000001';
84
84
  const B = '01a12719-28e5-735e-b5bb-000000000002';
@@ -113,7 +113,7 @@ const NASTY_TEXT = [
113
113
  ] as const;
114
114
 
115
115
  /** Named, so a failure says which row of the matrix it was. */
116
- const MATRIX_ROWS: Readonly<Record<string, MatrixWrite>> = Object.freeze({
116
+ export const MATRIX_ROWS: Readonly<Record<string, MatrixWrite>> = Object.freeze({
117
117
  'every array holds two members': {
118
118
  ...SCALARS,
119
119
  label: 'full',
@@ -279,7 +279,7 @@ const matches = async (driver: Driver, id: string, column: string, member: unkno
279
279
  };
280
280
 
281
281
  /** Fixed per row so a SQL subject and the memory reference write the same key. */
282
- const idFor = (index: number): string =>
282
+ export const idFor = (index: number): string =>
283
283
  `01a12719-28e5-735e-b5bb-0000000001${String(index).padStart(2, '0')}`;
284
284
 
285
285
  /** The ratchet: a kind added to `COLUMN_KINDS` with no column here is red, for every driver. */
@@ -0,0 +1,166 @@
1
+ // Entity conformance · FILTERED aggregates: `countBy(col, { where })` counts only the rows the filter
2
+ // passes yet keeps every group the chain matched (with 0 — what makes it no `andWhere`), and
3
+ // `aggregate({ name: measure })` answers several measures, each under its own filter, over exactly
4
+ // the rows `count()` counts: a count is 0 on nothing, a sum is null, money stays money.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Database } from '@ultimat3/entity';
8
+ import { entity, integer, money, 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 reactions = remember(
14
+ entity('ec_m_reactions', {
15
+ columns: {
16
+ id: uuid().primaryKey(),
17
+ orgId: uuid().tenant(),
18
+ postId: uuid().nullable(),
19
+ kind: text({ max: 10 }),
20
+ weight: integer(),
21
+ tip: money(),
22
+ deletedAt: timestamp().nullable(),
23
+ },
24
+ }),
25
+ );
26
+
27
+ const SET = { reactions };
28
+ type Db = Database<typeof SET>;
29
+ type Reaction = typeof reactions.$row;
30
+ const [ORG, OTHER_ORG] = [idAt('9a'), idAt('9b')];
31
+ const [POST_A, POST_B, POST_C] = [idAt('9aa'), idAt('9bb'), idAt('9cc')];
32
+ const eur = (minor: number) => ({ minor, currency: 'EUR' });
33
+
34
+ const reaction = (index: number, over: Partial<Reaction>): Reaction => ({
35
+ id: idAt(9000 + index),
36
+ orgId: ORG,
37
+ postId: POST_A,
38
+ kind: 'like',
39
+ weight: 1,
40
+ tip: eur(0),
41
+ deletedAt: null,
42
+ ...over,
43
+ });
44
+
45
+ /** A: like, like, love · B: like · C: love · none: love — then a deleted love and another org's. */
46
+ const SEED: readonly Reaction[] = [
47
+ reaction(1, { weight: 2, tip: eur(100) }),
48
+ reaction(2, { weight: 3, tip: eur(50) }),
49
+ reaction(3, { kind: 'love', weight: 5, tip: eur(25) }),
50
+ reaction(4, { postId: POST_B, weight: 7 }),
51
+ reaction(5, { postId: POST_C, kind: 'love', weight: 11 }),
52
+ reaction(6, { postId: null, kind: 'love', weight: 13 }),
53
+ reaction(7, { kind: 'love', weight: 1000, deletedAt: new Date('2026-02-02T00:00:00.000Z') }),
54
+ reaction(8, { kind: 'love', weight: 1000, orgId: OTHER_ORG }),
55
+ ];
56
+
57
+ const seeded = async (db: Db): Promise<void> => {
58
+ await db.reactions.insertAll(SEED);
59
+ };
60
+
61
+ const COUNT_BY = ['aggregate:countBy'] as const;
62
+
63
+ const countBy: readonly EntityDriverCheck[] = [
64
+ checkOver(
65
+ SET,
66
+ 'countBy with a where counts the rows it passes, and keeps every matched group at 0',
67
+ async (db) => {
68
+ await seeded(db);
69
+ const loves = await inOrg(ORG, () =>
70
+ db.reactions.where({ orgId: ORG }).countBy('postId', { where: [['kind', 'eq', 'love']] }),
71
+ );
72
+ expect([...loves].sort(([a], [b]) => String(a).localeCompare(String(b)))).toEqual([
73
+ [POST_A, 1],
74
+ [POST_B, 0],
75
+ [POST_C, 1],
76
+ [null, 1],
77
+ ]);
78
+ // The chain still decides which groups exist: the filter narrows counts, never groups.
79
+ const heavy = await inOrg(ORG, () =>
80
+ db.reactions
81
+ .andWhere('postId', 'in', [POST_A, POST_B])
82
+ .countBy('postId', { where: [['weight', 'gte', 3]] }),
83
+ );
84
+ expect([heavy.get(POST_A), heavy.get(POST_B), heavy.has(POST_C)]).toEqual([2, 1, false]);
85
+ },
86
+ COUNT_BY,
87
+ ),
88
+ checkOver(
89
+ SET,
90
+ 'a countBy filter naming no column of the entity is refused, never ignored',
91
+ async (db) => {
92
+ await seeded(db);
93
+ const refused = await inOrg(ORG, () =>
94
+ codeOf(() =>
95
+ db.reactions.countBy('postId', { where: [['nope' as never, 'eq', 'x' as never]] }),
96
+ ),
97
+ );
98
+ expect(refused).toBe('X_AGGREGATE_UNSUPPORTED');
99
+ },
100
+ COUNT_BY,
101
+ ),
102
+ ];
103
+
104
+ const measures: readonly EntityDriverCheck[] = [
105
+ checkOver(
106
+ SET,
107
+ 'aggregate answers every measure under its own filter, over the rows count() counts',
108
+ async (db) => {
109
+ await seeded(db);
110
+ const answer = await inOrg(ORG, () =>
111
+ db.reactions.where({ orgId: ORG }).aggregate({
112
+ all: { fn: 'count' },
113
+ loves: { fn: 'count', where: [['kind', 'eq', 'love']] },
114
+ weight: { fn: 'sum', column: 'weight' },
115
+ loveWeight: { fn: 'sum', column: 'weight', where: [['kind', 'eq', 'love']] },
116
+ heaviest: { fn: 'max', column: 'weight', where: [['kind', 'eq', 'like']] },
117
+ tips: { fn: 'sum', column: 'tip', where: [['postId', 'eq', POST_A]] },
118
+ }),
119
+ );
120
+ expect(answer).toEqual({
121
+ all: 6,
122
+ loves: 3,
123
+ weight: '41',
124
+ loveWeight: '29',
125
+ heaviest: 7,
126
+ tips: eur(175),
127
+ });
128
+ expect(await inOrg(ORG, () => db.reactions.count())).toBe(answer.all);
129
+ },
130
+ ['aggregate:sum', 'aggregate:max'],
131
+ ),
132
+ checkOver(
133
+ SET,
134
+ 'a measure whose filter passes nothing is 0 for a count and null for the rest',
135
+ async (db) => {
136
+ await seeded(db);
137
+ const none = [['kind', 'eq', 'nope']] as const;
138
+ const answer = await inOrg(ORG, () =>
139
+ db.reactions.aggregate({
140
+ n: { fn: 'count', where: none },
141
+ sum: { fn: 'sum', column: 'weight', where: none },
142
+ avg: { fn: 'avg', column: 'weight', where: none },
143
+ min: { fn: 'min', column: 'weight', where: none },
144
+ tips: { fn: 'sum', column: 'tip', where: none },
145
+ }),
146
+ );
147
+ expect(answer).toEqual({ n: 0, sum: null, avg: null, min: null, tips: null });
148
+ },
149
+ ['aggregate:sum', 'aggregate:avg', 'aggregate:min'],
150
+ ),
151
+ checkOver(
152
+ SET,
153
+ 'counts alone need no aggregate capability; with no actor on a tenant table they are refused',
154
+ async (db) => {
155
+ await seeded(db);
156
+ const counts = {
157
+ n: { fn: 'count' },
158
+ loves: { fn: 'count', where: [['kind', 'eq', 'love']] },
159
+ } as const;
160
+ expect(await inOrg(ORG, () => db.reactions.aggregate(counts))).toEqual({ n: 6, loves: 3 });
161
+ expect(await codeOf(() => db.reactions.aggregate(counts))).toBe('X_TENANCY_UNSCOPED');
162
+ },
163
+ ),
164
+ ];
165
+
166
+ export const MEASURE_CHECKS: readonly EntityDriverCheck[] = [...countBy, ...measures];
@@ -0,0 +1,57 @@
1
+ // Entity conformance · the page BYTE bound: a page whose raw cells weigh past `MAX_PAGE_BYTES` is
2
+ // refused with `X_ENTITY_PAGE_TOO_LARGE` before it is decoded, naming the two ways out — and both
3
+ // ways out, a narrower `select()` and a smaller `limit()`, answer. Every driver, one bound.
4
+
5
+ import { expect } from 'bun:test';
6
+ import { isUltimateError } from '@ultimat3/core';
7
+ import { entity, MAX_PAGE_BYTES, text, uuid } from '@ultimat3/entity';
8
+ import { remember } from './entity-conformance-entities';
9
+ import { checkOver, idAt } from './entity-conformance-support';
10
+ import type { EntityDriverCheck } from './entity-driver-conformance';
11
+
12
+ const heavy = remember(
13
+ entity('ec_pb_heavy', {
14
+ columns: { id: uuid().primaryKey(), label: text({ max: 20 }), body: text() },
15
+ }),
16
+ );
17
+
18
+ /** Five bodies, each just over a fifth of the bound: the whole table is past it, four are not. */
19
+ const ROWS = 5;
20
+ const BODY = 'x'.repeat(Math.floor(MAX_PAGE_BYTES / ROWS) + 1024);
21
+
22
+ /** The refusal's code and fix, or what the read answered when nothing was refused. */
23
+ const refusal = async (work: () => Promise<unknown>) => {
24
+ try {
25
+ return { answered: await work() };
26
+ } catch (error) {
27
+ return isUltimateError(error)
28
+ ? { code: error.code, fix: error.fix }
29
+ : { uncoded: String(error) };
30
+ }
31
+ };
32
+
33
+ export const PAGE_BYTE_CHECKS: readonly EntityDriverCheck[] = [
34
+ checkOver(
35
+ { heavy },
36
+ 'a page past the byte bound is refused, naming select() and a limit() — and both answer',
37
+ async (db) => {
38
+ // One row per statement: the bound is on what a READ answers, not on what a write binds.
39
+ for (let index = 1; index <= ROWS; index += 1) {
40
+ await db.heavy.insert({ id: idAt(index), label: `r${index}`, body: BODY });
41
+ }
42
+ const refused = await refusal(() => db.heavy.all());
43
+ expect(refused).toMatchObject({ code: 'X_ENTITY_PAGE_TOO_LARGE' });
44
+ const fix = 'fix' in refused ? String(refused.fix) : '';
45
+ expect([fix.includes('.select('), fix.includes('.limit(')]).toEqual([true, true]);
46
+ const narrow = await db.heavy.orderBy('id').select({ id: true, label: true }).all();
47
+ expect(narrow.map((row) => row.label)).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']);
48
+ const fewer = await db.heavy
49
+ .orderBy('id')
50
+ .limit(ROWS - 1)
51
+ .all();
52
+ expect(fewer.map((row) => [row.label, row.body.length])).toEqual(
53
+ [1, 2, 3, 4].map((index) => [`r${index}`, BODY.length]),
54
+ );
55
+ },
56
+ ),
57
+ ];
@@ -206,6 +206,7 @@ const writeTenancy: readonly EntityDriverCheck[] = [
206
206
 
207
207
  const VIOLATION = 'X_DB_FOREIGN_KEY_VIOLATION';
208
208
  const [THREAD_A, THREAD_B, MISSING] = [idAt('1a'), idAt('1b'), idAt('ff')];
209
+ const THREAD_C = idAt('1c');
209
210
  const SET = { orgs, threads, comments };
210
211
  const comment = (suffix: string, over: Record<string, unknown> = {}) =>
211
212
  ({ id: idAt(suffix), orgId: ORG, threadId: THREAD_A, ...over }) as never;
@@ -293,4 +294,48 @@ const sameTenant: readonly EntityDriverCheck[] = [
293
294
  ),
294
295
  ];
295
296
 
296
- export const TENANCY_CHECKS: readonly EntityDriverCheck[] = [...writeTenancy, ...sameTenant];
297
+ /** The many-row writes (`copyAll`, the count-only insert, `updateMany`, a chain write) refuse alike. */
298
+ const sameTenantBulk: readonly EntityDriverCheck[] = [
299
+ checkOver(
300
+ SET,
301
+ 'copyAll and insertAll({ returning: false }) refuse a reference into another tenant whole',
302
+ async (db) => {
303
+ await seedThreads(db);
304
+ const batch = [comment('81'), comment('82', { threadId: THREAD_B })];
305
+ expect(await codeOf(() => db.comments.copyAll(batch))).toBe(VIOLATION);
306
+ expect(await codeOf(() => db.comments.insertAll(batch, { returning: false }))).toBe(
307
+ VIOLATION,
308
+ );
309
+ expect(await db.comments.where({ orgId: ORG }).count()).toBe(0);
310
+ expect(await db.comments.copyAll([comment('83')])).toBe(1);
311
+ },
312
+ ),
313
+ checkOver(
314
+ SET,
315
+ 'updateMany and a chain updateAll refuse moving a row onto another tenant’s parent',
316
+ async (db) => {
317
+ await seedThreads(db);
318
+ await db.threads.insert({ id: THREAD_C, orgId: ORG, title: 'c' });
319
+ await db.comments.insertAll([comment('91'), comment('92')]);
320
+ // The first patch is legal: a batch that wrote row by row would move it before refusing.
321
+ const many = () =>
322
+ db.comments.updateMany([
323
+ { id: idAt('91'), patch: { threadId: THREAD_C } },
324
+ { id: idAt('92'), patch: { threadId: THREAD_B } },
325
+ ]);
326
+ // In the actor's own org: unscoped, these are `X_TENANCY_UNSCOPED` before any reference.
327
+ expect(await inOrg(ORG, () => codeOf(many))).toBe(VIOLATION);
328
+ const chain = () =>
329
+ db.comments.where({ orgId: ORG }).updateAll({ threadId: THREAD_B } as never);
330
+ expect(await inOrg(ORG, () => codeOf(chain))).toBe(VIOLATION);
331
+ const kept = await db.comments.where({ orgId: ORG }).orderBy('id').all();
332
+ expect(kept.map((row) => row.threadId)).toEqual([THREAD_A, THREAD_A]);
333
+ },
334
+ ),
335
+ ];
336
+
337
+ export const TENANCY_CHECKS: readonly EntityDriverCheck[] = [
338
+ ...writeTenancy,
339
+ ...sameTenant,
340
+ ...sameTenantBulk,
341
+ ];