| 1 | -- suite_nonces |
| 2 | -- |
| 3 | -- The suite contract's restore protection (spec §6.2). 0004 added |
| 4 | -- cards.nonce and events.nonce at 0; this gives every existing row a |
| 5 | -- random positive value, and makes both columns write-once and never zero. |
| 6 | -- |
| 7 | -- Written by hand: `rastrillo migration generate` knows nothing about |
| 8 | -- backfills or triggers, as 0002 records. |
| 9 | -- |
| 10 | -- random() is SQLite's, seeded from the operating system. The mask keeps |
| 11 | -- 62 bits and the + 1 keeps it positive, so no row is left at 0, which is |
| 12 | -- what "not yet set" means below. Existing cards' suite item ids change |
| 13 | -- with this, once — before any consumer has connected. |
| 14 | UPDATE cards SET nonce = (random() & 4611686018427387903) + 1 WHERE nonce = 0; |
| 15 | UPDATE events SET nonce = (random() & 4611686018427387903) + 1 WHERE nonce = 0; |
| 16 | |
| 17 | -- Never zero on insert: the code always sets one (store.go CreateCard and |
| 18 | -- logEvent), and a row without one would carry an item id or a cursor that |
| 19 | -- names nothing. |
| 20 | CREATE TRIGGER cards_nonce_is_set |
| 21 | BEFORE INSERT ON cards |
| 22 | WHEN NEW.nonce IS NULL OR NEW.nonce <= 0 |
| 23 | BEGIN |
| 24 | SELECT RAISE(ABORT, 'a card needs a nonce: it is half of its suite item id'); |
| 25 | END; |
| 26 | |
| 27 | CREATE TRIGGER events_nonce_is_set |
| 28 | BEFORE INSERT ON events |
| 29 | WHEN NEW.nonce IS NULL OR NEW.nonce <= 0 |
| 30 | BEGIN |
| 31 | SELECT RAISE(ABORT, 'an event needs a nonce: it is half of a suite feed cursor'); |
| 32 | END; |
| 33 | |
| 34 | -- Write-once: a nonce that moved would turn a consumer's held item id or |
| 35 | -- cursor into one that names nothing — or, worse, something else. |
| 36 | CREATE TRIGGER cards_nonce_is_write_once |
| 37 | BEFORE UPDATE OF nonce ON cards |
| 38 | WHEN NEW.nonce IS NOT OLD.nonce |
| 39 | BEGIN |
| 40 | SELECT RAISE(ABORT, 'a card nonce is written once'); |
| 41 | END; |
| 42 | |
| 43 | CREATE TRIGGER events_nonce_is_write_once |
| 44 | BEFORE UPDATE OF nonce ON events |
| 45 | WHEN NEW.nonce IS NOT OLD.nonce |
| 46 | BEGIN |
| 47 | SELECT RAISE(ABORT, 'an event nonce is written once'); |
| 48 | END; |
| 49 | |