@blueshed/joined 0.2.2 → 0.3.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/.claude/skills/joined/SKILL.md +9 -1
- package/.claude/skills/joined/reference.md +267 -53
- package/.claude/skills/joined-door/SKILL.md +57 -0
- package/README.md +19 -50
- package/docs/design.md +76 -10
- package/docs/introduction.md +18 -18
- package/docs/light-and-shadow.svg +1 -1
- package/examples/README.md +20 -0
- package/examples/account/account.json +1 -0
- package/examples/account/derive.ts +41 -0
- package/examples/account/generated/elements.ts +52 -0
- package/examples/account/generated/rows.ts +22 -0
- package/examples/account/generated/rules.ts +32 -0
- package/examples/account/routes.ts +5 -0
- package/examples/app.css +2 -1
- package/examples/cafe/books.html +2 -2
- package/examples/cafe/cafe.css +9 -16
- package/examples/cafe/generated/books.rows.ts +22 -0
- package/examples/cafe/generated/books.rules.ts +3 -2
- package/examples/cafe/generated/kitchen.rows.ts +27 -0
- package/examples/cafe/generated/kitchen.rules.ts +11 -1
- package/examples/cafe/generated/menu.rows.ts +22 -0
- package/examples/cafe/generated/menu.rules.ts +3 -2
- package/examples/cafe/generated/order.rows.ts +27 -0
- package/examples/cafe/generated/order.rules.ts +11 -1
- package/examples/cafe/generated/staff.rows.ts +22 -0
- package/examples/cafe/generated/staff.rules.ts +6 -1
- package/examples/cafe/generated/supplies.queries.ts +4 -2
- package/examples/cafe/generated/supplies.rows.ts +22 -0
- package/examples/cafe/generated/supplies.rules.ts +12 -1
- package/examples/cafe/generated/till.queries.ts +2 -0
- package/examples/cafe/generated/till.rows.ts +27 -0
- package/examples/cafe/generated/till.rules.ts +11 -1
- package/examples/cafe/index.html +14 -15
- package/examples/cafe/kitchen.ts +1 -1
- package/examples/cafe/look.ts +30 -0
- package/examples/cafe/menu.html +10 -26
- package/examples/cafe/menu.ts +8 -80
- package/examples/cafe/order.html +6 -6
- package/examples/cafe/order.ts +5 -1
- package/examples/cafe/routes.ts +0 -1
- package/examples/cafe/stories.jsonl +3 -1
- package/examples/cafe/supplies.html +34 -34
- package/examples/cafe/supplies.ts +14 -11
- package/examples/cafe/till.ts +5 -1
- package/examples/chart/arches.ts +148 -0
- package/examples/chart/chart.css +6 -0
- package/examples/chart/chart.json +87 -0
- package/examples/chart/generated/elements.ts +105 -0
- package/examples/chart/generated/queries.ts +36 -0
- package/examples/chart/generated/rows.ts +27 -0
- package/examples/chart/generated/rules.ts +111 -0
- package/examples/chart/grid.ts +118 -0
- package/examples/chart/index.html +78 -0
- package/examples/chart/migrations/001-chart.ts +6 -0
- package/examples/chart/migrations/002-create-conditions.ts +6 -0
- package/examples/chart/page.ts +20 -0
- package/examples/chart/routes.ts +7 -0
- package/examples/chart/stories.jsonl +14 -0
- package/examples/chart/teeth.ts +57 -0
- package/examples/desk/generated/rows.ts +22 -0
- package/examples/desk/generated/rules.ts +34 -1
- package/examples/desk/index.html +9 -2
- package/examples/desk/routes.ts +0 -2
- package/examples/desk/stories.jsonl +3 -2
- package/examples/desk/thumbs.ts +2 -2
- package/examples/hello/generated/elements.ts +2 -2
- package/examples/hello/generated/rules.ts +3 -2
- package/examples/hello/hello.css +2 -4
- package/examples/hello/index.html +10 -3
- package/examples/hello/page.ts +4 -4
- package/examples/index.html +4 -5
- package/examples/notes/generated/elements.ts +112 -0
- package/examples/notes/generated/queries.ts +36 -0
- package/examples/notes/generated/rows.ts +27 -0
- package/examples/notes/generated/rules.ts +133 -0
- package/examples/notes/index.html +32 -0
- package/examples/notes/look.ts +41 -0
- package/examples/notes/migrations/001-notes.ts +7 -0
- package/examples/notes/notes.json +78 -0
- package/examples/notes/page.ts +21 -0
- package/examples/notes/routes.ts +6 -0
- package/examples/notes/stories.jsonl +21 -0
- package/examples/people/generated/rows.ts +22 -0
- package/examples/people/generated/rules.ts +11 -1
- package/examples/people/links.ts +2 -1
- package/examples/people/routes.ts +1 -3
- package/examples/people/stories.jsonl +1 -0
- package/examples/people/view.ts +5 -2
- package/examples/trip/generated/elements.ts +4 -2
- package/examples/trip/generated/queries.ts +12 -1
- package/examples/trip/generated/rows.ts +27 -0
- package/examples/trip/generated/rules.ts +56 -2
- package/examples/trip/index.html +58 -12
- package/examples/trip/line.css +186 -0
- package/examples/trip/line.ts +51 -40
- package/examples/trip/page.ts +65 -71
- package/examples/trip/routes.ts +9 -5
- package/examples/trip/stays.css +12 -12
- package/examples/trip/stays.ts +15 -10
- package/examples/trip/stories.jsonl +2 -0
- package/examples/trip/told.ts +3 -26
- package/examples/trip/trip.css +16 -0
- package/examples/trips/generated/rows.ts +22 -0
- package/examples/trips/generated/rules.ts +9 -1
- package/examples/trips/index.html +10 -10
- package/examples/trips/map.ts +3 -14
- package/examples/trips/new-trip.ts +14 -16
- package/examples/weeks/generated/elements.ts +1 -1
- package/examples/weeks/generated/queries.ts +11 -0
- package/examples/weeks/generated/rows.ts +22 -0
- package/examples/weeks/generated/rules.ts +11 -5
- package/examples/weeks/routes.ts +3 -2
- package/examples/weeks/stories.jsonl +1 -0
- package/examples/welcome.css +7 -5
- package/package.json +8 -2
- package/src/awesome.ts +103 -0
- package/src/board.css +75 -0
- package/src/board.ts +173 -0
- package/src/cli.ts +15 -2
- package/src/compile.ts +569 -35
- package/src/definitions.ts +53 -15
- package/src/draft.ts +38 -23
- package/src/drawer.ts +222 -0
- package/src/engine.ts +240 -166
- package/src/fields.ts +268 -0
- package/src/files.ts +6 -4
- package/src/ground.ts +110 -0
- package/src/icon-names.ts +15 -2
- package/src/kit.ts +51 -0
- package/src/link.ts +3 -3
- package/src/map.css +133 -0
- package/src/map.ts +200 -0
- package/src/mcp.ts +106 -22
- package/src/members/demo.ts +13 -12
- package/src/members/generated/rows.ts +22 -0
- package/src/members/generated/rules.ts +3 -2
- package/src/members/group.ts +65 -39
- package/src/members/keys.ts +93 -77
- package/src/members/panel.css +23 -17
- package/src/members/panel.ts +49 -35
- package/src/migrate.ts +120 -104
- package/src/month.css +125 -0
- package/src/month.ts +179 -0
- package/src/page.css +8 -0
- package/src/page.ts +7 -4
- package/src/parts.css +462 -170
- package/src/parts.ts +209 -26
- package/src/plane.css +56 -0
- package/src/plane.ts +151 -0
- package/src/postgres-server.ts +60 -0
- package/src/reading.css +77 -0
- package/src/reading.ts +238 -0
- package/src/rows.css +308 -0
- package/src/rows.ts +780 -0
- package/src/search.css +80 -0
- package/src/search.ts +130 -0
- package/src/server.ts +205 -114
- package/src/settings.ts +9 -4
- package/src/sheet.ts +114 -0
- package/src/skill.ts +40 -0
- package/src/slots.css +94 -0
- package/src/slots.ts +213 -0
- package/src/specs.ts +38 -0
- package/src/starter.ts +5 -2
- package/src/store.ts +184 -143
- package/src/stories.ts +43 -11
- package/src/surface.ts +159 -0
- package/src/timeline.css +111 -0
- package/src/timeline.ts +226 -0
- package/src/toast.ts +21 -48
- package/src/together.ts +0 -7
- package/src/tokens.css +78 -1
- package/src/tokens.json +249 -0
- package/src/tool.ts +211 -0
- package/src/upkeep.ts +18 -20
- package/src/views.css +44 -0
- package/src/views.ts +94 -0
- package/src/week.css +151 -0
- package/src/week.ts +250 -0
- package/src/write.ts +202 -69
- package/starter/CLAUDE.md +3 -3
- package/starter/bunfig +4 -0
- package/starter/prettierignore +4 -0
- package/starter/tests/hello.test.ts +2 -0
- package/docs/learning.md +0 -76
- package/examples/cafe/trust.ts +0 -20
- package/examples/desk/trust.ts +0 -24
- package/examples/people/trust.ts +0 -14
- package/examples/trip/answer-rows.ts +0 -70
- package/examples/trip/bar.ts +0 -89
- package/examples/trip/calendar-map.css +0 -711
- package/examples/trip/calendar-map.ts +0 -249
- package/examples/trip/drags.ts +0 -143
- package/examples/trip/drawer.ts +0 -250
- package/examples/trip/event-form.ts +0 -200
- package/examples/trip/holding.ts +0 -61
- package/examples/trip/map.ts +0 -234
- package/examples/trip/month.ts +0 -87
- package/examples/trip/other-weeks.ts +0 -67
- package/examples/trip/peek.ts +0 -71
- package/examples/trip/people-chips.ts +0 -74
- package/examples/trip/shell.ts +0 -39
- package/examples/trip/trust.ts +0 -51
- package/examples/trip/week.ts +0 -237
- package/examples/trip/writes.ts +0 -91
- package/examples/trip/zones.ts +0 -16
- package/examples/weeks/derive.ts +0 -23
- package/src/scrim.ts +0 -81
package/src/store.ts
CHANGED
|
@@ -195,6 +195,8 @@ const BEHIND = 500;
|
|
|
195
195
|
|
|
196
196
|
/** The store in its database: migrated, joined's own and then each app's, in the order given. */
|
|
197
197
|
export async function openStore(db: Engine, given: { name: string; dir: string; rules: Rules }[]) {
|
|
198
|
+
/** This store's own name, on what it notifies: what it hears of its own is skipped. */
|
|
199
|
+
const self = crypto.randomUUID();
|
|
198
200
|
// each app's SQL as its engine says it
|
|
199
201
|
const apps = given.map((a) => ({
|
|
200
202
|
...a,
|
|
@@ -202,33 +204,42 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
202
204
|
}));
|
|
203
205
|
// what a write changes, noted by the database as each row was before its first change (none: added), whoever
|
|
204
206
|
// changes it, in the connection's own table; a Postgres store's triggers last, and are made again below
|
|
205
|
-
db.run(
|
|
207
|
+
await db.run(
|
|
206
208
|
`CREATE TEMP TABLE IF NOT EXISTS joined_touched (n ${db.dialect === "sqlite" ? "INTEGER PRIMARY KEY" : "SERIAL PRIMARY KEY"}, tbl TEXT NOT NULL, id INTEGER NOT NULL, was INTEGER, before TEXT, UNIQUE (tbl, id))`,
|
|
207
209
|
);
|
|
208
210
|
if (db.dialect === "postgres")
|
|
209
|
-
for (const like of [
|
|
210
|
-
|
|
211
|
+
for (const like of [
|
|
212
|
+
"joined_touch_%",
|
|
213
|
+
"joined_takes_%",
|
|
214
|
+
"joined_gives_%",
|
|
215
|
+
"joined_totals_%",
|
|
216
|
+
"joined_with_%",
|
|
217
|
+
"joined_frozen_%",
|
|
218
|
+
"joined_within_%",
|
|
219
|
+
"joined_apart_%",
|
|
220
|
+
])
|
|
221
|
+
await dropTriggers(db, like);
|
|
211
222
|
// each app's migrations, as its own: told its tables, so another's being there doesn't make it old here
|
|
212
223
|
const histories: Awaited<ReturnType<typeof fromFolder>>[] = [];
|
|
213
224
|
for (const [app, dir] of [["joined", OWN], ...apps.map((a) => [a.name, `${a.dir}/migrations`])] as const) {
|
|
214
225
|
const list = existsSync(dir) ? await fromFolder(dir) : [];
|
|
215
|
-
migrate(db, app, list);
|
|
226
|
+
await migrate(db, app, list);
|
|
216
227
|
histories.push(list);
|
|
217
228
|
}
|
|
218
229
|
// each link a foreign key (Postgres's made now) and guarded where it points, now every app's tables are there (one
|
|
219
230
|
// app's may link to another's after it)
|
|
220
231
|
const tables: State = Object.assign({}, ...histories.map(stateOf));
|
|
221
|
-
db.transaction(() => {
|
|
222
|
-
for (const [key, t] of Object.entries(tables)) (linked(db, key, t), guardHeld(db, key, t));
|
|
223
|
-
})
|
|
232
|
+
await db.transaction(async () => {
|
|
233
|
+
for (const [key, t] of Object.entries(tables)) (await linked(db, key, t), await guardHeld(db, key, t));
|
|
234
|
+
});
|
|
224
235
|
// a collection the migrations made no table for, or a field no column (or pairs), or a kind's rows no column to be
|
|
225
236
|
// kept with their instance by: its stories changed, and weren't compiled (or a migration that had run was changed)
|
|
226
237
|
for (const { name, rules } of apps.filter((a) => !a.rules.member))
|
|
227
238
|
for (const [coll, c] of Object.entries(rules.collections)) {
|
|
228
|
-
const cols = db.columns(coll);
|
|
239
|
+
const cols = await db.columns(coll);
|
|
229
240
|
if (!cols.length) throw new Error(`${name}'s ${coll} has no table: bun run compile writes its migrations`);
|
|
230
241
|
for (const f of [...Object.keys(c.fields), ...(rules.kind ? [rules.kind.column] : [])])
|
|
231
|
-
if (c.fields[f] === "ids" ? !db.columns(`${coll}_${f}`).length : !cols.includes(f))
|
|
242
|
+
if (c.fields[f] === "ids" ? !(await db.columns(`${coll}_${f}`)).length : !cols.includes(f))
|
|
232
243
|
throw new Error(`${name}'s ${coll}.${f} has nowhere to be kept: bun run compile writes its migrations`);
|
|
233
244
|
}
|
|
234
245
|
const docs = new Map(apps.map((a) => [a.rules.doc, a.rules]));
|
|
@@ -250,55 +261,61 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
250
261
|
const rules = apps.find((a) => a.rules.collections[coll])!.rules;
|
|
251
262
|
const keep = (row: string) =>
|
|
252
263
|
`INSERT INTO ${noted} (tbl, id, was, before) SELECT '${coll}', t.id, ${of}, CAST(${item} AS TEXT) FROM ${q(coll)} t WHERE t.id = ${row} ON CONFLICT DO NOTHING;`;
|
|
253
|
-
const on = (name: string, event: string, table: string, body: string) =>
|
|
254
|
-
db.run(
|
|
255
|
-
|
|
264
|
+
const on = async (name: string, event: string, table: string, body: string) =>
|
|
265
|
+
await db.run(
|
|
266
|
+
triggerSql(db.dialect, { name: `joined_touch_${name}`, at: "BEFORE", event, table, body, temp: true }),
|
|
267
|
+
);
|
|
268
|
+
await on(
|
|
256
269
|
`${coll}_insert`,
|
|
257
270
|
"INSERT",
|
|
258
271
|
coll,
|
|
259
272
|
`INSERT INTO ${noted} (tbl, id) VALUES ('${coll}', NEW.id) ON CONFLICT DO NOTHING;`,
|
|
260
273
|
);
|
|
261
|
-
on(`${coll}_update`, "UPDATE", coll, keep("OLD.id"));
|
|
262
|
-
on(`${coll}_delete`, "DELETE", coll, keep("OLD.id"));
|
|
274
|
+
await on(`${coll}_update`, "UPDATE", coll, keep("OLD.id"));
|
|
275
|
+
await on(`${coll}_delete`, "DELETE", coll, keep("OLD.id"));
|
|
263
276
|
for (const [f, t] of Object.entries(rules.collections[coll]!.fields))
|
|
264
277
|
if (t === "ids") {
|
|
265
|
-
on(`${coll}_${f}_insert`, "INSERT", `${coll}_${f}`, keep(`NEW.${q(coll)}`))
|
|
266
|
-
|
|
278
|
+
(await on(`${coll}_${f}_insert`, "INSERT", `${coll}_${f}`, keep(`NEW.${q(coll)}`)),
|
|
279
|
+
await on(`${coll}_${f}_delete`, "DELETE", `${coll}_${f}`, keep(`OLD.${q(coll)}`)));
|
|
267
280
|
}
|
|
268
281
|
}
|
|
269
282
|
// the rules over values, run in each write's transaction: made once the seeds are in (a seed is the state as it
|
|
270
283
|
// is: a supply delivered before isn't delivered again as it's taken)
|
|
271
284
|
const ruled = apps.flatMap(({ rules }) => rules.triggers ?? []);
|
|
272
|
-
const rule = (on: boolean) => {
|
|
273
|
-
for (const sql of ruled) db.run(on ? sql : dropTriggerSql(db.dialect, sql));
|
|
285
|
+
const rule = async (on: boolean) => {
|
|
286
|
+
for (const sql of ruled) await db.run(on ? sql : dropTriggerSql(db.dialect, sql));
|
|
274
287
|
};
|
|
275
|
-
rule(true);
|
|
288
|
+
await rule(true);
|
|
289
|
+
/** The triggers that wait for a write's end (Postgres's constraint triggers), by name. */
|
|
290
|
+
const waiting = ruled.flatMap((sql) => /CREATE CONSTRAINT TRIGGER ("(?:[^"]|"")+")/.exec(sql)?.[1] ?? []).join(", ");
|
|
276
291
|
/** The rows a write changed, in the order it first changed them: each as it was and is. */
|
|
277
|
-
const touched = (): Row[] =>
|
|
278
|
-
(
|
|
279
|
-
|
|
280
|
-
tbl
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
292
|
+
const touched = async (): Promise<Row[]> =>
|
|
293
|
+
Promise.all(
|
|
294
|
+
(
|
|
295
|
+
(await db.query(`SELECT tbl, id, was, before FROM ${noted} ORDER BY n`).all()) as {
|
|
296
|
+
tbl: string;
|
|
297
|
+
id: number;
|
|
298
|
+
was: number | null;
|
|
299
|
+
before: string | null;
|
|
300
|
+
}[]
|
|
301
|
+
).map(async ({ tbl, id, was, before }) => {
|
|
302
|
+
const { of, item } = holding.get(tbl)!;
|
|
303
|
+
const now = (await db
|
|
304
|
+
.query(`SELECT ${of} AS is_, CAST(${item} AS TEXT) AS item FROM ${q(tbl)} t WHERE t.id = ?`)
|
|
305
|
+
.get(id)) as {
|
|
306
|
+
is_: number | null;
|
|
307
|
+
item: string;
|
|
308
|
+
} | null;
|
|
309
|
+
return {
|
|
310
|
+
coll: tbl,
|
|
311
|
+
id,
|
|
312
|
+
before: before === null ? null : JSON.parse(before),
|
|
313
|
+
after: now && JSON.parse(now.item),
|
|
314
|
+
was,
|
|
315
|
+
is: now?.is_ ?? null,
|
|
316
|
+
};
|
|
317
|
+
}),
|
|
318
|
+
);
|
|
302
319
|
/** Each document a write's rows are in, by name (an instance's, shelf:1), and its ops in its own paths, with their
|
|
303
320
|
* inverse. The rows the write's own ops made, in the document written (`made`, by collection and id), are its ops
|
|
304
321
|
* as made. (An item never moves from one instance to another: no op writes the column it's kept with them by.) */
|
|
@@ -322,7 +339,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
322
339
|
// a document's own fields are its one row's, there from the start (a store from before has it, empty)
|
|
323
340
|
for (const { rules } of apps)
|
|
324
341
|
for (const [coll, c] of Object.entries(rules.collections))
|
|
325
|
-
if (c.own) db.run(`INSERT INTO ${q(coll)} (id) VALUES (1) ON CONFLICT DO NOTHING`);
|
|
342
|
+
if (c.own) await db.run(`INSERT INTO ${q(coll)} (id) VALUES (1) ON CONFLICT DO NOTHING`);
|
|
326
343
|
/** A document's rules, and, of a kind's instance (shelf:1), the column its rows are kept by and its root item.
|
|
327
344
|
* A name is one way of writing it alone: shelf:01 and shelf:1.0 are no document. */
|
|
328
345
|
const of = (doc: string) => {
|
|
@@ -365,11 +382,11 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
365
382
|
};
|
|
366
383
|
|
|
367
384
|
/** A list's ids, each a pair: one named twice is refused by its table, in its words. */
|
|
368
|
-
function setPairs(coll: string, field: string, id: number, ids: number[]) {
|
|
369
|
-
db.run(`DELETE FROM ${q(`${coll}_${field}`)} WHERE ${q(coll)} = ?`, [id]);
|
|
385
|
+
async function setPairs(coll: string, field: string, id: number, ids: number[]) {
|
|
386
|
+
await db.run(`DELETE FROM ${q(`${coll}_${field}`)} WHERE ${q(coll)} = ?`, [id]);
|
|
370
387
|
for (const to of ids)
|
|
371
|
-
db.run(`INSERT INTO ${q(`${coll}_${field}`)} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
372
|
-
nextId(`${coll}_${field}`),
|
|
388
|
+
await db.run(`INSERT INTO ${q(`${coll}_${field}`)} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
389
|
+
await nextId(`${coll}_${field}`),
|
|
373
390
|
id,
|
|
374
391
|
to,
|
|
375
392
|
]);
|
|
@@ -377,17 +394,17 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
377
394
|
|
|
378
395
|
/** One id added to an item's list (its table refusing one there already, or one that's no item), or taken from
|
|
379
396
|
* it: refused if it isn't there. */
|
|
380
|
-
function pair(coll: string, field: string, id: number, to: number, add: boolean) {
|
|
397
|
+
async function pair(coll: string, field: string, id: number, to: number, add: boolean) {
|
|
381
398
|
const table = q(`${coll}_${field}`);
|
|
382
|
-
if (!add && !db.query(`SELECT 1 FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`).get(id, to))
|
|
399
|
+
if (!add && !(await db.query(`SELECT 1 FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`).get(id, to)))
|
|
383
400
|
throw new Refused(`${field} doesn't link to ${to}`);
|
|
384
401
|
if (add)
|
|
385
|
-
db.run(`INSERT INTO ${table} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
386
|
-
nextId(`${coll}_${field}`),
|
|
402
|
+
await db.run(`INSERT INTO ${table} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
403
|
+
await nextId(`${coll}_${field}`),
|
|
387
404
|
id,
|
|
388
405
|
to,
|
|
389
406
|
]);
|
|
390
|
-
else db.run(`DELETE FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`, [id, to]);
|
|
407
|
+
else await db.run(`DELETE FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`, [id, to]);
|
|
391
408
|
}
|
|
392
409
|
|
|
393
410
|
/** The collection of a document's own fields (hello's), if it has them: named for it, of one item. */
|
|
@@ -404,14 +421,14 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
404
421
|
};
|
|
405
422
|
|
|
406
423
|
/** An item as the document has it: its fields, null ones left out, and its lists (none: left out). */
|
|
407
|
-
function itemAt(coll: string, c: Rules["collections"][string], id: number): Item {
|
|
408
|
-
const row = db.query(`SELECT * FROM ${q(coll)} WHERE id = ?`).get(id) as Item;
|
|
424
|
+
async function itemAt(coll: string, c: Rules["collections"][string], id: number): Promise<Item> {
|
|
425
|
+
const row = (await db.query(`SELECT * FROM ${q(coll)} WHERE id = ?`).get(id)) as Item;
|
|
409
426
|
const item: Item = { id };
|
|
410
427
|
for (const [f, t] of Object.entries(c.fields)) {
|
|
411
428
|
if (t === "ids") {
|
|
412
|
-
const ids = db
|
|
429
|
+
const ids = (await db
|
|
413
430
|
.query(`SELECT ${q(f)} AS to_ FROM ${q(`${coll}_${f}`)} WHERE ${q(coll)} = ? ORDER BY id`)
|
|
414
|
-
.all(id) as { to_: number }[];
|
|
431
|
+
.all(id)) as { to_: number }[];
|
|
415
432
|
if (ids.length) item[f] = ids.map((r) => r.to_);
|
|
416
433
|
} else if (row[f] !== null) item[f] = t === "boolean" ? row[f] === 1 : row[f];
|
|
417
434
|
}
|
|
@@ -421,7 +438,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
421
438
|
/** An op made on the rows, and the ops that put back what it did (its inverse): an add given the next id,
|
|
422
439
|
* which the pages are told, or, putting back an item removed, the id it had (an undo's, its value's id); an id
|
|
423
440
|
* added to a list or taken from it, the one pair. */
|
|
424
|
-
function apply(doc: string, o: Op, undoing: boolean): { applied: Op; inverse: Op[] } {
|
|
441
|
+
async function apply(doc: string, o: Op, undoing: boolean): Promise<{ applied: Op; inverse: Op[] }> {
|
|
425
442
|
const { coll, key, field, link } = parts(o.path);
|
|
426
443
|
const c = collectionOf(doc, coll);
|
|
427
444
|
// one of an object's fields (/orders/1/terms/days, its column terms.days), or an object whole (/orders/1/terms)
|
|
@@ -437,15 +454,15 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
437
454
|
if (back !== undefined && !undoing) throw new Refused("id is the server's to give");
|
|
438
455
|
const other = Object.keys(value).find((f) => !(f in c.fields));
|
|
439
456
|
if (other) throw new Refused(`${an(c.tag)} has no ${other}`);
|
|
440
|
-
const id = (back as number | undefined) ?? nextId(coll);
|
|
457
|
+
const id = (back as number | undefined) ?? (await nextId(coll));
|
|
441
458
|
const cols = Object.keys(value).filter((f) => c.fields[f] !== "ids");
|
|
442
459
|
const all = by ? [...cols, by.column] : cols;
|
|
443
|
-
db.run(
|
|
460
|
+
await db.run(
|
|
444
461
|
`INSERT INTO ${q(coll)} (${["id", ...all].map(q).join(", ")}) VALUES (${["?", ...all.map(() => "?")].join(", ")})`,
|
|
445
462
|
[id, ...cols.map((f) => cell(coll, f, c.fields[f]!, value[f])), ...(by ? [by.n] : [])] as any[],
|
|
446
463
|
);
|
|
447
464
|
for (const f of Object.keys(value).filter((f) => c.fields[f] === "ids"))
|
|
448
|
-
setPairs(coll, f, id, value[f] as number[]);
|
|
465
|
+
await setPairs(coll, f, id, value[f] as number[]);
|
|
449
466
|
return {
|
|
450
467
|
applied: { op: "add", path: `/${coll}/-`, value: { ...nest(value), id } },
|
|
451
468
|
inverse: [{ op: "remove", path: `/${coll}/${id}` }],
|
|
@@ -453,16 +470,16 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
453
470
|
}
|
|
454
471
|
const id = Number(key);
|
|
455
472
|
const { sql, args } = mine(doc, coll);
|
|
456
|
-
if (!db.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${sql}`).get(id, ...args))
|
|
473
|
+
if (!(await db.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${sql}`).get(id, ...args)))
|
|
457
474
|
throw new Refused(`no ${c.tag} at ${o.path}`);
|
|
458
|
-
const was = itemAt(coll, c, id);
|
|
475
|
+
const was = await itemAt(coll, c, id);
|
|
459
476
|
let inverse: Op[];
|
|
460
477
|
if (sub || whole.length) {
|
|
461
478
|
// an object's fields, each its column: one, or all of them (one not given, emptied)
|
|
462
479
|
const cols = sub ? [sub] : whole,
|
|
463
480
|
given = sub ? { [sub]: o.value } : flat({ [field!]: o.value ?? {} });
|
|
464
481
|
for (const col of cols)
|
|
465
|
-
db.run(`UPDATE ${q(coll)} SET ${q(col)} = ? WHERE id = ?`, [
|
|
482
|
+
await db.run(`UPDATE ${q(coll)} SET ${q(col)} = ? WHERE id = ?`, [
|
|
466
483
|
o.op === "remove" ? null : cell(coll, col, c.fields[col]!, given[col]),
|
|
467
484
|
id,
|
|
468
485
|
] as any[]);
|
|
@@ -473,20 +490,20 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
473
490
|
inverse = [had === undefined ? { op: "remove", path } : { op: "replace", path, value: had }];
|
|
474
491
|
} else if (link !== undefined) {
|
|
475
492
|
const to = o.op === "add" ? (o.value as number) : Number(link);
|
|
476
|
-
pair(coll, field!, id, to, o.op === "add");
|
|
493
|
+
await pair(coll, field!, id, to, o.op === "add");
|
|
477
494
|
inverse = [
|
|
478
495
|
o.op === "add"
|
|
479
496
|
? { op: "remove", path: `/${coll}/${id}/${field}/${to}` }
|
|
480
497
|
: { op: "add", path: `/${coll}/${id}/${field}/-`, value: to },
|
|
481
498
|
];
|
|
482
499
|
} else if (o.op === "remove" && field === undefined) {
|
|
483
|
-
for (const [f, t] of Object.entries(c.fields)) if (t === "ids") setPairs(coll, f, id, []);
|
|
484
|
-
db.run(`DELETE FROM ${q(coll)} WHERE id = ?`, [id]);
|
|
500
|
+
for (const [f, t] of Object.entries(c.fields)) if (t === "ids") await setPairs(coll, f, id, []);
|
|
501
|
+
await db.run(`DELETE FROM ${q(coll)} WHERE id = ?`, [id]);
|
|
485
502
|
inverse = [{ op: "add", path: `/${coll}/-`, value: was }];
|
|
486
503
|
} else {
|
|
487
|
-
if (c.fields[field!] === "ids") setPairs(coll, field!, id, o.op === "remove" ? [] : (o.value as number[]));
|
|
504
|
+
if (c.fields[field!] === "ids") await setPairs(coll, field!, id, o.op === "remove" ? [] : (o.value as number[]));
|
|
488
505
|
else
|
|
489
|
-
db.run(`UPDATE ${q(coll)} SET ${q(field!)} = ? WHERE id = ?`, [
|
|
506
|
+
await db.run(`UPDATE ${q(coll)} SET ${q(field!)} = ? WHERE id = ?`, [
|
|
490
507
|
o.op === "remove" ? null : cell(coll, field!, c.fields[field!]!, o.value),
|
|
491
508
|
id,
|
|
492
509
|
] as any[]);
|
|
@@ -496,47 +513,52 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
496
513
|
return { applied: o, inverse };
|
|
497
514
|
}
|
|
498
515
|
|
|
499
|
-
const versionOf = (doc: string) =>
|
|
500
|
-
(db.query("SELECT version FROM documents WHERE name = ?").get(doc) as { version: number } | null)?.version;
|
|
516
|
+
const versionOf = async (doc: string) =>
|
|
517
|
+
((await db.query("SELECT version FROM documents WHERE name = ?").get(doc)) as { version: number } | null)?.version;
|
|
501
518
|
/** A document's version moved on, its new one: an instance of a kind is begun by its first write, at version 0. */
|
|
502
|
-
function moved(doc: string) {
|
|
503
|
-
const
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
519
|
+
async function moved(doc: string) {
|
|
520
|
+
const r = (await db
|
|
521
|
+
.query("UPDATE documents SET version = version + 1 WHERE name = ? RETURNING version")
|
|
522
|
+
.get(doc)) as {
|
|
523
|
+
version: number;
|
|
524
|
+
} | null;
|
|
525
|
+
if (r) return r.version;
|
|
526
|
+
await db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, 1)", [await nextId("documents"), doc]);
|
|
527
|
+
return 1;
|
|
508
528
|
}
|
|
509
529
|
|
|
510
530
|
return {
|
|
511
531
|
db,
|
|
512
532
|
/** Whether a document holds an item: what a link may point at. */
|
|
513
|
-
has: (doc: string, coll: string, id: number) =>
|
|
533
|
+
has: async (doc: string, coll: string, id: number) =>
|
|
514
534
|
!!of(doc).rules?.collections[coll] &&
|
|
515
|
-
!!
|
|
535
|
+
!!(await db
|
|
536
|
+
.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${mine(doc, coll).sql}`)
|
|
537
|
+
.get(id, ...mine(doc, coll).args)),
|
|
516
538
|
/** Whether a document can be held: one of the documents, or an instance of a kind whose root item is there. */
|
|
517
|
-
exists(doc: string) {
|
|
539
|
+
async exists(doc: string): Promise<boolean> {
|
|
518
540
|
const { base, params } = docParts(doc);
|
|
519
541
|
const { rules, by } = of(base);
|
|
520
542
|
if (!rules || base.includes(":") !== !!rules.kind) return false;
|
|
521
543
|
// a window is written one way alone: its parameters, in its order, each once, a date one a date
|
|
522
544
|
if (doc.includes("?") && doc !== windowed(base, rules, params)) return false;
|
|
523
|
-
return !by || this.has(rules.kind!.doc, rules.kind!.root, by.n);
|
|
545
|
+
return !by || (await this.has(rules.kind!.doc, rules.kind!.root, by.n));
|
|
524
546
|
},
|
|
525
547
|
|
|
526
548
|
/** A document, whole, as a page is sent it, read by its query: each item with its fields, null ones left out,
|
|
527
549
|
* and its lists. */
|
|
528
|
-
read(doc: string, member?: number): Doc {
|
|
550
|
+
async read(doc: string, member?: number): Promise<Doc> {
|
|
529
551
|
const { base, params } = docParts(doc);
|
|
530
552
|
const { rules, by } = of(base);
|
|
531
553
|
// each of its window's parameters, given or not (null: the whole of it); a document read by member, its
|
|
532
554
|
// member's (nobody: 0)
|
|
533
555
|
const window = Object.fromEntries(windowOf(rules!).map((p) => [p, params[p] ?? null]));
|
|
534
|
-
const row = db.query(rules!.query).get({
|
|
556
|
+
const row = (await db.query(rules!.query).get({
|
|
535
557
|
doc: base,
|
|
536
558
|
...(by ? { key: by.n } : {}),
|
|
537
559
|
...window,
|
|
538
560
|
...(rules!.member ? { member: member ?? 0 } : rules!.sees ? { member: member ?? null } : {}),
|
|
539
|
-
}) as {
|
|
561
|
+
})) as {
|
|
540
562
|
doc: string;
|
|
541
563
|
};
|
|
542
564
|
return JSON.parse(row.doc);
|
|
@@ -548,20 +570,20 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
548
570
|
* (first, its ops as they leave it), and every other a rule reached (`followed`). `undoes`, the version an undo
|
|
549
571
|
* puts back. Its changes, with the ops as they were made (what an add was given), and the rows it changed; or a
|
|
550
572
|
* refusal, with why. */
|
|
551
|
-
write(
|
|
573
|
+
async write(
|
|
552
574
|
name: string,
|
|
553
575
|
ops: Op[],
|
|
554
576
|
by: number | null,
|
|
555
577
|
via: string | null,
|
|
556
|
-
within?: (applied: Op[]) =>
|
|
578
|
+
within?: (applied: Op[]) => unknown,
|
|
557
579
|
{ undoes }: { undoes?: number } = {},
|
|
558
|
-
): { changes: Change[]; applied: Op[]; rows: Record<string, Row[]>; tables: string[] } {
|
|
580
|
+
): Promise<{ changes: Change[]; applied: Op[]; rows: Record<string, Row[]>; tables: string[] }> {
|
|
559
581
|
// a window's write is its document's
|
|
560
582
|
const doc = docParts(name).base;
|
|
561
|
-
return db.transaction(() => {
|
|
562
|
-
db.run(`DELETE FROM ${noted}`);
|
|
583
|
+
return db.transaction(async () => {
|
|
584
|
+
await db.run(`DELETE FROM ${noted}`);
|
|
563
585
|
// a value naming an add before it in this write ("$1", the first add's) is the id that add was given
|
|
564
|
-
const done: ReturnType<typeof apply
|
|
586
|
+
const done: Awaited<ReturnType<typeof apply>>[] = [];
|
|
565
587
|
const minted: number[] = [];
|
|
566
588
|
const named = (v: unknown): unknown =>
|
|
567
589
|
typeof v === "string" && /^\$[1-9]\d*$/.test(v)
|
|
@@ -572,7 +594,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
572
594
|
? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, named(x)]))
|
|
573
595
|
: v;
|
|
574
596
|
for (const o of ops) {
|
|
575
|
-
const d = apply(
|
|
597
|
+
const d = await apply(
|
|
576
598
|
doc,
|
|
577
599
|
inward(doc, { ...o, ...("value" in o ? { value: named(o.value) } : {}) }),
|
|
578
600
|
undoes !== undefined,
|
|
@@ -581,7 +603,9 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
581
603
|
done.push(d);
|
|
582
604
|
}
|
|
583
605
|
const applied = done.map((d) => outward(doc, d.applied));
|
|
584
|
-
within?.(applied);
|
|
606
|
+
await within?.(applied);
|
|
607
|
+
// what waits for the write's end (Postgres's lists, within and apart), held now: refused in its words
|
|
608
|
+
if (waiting.length) await db.run(`SET CONSTRAINTS ${waiting} IMMEDIATE; SET CONSTRAINTS ${waiting} DEFERRED`);
|
|
585
609
|
// the document written is told its ops as made (what an add was given), and what a rule changed of it besides
|
|
586
610
|
const made = new Set(
|
|
587
611
|
done.map(({ applied: o }) => {
|
|
@@ -589,7 +613,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
589
613
|
return `${coll}/${key === "-" ? o.value.id : key}`;
|
|
590
614
|
}),
|
|
591
615
|
);
|
|
592
|
-
const all = touched(),
|
|
616
|
+
const all = await touched(),
|
|
593
617
|
names = told(all, doc, made);
|
|
594
618
|
const own = names.get(doc) ?? { ops: [], inverse: [], rows: [] };
|
|
595
619
|
// an item it added as the write left it: what the server filled, and what a rule worked out (an order's total)
|
|
@@ -606,13 +630,14 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
606
630
|
],
|
|
607
631
|
inverse: [...own.inverse, ...done.flatMap((d) => d.inverse.map((o) => outward(doc, o))).reverse()],
|
|
608
632
|
});
|
|
609
|
-
const changes
|
|
633
|
+
const changes: Change[] = [];
|
|
634
|
+
for (const name of [doc, ...[...names.keys()].filter((n) => n !== doc)]) {
|
|
610
635
|
const { ops, inverse } = names.get(name)!,
|
|
611
|
-
version = moved(name);
|
|
612
|
-
db.run(
|
|
636
|
+
version = await moved(name);
|
|
637
|
+
await db.run(
|
|
613
638
|
"INSERT INTO changes (id, doc, version, ops, inverse, undoes, followed, member, via, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
614
639
|
[
|
|
615
|
-
nextId("changes"),
|
|
640
|
+
await nextId("changes"),
|
|
616
641
|
name,
|
|
617
642
|
version,
|
|
618
643
|
JSON.stringify(ops),
|
|
@@ -624,8 +649,10 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
624
649
|
new Date().toISOString(),
|
|
625
650
|
],
|
|
626
651
|
);
|
|
627
|
-
|
|
628
|
-
|
|
652
|
+
changes.push({ doc: name, version, ops, by, via });
|
|
653
|
+
// every server on the database told it as it commits (Postgres's NOTIFY; SQLite's one server tells its own)
|
|
654
|
+
await db.notify("joined", JSON.stringify({ doc: name, version, from: self }));
|
|
655
|
+
}
|
|
629
656
|
return {
|
|
630
657
|
changes,
|
|
631
658
|
applied,
|
|
@@ -633,7 +660,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
633
660
|
// every table it changed, whatever holds it (a document holding only some of a table's rows is told as a whole)
|
|
634
661
|
tables: [...new Set(all.map((r) => r.coll))],
|
|
635
662
|
};
|
|
636
|
-
})
|
|
663
|
+
});
|
|
637
664
|
},
|
|
638
665
|
|
|
639
666
|
/** A document's version moved on, with no change of its own to keep (one read as each member has it, whose
|
|
@@ -642,10 +669,10 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
642
669
|
|
|
643
670
|
/** A change as its row keeps it: its ops, their inverse, what it undoes, and whether a rule made it;
|
|
644
671
|
* or undefined, if it isn't kept (let go, or from before inverses were). */
|
|
645
|
-
change(doc: string, version: number): Kept | undefined {
|
|
646
|
-
const r = db
|
|
672
|
+
async change(doc: string, version: number): Promise<Kept | undefined> {
|
|
673
|
+
const r = (await db
|
|
647
674
|
.query("SELECT ops, inverse, undoes, followed, member, via FROM changes WHERE doc = ? AND version = ?")
|
|
648
|
-
.get(doc, version) as {
|
|
675
|
+
.get(doc, version)) as {
|
|
649
676
|
ops: string;
|
|
650
677
|
inverse: string | null;
|
|
651
678
|
undoes: number | null;
|
|
@@ -669,8 +696,8 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
669
696
|
/** The ops that undo a change, guarded as delta's walk is: what it left at each path it changed (an item it
|
|
670
697
|
* added, whole; a field it set or cleared; an id it put in a list or took out) must be there still. A value
|
|
671
698
|
* someone has changed since refuses the undo, saying where: undone, it would lose their change. */
|
|
672
|
-
undoing(doc: string, version: number): Op[] {
|
|
673
|
-
const c = this.change(doc, version);
|
|
699
|
+
async undoing(doc: string, version: number): Promise<Op[]> {
|
|
700
|
+
const c = await this.change(doc, version);
|
|
674
701
|
if (!c) throw new Refused(`${doc}'s change ${version} isn't kept, so it can't be undone`);
|
|
675
702
|
if (c.followed) throw new Refused(`${doc}'s change ${version} followed another write: undo that`);
|
|
676
703
|
const left = new Map<string, unknown>();
|
|
@@ -694,18 +721,18 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
694
721
|
}
|
|
695
722
|
}
|
|
696
723
|
// each row as it is now, read by its id (a document holding only some rows may hold it no longer)
|
|
697
|
-
const at = (coll: string, id: string) => {
|
|
698
|
-
if (of(doc).rules!.collections[coll]?.own) return ownOf(this.read(doc)) as Item;
|
|
699
|
-
const row = db
|
|
724
|
+
const at = async (coll: string, id: string) => {
|
|
725
|
+
if (of(doc).rules!.collections[coll]?.own) return ownOf(await this.read(doc)) as Item;
|
|
726
|
+
const row = (await db
|
|
700
727
|
.query(`SELECT ${holding.get(coll)!.item} AS item FROM ${q(coll)} t WHERE t.id = ?`)
|
|
701
|
-
.get(Number(id)) as {
|
|
728
|
+
.get(Number(id))) as {
|
|
702
729
|
item: string;
|
|
703
730
|
} | null;
|
|
704
731
|
return row ? (JSON.parse(row.item) as Item) : undefined;
|
|
705
732
|
};
|
|
706
733
|
for (const [path, was] of left) {
|
|
707
734
|
const [, coll, id, field, to] = path.split("/") as [string, string, string, string?, string?];
|
|
708
|
-
const here = at(coll, id);
|
|
735
|
+
const here = await at(coll, id);
|
|
709
736
|
const still =
|
|
710
737
|
field === undefined
|
|
711
738
|
? same(here, was)
|
|
@@ -720,50 +747,53 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
720
747
|
/** The changes after a version, in order, for a page catching up; null when they aren't all here (a
|
|
721
748
|
* document brought in from its JSON has no changes for the versions before it), or it's too far
|
|
722
749
|
* behind, or ahead (a page from before the store was): then it must be sent the document whole. */
|
|
723
|
-
since(doc: string, version: number): Change[] | null {
|
|
724
|
-
const now = versionOf(doc) ?? 0;
|
|
750
|
+
async since(doc: string, version: number): Promise<Change[] | null> {
|
|
751
|
+
const now = (await versionOf(doc)) ?? 0;
|
|
725
752
|
if (version > now || now - version > BEHIND) return null;
|
|
726
|
-
const rows = db
|
|
753
|
+
const rows = (await db
|
|
727
754
|
.query("SELECT version, ops, member, via FROM changes WHERE doc = ? AND version > ? ORDER BY version")
|
|
728
|
-
.all(doc, version) as { version: number; ops: string; member: number | null; via: string | null }[];
|
|
755
|
+
.all(doc, version)) as { version: number; ops: string; member: number | null; via: string | null }[];
|
|
729
756
|
if (rows.length !== now - version) return null;
|
|
730
757
|
return rows.map((r) => ({ doc, version: r.version, ops: JSON.parse(r.ops), by: r.member, via: r.via }));
|
|
731
758
|
},
|
|
732
759
|
|
|
733
760
|
/** The changes made before a time (ms) that no page catching up needs, each beyond its document's last
|
|
734
761
|
* BEHIND, let go; how many. */
|
|
735
|
-
trim: (before: number) =>
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
762
|
+
trim: async (before: number) =>
|
|
763
|
+
(
|
|
764
|
+
await db.run(
|
|
765
|
+
"DELETE FROM changes WHERE at < ? AND version <= (SELECT version FROM documents WHERE name = changes.doc) - ?",
|
|
766
|
+
[new Date(before).toISOString(), BEHIND],
|
|
767
|
+
)
|
|
739
768
|
).changes,
|
|
740
769
|
|
|
741
770
|
/** A document's version, or a kind's (order: every instance's, together): what a document derived from it is
|
|
742
771
|
* versioned by. */
|
|
743
|
-
versions: (name: string) =>
|
|
772
|
+
versions: async (name: string) =>
|
|
744
773
|
(
|
|
745
|
-
db
|
|
746
|
-
.query("SELECT COALESCE(SUM(version), 0) AS n FROM documents WHERE name = ? OR name LIKE ?
|
|
747
|
-
.get(name, name) as { n: number }
|
|
774
|
+
(await db
|
|
775
|
+
.query("SELECT COALESCE(SUM(version), 0) AS n FROM documents WHERE name = ? OR name LIKE ?")
|
|
776
|
+
.get(name, `${name}:%`)) as { n: number }
|
|
748
777
|
).n,
|
|
749
778
|
|
|
750
779
|
/** Whether a document is here yet: a new store is begun from a document's JSON (`take`). */
|
|
751
|
-
holds: (doc: string) => versionOf(doc) !== undefined,
|
|
780
|
+
holds: async (doc: string) => (await versionOf(doc)) !== undefined,
|
|
752
781
|
|
|
753
782
|
/** A document begun from its JSON (the seed, or a file from before the store): its items with their ids,
|
|
754
783
|
* each sequence past the largest, and its version; all in one transaction. `again`: a static document's, its
|
|
755
784
|
* seed a release's, in place of what was. */
|
|
756
|
-
take(doc: string, json: Doc, again = false) {
|
|
785
|
+
async take(doc: string, json: Doc, again = false) {
|
|
757
786
|
const rules = docs.get(doc)!;
|
|
758
|
-
db.transaction(() => {
|
|
787
|
+
await db.transaction(async () => {
|
|
759
788
|
// a seed's items may link to those further on: its links whole by commit
|
|
760
|
-
db.defer();
|
|
789
|
+
await db.defer();
|
|
761
790
|
if (again) {
|
|
762
791
|
for (const [coll, c] of Object.entries(rules.collections)) {
|
|
763
|
-
for (const [f, t] of Object.entries(c.fields))
|
|
764
|
-
|
|
792
|
+
for (const [f, t] of Object.entries(c.fields))
|
|
793
|
+
if (t === "ids") await db.run(`DELETE FROM ${q(`${coll}_${f}`)}`);
|
|
794
|
+
await db.run(`DELETE FROM ${q(coll)}`);
|
|
765
795
|
}
|
|
766
|
-
db.run("DELETE FROM documents WHERE name = ?", [doc]);
|
|
796
|
+
await db.run("DELETE FROM documents WHERE name = ?", [doc]);
|
|
767
797
|
}
|
|
768
798
|
for (const [coll, c] of Object.entries(rules.collections)) {
|
|
769
799
|
// an item the seed gives no id is numbered after the largest it gives, as an add would be
|
|
@@ -778,8 +808,8 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
778
808
|
(f) => c.fields[f] !== "ids" && item[f] !== undefined,
|
|
779
809
|
);
|
|
780
810
|
// (the document's own row is there already: put in its place)
|
|
781
|
-
if (c.own) db.run(`DELETE FROM ${q(coll)} WHERE id = 1`);
|
|
782
|
-
db.run(
|
|
811
|
+
if (c.own) await db.run(`DELETE FROM ${q(coll)} WHERE id = 1`);
|
|
812
|
+
await db.run(
|
|
783
813
|
`INSERT INTO ${q(coll)} (${["id", ...cols].map(q).join(", ")}) VALUES (${["?", ...cols.map(() => "?")].join(", ")})`,
|
|
784
814
|
[item.id, ...cols.map((f) => cell(coll, f, c.fields[f] ?? "integer", item[f]))] as any[],
|
|
785
815
|
);
|
|
@@ -787,28 +817,39 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
787
817
|
// the pairs once every item is in: a list may name an item of this collection further on
|
|
788
818
|
for (const item of c.own ? [] : items)
|
|
789
819
|
for (const [f, t] of Object.entries(c.fields))
|
|
790
|
-
if (t === "ids" && Array.isArray(item[f])) setPairs(coll, f, item.id, item[f] as number[]);
|
|
791
|
-
passed(db, coll, c.own ? 1 : last);
|
|
820
|
+
if (t === "ids" && Array.isArray(item[f])) await setPairs(coll, f, item.id, item[f] as number[]);
|
|
821
|
+
await passed(db, coll, c.own ? 1 : last);
|
|
792
822
|
}
|
|
793
|
-
db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, ?)", [
|
|
794
|
-
|
|
823
|
+
await db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, ?)", [
|
|
824
|
+
await nextId("documents"),
|
|
825
|
+
doc,
|
|
826
|
+
json.version,
|
|
827
|
+
]);
|
|
828
|
+
});
|
|
795
829
|
},
|
|
796
830
|
|
|
797
831
|
/** Documents begun from their JSON, together, in one transaction: one's may link to another's. */
|
|
798
|
-
takeAll(docs: { doc: string; json: Doc; again?: boolean }[]) {
|
|
799
|
-
rule(false);
|
|
832
|
+
async takeAll(docs: { doc: string; json: Doc; again?: boolean }[]) {
|
|
833
|
+
await rule(false);
|
|
800
834
|
try {
|
|
801
|
-
db.transaction(() => {
|
|
802
|
-
db.defer();
|
|
803
|
-
for (const { doc, json, again } of docs) this.take(doc, json, again);
|
|
804
|
-
})
|
|
835
|
+
await db.transaction(async () => {
|
|
836
|
+
await db.defer();
|
|
837
|
+
for (const { doc, json, again } of docs) await this.take(doc, json, again);
|
|
838
|
+
});
|
|
805
839
|
} finally {
|
|
806
|
-
rule(true);
|
|
840
|
+
await rule(true);
|
|
807
841
|
}
|
|
808
842
|
},
|
|
809
843
|
|
|
810
844
|
/** The file let go (a server stopped). */
|
|
811
845
|
close: () => db.close(),
|
|
846
|
+
/** Each change committed by another server on the database, heard as its document and version (Postgres's
|
|
847
|
+
* LISTEN): this one's own it tells as it writes. */
|
|
848
|
+
heard: (fn: (doc: string, version: number) => void) =>
|
|
849
|
+
db.listen("joined", (payload) => {
|
|
850
|
+
const { doc, version, from } = JSON.parse(payload) as { doc: string; version: number; from: string };
|
|
851
|
+
if (from !== self) fn(doc, version);
|
|
852
|
+
}),
|
|
812
853
|
};
|
|
813
854
|
}
|
|
814
855
|
|