# santoku-sqlite: sync module > sync existing SQLite tables peer to peer, with trigger-captured writes and last-writer-wins over a hybrid logical clock This file is one tab of the santoku reference, at https://santoku.dev/santoku-sqlite/sync/llms.txt. https://santoku.dev/santoku-sqlite/sync is the same tab in a browser, https://santoku.dev/llms.txt indexes every tab, and https://santoku.dev/llms-small.txt summarizes them all on one page. santoku.sqlite.sync makes tables you already have syncable between peers. create generates the triggers that capture every ordinary SQL write, and conflicts resolve last-writer-wins over a hybrid logical clock. The module produces and consumes plain Lua tables and never opens a socket, so the examples run two peers in-process. - santoku.sqlite.sync ships in the santoku-sqlite rock: https://santoku.dev/santoku-sqlite - You describe which tables and columns participate. The application writes as before, with no funnel, no setters and no change to its SQL. - The hybrid logical clock (hlc) is a fixed-width string. Causal order is plain string comparison, so SQLite itself can compare clocks. - Sync is symmetric and peer to peer. - The application ships the bytes over HTTP, a websocket, or a file on a USB stick. - Two peers converging is two in-memory databases and some function calls, with no network at all. - Encryption, the additional authenticated data that binds it, the handling of a record that won't decrypt, and writes that don't sync are all application choices. The cards below show each one. ## Tracking tables ### Sync on a populated table sync.create(db, config) makes the configured tables syncable. It emits a shadow table per synced table, installs the triggers, and backfills the rows already present. Run it on every startup after your migrations. - The config names each table's primary key (pk) and the columns that participate (columns). - Columns you leave out stay local and never travel. - The backfill lets existing data join sync without a migration. - create is idempotent, exactly like santoku.migrate: https://santoku.dev/santoku-migrate ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local db = sql(sqlite.open_memory()) db.exec([==[ create table notes ( id text primary key, title text not null default '', draft text ) ]==]) local add = db.runner("insert into notes (id, title) values (?1, ?2)") add("n1", "already here") add("n2", "also here") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } }, }, }) local tracked = db.getter("select count(*) from notes_sync") print("replica:", s.id()) print("rows tracked after backfill:", tracked()) return tracked() ``` ### Seeded row versions The seed option points the backfill at a column that already holds a version per row. The backfill adopts those values, so a genuinely old row stays old and can't overwrite a peer that holds a newer edit. - Without seed, the backfill stamps every pre-existing row with the current clock. That suits data that has never synced and is wrong for data that has. - Use seed when you migrate from something that already tracked a version per row. - A row whose seed value is null or empty falls back to a minted clock, so a partially versioned table works. - Seeded values must be comparable with generated ones, in the same fixed-width format, because the whole ordering rests on string comparison. - create ratchets its clock past the highest seeded value. Otherwise the first local write after the migration would mint a lower value and lose. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local OLDER = "00000000000001.00000000.0000000000000001" local NEWER = "00000000000002.00000000.0000000000000002" local function peer (ver) local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text default '', ver text)") db.runner("insert into notes (id, title, ver) values (?1, ?2, ?3)")( "n1", "written at " .. ver, ver) local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" }, seed = "ver" }, }, }) return { sync = s, title = db.getter("select title from notes where id = ?1") } end local a, b = peer(OLDER), peer(NEWER) for _ = 1, 3 do a.sync.apply(b.sync.respond(a.sync.request(b.sync.id()))) b.sync.apply(a.sync.respond(b.sync.request(a.sync.id()))) end print("a holds:", a.title("n1")) print("b holds:", b.title("n1")) return a.title("n1") == b.title("n1") ``` ### Captured SQL writes The triggers fire on plain inserts, updates and deletes issued anywhere in the application. No write routes through the module. - An update stamps a new clock value on the same row. - A delete leaves a tombstone, so the deletion can travel. - A write to draft, which isn't in the config, stamps nothing. Local-only columns cost nothing. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '', draft text)") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) local tracked = db.getter("select count(*) from notes_sync") local tombs = db.getter("select count(*) from notes_sync where del = 1") db.exec("insert into notes (id, title) values ('n1', 'hello')") print("after insert:", tracked(), "tracked,", s.seq(), "changes") db.exec("update notes set title = 'hello again' where id = 'n1'") print("after update:", tracked(), "tracked,", s.seq(), "changes") db.exec("update notes set draft = 'unsynced column' where id = 'n1'") print("after local-only write:", tracked(), "tracked,", s.seq(), "changes") db.exec("delete from notes where id = 'n1'") print("after delete:", tombs(), "tombstone,", s.seq(), "changes") return tombs() ``` ## Exchanging changes ### Two peers converging request builds what one peer wants, respond answers it, and apply merges the result. That's the whole protocol. Here each peer starts with rows the other has never seen, and one exchange in each direction converges them. - All three are plain Lua tables, so the transport is whatever the application wants. Here the transport is a function call. - Everything runs in-process, so you can test a sync protocol without a network. The module's own specs work this way. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), settitle = db.runner("update notes set title = ?2 where id = ?1"), list = db.all("select id, title from notes order by id", true), } end local function pull (dst, src) return dst.sync.apply(src.sync.respond(dst.sync.request(src.sync.id()))) end local a, b = peer(), peer() a.add("a1", "written on a") b.add("b1", "written on b") local got = pull(a, b) print("a applied", got.applied, "from b") pull(b, a) for _, r in ipairs(a.list()) do print("a holds:", r.id, r.title) end for _, r in ipairs(b.list()) do print("b holds:", r.id, r.title) end return #a.list() ``` ### Concurrent edits and deletes When both peers edit the same row while apart, the clock decides. Both sides reach the same answer, and the losing edit stops propagating instead of ping-ponging. - A delete that races an edit resolves the same way. The tombstone wins ties, so a simultaneous edit can't silently undo a deletion. - Resolution is last-writer-wins. The winner is deterministic, but the module picks one edit and doesn't merge the two. The losing edit is gone. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), settitle = db.runner("update notes set title = ?2 where id = ?1"), drop = db.runner("delete from notes where id = ?1"), title = db.getter("select title from notes where id = ?1"), count = db.getter("select count(*) from notes"), } end local function pull (dst, src) return dst.sync.apply(src.sync.respond(dst.sync.request(src.sync.id()))) end local function converge (x, y) for _ = 1, 8 do local p, q = pull(x, y), pull(y, x) if p.applied == 0 and q.applied == 0 then return end end end local a, b = peer(), peer() a.add("n1", "seed") a.add("n2", "second") converge(a, b) a.settitle("n1", "edited on a") b.settitle("n1", "edited on b") converge(a, b) print("a sees:", a.title("n1")) print("b sees:", b.title("n1")) a.drop("n2") b.settitle("n2", "edited while a deleted it") converge(a, b) print("rows on a:", a.count(), "rows on b:", b.count()) return a.title("n1") == b.title("n1") ``` ### One-way push bundles push(peer) builds a bundle of what that peer hasn't been told about yet, and apply treats the bundle like a response. Use it when the puller can't ask, as with a file, an email attachment or a bucket blob. - request and respond assume the puller can ask. push serves transports with no round trip. - Delivery is at-least-once by design. push doesn't advance its own high-water mark, so the next push rebuilds a bundle lost in transit. - Call ack(peer, bundle.seq) once you know the bundle landed. - Applying the same bundle twice is safe, so a duplicate costs nothing. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), count = db.getter("select count(*) from notes"), } end local a, b = peer(), peer() a.add("n1", "first") local bundle = a.sync.push(b.sync.id()) print("bundle carries", #bundle.changes, "change") print("applied:", b.sync.apply(bundle).applied) print("applied again:", b.sync.apply(bundle).applied) print("rows on b:", b.count()) a.sync.ack(b.sync.id(), bundle.seq) a.add("n2", "second") print("next bundle carries", #a.sync.push(b.sync.id()).changes, "change") return b.count() ``` ### Push and pull together respond(req, pushed) answers a request and leaves out the changes that pushed won. A client that sends its push with its request then never gets its own rows back. - pushed is the bundle the requester sent, applied by the responder before it answers. - respond drops a change when pushed carries the same table, rid and hlc. - A pushed change that lost has another hlc on the responder, so the answer carries the winner back. - The answer's seq still covers the dropped changes, so the requester's cursor moves past them. - Ack the push before applying the answer. apply then counts the rows it takes as served, and the next push leaves them out. - Without pushed, respond answers as before, own rows included. - The PWA scaffold runs this exchange over POST /api/sync: https://santoku.dev/start-web Since santoku-sqlite 6.3.0 ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)") } end local server, client = peer(), peer() server.add("s1", "from the server") client.add("c1", "from the client") local id = server.sync.id() local push = client.sync.push(id) server.sync.apply(push) local res = server.sync.respond(client.sync.request(id), push) client.sync.ack(id, push.seq) print("answer carries", #res.changes, "change:", res.changes[1].vals.title) print("client applied", client.sync.apply(res).applied) print("next push carries", #client.sync.push(id).changes, "changes") return #res.changes ``` ### Divergence repair digest folds every tracked row into buckets, compare names the buckets that differ, and manifest lists what is in them. reconcile turns the other side's manifest into the exact set of rows to fetch. - Row counts can't find divergence when two peers hold the right number of wrong rows. - The set from reconcile feeds the fetch option of request. That request returns those rows without disturbing the ordinary cursor. - The repair takes two round trips, bounded by what actually differs. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) return { db = db, sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), title = db.getter("select title from notes where id = ?1"), } end local function pull (dst, src) return dst.sync.apply(src.sync.respond(dst.sync.request(src.sync.id()))) end local a, b = peer(), peer() a.add("n1", "correct") a.add("n2", "also correct") pull(b, a) pull(a, b) print("buckets differing while healthy:", next(a.sync.compare(b.sync.digest())) == nil and "none" or "some") b.db.exec("update notes set title = 'corrupted' where id = 'n1'") b.db.exec([==[ update notes_sync set hlc = '00000000000001.00000000.0000000000000000' where rid = json_array('n1') ]==]) local diff = a.sync.compare(b.sync.digest()) print("tables reported as differing:", diff.notes and #diff.notes or 0, "buckets") local plan = b.sync.reconcile(a.sync.manifest(diff)) print("rows to fetch:", #plan.fetch.notes) b.sync.apply(a.sync.respond(b.sync.request(a.sync.id(), { fetch = plan.fetch }))) print("b now sees:", b.title("n1")) return b.title("n1") ``` ### Per-column resolution A table spec's granularity = "column" tracks a clock per column. Two peers that edit different fields of the same row then both keep their edit. The default, "row", treats a record as one value. - Under row granularity the newest write wins entirely, so an edit to one field discards a concurrent edit to another. - Column granularity costs one extra tracking row per column that has ever changed. - Concurrent edits to the same field still resolve last-writer-wins, because column granularity doesn't merge them. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer (granularity) local db = sql(sqlite.open_memory()) db.exec("create table people (id text primary key, name text default '', phone text default '')") local s = sync.create(db, { space = "demo", tables = { people = { pk = { "id" }, columns = { "name", "phone" }, granularity = granularity }, }, }) return { sync = s, add = db.runner("insert into people (id, name, phone) values (?1, ?2, ?3)"), setname = db.runner("update people set name = ?2 where id = ?1"), setphone = db.runner("update people set phone = ?2 where id = ?1"), row = db.getter("select name || ' / ' || phone from people where id = ?1"), } end local function converge (x, y) for _ = 1, 8 do local p = x.sync.apply(y.sync.respond(x.sync.request(y.sync.id()))) local q = y.sync.apply(x.sync.respond(y.sync.request(x.sync.id()))) if p.applied == 0 and q.applied == 0 then return end end end for _, mode in ipairs({ "row", "column" }) do local a, b = peer(mode), peer(mode) a.add("p1", "Ada", "555-0100") converge(a, b) a.setname("p1", "Ada Lovelace") b.setphone("p1", "555-0199") converge(a, b) print(mode .. ":", a.row("p1")) end return true ``` ## Local state ### Derived state after apply after_apply runs once per applied row, inside apply's transaction, after the row is written. Use it to rebuild what your application computes from synced columns, such as a search index or a cached count. - apply writes the synced columns and nothing else. It doesn't maintain a search index, a denormalized projection or a cached count for you. - Ordinary writes go through your own code, which can do that work inline. Applied writes don't, because the module drives them. - after_apply receives the operation, the row id, the decoded values (nil for a delete) and the winning clock. - Writes from inside after_apply aren't captured as local changes. A recomputed column can't re-stamp the row and echo it back to the peer it came from. - The clock arrives as an argument. A schema with its own version column can mirror the clock there instead of reading it out of the shadow table. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer () local db = sql(sqlite.open_memory()) db.exec([==[ create table notes ( id text primary key, title text not null default '', words integer not null default 0, version text ) ]==]) local derive = db.runner( "update notes set words = ?2, version = ?3 where json_array(id) = ?1") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" }, after_apply = function (op, rid, vals, hlc) if op == "delete" then return end local n = 0 for _ in (vals.title or ""):gmatch("%S+") do n = n + 1 end derive(rid, n, hlc) end, }, }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), row = db.getter("select title || ' -> ' || words from notes where id = ?1"), version = db.getter("select version from notes where id = ?1"), } end local a, b = peer(), peer() a.add("n1", "four little words here") local res = a.sync.respond(b.sync.request(a.sync.id())) b.sync.apply(res) print("receiver rebuilt:", b.row("n1")) print("clock mirrored:", b.version("n1") == res.changes[1].hlc) return b.row("n1") ``` ### Writes that don't sync quiet(fn) runs fn with capture suppressed. The write lands, the clock doesn't move, and nothing resyncs. Use it to recompute a cached or derived value locally, or to repair a row. - Triggers capture every write to a tracked column, which is usually what you want. A local recompute or a repair shouldn't go out to every peer as an edit. - quiet nests safely. It restores suppression correctly if fn raises an error, so it's also safe inside an apply hook. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) local add = db.runner("insert into notes (id, title) values (?1, ?2)") local retitle = db.runner("update notes set title = ?2 where id = ?1") add("n1", "hello") print("changes after insert:", s.seq()) retitle("n1", "edited by the user") print("after an ordinary edit:", s.seq()) s.quiet(function () retitle("n1", "recomputed locally") end) print("after a quiet edit:", s.seq()) local title = db.getter("select title from notes where id = ?1") print("the row did change:", title("n1")) return s.seq() ``` ## Encryption ### Encrypted changes on the wire The codec hook encrypts only what goes on the wire, and rows stay plaintext locally. A relay can carry and merge changes it can't read, because merging needs the row id and the clock and never the values. - The additional authenticated data (aad) binds each ciphertext to its space, table, row and clock value. - With that binding, a peer can't move a payload onto another row or replay it under a newer version. - The codec here is a santoku-monocypher XChaCha20-Poly1305 key, which takes the aad directly: https://santoku.dev/santoku-monocypher - Row identifiers, clocks and tombstones stay visible as metadata. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local crypto = require("santoku.monocypher") local key = crypto.derive_key("demo passphrase", crypto.derive_identity("demo passphrase", 1024, 1)) local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, encode = function (v) return v.id .. "\30" .. v.title end, decode = function (s2) local id, title = s2:match("^(.-)\30(.*)$") return { id = id, title = title } end, codec = { enc = function (plain, aad) return key:encrypt(plain, aad) end, dec = function (ct, aad) return key:decrypt(ct, aad) end, }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), title = db.getter("select title from notes where id = ?1"), } end local a, b = peer(), peer() a.add("n1", "confidential") local res = a.sync.respond(b.sync.request(a.sync.id())) local change = res.changes[1] print("plaintext on the wire:", change.vals == nil and "none" or "leaked") print("ciphertext present:", change.ct ~= nil) b.sync.apply(res) print("b decrypted:", b.title("n1")) return b.title("n1") ``` ### Unreadable records on_codec_error picks what apply does with a record that fails to decrypt. "abort", the default, rolls back the whole batch. "quarantine" applies the healthy records and reports the bad ones in stats.unreadable. - A key rotation gone wrong, a partial restore or a hostile peer each produce a record that won't decrypt. - "abort": the cursor never advances. The batch stays atomic, but one bad record halts sync permanently. - "quarantine": each bad record lands in stats.unreadable with a reason. The cursor holds back, so apply skips nothing silently. - The application decides the next step. It can surface the record, discard it, or wait for a peer that holds a readable copy. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local crypto = require("santoku.monocypher") local key = crypto.derive_key("demo passphrase", crypto.derive_identity("demo passphrase", 1024, 1)) local function peer (mode) local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", on_codec_error = mode, tables = { notes = { pk = { "id" }, columns = { "title" } } }, encode = function (v) return v.id .. "\30" .. v.title end, decode = function (s2) local id, title = s2:match("^(.-)\30(.*)$") return { id = id, title = title } end, codec = { enc = function (plain, ad) return key:encrypt(plain, ad) end, dec = function (ct, ad) return key:decrypt(ct, ad) end, }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), count = db.getter("select count(*) from notes"), } end local src = peer("abort") src.add("n1", "damaged in transit") src.add("n2", "perfectly fine") local dst = peer("quarantine") local res = src.sync.respond(dst.sync.request(src.sync.id())) local n1, n2 for _, c in ipairs(res.changes) do if c.rid:find("n1", 1, true) then n1 = c end if c.rid:find("n2", 1, true) then n2 = c end end n1.ct = n2.ct local stats = dst.sync.apply(res) print("applied:", stats.applied, "unreadable:", #stats.unreadable) print("reason:", stats.unreadable[1].reason) print("rows that landed:", dst.count()) print("cursor held at:", stats.cursor) return #stats.unreadable ``` ### Custom additional authenticated data The aad option lets you build the additional authenticated data string. Use it to match the binding your existing records are already encrypted under. The default is space:table:rid:hlc, where rid is the JSON-encoded primary key. - The default suits a new database. - An existing database that encrypts records under another binding must match that binding exactly. Otherwise adopting sync means re-encrypting every record you own. - Keep whatever identifies the record and its version in the string. Without the clock, a peer could replay an old payload under a newer one. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local crypto = require("santoku.monocypher") local key = crypto.derive_key("demo passphrase", crypto.derive_identity("demo passphrase", 1024, 1)) local seen = {} local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "account-7", tables = { notes = { pk = { "id" }, columns = { "title" } } }, aad = function (space, _, rid, hlc) return space .. ":" .. (rid:match('^%["(.-)"%]$') or rid) .. ":" .. hlc end, encode = function (v) return v.id .. "\30" .. v.title end, decode = function (s2) local id, title = s2:match("^(.-)\30(.*)$") return { id = id, title = title } end, codec = { enc = function (plain, ad) seen[#seen + 1] = ad return key:encrypt(plain, ad) end, dec = function (ct, ad) return key:decrypt(ct, ad) end, }, }) return { sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), title = db.getter("select title from notes where id = ?1"), } end local a, b = peer(), peer() a.add("n1", "bound to a bare id") local res = a.sync.respond(b.sync.request(a.sync.id())) print("aad used:", seen[1]) b.sync.apply(res) print("decrypted on the other side:", b.title("n1")) return seen[1] ``` ## Operations ### Tombstone gc and peers gc(before) deletes the tombstones whose hlc sorts below before, in one transaction, and returns the count. peers() lists the peers this replica has synced with, and forget(peer) and detach(name) remove a peer or a table. - A delete leaves a tombstone in the table's shadow so the delete can reach every peer. - before is an hlc string: 14-digit milliseconds, 8 hex counter digits and 16 hex random digits. - gc records the current seq as the gc point. - respond answers err = "reset" to a request whose cursor is above 0 and below the gc point. That peer may have missed a dropped delete. - apply then raises "sync.apply: peer error reset". - peers() returns { peer, cursor, served } for each peer, ordered by peer. - forget(peer) deletes that peer's row, so the next request to that peer starts at cursor 0 and pulls every row. - A full pull carries no tombstone, so a peer that never saw a dropped delete keeps the row. Pick a before older than every peer's last sync. - detach(name) drops a table's triggers, indexes and shadow tables and stops syncing the table. The table and its rows stay. Since santoku-sqlite 4.1.3 ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer () local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = "demo", tables = { notes = { pk = { "id" }, columns = { "title" } } }, }) return { db = db, sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)"), drop = db.runner("delete from notes where id = ?1"), count = db.getter("select count(*) from notes"), } end local function pull (dst, src) return dst.sync.apply(src.sync.respond(dst.sync.request(src.sync.id()))) end local a, b = peer(), peer() a.add("n1", "kept") a.add("n2", "deleted later") pull(b, a) for _, p in ipairs(b.sync.peers()) do print("b knows", p.peer == a.sync.id() and "a" or p.peer, "cursor", p.cursor) end a.drop("n2") local stale = b.sync.request(a.sync.id()) print("tombstones dropped:", a.sync.gc("99999999999999.00000000.0000000000000000")) print("stale request answered:", a.sync.respond(stale).err) b.sync.forget(a.sync.id()) print("b peers after forget:", #b.sync.peers()) pull(b, a) print("rows on a:", a.count(), "rows on b:", b.count()) a.sync.detach("notes") a.add("n3", "not captured") print("a after detach:", a.count(), "rows, seq", a.sync.seq()) return b.count() ``` ### create options and errors sync.create takes options beyond tables and space, and each table spec takes its own. respond answers a mismatched peer with an error code, and apply raises that code. - prefix ("sync") names the bookkeeping tables and the triggers. The tables are _meta, _peer and _. - schema qualifies the synced tables and the bookkeeping tables with an attached database name. - batch (500) caps the changes in one response. The response sets more = true while changes remain. - max_skew (86400000 ms) makes apply skip a change whose hlc runs more than max_skew ahead of the local clock. apply counts the change in stats.poisoned. - hash (a string hash that returns an integer) buckets rows for digest and compare. - A table spec takes version (1). Peers that share the table must agree on its version. - A table spec's blobs is a list of columns that travel hex-encoded and decode on apply. - err = "proto": the request's protocol differs. - err = "space": the request's space differs. - err = "version": a shared table's version differs. - apply raises "sync.apply: peer error" with that code. - apply returns stats with peer, applied, skipped, poisoned, unreadable, more and cursor. skipped counts the changes that lost to a newer local hlc. ```lua local sqlite = require("santoku.sqlite.db") local sql = require("santoku.sqlite") local sync = require("santoku.sqlite.sync") local function peer (opts) local db = sql(sqlite.open_memory()) db.exec("create table notes (id text primary key, title text not null default '')") local s = sync.create(db, { space = opts.space or "demo", prefix = "rep", batch = 2, tables = { notes = { pk = { "id" }, columns = { "title" }, version = opts.version } }, }) return { db = db, sync = s, add = db.runner("insert into notes (id, title) values (?1, ?2)") } end local a, b = peer({}), peer({}) for i = 1, 5 do a.add("n" .. i, "row " .. i) end local pages = 0 repeat local stats = b.sync.apply(a.sync.respond(b.sync.request(a.sync.id()))) pages = pages + 1 print("page", pages, "applied", stats.applied, "more", stats.more, "cursor", stats.cursor) until not stats.more print("meta table:", a.db.getter("select count(*) from sqlite_master where name = 'rep_meta'")()) print("other space:", a.sync.respond(peer({ space = "other" }).sync.request()).err) print("other version:", a.sync.respond(peer({ version = 2 }).sync.request()).err) local c = peer({}) local res = a.sync.respond(c.sync.request(a.sync.id())) res.changes[1].hlc = "99999999999999.00000000.0000000000000000" local stats = c.sync.apply(res) print("poisoned:", stats.poisoned, "applied:", stats.applied) return pages ``` ### Sync behind OpenResty Under nginx, call create inside the store builder that santoku.resty.sqlite.store registers. Hand the sync methods out through the builder's tables, with respond under read and apply under write. - santoku.resty.sqlite runs the builder in every worker, on that worker's connection, with busy_timeout at 5000 ms: https://santoku.dev/santoku-resty - santoku.resty.sqlite sets query_only on a reader and applies retry_busy only after the builder returns. The builder may write in every role. - create is safe to run in each worker. Its DDL is create-if-not-exists and its backfill inserts only missing rows. - The first worker does the work, and the others find nothing to do. - respond goes under read, so each worker answers on its own connection. - With writer = "local", apply runs in the store's transaction. - With writer = "single", a reader's call to apply runs in the writer's batch. - The code replaces the API scaffold's server/lib/my_api/store.lua. server/lib/my_api/web/db.lua registers that file from init_by_lua. - Handlers reach respond and apply through require("my_api.web.db"). Since santoku-resty 2.9.0 ```lua local sync = require("santoku.sqlite.sync") return function (db) local s = sync.create(db, { space = "my-api", tables = { items = { pk = { "id" }, columns = { "name" } }, }, }) local list = db.getter([=[ select json_object('items', coalesce(( select json_group_array(json_object('id', id, 'name', name, 'created_at', created_at)) from (select id, name, created_at from items order by id desc limit ?1) ), json_array())) ]=]) return { read = { list_items = function (limit) return list(limit or 50) end, respond = s.respond, }, write = { create_item = db.inserter("insert into items (name) values (?1)"), apply = s.apply, }, } end ```