@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.8.0",
3
+ "version": "31.10.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,26 +47,26 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.8.0",
51
- "@ultimat3/ai": "31.8.0",
52
- "@ultimat3/auth": "31.8.0",
53
- "@ultimat3/cache": "31.8.0",
54
- "@ultimat3/core": "31.8.0",
55
- "@ultimat3/db": "31.8.0",
56
- "@ultimat3/entity": "31.8.0",
57
- "@ultimat3/http": "31.8.0",
58
- "@ultimat3/i18n": "31.8.0",
59
- "@ultimat3/jobs": "31.8.0",
60
- "@ultimat3/mail": "31.8.0",
61
- "@ultimat3/notify": "31.8.0",
62
- "@ultimat3/policy": "31.8.0",
63
- "@ultimat3/pwa": "31.8.0",
64
- "@ultimat3/query": "31.8.0",
65
- "@ultimat3/realtime": "31.8.0",
66
- "@ultimat3/render": "31.8.0",
67
- "@ultimat3/schema": "31.8.0",
68
- "@ultimat3/scraping": "31.8.0",
69
- "@ultimat3/seo": "31.8.0",
70
- "@ultimat3/time": "31.8.0"
50
+ "@ultimat3/action": "31.10.0",
51
+ "@ultimat3/ai": "31.10.0",
52
+ "@ultimat3/auth": "31.10.0",
53
+ "@ultimat3/cache": "31.10.0",
54
+ "@ultimat3/core": "31.10.0",
55
+ "@ultimat3/db": "31.10.0",
56
+ "@ultimat3/entity": "31.10.0",
57
+ "@ultimat3/http": "31.10.0",
58
+ "@ultimat3/i18n": "31.10.0",
59
+ "@ultimat3/jobs": "31.10.0",
60
+ "@ultimat3/mail": "31.10.0",
61
+ "@ultimat3/notify": "31.10.0",
62
+ "@ultimat3/policy": "31.10.0",
63
+ "@ultimat3/pwa": "31.10.0",
64
+ "@ultimat3/query": "31.10.0",
65
+ "@ultimat3/realtime": "31.10.0",
66
+ "@ultimat3/render": "31.10.0",
67
+ "@ultimat3/schema": "31.10.0",
68
+ "@ultimat3/scraping": "31.10.0",
69
+ "@ultimat3/seo": "31.10.0",
70
+ "@ultimat3/time": "31.10.0"
71
71
  }
72
72
  }
@@ -40,6 +40,25 @@ export const AUTH_ADAPTER_SESSION_CHECKS: readonly AuthAdapterCheck[] = [
40
40
  expect(await adapter.updateSession(idOf('nobody'), { lastSeenAt: at(1) })).toBeNull();
41
41
  },
42
42
  },
