BEGIN IMMEDIATE; CREATE TABLE IF NOT EXISTS quote_events ( seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets, yes_bid INTEGER, yes_ask INTEGER, at_ms INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS quote_market_seq ON quote_events(market,seq); CREATE INDEX IF NOT EXISTS live_order_price ON orders(market,outcome,side,price) WHERE status='live'; CREATE TABLE IF NOT EXISTS quote_pending (market TEXT PRIMARY KEY); CREATE TRIGGER IF NOT EXISTS mark_quote_insert AFTER INSERT ON orders WHEN NEW.status='live' BEGIN INSERT OR IGNORE INTO quote_pending VALUES(NEW.market); END; -- Order market, side, outcome and price are immutable. Only entering or -- leaving the live set can change the best price of an existing order. CREATE TRIGGER IF NOT EXISTS mark_quote_status AFTER UPDATE OF status ON orders WHEN (OLD.status='live')<>(NEW.status='live') BEGIN INSERT OR IGNORE INTO quote_pending VALUES(NEW.market); END; -- Capture the final book of a successful command in its receipt transaction. CREATE TRIGGER IF NOT EXISTS record_quote_on_receipt AFTER INSERT ON requests WHEN EXISTS(SELECT 1 FROM quote_pending) BEGIN INSERT INTO quote_events(market,yes_bid,yes_ask,at_ms) SELECT * FROM changed_quotes; DELETE FROM quote_pending; END; -- On first install, observe the current live book, without dating it to the -- original order time. Concurrent installers can only enqueue another diff. INSERT OR IGNORE INTO quote_pending SELECT DISTINCT market FROM orders WHERE status='live'; COMMIT;