@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.10
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/AGENTS.md +4 -3
- package/dist/index.d.ts +169 -9
- package/dist/index.js +4512 -2338
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2639 -0
- package/dist/sqlite-open.js +1 -1
- package/dist/sqlite-worker.js +1 -1
- package/dist/types.d.ts +129 -13
- package/package.json +9 -4
- package/scripts/check-worker-entries.mjs +15 -2
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/bucket-handle.ts +21 -1
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/services.ts +4 -1
- package/src/client/sp00ky-client.test.ts +143 -1
- package/src/client/sp00ky-client.ts +157 -19
- package/src/index.ts +9 -0
- package/src/kernel/effects.ts +12 -2
- package/src/kernel/interpreter.test.ts +17 -0
- package/src/kernel/interpreter.ts +5 -2
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +2 -2
- package/src/modules/devtools/storage-info.ts +4 -3
- package/src/query/materialize.saga.test.ts +16 -0
- package/src/query/materialize.saga.ts +7 -26
- package/src/query/materialize.ts +79 -3
- package/src/query/register.saga.test.ts +61 -0
- package/src/query/register.saga.ts +39 -2
- package/src/services/database/cache-engine.ts +17 -3
- package/src/services/database/engine-factory.ts +7 -0
- package/src/services/database/index.ts +1 -0
- package/src/services/database/rows-cache-engine.test.ts +1014 -0
- package/src/services/database/rows-cache-engine.ts +921 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +225 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +588 -0
- package/src/services/database/sqlite-cache-engine.test.ts +22 -1
- package/src/services/database/sqlite-cache-engine.ts +55 -34
- package/src/services/database/sqlite-transport.ts +7 -5
- package/src/services/tabs/support.ts +6 -4
- package/src/types.ts +39 -6
- package/tsdown.config.ts +42 -1
- package/vitest.config.ts +4 -0
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
|
2
|
+
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
|
|
3
|
+
import type { QueryPlan, WhereComparison, WhereNode } from '@spooky-sync/query-builder';
|
|
4
|
+
import { executeSelect, type SelectDb } from './sqlite-select';
|
|
5
|
+
import { fromBase64, renderOrderSql, renderWhereSql, reviveRow, serializeMergeRow, serializeRow } from './sqlite-plan-sql';
|
|
6
|
+
import type { OrderBy, Row } from './cache-engine';
|
|
7
|
+
import { MemoryFile, RowStore } from './rows-store';
|
|
8
|
+
import { RowsExec, parseRowBytes, visibleTables, type WireOp } from './rows-exec';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The row store has to answer a query the way the SQLite engine does, since an
|
|
12
|
+
* app may run on either. These tests load the same rows into both, a real
|
|
13
|
+
* in-memory SQLite (the build the SQLite worker loads) and a row store, run
|
|
14
|
+
* the same plan against each and compare the answers: hand-picked plans for
|
|
15
|
+
* every feature, then a few hundred random filters over values of every type.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
let db: any;
|
|
19
|
+
let selectDb: SelectDb;
|
|
20
|
+
let store: RowStore;
|
|
21
|
+
let exec: RowsExec;
|
|
22
|
+
|
|
23
|
+
const enc = new TextEncoder();
|
|
24
|
+
|
|
25
|
+
/** What the engine sends for a batch of rows: one buffer, one op per row. */
|
|
26
|
+
function pack(table: string, rows: Row[], mode: 'put' | 'merge'): { ops: WireOp[]; buf: ArrayBuffer } {
|
|
27
|
+
const parts: Uint8Array[] = [];
|
|
28
|
+
const ops: WireOp[] = [];
|
|
29
|
+
let at = 0;
|
|
30
|
+
for (const row of rows) {
|
|
31
|
+
const { insert, patch } = mode === 'merge' ? serializeMergeRow(row) : { insert: serializeRow(row), patch: '' };
|
|
32
|
+
const body = enc.encode(insert);
|
|
33
|
+
const flags = insert.includes('"__u8"') ? 1 : 0;
|
|
34
|
+
const rv = Number(row._00_rv) || 0;
|
|
35
|
+
parts.push(body);
|
|
36
|
+
if (mode === 'put') ops.push(['put', table, String(row.id), rv, flags, at, body.length]);
|
|
37
|
+
else if (patch === insert) ops.push(['merge', table, String(row.id), rv, flags, at, body.length, 0, 0]);
|
|
38
|
+
else {
|
|
39
|
+
const patchBytes = enc.encode(patch);
|
|
40
|
+
parts.push(patchBytes);
|
|
41
|
+
ops.push(['merge', table, String(row.id), rv, flags, at, body.length, at + body.length, patchBytes.length]);
|
|
42
|
+
at += patchBytes.length;
|
|
43
|
+
}
|
|
44
|
+
at += body.length;
|
|
45
|
+
}
|
|
46
|
+
const buf = new Uint8Array(at);
|
|
47
|
+
let p = 0;
|
|
48
|
+
for (const part of parts) {
|
|
49
|
+
buf.set(part, p);
|
|
50
|
+
p += part.length;
|
|
51
|
+
}
|
|
52
|
+
return { ops, buf: buf.buffer };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function seed(table: string, rows: Row[]): void {
|
|
56
|
+
db.exec({ sql: `CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)` });
|
|
57
|
+
selectDb.knownTables.add(table);
|
|
58
|
+
for (const row of rows) {
|
|
59
|
+
db.exec({ sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?)`, bind: [row.id, serializeRow(row)] });
|
|
60
|
+
}
|
|
61
|
+
const { ops, buf } = pack(table, rows, 'put');
|
|
62
|
+
exec.write(ops, buf, false);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function both(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<{ sqlite: Row[]; rows: Row[] }> {
|
|
66
|
+
const sqlite = (await executeSelect(plan, params, selectDb)).rows;
|
|
67
|
+
const rows = parseRowBytes<Row[]>(await exec.select(plan, params), fromBase64);
|
|
68
|
+
return { sqlite, rows };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function same(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<Row[]> {
|
|
72
|
+
const { sqlite, rows } = await both(plan, params);
|
|
73
|
+
expect(rows, JSON.stringify(plan)).toEqual(sqlite);
|
|
74
|
+
return rows;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const GAMES: Row[] = [
|
|
78
|
+
{ id: 'game:a', title: 'Alpha', moves: 34, rating: 2140.5, rated: true, white: 'user:1', black: 'user:2', tags: ['blitz', 'rated'], meta: { opening: 'B90', depth: 3 }, _00_rv: 4 },
|
|
79
|
+
{ id: 'game:b', title: 'beta', moves: 12, rating: 1800, rated: false, white: 'user:2', black: 'user:1', tags: [], meta: { opening: 'C42' }, _00_rv: 1 },
|
|
80
|
+
{ id: 'game:c', title: 'Gamma', moves: 0, rating: null, rated: true, white: 'user:3', black: null, _00_rv: 9 },
|
|
81
|
+
{ id: 'game:d', title: '10', moves: 10, rating: -3.25, white: 'Magnus', black: 'user:1', meta: { opening: null, depth: 0 }, _00_rv: 2 },
|
|
82
|
+
{ id: 'game:e', title: 'Épée', moves: 77, rating: 1e3, rated: false, white: 'user:1', black: 'user:3', blob: new Uint8Array([0, 1, 2, 250, 255]), _00_rv: 0 },
|
|
83
|
+
{ id: 'game:f', title: '\u{1f600} grin', moves: 5, rating: 2140.5, rated: true, white: 'user:9', black: 'user:2', meta: { opening: 'A00', depth: 12 } },
|
|
84
|
+
{ id: 'game:g', title: ' high', moves: '34', rating: '2140.5', rated: 1, white: 'user:1', black: 'user:2', tags: ['x'], _00_rv: 3 },
|
|
85
|
+
{ id: 'game:h', title: '', moves: 34, rating: 0, rated: 0, white: 'user:2', black: 'user:3', meta: 'not an object', _00_rv: 6 },
|
|
86
|
+
{ id: 'game:10', title: 'zeta', moves: 1.5, rating: 99, rated: true, white: 'user:3', black: 'user:1', tags: ['blitz'] },
|
|
87
|
+
{ id: 'game:9', title: 'Zeta', moves: -1, rating: 100, rated: null, white: 'user:1', black: 'user:1', meta: { opening: 'B90', depth: 3 } },
|
|
88
|
+
];
|
|
89
|
+
const USERS: Row[] = [
|
|
90
|
+
{ id: 'user:1', name: 'Ada', elo: 2100, club: 'club:x' },
|
|
91
|
+
{ id: 'user:2', name: 'Bob', elo: 1900, club: 'club:y' },
|
|
92
|
+
{ id: 'user:3', name: 'Cyd', elo: 2300, club: null },
|
|
93
|
+
];
|
|
94
|
+
const CLUBS: Row[] = [
|
|
95
|
+
{ id: 'club:x', name: 'Xenon' },
|
|
96
|
+
{ id: 'club:y', name: 'Yttrium' },
|
|
97
|
+
];
|
|
98
|
+
const COMMENTS: Row[] = Array.from({ length: 40 }, (_, i) => ({
|
|
99
|
+
id: `comment:${String(i).padStart(2, '0')}`,
|
|
100
|
+
game: i % 7 === 6 ? null : `game:${'abcdefgh'[i % 8]}`,
|
|
101
|
+
author: `user:${(i % 3) + 1}`,
|
|
102
|
+
rank: (i * 37) % 11,
|
|
103
|
+
hidden: i % 5 === 0,
|
|
104
|
+
text: `comment ${i}`,
|
|
105
|
+
}));
|
|
106
|
+
|
|
107
|
+
beforeAll(async () => {
|
|
108
|
+
const sqlite3: any = await sqlite3InitModule();
|
|
109
|
+
db = new sqlite3.oo1.DB(':memory:', 'c');
|
|
110
|
+
selectDb = {
|
|
111
|
+
exec: (sql, bind) => db.exec({ sql, bind, rowMode: 'object', returnValue: 'resultRows' }) as { data: string }[],
|
|
112
|
+
run: (sql, bind) => {
|
|
113
|
+
db.exec({ sql, bind });
|
|
114
|
+
},
|
|
115
|
+
knownTables: new Set<string>(),
|
|
116
|
+
};
|
|
117
|
+
const files = { a: new MemoryFile(), b: new MemoryFile() };
|
|
118
|
+
store = await RowStore.open({ open: (name) => files[name] });
|
|
119
|
+
exec = new RowsExec(store);
|
|
120
|
+
seed('game', GAMES);
|
|
121
|
+
seed('user', USERS);
|
|
122
|
+
seed('club', CLUBS);
|
|
123
|
+
seed('comment', COMMENTS);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
afterAll(() => {
|
|
127
|
+
db?.close();
|
|
128
|
+
store?.close();
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
describe('row store vs SQLite: select', () => {
|
|
132
|
+
it('reads a whole table in id order', async () => {
|
|
133
|
+
const rows = await same({ table: 'game' });
|
|
134
|
+
expect(rows.map((r) => r.id)).toEqual(
|
|
135
|
+
GAMES.map((g) => String(g.id)).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)))
|
|
136
|
+
);
|
|
137
|
+
expect(rows.find((r) => r.id === 'game:e')?.blob).toEqual(new Uint8Array([0, 1, 2, 250, 255]));
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('reads a table that does not exist as empty', async () => {
|
|
141
|
+
await same({ table: 'nothing_here' });
|
|
142
|
+
await same({ table: 'nothing_here', where: [{ field: 'a', op: '=', value: 1 }] });
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('filters by every operator and value type', async () => {
|
|
146
|
+
const values = [34, '34', 0, 1, true, false, null, 'user:1', 2140.5, '2140.5', '', 'Alpha', 'beta', -1, 1.5, 1000];
|
|
147
|
+
const fields = ['moves', 'rating', 'rated', 'title', 'white', 'black', 'id', 'missing', 'meta.depth', 'meta.opening', 'tags', 'meta'];
|
|
148
|
+
for (const field of fields) {
|
|
149
|
+
for (const op of ['=', '!=', '<', '<=', '>', '>=']) {
|
|
150
|
+
for (const value of values) {
|
|
151
|
+
await same({ table: 'game', where: [{ field, op, value }] });
|
|
152
|
+
await same({ table: 'game', where: [{ field, op, value, swap: true }] });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('matches a record link whether it is bound as a string or an object', async () => {
|
|
159
|
+
const link = { tb: 'user', id: '1' };
|
|
160
|
+
const rows = await same({ table: 'game', where: [{ field: 'white', op: '=', value: link }] });
|
|
161
|
+
expect(rows.length).toBe(4);
|
|
162
|
+
await same({ table: 'game', where: [{ field: 'id', op: '=', value: { tb: 'game', id: 'a' } }] });
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('combines AND with OR groups', async () => {
|
|
166
|
+
await same({
|
|
167
|
+
table: 'game',
|
|
168
|
+
where: [
|
|
169
|
+
{ or: [{ field: 'white', op: '=', value: 'user:1' }, { field: 'black', op: '=', value: 'user:1' }] },
|
|
170
|
+
{ field: 'moves', op: '>', value: 5 },
|
|
171
|
+
],
|
|
172
|
+
});
|
|
173
|
+
await same({ table: 'game', where: [{ or: [{ field: 'rated', op: '=', value: true }, { field: 'rating', op: '<', value: 0 }] }] });
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('prefers the query param over the baked value', async () => {
|
|
177
|
+
const where: WhereNode[] = [{ field: 'white', op: '=', value: 'user:2', paramRef: 'white' }];
|
|
178
|
+
expect((await same({ table: 'game', where }, { white: 'user:1' })).length).toBe(4);
|
|
179
|
+
expect((await same({ table: 'game', where }, {})).length).toBe(2);
|
|
180
|
+
await same({ table: 'game', where: [{ field: 'moves', op: '>=', value: undefined, paramRef: 'min' }] }, { min: 30 });
|
|
181
|
+
await same({ table: 'game', where: [{ field: 'moves', op: '>=', value: undefined, paramRef: 'min' }] }, {});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('orders by any field, either way, with a window', async () => {
|
|
185
|
+
for (const field of ['moves', 'rating', 'rated', 'title', 'white', 'missing', 'meta.depth', 'tags']) {
|
|
186
|
+
for (const dir of ['asc', 'desc'] as const) {
|
|
187
|
+
// The id breaks ties, which SQL leaves in no particular order.
|
|
188
|
+
const orderBy: OrderBy = [
|
|
189
|
+
[field, dir],
|
|
190
|
+
['id', 'asc'],
|
|
191
|
+
];
|
|
192
|
+
await same({ table: 'game', orderBy });
|
|
193
|
+
await same({ table: 'game', orderBy, limit: 3 });
|
|
194
|
+
await same({ table: 'game', orderBy, limit: 4, offset: 3 });
|
|
195
|
+
await same({ table: 'game', orderBy, where: [{ field: 'moves', op: '>', value: 0 }], limit: 2, offset: 1 });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it('windows an unordered query in id order', async () => {
|
|
201
|
+
await same({ table: 'comment', limit: 7 });
|
|
202
|
+
await same({ table: 'comment', limit: 7, offset: 30 });
|
|
203
|
+
await same({ table: 'comment', limit: 100, offset: 39 });
|
|
204
|
+
await same({ table: 'comment', limit: 0 });
|
|
205
|
+
await same({ table: 'comment', where: [{ field: 'hidden', op: '=', value: true }], limit: 3, offset: 2 });
|
|
206
|
+
await same({ table: 'comment', where: [{ field: 'rank', op: '>', value: 100 }], limit: 3 });
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it('materializes a window of ids in the order given', async () => {
|
|
210
|
+
const ids = ['game:h', 'game:a', 'game:missing', 'game:10', 'game:a', 'game:e'];
|
|
211
|
+
const rows = await same({ table: 'game', ids });
|
|
212
|
+
// A repeated id counts where it appears last, as in the SQLite engine.
|
|
213
|
+
expect(rows.map((r) => r.id)).toEqual(['game:h', 'game:10', 'game:a', 'game:e']);
|
|
214
|
+
await same({ table: 'game', ids: [] });
|
|
215
|
+
await same({ table: 'game', ids: ['game:nope'] });
|
|
216
|
+
await same({ table: 'game', ids, orderBy: [['moves', 'desc'], ['id', 'asc']] });
|
|
217
|
+
await same({ table: 'game', ids: [{ tb: 'game', id: 'c' }, 'game:b'] });
|
|
218
|
+
// `where`, `limit` and `offset` do not apply to a window.
|
|
219
|
+
await same({ table: 'game', ids, where: [{ field: 'moves', op: '=', value: -5 }], limit: 1, offset: 1 });
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('projects fields, keeping booleans and absent keys as they are', async () => {
|
|
223
|
+
const rows = await same({ table: 'game', select: ['title', 'rated', 'meta', 'blob', 'missing'] });
|
|
224
|
+
expect(rows.find((r) => r.id === 'game:a')).toEqual({ id: 'game:a', title: 'Alpha', rated: true, meta: { opening: 'B90', depth: 3 } });
|
|
225
|
+
expect(rows.find((r) => r.id === 'game:d')).toEqual({ id: 'game:d', title: '10', meta: { opening: null, depth: 0 } });
|
|
226
|
+
await same({ table: 'game', ids: ['game:e', 'game:b'], select: ['blob', 'rated'] });
|
|
227
|
+
await same({ table: 'game', select: ['moves'], orderBy: [['rating', 'desc'], ['id', 'asc']], limit: 4 });
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it('resolves to-one and to-many relations, nested', async () => {
|
|
231
|
+
const plan: QueryPlan = {
|
|
232
|
+
table: 'game',
|
|
233
|
+
orderBy: [['id', 'asc']],
|
|
234
|
+
relations: [
|
|
235
|
+
{
|
|
236
|
+
alias: 'white',
|
|
237
|
+
table: 'user',
|
|
238
|
+
cardinality: 'one',
|
|
239
|
+
foreignKeyField: 'white',
|
|
240
|
+
relations: [{ alias: 'club', table: 'club', cardinality: 'one', foreignKeyField: 'club' }],
|
|
241
|
+
},
|
|
242
|
+
{ alias: 'black', table: 'user', cardinality: 'one', foreignKeyField: 'black', select: ['name'] },
|
|
243
|
+
{
|
|
244
|
+
alias: 'comments',
|
|
245
|
+
table: 'comment',
|
|
246
|
+
cardinality: 'many',
|
|
247
|
+
foreignKeyField: 'game',
|
|
248
|
+
where: [{ field: 'hidden', op: '=', value: false }],
|
|
249
|
+
orderBy: [['rank', 'desc'], ['id', 'asc']],
|
|
250
|
+
limit: 3,
|
|
251
|
+
relations: [{ alias: 'author', table: 'user', cardinality: 'one', foreignKeyField: 'author', select: ['name'] }],
|
|
252
|
+
},
|
|
253
|
+
],
|
|
254
|
+
};
|
|
255
|
+
const rows = await same(plan);
|
|
256
|
+
const a = rows.find((r) => r.id === 'game:a')!;
|
|
257
|
+
expect((a.white as Row).name).toBe('Ada');
|
|
258
|
+
expect(((a.white as Row).club as Row).name).toBe('Xenon');
|
|
259
|
+
expect((a.comments as Row[]).length).toBe(3);
|
|
260
|
+
// A value that is not a link stays what it was; a dangling link reads null.
|
|
261
|
+
expect(rows.find((r) => r.id === 'game:d')!.white).toBe('Magnus');
|
|
262
|
+
expect(rows.find((r) => r.id === 'game:f')!.white).toBeNull();
|
|
263
|
+
await same({ ...plan, ids: ['game:c', 'game:a'], orderBy: undefined });
|
|
264
|
+
await same({ ...plan, select: ['white', 'title'], limit: 4 });
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('returns the children of an unordered to-many relation as the same set', async () => {
|
|
268
|
+
const plan: QueryPlan = {
|
|
269
|
+
table: 'game',
|
|
270
|
+
relations: [{ alias: 'comments', table: 'comment', cardinality: 'many', foreignKeyField: 'game' }],
|
|
271
|
+
};
|
|
272
|
+
const { sqlite, rows } = await both(plan);
|
|
273
|
+
const byId = (list: Row[]): Row[] => [...list].sort((x, y) => String(x.id).localeCompare(String(y.id)));
|
|
274
|
+
expect(rows.map((r) => ({ ...r, comments: byId(r.comments as Row[]) }))).toEqual(
|
|
275
|
+
sqlite.map((r) => ({ ...r, comments: byId(r.comments as Row[]) }))
|
|
276
|
+
);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('keeps a relation right after the child table is written to', async () => {
|
|
280
|
+
const plan: QueryPlan = {
|
|
281
|
+
table: 'user',
|
|
282
|
+
relations: [{ alias: 'comments', table: 'comment', cardinality: 'many', foreignKeyField: 'author', orderBy: [['id', 'asc']] }],
|
|
283
|
+
};
|
|
284
|
+
await same(plan);
|
|
285
|
+
const moved: Row = { ...COMMENTS[0], author: 'user:3', text: 'moved' };
|
|
286
|
+
const added: Row = { id: 'comment:zz', game: 'game:a', author: 'user:2', rank: 1, hidden: false, text: 'new' };
|
|
287
|
+
for (const row of [moved, added]) {
|
|
288
|
+
db.exec({ sql: `INSERT INTO "comment"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`, bind: [row.id, serializeRow(row)] });
|
|
289
|
+
}
|
|
290
|
+
const { ops, buf } = pack('comment', [moved, added], 'put');
|
|
291
|
+
exec.write(ops, buf, false);
|
|
292
|
+
db.exec({ sql: `DELETE FROM "comment" WHERE id = ?`, bind: ['comment:01'] });
|
|
293
|
+
exec.write([['del', 'comment', 'comment:01']], null, false);
|
|
294
|
+
const rows = await same(plan);
|
|
295
|
+
expect((rows[2].comments as Row[]).some((c) => c.text === 'moved')).toBe(true);
|
|
296
|
+
expect((rows[1].comments as Row[]).some((c) => c.id === 'comment:01')).toBe(false);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('agrees on a few hundred random filters', async () => {
|
|
300
|
+
let seedValue = 20261117;
|
|
301
|
+
const rnd = (n: number): number => {
|
|
302
|
+
seedValue = (Math.imul(seedValue, 1103515245) + 12345) & 0x7fffffff;
|
|
303
|
+
return seedValue % n;
|
|
304
|
+
};
|
|
305
|
+
const fields = ['moves', 'rating', 'rated', 'title', 'white', 'black', 'id', 'meta.depth', 'meta.opening', 'missing', '_00_rv'];
|
|
306
|
+
const ops = ['=', '!=', '<', '<=', '>', '>='];
|
|
307
|
+
const pool: unknown[] = [0, 1, 34, -1, 1.5, 2140.5, 1000, '34', '10', 'user:1', 'user:2', 'game:c', 'B90', '', 'Alpha', 'zeta', true, false, null, 3];
|
|
308
|
+
const comparison = (): WhereComparison => ({
|
|
309
|
+
field: fields[rnd(fields.length)],
|
|
310
|
+
op: ops[rnd(ops.length)],
|
|
311
|
+
value: pool[rnd(pool.length)],
|
|
312
|
+
...(rnd(6) === 0 ? { swap: true } : {}),
|
|
313
|
+
});
|
|
314
|
+
for (let i = 0; i < 400; i++) {
|
|
315
|
+
const where: WhereNode[] = [];
|
|
316
|
+
for (let k = rnd(3) + 1; k > 0; k--) {
|
|
317
|
+
where.push(rnd(4) === 0 ? { or: [comparison(), comparison()] } : comparison());
|
|
318
|
+
}
|
|
319
|
+
const plan: QueryPlan = { table: 'game', where };
|
|
320
|
+
if (rnd(3) === 0) plan.orderBy = [[fields[rnd(fields.length)], rnd(2) ? 'asc' : 'desc'], ['id', 'asc']];
|
|
321
|
+
if (rnd(3) === 0) plan.limit = rnd(5);
|
|
322
|
+
if (plan.limit !== undefined && rnd(2) === 0) plan.offset = rnd(4);
|
|
323
|
+
await same(plan);
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
describe('row store vs SQLite: the raw-statement verbs', () => {
|
|
329
|
+
const sqliteRows = (table: string, where?: WhereNode[], orderBy?: OrderBy, limit?: number, start?: number): Row[] => {
|
|
330
|
+
const bind: unknown[] = [];
|
|
331
|
+
let sql = `SELECT data FROM "${table}"`;
|
|
332
|
+
if (where?.length) sql += ` WHERE ${renderWhereSql(where, bind, {})}`;
|
|
333
|
+
sql += orderBy?.length ? renderOrderSql(orderBy) : ' ORDER BY id';
|
|
334
|
+
if (limit !== undefined) sql += ` LIMIT ${limit}`;
|
|
335
|
+
else if (start !== undefined) sql += ' LIMIT -1';
|
|
336
|
+
if (start !== undefined) sql += ` OFFSET ${start}`;
|
|
337
|
+
return selectDb.exec(sql, bind).map((r) => reviveRow(r.data));
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
it('selects a table with a filter, an order and a window', () => {
|
|
341
|
+
const cases: [WhereNode[] | undefined, OrderBy | undefined, number | undefined, number | undefined][] = [
|
|
342
|
+
[undefined, undefined, undefined, undefined],
|
|
343
|
+
[[{ field: 'rated', op: '=', value: true }], undefined, undefined, undefined],
|
|
344
|
+
[undefined, [['moves', 'desc'], ['id', 'asc']], 3, undefined],
|
|
345
|
+
[undefined, [['title', 'asc']], 4, 2],
|
|
346
|
+
[undefined, undefined, undefined, 6],
|
|
347
|
+
[[{ field: 'moves', op: '>', value: 5 }], [['rating', 'asc'], ['id', 'desc']], 2, 1],
|
|
348
|
+
];
|
|
349
|
+
for (const [where, orderBy, limit, start] of cases) {
|
|
350
|
+
const rows = parseRowBytes<Row[]>(exec.selectTable('game', where, orderBy, limit, start), fromBase64);
|
|
351
|
+
expect(rows).toEqual(sqliteRows('game', where, orderBy, limit, start));
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it('counts, with and without a filter', () => {
|
|
356
|
+
const count = (where?: WhereNode[]): number => {
|
|
357
|
+
const bind: unknown[] = [];
|
|
358
|
+
const sql = `SELECT COUNT(*) AS n FROM "game"` + (where ? ` WHERE ${renderWhereSql(where, bind, {})}` : '');
|
|
359
|
+
return (db.exec({ sql, bind, rowMode: 'object', returnValue: 'resultRows' }) as { n: number }[])[0].n;
|
|
360
|
+
};
|
|
361
|
+
expect(exec.count('game', undefined)).toBe(count());
|
|
362
|
+
for (const where of [
|
|
363
|
+
[{ field: 'rated', op: '=', value: true }],
|
|
364
|
+
[{ field: 'moves', op: '>=', value: 34 }],
|
|
365
|
+
[{ field: 'missing', op: '!=', value: 1 }],
|
|
366
|
+
] as WhereNode[][]) {
|
|
367
|
+
expect(exec.count('game', where)).toBe(count(where));
|
|
368
|
+
}
|
|
369
|
+
expect(exec.count('never_written', undefined)).toBe(0);
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
it('reads one row, or null', () => {
|
|
373
|
+
expect(parseRowBytes<Row | null>(exec.get('game', 'game:e'), fromBase64)).toEqual(sqliteRows('game', [{ field: 'id', op: '=', value: 'game:e' }])[0]);
|
|
374
|
+
expect(parseRowBytes<Row | null>(exec.get('game', 'game:none'), fromBase64)).toBeNull();
|
|
375
|
+
expect(parseRowBytes<Row | null>(exec.get('none', 'x'), fromBase64)).toBeNull();
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
it('reads the versions from the index alone', () => {
|
|
379
|
+
const rows = db.exec({
|
|
380
|
+
sql: `SELECT id, json_extract(data, '$._00_rv') AS rv FROM "game" ORDER BY id`,
|
|
381
|
+
rowMode: 'object',
|
|
382
|
+
returnValue: 'resultRows',
|
|
383
|
+
}) as { id: string; rv: unknown }[];
|
|
384
|
+
expect(exec.versions(['game', 'nope'])).toEqual({ game: rows.map((r) => [r.id, Number(r.rv) || 0]), nope: [] });
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
describe('row store vs SQLite: merge', () => {
|
|
389
|
+
const merged = (table: string, id: string): Row | null => {
|
|
390
|
+
const rows = selectDb.exec(`SELECT data FROM "${table}" WHERE id = ?`, [id]);
|
|
391
|
+
return rows[0] ? reviveRow(rows[0].data) : null;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
function mergeBoth(table: string, row: Row): void {
|
|
395
|
+
const { insert, patch } = serializeMergeRow(row);
|
|
396
|
+
db.exec({
|
|
397
|
+
sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
|
|
398
|
+
bind: [row.id, insert, patch],
|
|
399
|
+
});
|
|
400
|
+
const { ops, buf } = pack(table, [row], 'merge');
|
|
401
|
+
exec.write(ops, buf, false);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
beforeAll(() => {
|
|
405
|
+
db.exec({ sql: `CREATE TABLE IF NOT EXISTS "doc" (id TEXT PRIMARY KEY, data TEXT NOT NULL)` });
|
|
406
|
+
selectDb.knownTables.add('doc');
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
it('folds a patch into the stored row as json_patch does', () => {
|
|
410
|
+
const steps: Row[] = [
|
|
411
|
+
{ id: 'doc:1', a: 1, nested: { x: 1, y: { z: [1, 2] } }, list: [1, 2, 3], gone: 'soon', _00_rv: 1 },
|
|
412
|
+
{ id: 'doc:1', a: 2, nested: { y: { w: true } }, _00_rv: 2 },
|
|
413
|
+
{ id: 'doc:1', nested: { x: null }, list: [9], gone: undefined, _00_rv: 3 },
|
|
414
|
+
{ id: 'doc:1', nested: 'now a string', extra: { deep: { deeper: null, kept: 0 } } },
|
|
415
|
+
{ id: 'doc:1', nested: { fresh: 1 }, blob: new Uint8Array([1, 2, 3]), a: null },
|
|
416
|
+
{ id: 'doc:1', blob: new Uint8Array([9]), extra: { deep: { kept: false } }, _00_rv: 10 },
|
|
417
|
+
];
|
|
418
|
+
for (const step of steps) {
|
|
419
|
+
mergeBoth('doc', step);
|
|
420
|
+
expect(parseRowBytes<Row>(exec.get('doc', 'doc:1'), fromBase64)).toEqual(merged('doc', 'doc:1'));
|
|
421
|
+
}
|
|
422
|
+
expect(store.find('doc', 'doc:1')?.rv).toBe(10);
|
|
423
|
+
expect(store.find('doc', 'doc:1')?.flags).toBe(1);
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
it('keeps a first write as it came, nulls included', () => {
|
|
427
|
+
mergeBoth('doc', { id: 'doc:2', kept: null, cleared: undefined, n: 1 });
|
|
428
|
+
expect(parseRowBytes<Row>(exec.get('doc', 'doc:2'), fromBase64)).toEqual(merged('doc', 'doc:2'));
|
|
429
|
+
expect(merged('doc', 'doc:2')).toEqual({ id: 'doc:2', kept: null, n: 1 });
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
it('merges against an earlier op of the same batch', () => {
|
|
433
|
+
const first = { id: 'doc:3', a: 1, b: { c: 1 } };
|
|
434
|
+
const second = { id: 'doc:3', b: { d: 2 }, e: 5 };
|
|
435
|
+
for (const row of [first, second]) {
|
|
436
|
+
const { insert, patch } = serializeMergeRow(row);
|
|
437
|
+
db.exec({
|
|
438
|
+
sql: `INSERT INTO "doc"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
|
|
439
|
+
bind: [row.id, insert, patch],
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
const a = pack('doc', [first], 'merge');
|
|
443
|
+
const b = pack('doc', [second], 'merge');
|
|
444
|
+
const buf = new Uint8Array(a.buf.byteLength + b.buf.byteLength);
|
|
445
|
+
buf.set(new Uint8Array(a.buf));
|
|
446
|
+
buf.set(new Uint8Array(b.buf), a.buf.byteLength);
|
|
447
|
+
const shifted = b.ops.map((op) => (op[0] === 'merge' ? ([...op.slice(0, 5), (op[5] as number) + a.buf.byteLength, ...op.slice(6)] as WireOp) : op));
|
|
448
|
+
exec.write([...a.ops, ...shifted], buf.buffer, false);
|
|
449
|
+
expect(parseRowBytes<Row>(exec.get('doc', 'doc:3'), fromBase64)).toEqual(merged('doc', 'doc:3'));
|
|
450
|
+
expect(merged('doc', 'doc:3')).toEqual({ id: 'doc:3', a: 1, b: { c: 1, d: 2 }, e: 5 });
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
it('treats a merge after a delete or a clear in the same batch as a first write', () => {
|
|
454
|
+
mergeBoth('doc', { id: 'doc:4', old: true });
|
|
455
|
+
const fresh = pack('doc', [{ id: 'doc:4', fresh: true }], 'merge');
|
|
456
|
+
exec.write([['del', 'doc', 'doc:4'], ...fresh.ops], fresh.buf, false);
|
|
457
|
+
expect(parseRowBytes<Row>(exec.get('doc', 'doc:4'), fromBase64)).toEqual({ id: 'doc:4', fresh: true });
|
|
458
|
+
const again = pack('doc', [{ id: 'doc:4', again: true }], 'merge');
|
|
459
|
+
exec.write([['clear', 'doc'], ...again.ops], again.buf, false);
|
|
460
|
+
expect(parseRowBytes<Row[]>(exec.selectTable('doc', undefined, undefined, undefined, undefined), fromBase64)).toEqual([{ id: 'doc:4', again: true }]);
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
describe('row store: version reset and blobs', () => {
|
|
465
|
+
it('resets every cached version except the kept rows', () => {
|
|
466
|
+
const before = exec.versions(['user']).user;
|
|
467
|
+
expect(before.every(([, rv]) => rv === 0)).toBe(true);
|
|
468
|
+
const { ops, buf } = pack('versioned', [
|
|
469
|
+
{ id: 'versioned:1', _00_rv: 5, v: 1 },
|
|
470
|
+
{ id: 'versioned:2', _00_rv: 7, v: 2 },
|
|
471
|
+
{ id: 'versioned:3', v: 3 },
|
|
472
|
+
{ id: 'versioned:4', _00_rv: 0, v: 4 },
|
|
473
|
+
], 'put');
|
|
474
|
+
exec.write(ops, buf, false);
|
|
475
|
+
expect(exec.resetVersions(['versioned', 'absent'], ['versioned:2'])).toBe(1);
|
|
476
|
+
expect(exec.versions(['versioned']).versioned).toEqual([
|
|
477
|
+
['versioned:1', 0],
|
|
478
|
+
['versioned:2', 7],
|
|
479
|
+
['versioned:3', 0],
|
|
480
|
+
['versioned:4', 0],
|
|
481
|
+
]);
|
|
482
|
+
const rows = parseRowBytes<Row[]>(exec.selectTable('versioned', undefined, undefined, undefined, undefined), fromBase64);
|
|
483
|
+
expect(rows).toEqual([
|
|
484
|
+
{ id: 'versioned:1', _00_rv: 0, v: 1 },
|
|
485
|
+
{ id: 'versioned:2', _00_rv: 7, v: 2 },
|
|
486
|
+
{ id: 'versioned:3', v: 3 },
|
|
487
|
+
{ id: 'versioned:4', _00_rv: 0, v: 4 },
|
|
488
|
+
]);
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
it('stores a blob beside its meta and keeps both out of row reads', () => {
|
|
492
|
+
const bytes = new Uint8Array(70_000);
|
|
493
|
+
for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 7) & 255;
|
|
494
|
+
exec.putBlob('_00_circuit_snapshot', 'circuit', bytes.slice().buffer, JSON.stringify({ formatVersion: 3 }));
|
|
495
|
+
const got = exec.getBlob('_00_circuit_snapshot', 'circuit');
|
|
496
|
+
expect(new Uint8Array(got.bytes!)).toEqual(bytes);
|
|
497
|
+
expect(JSON.parse(got.meta!)).toEqual({ formatVersion: 3 });
|
|
498
|
+
expect(parseRowBytes<Row[]>(exec.selectTable('_00_circuit_snapshot', undefined, undefined, undefined, undefined), fromBase64)).toEqual([]);
|
|
499
|
+
expect(exec.count('_00_circuit_snapshot', [{ field: 'a', op: '=', value: 1 }])).toBe(0);
|
|
500
|
+
exec.deleteBlob('_00_circuit_snapshot', 'circuit');
|
|
501
|
+
expect(exec.getBlob('_00_circuit_snapshot', 'circuit')).toEqual({ bytes: null, meta: null });
|
|
502
|
+
});
|
|
503
|
+
});
|
|
504
|
+
|
|
505
|
+
describe('row store vs SQLite: indexes', () => {
|
|
506
|
+
const hidden = (): string[] => store.tableNames().filter((t) => t.startsWith('\u0001i'));
|
|
507
|
+
|
|
508
|
+
it('indexes record links as rows are written, and filtered fields on first use', async () => {
|
|
509
|
+
// `white`, `black` and the comments' links were found while seeding.
|
|
510
|
+
expect(hidden()).toEqual(expect.arrayContaining(['\u0001i\u0001game\u0001white', '\u0001i\u0001comment\u0001game', '\u0001i\u0001comment\u0001author']));
|
|
511
|
+
// `title` got one when a query filtered on it; nothing ever filtered on `blob`.
|
|
512
|
+
expect(hidden()).toContain('\u0001i\u0001game\u0001title');
|
|
513
|
+
expect(hidden()).not.toContain('\u0001i\u0001game\u0001blob');
|
|
514
|
+
// A URL is not a link.
|
|
515
|
+
const { ops, buf } = pack('site', [{ id: 'site:1', url: 'https://example.com/a', owner: 'user:1' }], 'put');
|
|
516
|
+
exec.write(ops, buf, false);
|
|
517
|
+
expect(hidden()).toContain('\u0001i\u0001site\u0001owner');
|
|
518
|
+
expect(hidden()).not.toContain('\u0001i\u0001site\u0001url');
|
|
519
|
+
// The client's own tables are read whole.
|
|
520
|
+
const internal = pack('_00_view', [{ id: '_00_view:1', owner: 'user:1' }], 'put');
|
|
521
|
+
exec.write(internal.ops, internal.buf, false);
|
|
522
|
+
expect(hidden().some((t) => t.includes('_00_view'))).toBe(false);
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
it('stays right through inserts, updates, deletes and clears, and across a reopen', async () => {
|
|
526
|
+
let seedValue = 4242;
|
|
527
|
+
const rnd = (n: number): number => {
|
|
528
|
+
seedValue = (Math.imul(seedValue, 1103515245) + 12345) & 0x7fffffff;
|
|
529
|
+
return seedValue % n;
|
|
530
|
+
};
|
|
531
|
+
db.exec({ sql: `CREATE TABLE IF NOT EXISTS "churn" (id TEXT PRIMARY KEY, data TEXT NOT NULL)` });
|
|
532
|
+
selectDb.knownTables.add('churn');
|
|
533
|
+
const owners = Array.from({ length: 12 }, (_, i) => `user:${i}`);
|
|
534
|
+
const kinds = Array.from({ length: 20 }, (_, i) => `kind-${i}`);
|
|
535
|
+
const check = async (): Promise<void> => {
|
|
536
|
+
for (const owner of [owners[rnd(12)], owners[rnd(12)], 'user:none']) {
|
|
537
|
+
await same({ table: 'churn', where: [{ field: 'owner', op: '=', value: owner }] });
|
|
538
|
+
await same({ table: 'churn', where: [{ field: 'owner', op: '=', value: owner }, { field: 'n', op: '>', value: 40 }], orderBy: [['n', 'desc'], ['id', 'asc']], limit: 5 });
|
|
539
|
+
}
|
|
540
|
+
await same({ table: 'churn', where: [{ field: 'kind', op: '=', value: kinds[rnd(20)] }] });
|
|
541
|
+
await same({ table: 'churn', where: [{ field: 'flag', op: '=', value: true }], limit: 7 });
|
|
542
|
+
await same({ table: 'churn', where: [{ field: 'n', op: '=', value: rnd(100) }] });
|
|
543
|
+
await same({ table: 'churn', where: [{ field: 'id', op: '=', value: `churn:${rnd(150)}` }] });
|
|
544
|
+
await same({ table: 'churn', where: [{ field: 'owner', op: '=', value: null }] });
|
|
545
|
+
const keys = [owners[rnd(12)], owners[rnd(12)], owners[rnd(12)]];
|
|
546
|
+
const mine = parseRowBytes<Row[]>(exec.relation({ table: 'churn', matchField: 'owner', keys, orderBy: [['id', 'asc']] }), fromBase64);
|
|
547
|
+
const bind = keys.map(() => '?').join(', ');
|
|
548
|
+
const theirs = selectDb.exec(`SELECT data FROM "churn" WHERE json_extract(data, '$.owner') IN (${bind}) ORDER BY id`, keys).map((r) => reviveRow(r.data));
|
|
549
|
+
expect(mine).toEqual(theirs);
|
|
550
|
+
};
|
|
551
|
+
for (let step = 0; step < 500; step++) {
|
|
552
|
+
const id = `churn:${rnd(150)}`;
|
|
553
|
+
const roll = rnd(100);
|
|
554
|
+
if (roll < 2) {
|
|
555
|
+
db.exec({ sql: `DELETE FROM "churn"` });
|
|
556
|
+
exec.write([['clear', 'churn']], null, false);
|
|
557
|
+
} else if (roll < 20) {
|
|
558
|
+
db.exec({ sql: `DELETE FROM "churn" WHERE id = ?`, bind: [id] });
|
|
559
|
+
exec.write([['del', 'churn', id]], null, false);
|
|
560
|
+
} else {
|
|
561
|
+
const row: Row = { id, n: rnd(100) };
|
|
562
|
+
if (rnd(4) !== 0) row.owner = rnd(10) === 0 ? null : owners[rnd(12)];
|
|
563
|
+
if (rnd(3) !== 0) row.kind = kinds[rnd(20)];
|
|
564
|
+
if (rnd(3) === 0) row.flag = rnd(2) === 0;
|
|
565
|
+
const { insert, patch } = serializeMergeRow(row);
|
|
566
|
+
db.exec({
|
|
567
|
+
sql: `INSERT INTO "churn"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
|
|
568
|
+
bind: [id, insert, patch],
|
|
569
|
+
});
|
|
570
|
+
const packed = pack('churn', [row], rnd(5) === 0 ? 'put' : 'merge');
|
|
571
|
+
if (packed.ops[0][0] === 'put') db.exec({ sql: `UPDATE "churn" SET data = ? WHERE id = ?`, bind: [insert, id] });
|
|
572
|
+
exec.write(packed.ops, packed.buf, false);
|
|
573
|
+
}
|
|
574
|
+
if (step % 50 === 49) await check();
|
|
575
|
+
if (step === 250) {
|
|
576
|
+
store.checkpoint();
|
|
577
|
+
exec = new RowsExec(store);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
await check();
|
|
581
|
+
// `owner` (links) and `kind` (20 values) are indexed; `flag` (2 values) is left to scans.
|
|
582
|
+
expect(hidden()).toEqual(expect.arrayContaining(['\u0001i\u0001churn\u0001owner', '\u0001i\u0001churn\u0001kind']));
|
|
583
|
+
});
|
|
584
|
+
|
|
585
|
+
it('hands out only the tables a client wrote', () => {
|
|
586
|
+
expect(visibleTables(store).some((t) => t.startsWith('\u0001'))).toBe(false);
|
|
587
|
+
expect(visibleTables(store)).toContain('game');
|
|
588
|
+
});
|
|
589
|
+
});
|