48 lines · 1.9 KB · TypeScriptRaw
/** * Where a planned change becomes a row of the object. The Rust engine's * changes are last-write-wins upserts onto (table, id): a row the object does * not hold is made under that id with the batch's stamps, a row it holds takes * the patch (a patch that changes nothing writes nothing), a retract tombstones * it. Rows go through the object's own engine, so the definitions' columns, * links and rules hold for an import as for any write. */import type { Engine, Outcome } from "../engine.ts";import type { Stamps, StoredRow } from "../store.ts";import type { Change } from "./contacts.ts";export interface Applied { /** Rows made, by table. */ made: Map<string, number>; /** Rows a patch changed, by table. */ changed: Map<string, number>;}export function newApplied(): Applied { return { made: new Map(), changed: new Map() };}const bump = (m: Map<string, number>, table: string): void => { m.set(table, (m.get(table) ?? 0) + 1);};export function applyChanges(engine: Engine, changes: Change[], version: number, outcome: Outcome, applied: Applied): void { const store = engine.store; for (const change of changes) { const held: StoredRow | null = store.any(change.table, change.id); if (change.retract) { if (held && !held.deleted) { engine.delete(held, version, outcome); bump(applied.changed, change.table); } continue; } const patch = change.patch ?? {}; const stamps: Stamps = {}; if (typeof patch.updated_at === "string") stamps.updated_at = patch.updated_at; if (!held || held.deleted) { if (typeof patch.created_at === "string") stamps.created_at = patch.created_at; engine.create(change.table, patch, version, outcome, 0, { id: change.id, ...stamps }); bump(applied.made, change.table); } else if (engine.update(held, patch, version, outcome, 0, stamps) !== held) bump(applied.changed, change.table); }}