-- Sync protocol 2. -- -- Rows are now written only by compare-and-swap on change_seq (see -- server/src/db.ts), keyed by a JSON array of the key's values, and every -- user's data belongs to an epoch: a random id that changes whenever the -- server's copy is thrown away, so a client can tell it is talking to a -- server that no longer holds what it pushed and must hydrate from scratch. CREATE TABLE IF NOT EXISTS sync_meta ( k TEXT PRIMARY KEY, v TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS sync_epoch ( user_id TEXT PRIMARY KEY, epoch TEXT NOT NULL ); -- Protocol 1 rows cannot be read as protocol 2: their keys were joined with -- a space and every one was ordered by a client's clock. They are dropped -- once, and each user's epoch with them — so every client re-hydrates and -- offers its own database back, which is the copy that was always the -- source of truth. No deployment held protocol 1 data when this shipped. DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM sync_meta WHERE k = 'protocol' AND v = '2') THEN DELETE FROM sync_row; DELETE FROM sync_epoch; INSERT INTO sync_meta (k, v) VALUES ('protocol', '2') ON CONFLICT (k) DO UPDATE SET v = EXCLUDED.v; END IF; END $$;