43
+ {
44
+ // The one-round-trip read `authenticate` prefers. Optional on the seam, so an adapter without
45
+ // it passes here and `authenticate` falls back to the two reads this compares against.
46
+ name: 'getSessionWithUser answers exactly what getSession then findUserById answer',
47
+ async run({ adapter }) {
48
+ if (adapter.getSessionWithUser === undefined) return;
49
+ const owner = await seedUser(adapter, { orgId: crypto.randomUUID(), roles: ['editor'] });
50
+ await adapter.updateUser(owner, { disabledAt: at(5), scopes: ['tenancy:cross'] });
51
+ const row = session(owner);
52
+ await adapter.createSession(row);
53
+ const separately: unknown = {
54
+ session: await adapter.getSession(row.id),
55
+ user: await adapter.findUserById(owner),
56
+ };
57
+ expect<unknown>(await adapter.getSessionWithUser(row.id)).toEqual(separately);
58
+ expect((await adapter.getSessionWithUser(row.id))?.session).toEqual(row);
59
+ expect(await adapter.getSessionWithUser(idOf('nobody'))).toBeNull();
60
+ },
61
+ },
43
62
  {
44
63
  name: `${DELETERS} concurrent deletes of one session: exactly one answers true`,
45
64
  async run({ adapter }) {
@@ -0,0 +1,350 @@
1
+ // Entity conformance · the WRITE TERMINALS of the read chain: `db.x.where(…).updateAll(patch)` and
2
+ // `.deleteAll()` write exactly the rows the same chain reads — tenant-scoped as the read, soft delete
3
+ // and append-only honoured, a JS-only rule judged before anything stays, sealed values sealed, the
4
+ // change reported, history recorded — and an empty predicate is refused, never every row.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Database } from '@ultimat3/entity';
8
+ import { history } from '@ultimat3/entity';
9
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
10
+ import {
11
+ ledger,
12
+ logged,
13
+ loggedHistory,
14
+ notes,
15
+ posts,
16
+ swept,
17
+ vault,
18
+ } from './entity-conformance-write-entities';
19
+ import { accountedFor, heard } from './entity-conformance-write-support';
20
+ import type { EntityDriverCheck } from './entity-driver-conformance';
21
+
22
+ const [ONE, TWO, THREE] = [idAt('c1'), idAt('c2'), idAt('c3')];
23
+ const ORG = idAt('ca');
24
+ const OTHER_ORG = idAt('cb');
25
+ const WHEN = new Date('2020-01-02T03:04:05.000Z');
26
+ const UNFILTERED = 'X_WRITE_UNFILTERED';
27
+
28
+ const seedNotes = async (db: Database<{ notes: typeof notes }>): Promise<void> => {
29
+ await db.notes.insertAll([
30
+ { id: ONE, kind: 'a', title: 'one', body: 'b1', updatedAt: WHEN },
31
+ { id: TWO, kind: 'a', title: 'two', body: 'b2', updatedAt: WHEN },
32
+ { id: THREE, kind: 'b', title: 'three', body: 'b3', updatedAt: WHEN },
33
+ ]);
34
+ };
35
+
36
+ const titles = async (db: Database<{ notes: typeof notes }>) =>
37
+ (await db.notes.orderBy('id').all()).map((row) => [row.id, row.title, row.body]);
38
+
39
+ const terminals: readonly EntityDriverCheck[] = [
40
+ checkOver(
41
+ { notes },
42
+ 'chain updateAll writes the rows the chain reads, answers their count, keeps the rest',
43
+ async (db) => {
44
+ await seedNotes(db);
45
+ expect(await db.notes.where({ kind: 'a' }).updateAll({ title: 'swept' })).toBe(2);
46
+ expect(await titles(db)).toEqual([
47
+ [ONE, 'swept', 'b1'],
48
+ [TWO, 'swept', 'b2'],
49
+ [THREE, 'three', 'b3'],
50
+ ]);
51
+ },
52
+ ),
53
+ checkOver(
54
+ { notes },
55
+ 'chain updateAll and deleteAll over an in-list reach those ids',
56
+ async (db) => {
57
+ await seedNotes(db);
58
+ expect(await db.notes.andWhere('id', 'in', [ONE, THREE]).updateAll({ body: null })).toBe(2);
59
+ expect(await titles(db)).toEqual([
60
+ [ONE, 'one', null],
61
+ [TWO, 'two', 'b2'],
62
+ [THREE, 'three', null],
63
+ ]);
64
+ expect(await db.notes.andWhere('id', 'in', [ONE, THREE, idAt('cf')]).deleteAll()).toBe(2);
65
+ expect(await titles(db)).toEqual([[TWO, 'two', 'b2']]);
66
+ },
67
+ ),
68
+ checkOver(
69
+ { notes },
70
+ 'chain updateAll keeps a column the patch names as undefined, and stamps onUpdateNow',
71
+ async (db) => {
72
+ await seedNotes(db);
73
+ expect(await db.notes.where({ id: ONE }).updateAll({ title: 'moved', body: undefined })).toBe(
74
+ 1,
75
+ );
76
+ const row = await db.notes.where({ id: ONE }).one();
77
+ expect([row?.title, row?.body, row?.updatedAt.getTime() === WHEN.getTime()]).toEqual([
78
+ 'moved',
79
+ 'b1',
80
+ false,
81
+ ]);
82
+ },
83
+ ),
84
+ checkOver(
85
+ { notes },
86
+ 'an empty chain is refused, never every row; an empty patch is refused',
87
+ async (db) => {
88
+ await seedNotes(db);
89
+ const refusals = await Promise.all([
90
+ codeOf(() => db.notes.where({}).updateAll({ title: 'all' })),
91
+ codeOf(() => db.notes.where({}).deleteAll()),
92
+ codeOf(() => db.notes.where({ id: undefined }).deleteAll()),
93
+ codeOf(() => db.notes.where({ kind: 'a' }).updateAll({})),
94
+ ]);
95
+ expect(refusals).toEqual([UNFILTERED, UNFILTERED, UNFILTERED, 'X_PATCH_EMPTY']);
96
+ expect(await db.notes.count()).toBe(3);
97
+ expect((await titles(db)).map(([, title]) => title)).toEqual(['one', 'two', 'three']);
98
+ },
99
+ ),
100
+ checkOver(
101
+ { notes },
102
+ 'a write chain with a page — limit() or after() — is refused; an order is not a page',
103
+ async (db) => {
104
+ await seedNotes(db);
105
+ const paged = await Promise.all([
106
+ codeOf(() => db.notes.where({ kind: 'a' }).limit(1).updateAll({ title: 'x' })),
107
+ codeOf(() => db.notes.where({ kind: 'a' }).limit(1).deleteAll()),
108
+ codeOf(() => db.notes.where({ kind: 'a' }).after('cursor').deleteAll()),
109
+ ]);
110
+ expect(paged).toEqual([
111
+ 'X_INVARIANT_VIOLATED',
112
+ 'X_INVARIANT_VIOLATED',
113
+ 'X_INVARIANT_VIOLATED',
114
+ ]);
115
+ expect(await db.notes.count()).toBe(3);
116
+ expect(await db.notes.where({ kind: 'a' }).orderBy('title', 'desc').deleteAll()).toBe(2);
117
+ expect(await db.notes.count()).toBe(1);
118
+ },
119
+ ),
120
+ checkOver({ notes }, 'a chain matching no row writes nothing and answers 0', async (db) => {
121
+ await seedNotes(db);
122
+ expect(await db.notes.where({ kind: 'none' }).updateAll({ title: 'x' })).toBe(0);
123
+ expect(await db.notes.where({ kind: 'none' }).deleteAll()).toBe(0);
124
+ expect(await db.notes.count()).toBe(3);
125
+ }),
126
+ ];
127
+
128
+ const held = async (db: Database<{ posts: typeof posts }>) =>
129
+ [
130
+ ...(await db.posts.where({ orgId: ORG }).all()),
131
+ ...(await db.posts.where({ orgId: OTHER_ORG }).all()),
132
+ ]
133
+ .map((row) => `${row.orgId === ORG ? 'ours' : 'theirs'}:${row.title}`)
134
+ .sort();
135
+
136
+ const tenancy: readonly EntityDriverCheck[] = [
137
+ checkOver(
138
+ { posts },
139
+ 'chain updateAll and deleteAll reach only the actor’s tenant, as the chain’s read does',
140
+ async (db) => {
141
+ await db.posts.insertAll([
142
+ { id: ONE, orgId: ORG, title: 'same' },
143
+ { id: TWO, orgId: OTHER_ORG, title: 'same' },
144
+ ]);
145
+ expect(
146
+ await inOrg(ORG, () => db.posts.where({ title: 'same' }).updateAll({ title: 'x' })),
147
+ ).toBe(1);
148
+ expect(await held(db)).toEqual(['ours:x', 'theirs:same']);
149
+ expect(
150
+ await inOrg(ORG, () => db.posts.andWhere('title', 'in', ['x', 'same']).deleteAll()),
151
+ ).toBe(1);
152
+ expect(await held(db)).toEqual(['theirs:same']);
153
+ },
154
+ ),
155
+ checkOver(
156
+ { posts },
157
+ 'a chain the read refuses — no request, another tenant named — refuses the write alike',
158
+ async (db) => {
159
+ await db.posts.insertAll([
160
+ { id: ONE, orgId: ORG, title: 'same' },
161
+ { id: TWO, orgId: OTHER_ORG, title: 'same' },
162
+ ]);
163
+ const unscoped = db.posts.where({ title: 'same' });
164
+ const foreign = db.posts.where({ orgId: OTHER_ORG });
165
+ const answers = [
166
+ await codeOf(() => unscoped.all()),
167
+ await codeOf(() => unscoped.updateAll({ title: 'x' })),
168
+ await codeOf(() => unscoped.deleteAll()),
169
+ await inOrg(ORG, () => codeOf(() => foreign.all())),
170
+ await inOrg(ORG, () => codeOf(() => foreign.updateAll({ title: 'x' }))),
171
+ await inOrg(ORG, () => codeOf(() => foreign.deleteAll())),
172
+ ];
173
+ expect(answers).toEqual([
174
+ 'X_TENANCY_UNSCOPED',
175
+ 'X_TENANCY_UNSCOPED',
176
+ 'X_TENANCY_UNSCOPED',
177
+ 'X_TENANCY_ACTOR_MISMATCH',
178
+ 'X_TENANCY_ACTOR_MISMATCH',
179
+ 'X_TENANCY_ACTOR_MISMATCH',
180
+ ]);
181
+ expect(await held(db)).toEqual(['ours:same', 'theirs:same']);
182
+ },
183
+ ),
184
+ checkOver(
185
+ { posts },
186
+ 'a chain updateAll handing rows to another tenant is refused, matched or not',
187
+ async (db) => {
188
+ await db.posts.insert({ id: ONE, orgId: ORG, title: 'same' });
189
+ for (const title of ['same', 'none']) {
190
+ const move = () => db.posts.where({ title }).updateAll({ orgId: OTHER_ORG });
191
+ expect([title, await inOrg(ORG, () => codeOf(move))]).toEqual([
192
+ title,
193
+ 'X_TENANCY_ACTOR_MISMATCH',
194
+ ]);
195
+ }
196
+ expect(await held(db)).toEqual(['ours:same']);
197
+ },
198
+ ),
199
+ ];
200
+
201
+ const semantics: readonly EntityDriverCheck[] = [
202
+ checkOver(
203
+ { swept },
204
+ 'chain deleteAll soft-deletes; chain updateAll cannot reach a soft-deleted row',
205
+ async (db, { driver }) => {
206
+ await db.swept.insertAll([
207
+ { id: ONE, kind: 'k', reason: 'r', deletedAt: null },
208
+ { id: TWO, kind: 'k', reason: 'r', deletedAt: null },
209
+ ]);
210
+ expect(await db.swept.where({ id: ONE }).deleteAll()).toBe(1);
211
+ expect(await db.swept.where({ kind: 'k' }).updateAll({ reason: 'later' })).toBe(1);
212
+ const { rows } = await driver.repo(swept).findMany({
213
+ includeDeleted: true,
214
+ orderBy: [{ column: 'id', direction: 'asc' }],
215
+ });
216
+ expect(rows.map((row) => [row.id, row.reason, row.deletedAt === null])).toEqual([
217
+ [ONE, 'r', false],
218
+ [TWO, 'later', true],
219
+ ]);
220
+ },
221
+ ),
222
+ checkOver(
223
+ { swept },
224
+ 'a chain write breaking a JS-only rule on one row is refused as one; no row moves',
225
+ async (db) => {
226
+ await db.swept.insertAll([
227
+ { id: ONE, kind: 'k', reason: 'fine', deletedAt: null },
228
+ { id: TWO, kind: 'k', reason: null, deletedAt: null },
229
+ ]);
230
+ const stamp = () => db.swept.where({ kind: 'k' }).updateAll({ deletedAt: WHEN });
231
+ expect(await codeOf(stamp)).toBe('X_INVARIANT_VIOLATED');
232
+ expect(await codeOf(() => db.swept.where({ kind: 'k' }).deleteAll())).toBe(
233
+ 'X_INVARIANT_VIOLATED',
234
+ );
235
+ expect((await db.swept.orderBy('id').all()).map((row) => row.reason)).toEqual(['fine', null]);
236
+ },
237
+ ),
238
+ checkOver(
239
+ { ledger },
240
+ 'an append-only table refuses chain updateAll and deleteAll',
241
+ async (db) => {
242
+ await db.ledger.insert({ id: ONE, account: 'cash', note: 'n' });
243
+ expect(
244
+ await codeOf(() => db.ledger.where({ account: 'cash' }).updateAll({ note: 'x' })),
245
+ ).toBe('X_ENTITY_APPEND_ONLY');
246
+ expect(await codeOf(() => db.ledger.where({ account: 'cash' }).deleteAll())).toBe(
247
+ 'X_ENTITY_APPEND_ONLY',
248
+ );
249
+ expect((await db.ledger.all()).map((row) => row.note)).toEqual(['n']);
250
+ },
251
+ ),
252
+ checkOver(
253
+ { vault },
254
+ 'a chain updateAll seals what it writes, filters on a lookup column, refuses a sealed one',
255
+ async (db) => {
256
+ await db.vault.insertAll([
257
+ { id: ONE, label: 'a', secret: null, email: 'a@example.com' },
258
+ { id: TWO, label: 'b', secret: null, email: 'b@example.com' },
259
+ ]);
260
+ expect(
261
+ await db.vault.where({ email: 'a@example.com' }).updateAll({ secret: 'hunter2' }),
262
+ ).toBe(1);
263
+ const [one, two] = await db.vault.orderBy('id').all();
264
+ expect([one?.secret, two?.secret]).toEqual(['hunter2', null]);
265
+ // `secret` is sealed and not a lookup: no predicate may name it, on a write as on a read.
266
+ const named = db.vault.where({ secret: 'hunter2' } as never);
267
+ expect(await codeOf(() => named.updateAll({ label: 'x' }))).toBe('X_ENTITY_SEALED_PREDICATE');
268
+ expect(await codeOf(() => named.deleteAll())).toBe('X_ENTITY_SEALED_PREDICATE');
269
+ expect(await db.vault.count()).toBe(2);
270
+ },
271
+ ),
272
+ ];
273
+
274
+ const reported: readonly EntityDriverCheck[] = [
275
+ checkOver(
276
+ { notes },
277
+ 'a chain write is reported to the row observer as the count it wrote, never silence',
278
+ async (db) => {
279
+ await seedNotes(db);
280
+ const update = await heard('ec_wr_notes', () =>
281
+ db.notes.where({ kind: 'a' }).updateAll({ title: 'x' }),
282
+ );
283
+ const nothing = await heard('ec_wr_notes', () =>
284
+ db.notes.where({ kind: 'none' }).updateAll({ title: 'x' }),
285
+ );
286
+ const remove = await heard('ec_wr_notes', () => db.notes.where({ kind: 'a' }).deleteAll());
287
+ expect([update.answer, accountedFor(update.heard)]).toEqual([2, 2]);
288
+ expect(update.heard.bulk).toEqual([{ entity: 'ec_wr_notes', op: 'update', rows: 2 }]);
289
+ expect([nothing.answer, accountedFor(nothing.heard)]).toEqual([0, 0]);
290
+ expect([remove.answer, accountedFor(remove.heard)]).toEqual([2, 2]);
291
+ expect(remove.heard.bulk).toEqual([{ entity: 'ec_wr_notes', op: 'delete', rows: 2 }]);
292
+ },
293
+ ),
294
+ checkOver(
295
+ { logged, loggedHistory },
296
+ 'a chain updateAll and deleteAll each write one history version per row',
297
+ async (db, raw) => {
298
+ // A `defineDriver` store records no history (`EntityDriverSubject.history`): no claim to hold.
299
+ if (!raw.history) return;
300
+ const versions = await inOrg(ORG, async () => {
301
+ await db.logged.insertAll([
302
+ { id: ONE, orgId: ORG, title: 'a' },
303
+ { id: TWO, orgId: ORG, title: 'a' },
304
+ ]);
305
+ await db.logged.where({ title: 'a' }).updateAll({ title: 'b' });
306
+ await db.logged.where({ id: ONE }).deleteAll();
307
+ return [await history(db.loggedHistory, ONE), await history(db.loggedHistory, TWO)];
308
+ });
309
+ const title = (image: unknown): string | null =>
310
+ (image as { title?: string } | null)?.title ?? null;
311
+ expect(
312
+ versions.map((all) => all.map((v) => [v.op, title(v.before), title(v.after)])),
313
+ ).toEqual([
314
+ [
315
+ ['insert', null, 'a'],
316
+ ['update', 'a', 'b'],
317
+ ['delete', 'b', null],
318
+ ],
319
+ [
320
+ ['insert', null, 'a'],
321
+ ['update', 'a', 'b'],
322
+ ],
323
+ ]);
324
+ },
325
+ ),
326
+ checkOver(
327
+ { notes },
328
+ 'a chain write inside a transaction that fails is undone with it',
329
+ async (db, { driver }) => {
330
+ await seedNotes(db);
331
+ const failed = await codeOf(() =>
332
+ driver.transactor().run(async () => {
333
+ await db.notes.where({ kind: 'a' }).updateAll({ title: 'gone' });
334
+ await db.notes.where({ kind: 'b' }).deleteAll();
335
+ await db.notes.insert({ id: ONE, kind: 'dup', title: 'dup' });
336
+ }),
337
+ );
338
+ expect(failed).toBe('X_DB_UNIQUE_VIOLATION');
339
+ expect((await titles(db)).map(([, title]) => title)).toEqual(['one', 'two', 'three']);
340
+ },
341
+ ['transactions'],
342
+ ),
343
+ ];
344
+
345
+ export const CHAIN_WRITE_CHECKS: readonly EntityDriverCheck[] = [
346
+ ...terminals,
347
+ ...tenancy,
348
+ ...semantics,
349
+ ...reported,
350
+ ];
@@ -4,12 +4,23 @@
4
4
  import { AGGREGATE_CHECKS } from './entity-conformance-aggregates';
5
5
  import { BATCH_CHECKS } from './entity-conformance-batches';
6
6
  import { BULK_CHECKS } from './entity-conformance-bulk';
7
+ import { CHAIN_WRITE_CHECKS } from './entity-conformance-chain-writes';
8
+ import { CONTAINS_CHECKS } from './entity-conformance-contains';
9
+ import { COUNTED_IN_CHECKS } from './entity-conformance-counted-in';
7
10
  import { HISTORY_CHECKS } from './entity-conformance-history';
11
+ import { LATEST_BY_CHECKS } from './entity-conformance-latest-by';
12
+ import { LOCK_KEYS_CHECKS } from './entity-conformance-lock-keys';
8
13
  import { LOCK_CHECKS } from './entity-conformance-locks';
9
14
  import { MATRIX_CHECKS } from './entity-conformance-matrix';
15
+ import { MATRIX_WRITE_CHECKS } from './entity-conformance-matrix-writes';
16
+ import { MEASURE_CHECKS } from './entity-conformance-measures';
17
+ import { PAGE_BYTE_CHECKS } from './entity-conformance-page-bytes';
10
18
  import { READ_CHECKS } from './entity-conformance-reads';
11
19
  import { TENANCY_CHECKS } from './entity-conformance-tenancy';
20
+ import { UNRETURNED_CHECKS } from './entity-conformance-unreturned';
21
+ import { UPDATE_MANY_CHECKS } from './entity-conformance-update-many';
12
22
  import { VALUE_CHECKS } from './entity-conformance-values';
23
+ import { VERSION_LOCK_CHECKS } from './entity-conformance-version-lock';
13
24
  import { VERSION_CHECKS } from './entity-conformance-versions';
14
25
  import { WRITE_CHECKS } from './entity-conformance-writes';
15
26
  import type { EntityDriverCheck } from './entity-driver-conformance';
@@ -18,12 +29,23 @@ export const ENTITY_DRIVER_CHECKS: readonly EntityDriverCheck[] = [
18
29
  ...WRITE_CHECKS,
19
30
  ...VALUE_CHECKS,
20
31
  ...READ_CHECKS,
32
+ ...PAGE_BYTE_CHECKS,
21
33
  ...BULK_CHECKS,
34
+ ...CHAIN_WRITE_CHECKS,
35
+ ...UPDATE_MANY_CHECKS,
36
+ ...UNRETURNED_CHECKS,
22
37
  ...AGGREGATE_CHECKS,
38
+ ...MEASURE_CHECKS,
39
+ ...CONTAINS_CHECKS,
23
40
  ...TENANCY_CHECKS,
24
41
  ...BATCH_CHECKS,
42
+ ...LATEST_BY_CHECKS,
25
43
  ...LOCK_CHECKS,
44
+ ...LOCK_KEYS_CHECKS,
26
45
  ...MATRIX_CHECKS,
46
+ ...MATRIX_WRITE_CHECKS,
27
47
  ...VERSION_CHECKS,
48
+ ...VERSION_LOCK_CHECKS,
28
49
  ...HISTORY_CHECKS,
50
+ ...COUNTED_IN_CHECKS,
29
51
  ];
@@ -0,0 +1,145 @@
1
+ // Entity conformance · `contains` on a text column: a case-insensitive substring, over a table whose
2
+ // `gin_trgm_ops` index the migration builds (`pg_trgm` created first). `%`, `_` and `\` are found as
3
+ // themselves, never wildcards; a term that is no string matches nothing; a sealed column refuses it;
4
+ // and `contains` on an array column still means containment, decided by the column's kind.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Database } from '@ultimat3/entity';
8
+ import { arrayOf, entity, text, 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 titles = remember(
14
+ entity('ec_tc_titles', {
15
+ columns: {
16
+ id: uuid().primaryKey(),
17
+ orgId: uuid().tenant(),
18
+ title: text({ max: 40 }),
19
+ note: text({ max: 40 }).nullable(),
20
+ secret: text({ max: 40 }).sealed(),
21
+ tags: arrayOf(text({ max: 10 })),
22
+ },
23
+ indexes: [
24
+ { on: ['title'], using: 'gin', operatorClass: 'gin_trgm_ops' },
25
+ { on: ['note'], using: 'gin', operatorClass: 'gin_trgm_ops' },
26
+ ],
27
+ }),
28
+ );
29
+
30
+ const SET = { titles };
31
+ type Db = Database<typeof SET>;
32
+ const ORG = idAt('a1');
33
+
34
+ const seed = async (db: Db, rows: readonly (readonly [string, string | null])[]) => {
35
+ await db.titles.insertAll(
36
+ rows.map(([title, note], index) => ({
37
+ id: idAt(`a${100 + index}`),
38
+ orgId: ORG,
39
+ title,
40
+ note,
41
+ secret: 's',
42
+ tags: [title.slice(0, 10)],
43
+ })),
44
+ );
45
+ };
46
+
47
+ /** The titles `contains` finds on `column`, sorted so no driver's order is asserted. */
48
+ const found = async (db: Db, column: 'title' | 'note', term: unknown) =>
49
+ (
50
+ await inOrg(ORG, () =>
51
+ db.titles
52
+ .where({ orgId: ORG })
53
+ .andWhere(column, 'contains', term as string)
54
+ .all(),
55
+ )
56
+ )
57
+ .map((row) => row.title)
58
+ .sort();
59
+
60
+ const checks: readonly EntityDriverCheck[] = [
61
+ checkOver(SET, 'text contains finds a substring in any ASCII case', async (db) => {
62
+ await seed(db, [
63
+ ['Hello World', null],
64
+ ['HELLO', null],
65
+ ['say hello!', null],
66
+ ['help', null],
67
+ ]);
68
+ expect([
69
+ await found(db, 'title', 'hello'),
70
+ await found(db, 'title', 'LLO w'),
71
+ await found(db, 'title', 'xyz'),
72
+ ]).toEqual([['HELLO', 'Hello World', 'say hello!'], ['Hello World'], []]);
73
+ }),
74
+ checkOver(
75
+ SET,
76
+ 'text contains folds a non-ASCII letter’s case as every driver does',
77
+ async (db) => {
78
+ await seed(db, [
79
+ ['École', null],
80
+ ['ÉCOLE', null],
81
+ ['STRASSE', null],
82
+ ]);
83
+ expect([await found(db, 'title', 'école'), await found(db, 'title', 'É')]).toEqual([
84
+ ['ÉCOLE', 'École'],
85
+ ['ÉCOLE', 'École'],
86
+ ]);
87
+ },
88
+ ),
89
+ checkOver(
90
+ SET,
91
+ 'text contains finds %, _ and \\ as themselves, never as wildcards',
92
+ async (db) => {
93
+ await seed(db, [
94
+ ['100%', null],
95
+ ['100 percent', null],
96
+ ['a_b', null],
97
+ ['axb', null],
98
+ ['back\\slash', null],
99
+ ['backslash', null],
100
+ ]);
101
+ expect([
102
+ await found(db, 'title', '%'),
103
+ await found(db, 'title', '0%'),
104
+ await found(db, 'title', '_'),
105
+ await found(db, 'title', 'a_'),
106
+ await found(db, 'title', '\\'),
107
+ await found(db, 'title', 'k\\s'),
108
+ ]).toEqual([['100%'], ['100%'], ['a_b'], ['a_b'], ['back\\slash'], ['back\\slash']]);
109
+ },
110
+ ),
111
+ checkOver(
112
+ SET,
113
+ 'text contains over a nullable column never matches NULL; an empty term matches every value',
114
+ async (db) => {
115
+ await seed(db, [
116
+ ['one', 'Draft'],
117
+ ['two', null],
118
+ ['three', ''],
119
+ ]);
120
+ expect([await found(db, 'note', 'dra'), await found(db, 'note', '')]).toEqual([
121
+ ['one'],
122
+ ['one', 'three'],
123
+ ]);
124
+ },
125
+ ),
126
+ checkOver(
127
+ SET,
128
+ 'contains on a sealed column is refused; on an array column it is still containment',
129
+ async (db) => {
130
+ await seed(db, [
131
+ ['alpha', null],
132
+ ['alphabet', null],
133
+ ]);
134
+ const sealed = () =>
135
+ inOrg(ORG, () => db.titles.andWhere('secret' as never, 'contains', 's' as never).all());
136
+ expect(await codeOf(sealed)).toBe('X_ENTITY_SEALED_PREDICATE');
137
+ const tagged = await inOrg(ORG, () =>
138
+ db.titles.andWhere('tags', 'contains', ['alpha']).all(),
139
+ );
140
+ expect(tagged.map((row) => row.title)).toEqual(['alpha']);
141
+ },
142
+ ),
143
+ ];
144
+
145
+ export const CONTAINS_CHECKS: readonly EntityDriverCheck[] = checks;