//// An old CHECK constraint must not reject new letter kinds or lose delivered //// mail and its indexes during the table copy. Current writes cannot create //// this legacy schema; seed it directly and run the storage owner's upgrade. import albedo/daemon/mail import albedo/daemon/store import gleam/dynamic/decode import gleam/list import gleeunit/should import sqlight const legacy_schema = " CREATE TABLE sessions(id TEXT PRIMARY KEY); INSERT INTO sessions VALUES('recipient'); CREATE TABLE mail ( id TEXT PRIMARY KEY, recipient TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, sender TEXT REFERENCES sessions(id) ON DELETE SET NULL, sender_name TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('task','message','result','unreviewed','webhook')), body TEXT NOT NULL, created_at INTEGER NOT NULL, delivered_at INTEGER, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT ); CREATE INDEX mail_pending ON mail(created_at) WHERE delivered_at IS NULL; INSERT INTO mail(id,recipient,sender_name,kind,body,created_at,delivered_at) VALUES('old-letter','recipient','hook','webhook','old body',1,2); " pub fn old_kinds_are_copied_without_losing_mail_or_indexes_test() -> Nil { let assert Ok(db) = store.start(":memory:", legacy_schema) mail.initialise(db) |> should.equal(Ok(Nil)) // Running the owner again must not recopy or duplicate the delivered letter. mail.initialise(db) |> should.equal(Ok(Nil)) store.read( db, "SELECT recipient,kind,body,delivered_at,delivery_owner FROM mail", [], { use recipient <- decode.field(0, decode.string) use kind <- decode.field(1, decode.string) use body <- decode.field(2, decode.string) use delivered <- decode.field(3, decode.int) use owner <- decode.field(4, decode.string) decode.success(#(recipient, kind, body, delivered, owner)) }, ) |> should.equal(Ok([#("recipient", "webhook", "old body", 2, "mail")])) let assert Ok(indexes) = store.read( db, "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='mail'", [], decode.field(0, decode.string, decode.success), ) list.each(["mail_pending", "mail_conversation", "mail_outgoing"], fn(name) { list.contains(indexes, name) |> should.be_true }) store.read( db, "SELECT name FROM sqlite_master WHERE name='mail_old_kinds'", [], decode.field(0, decode.string, decode.success), ) |> should.equal(Ok([])) list.each(["event_turn", "request"], fn(kind) { store.write( db, "INSERT INTO mail(id,recipient,sender_name,kind,body,created_at) VALUES(?,'recipient','new',?,'hi',3)", [sqlight.text(kind), sqlight.text(kind)], ) |> should.equal(Ok(Nil)) }) store.close(db) }