1pub const SQL_SCHEMA: &str = r#"
4-- Profiles table (plaintext - public data)
5CREATE TABLE IF NOT EXISTS profiles (
6 id INTEGER PRIMARY KEY AUTOINCREMENT,
7 npub TEXT UNIQUE NOT NULL,
8 name TEXT NOT NULL DEFAULT '',
9 display_name TEXT NOT NULL DEFAULT '',
10 nickname TEXT NOT NULL DEFAULT '',
11 lud06 TEXT NOT NULL DEFAULT '',
12 lud16 TEXT NOT NULL DEFAULT '',
13 banner TEXT NOT NULL DEFAULT '',
14 avatar TEXT NOT NULL DEFAULT '',
15 about TEXT NOT NULL DEFAULT '',
16 website TEXT NOT NULL DEFAULT '',
17 nip05 TEXT NOT NULL DEFAULT '',
18 status_content TEXT NOT NULL DEFAULT '',
19 status_url TEXT NOT NULL DEFAULT '',
20 muted INTEGER NOT NULL DEFAULT 0,
21 bot INTEGER NOT NULL DEFAULT 0,
22 avatar_cached TEXT NOT NULL DEFAULT '',
23 banner_cached TEXT NOT NULL DEFAULT ''
24);
25CREATE INDEX IF NOT EXISTS idx_profiles_npub ON profiles(npub);
26CREATE INDEX IF NOT EXISTS idx_profiles_name ON profiles(name);
27
28-- Chats table (plaintext - metadata)
29CREATE TABLE IF NOT EXISTS chats (
30 id INTEGER PRIMARY KEY AUTOINCREMENT,
31 chat_identifier TEXT UNIQUE NOT NULL,
32 chat_type INTEGER NOT NULL,
33 participants TEXT NOT NULL,
34 last_read TEXT NOT NULL DEFAULT '',
35 created_at INTEGER NOT NULL,
36 metadata TEXT NOT NULL DEFAULT '{}',
37 muted INTEGER NOT NULL DEFAULT 0
38);
39CREATE INDEX IF NOT EXISTS idx_chats_identifier ON chats(chat_identifier);
40CREATE INDEX IF NOT EXISTS idx_chats_created ON chats(created_at DESC);
41
42
43-- Settings table (key-value pairs)
44CREATE TABLE IF NOT EXISTS settings (
45 key TEXT PRIMARY KEY,
46 value TEXT NOT NULL
47);
48
49-- Events table: flat, protocol-aligned storage for all Nostr events
50CREATE TABLE IF NOT EXISTS events (
51 id TEXT PRIMARY KEY,
52 kind INTEGER NOT NULL,
53 chat_id INTEGER NOT NULL,
54 user_id INTEGER,
55 content TEXT NOT NULL,
56 tags TEXT NOT NULL DEFAULT '[]',
57 reference_id TEXT,
58 created_at INTEGER NOT NULL,
59 received_at INTEGER NOT NULL,
60 mine INTEGER NOT NULL DEFAULT 0,
61 pending INTEGER NOT NULL DEFAULT 0,
62 failed INTEGER NOT NULL DEFAULT 0,
63 wrapper_event_id TEXT,
64 npub TEXT,
65 preview_metadata TEXT,
66 FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE,
67 FOREIGN KEY (user_id) REFERENCES profiles(id) ON DELETE SET NULL
68);
69-- Pages a chat newest-first with no sort step, rejecting other kinds without reading the row.
70CREATE INDEX IF NOT EXISTS idx_events_chat_page ON events(chat_id, created_at DESC, received_at DESC, kind);
71CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind);
72-- Covers the community member fold (authors + newest activity per channel) without touching rows.
73CREATE INDEX IF NOT EXISTS idx_events_chat_kind_npub ON events(chat_id, kind, npub, created_at);
74CREATE INDEX IF NOT EXISTS idx_events_reference ON events(reference_id) WHERE reference_id IS NOT NULL;
75CREATE INDEX IF NOT EXISTS idx_events_wrapper ON events(wrapper_event_id) WHERE wrapper_event_id IS NOT NULL;
76
77-- PIVX Promos table
78CREATE TABLE IF NOT EXISTS pivx_promos (
79 id INTEGER PRIMARY KEY AUTOINCREMENT,
80 gift_code TEXT NOT NULL UNIQUE,
81 address TEXT NOT NULL,
82 privkey_encrypted TEXT NOT NULL,
83 created_at INTEGER NOT NULL,
84 claimed_at INTEGER,
85 amount_piv REAL,
86 status TEXT NOT NULL DEFAULT 'active'
87);
88CREATE INDEX IF NOT EXISTS idx_pivx_promos_code ON pivx_promos(gift_code);
89CREATE INDEX IF NOT EXISTS idx_pivx_promos_address ON pivx_promos(address);
90CREATE INDEX IF NOT EXISTS idx_pivx_promos_status ON pivx_promos(status);
91
92-- Mini Apps history table
93CREATE TABLE IF NOT EXISTS miniapps_history (
94 id INTEGER PRIMARY KEY AUTOINCREMENT,
95 name TEXT NOT NULL UNIQUE,
96 src_url TEXT NOT NULL,
97 attachment_ref TEXT,
98 open_count INTEGER DEFAULT 1,
99 last_opened_at INTEGER NOT NULL,
100 is_favorite INTEGER NOT NULL DEFAULT 0,
101 categories TEXT NOT NULL DEFAULT '',
102 marketplace_id TEXT DEFAULT NULL,
103 installed_version TEXT DEFAULT NULL
104);
105
106-- Mini App permissions table
107CREATE TABLE IF NOT EXISTS miniapp_permissions (
108 id INTEGER PRIMARY KEY AUTOINCREMENT,
109 file_hash TEXT NOT NULL,
110 permission TEXT NOT NULL,
111 granted INTEGER NOT NULL DEFAULT 0,
112 granted_at INTEGER,
113 UNIQUE(file_hash, permission)
114);
115CREATE INDEX IF NOT EXISTS idx_miniapp_permissions_hash ON miniapp_permissions(file_hash);
116
117-- Processed wrappers table (NIP-59 gift wrap dedup + NIP-77 negentropy)
118-- Universal outer-event ledger across transports. The `transport` discriminator
119-- (0 = nip17 gift-wrap, 1 = concord channel envelope, …) is added by migration 42 so the
120-- dedup is shared but NIP-77 negentropy only fingerprints the nip17 (0) subset.
121CREATE TABLE IF NOT EXISTS processed_wrappers (
122 wrapper_id BLOB PRIMARY KEY,
123 wrapper_created_at INTEGER NOT NULL DEFAULT 0
124);
125
126-- The nip17_wrap_keys vault is introduced by migration 21. The legacy MLS
127-- tables (mls_wrap_keys / mls_pending_events from migrations 22/23) are dropped
128-- by migration 41, so on a fresh DB they're created in order and then removed.
129
130-- Schema migrations tracking table
131CREATE TABLE IF NOT EXISTS schema_migrations (
132 id INTEGER PRIMARY KEY,
133 applied_at INTEGER NOT NULL
134);
135"#;
136
137pub const HIGHEST_MIGRATION_ID: u32 = 127;
148
149pub fn applied_migration_high_water(conn: &rusqlite::Connection) -> u32 {
155 conn.query_row("SELECT MAX(id) FROM schema_migrations", [], |row| {
156 row.get::<_, Option<u32>>(0)
157 })
158 .ok()
159 .flatten()
160 .unwrap_or(0)
161}
162
163pub fn migration_applied(conn: &rusqlite::Connection, migration_id: u32) -> bool {
165 conn.query_row(
166 "SELECT 1 FROM schema_migrations WHERE id = ?1",
167 rusqlite::params![migration_id],
168 |_| Ok(())
169 ).is_ok()
170}
171
172pub fn mark_migration_applied(tx: &rusqlite::Transaction, migration_id: u32) -> Result<(), String> {
174 let now = crate::clock::now_secs() as i64;
175
176 tx.execute(
177 "INSERT INTO schema_migrations (id, applied_at) VALUES (?1, ?2)",
178 rusqlite::params![migration_id, now],
179 ).map_err(|e| format!("[DB] Migration {}: Failed to record: {}", migration_id, e))?;
180
181 Ok(())
182}
183
184fn run_atomic_migration<F>(
193 conn: &mut rusqlite::Connection,
194 id: u32,
195 name: &str,
196 migrate: F,
197) -> Result<(), String>
198where
199 F: FnOnce(&rusqlite::Transaction) -> Result<(), String>,
200{
201 debug_assert!(
206 id <= HIGHEST_MIGRATION_ID,
207 "migration {id} exceeds HIGHEST_MIGRATION_ID ({HIGHEST_MIGRATION_ID}); bump the constant \
208 or this build will refuse the database it just wrote"
209 );
210
211 if migration_applied(conn, id) {
213 return Ok(());
214 }
215
216 crate::log_info!("[DB] Migration {}: {}...", id, name);
217
218 let tx = conn.transaction()
220 .map_err(|e| format!("[DB] Migration {}: Failed to start transaction: {}", id, e))?;
221
222 match migrate(&tx) {
224 Ok(()) => {
225 mark_migration_applied(&tx, id)?;
227
228 tx.commit()
230 .map_err(|e| format!("[DB] Migration {}: Failed to commit: {}", id, e))?;
231
232 crate::log_info!("[DB] Migration {} complete", id);
233 Ok(())
234 }
235 Err(e) => {
236 eprintln!("[DB] Migration {} FAILED: {} - rolling back", id, e);
238 Err(e)
239 }
240 }
241}
242
243#[allow(dead_code)]
247fn ensure_column_exists(
248 conn: &mut rusqlite::Connection,
249 table: &str,
250 column: &str,
251 col_type: &str,
252) -> Result<(), String> {
253 let exists: bool = conn.query_row(
254 &format!("SELECT COUNT(*) FROM pragma_table_info('{}') WHERE name='{}'", table, column),
255 [],
256 |row| row.get::<_, i32>(0),
257 ).map(|c| c > 0).unwrap_or(false);
258
259 if !exists {
260 crate::log_warn!("[DB] Safety net: adding missing column {}.{}", table, column);
261 conn.execute(
262 &format!("ALTER TABLE {} ADD COLUMN {} {}", table, column, col_type),
263 [],
264 ).map_err(|e| format!("[DB] Failed to add column {}.{}: {}", table, column, e))?;
265 }
266 Ok(())
267}
268
269pub fn run_migrations(conn: &mut rusqlite::Connection) -> Result<(), String> {
277 conn.execute(
279 "CREATE TABLE IF NOT EXISTS schema_migrations (
280 id INTEGER PRIMARY KEY,
281 applied_at INTEGER NOT NULL
282 )",
283 [],
284 ).map_err(|e| format!("[DB] Failed to create schema_migrations table: {}", e))?;
285
286 run_atomic_migration(conn, 19, "Create marketplace_cache table", |tx| {
294 tx.execute_batch(
295 "CREATE TABLE IF NOT EXISTS marketplace_cache (
296 id TEXT PRIMARY KEY,
297 data TEXT NOT NULL,
298 fetched_at INTEGER NOT NULL
299 );"
300 ).map_err(|e| format!("Failed to create marketplace_cache table: {}", e))?;
301 Ok(())
302 })?;
303
304 run_atomic_migration(conn, 20, "Add is_blocked column to profiles", |tx| {
310 tx.execute_batch(
311 "ALTER TABLE profiles ADD COLUMN is_blocked INTEGER NOT NULL DEFAULT 0;"
312 ).map_err(|e| format!("Failed to add is_blocked column: {}", e))?;
313 Ok(())
314 })?;
315
316 run_atomic_migration(conn, 21, "Create nip17_wrap_keys table", |tx| {
327 tx.execute_batch(
328 "CREATE TABLE IF NOT EXISTS nip17_wrap_keys (
329 wrap_event_id TEXT PRIMARY KEY,
330 rumor_id TEXT NOT NULL,
331 recipient_pubkey TEXT NOT NULL,
332 role INTEGER NOT NULL,
333 secret BLOB NOT NULL,
334 relay_urls TEXT NOT NULL,
335 created_at INTEGER NOT NULL
336 );
337 CREATE INDEX IF NOT EXISTS idx_nip17_wrap_keys_rumor ON nip17_wrap_keys(rumor_id);"
338 ).map_err(|e| format!("Failed to create nip17_wrap_keys table: {}", e))?;
339 Ok(())
340 })?;
341
342 run_atomic_migration(conn, 22, "Create mls_wrap_keys table", |tx| {
351 tx.execute_batch(
352 "CREATE TABLE IF NOT EXISTS mls_wrap_keys (
353 wrap_event_id TEXT PRIMARY KEY,
354 message_id TEXT NOT NULL,
355 group_id TEXT NOT NULL,
356 secret BLOB NOT NULL,
357 relay_urls TEXT NOT NULL,
358 created_at INTEGER NOT NULL
359 );
360 CREATE INDEX IF NOT EXISTS idx_mls_wrap_keys_message ON mls_wrap_keys(message_id);
361 CREATE INDEX IF NOT EXISTS idx_mls_wrap_keys_group ON mls_wrap_keys(group_id);"
362 ).map_err(|e| format!("Failed to create mls_wrap_keys table: {}", e))?;
363 Ok(())
364 })?;
365
366 run_atomic_migration(conn, 23, "Create mls_pending_events table", |tx| {
375 tx.execute_batch(
376 "CREATE TABLE IF NOT EXISTS mls_pending_events (
377 event_id TEXT PRIMARY KEY,
378 group_id TEXT NOT NULL,
379 event_json TEXT NOT NULL,
380 first_seen_at INTEGER NOT NULL,
381 last_retry_at INTEGER NOT NULL,
382 retry_count INTEGER NOT NULL DEFAULT 0
383 );
384 CREATE INDEX IF NOT EXISTS idx_mls_pending_events_group ON mls_pending_events(group_id);
385 CREATE INDEX IF NOT EXISTS idx_mls_pending_events_first_seen ON mls_pending_events(first_seen_at);"
386 ).map_err(|e| format!("Failed to create mls_pending_events table: {}", e))?;
387 Ok(())
388 })?;
389
390 run_atomic_migration(conn, 24, "Create blossom_server_capabilities table", |tx| {
394 tx.execute_batch(
395 "CREATE TABLE IF NOT EXISTS blossom_server_capabilities (
396 server_url TEXT NOT NULL,
397 mime_type TEXT NOT NULL,
398 outcome INTEGER NOT NULL,
399 max_accepted_size INTEGER NOT NULL DEFAULT 0,
400 updated_at INTEGER NOT NULL,
401 PRIMARY KEY (server_url, mime_type)
402 );"
403 ).map_err(|e| format!("Failed to create blossom_server_capabilities table: {}", e))?;
404 Ok(())
405 })?;
406
407 run_atomic_migration(conn, 25, "Add min_rejected_size to blossom_server_capabilities", |tx| {
411 tx.execute_batch(
412 "ALTER TABLE blossom_server_capabilities ADD COLUMN min_rejected_size INTEGER;"
413 ).map_err(|e| format!("Failed to add min_rejected_size column: {}", e))?;
414 Ok(())
415 })?;
416
417 run_atomic_migration(conn, 26, "Add is_encrypted to capability cache PK", |tx| {
423 tx.execute_batch(
424 "DROP TABLE IF EXISTS blossom_server_capabilities;
425 CREATE TABLE blossom_server_capabilities (
426 server_url TEXT NOT NULL,
427 mime_type TEXT NOT NULL,
428 is_encrypted INTEGER NOT NULL DEFAULT 0,
429 outcome INTEGER NOT NULL,
430 max_accepted_size INTEGER NOT NULL DEFAULT 0,
431 min_rejected_size INTEGER,
432 updated_at INTEGER NOT NULL,
433 PRIMARY KEY (server_url, mime_type, is_encrypted)
434 );"
435 ).map_err(|e| format!("Failed to recreate blossom_server_capabilities: {}", e))?;
436 Ok(())
437 })?;
438
439 run_atomic_migration(conn, 27, "Backfill signer_type=local for pre-NIP-46 accounts", |tx| {
450 tx.execute(
451 "INSERT OR IGNORE INTO settings (key, value) VALUES ('signer_type', 'local')",
452 [],
453 ).map_err(|e| format!("Failed to backfill signer_type: {}", e))?;
454 Ok(())
455 })?;
456
457 run_atomic_migration(conn, 28, "Create emoji pack tables", |tx| {
465 tx.execute_batch(
466 "CREATE TABLE IF NOT EXISTS emoji_packs (
467 addr TEXT PRIMARY KEY,
468 pubkey TEXT NOT NULL,
469 identifier TEXT NOT NULL,
470 title TEXT NOT NULL DEFAULT '',
471 image_url TEXT NOT NULL DEFAULT '',
472 description TEXT NOT NULL DEFAULT '',
473 is_own INTEGER NOT NULL DEFAULT 0,
474 updated_at INTEGER NOT NULL,
475 raw_event TEXT NOT NULL DEFAULT ''
476 );
477 CREATE INDEX IF NOT EXISTS idx_emoji_packs_pubkey ON emoji_packs(pubkey);
478 CREATE INDEX IF NOT EXISTS idx_emoji_packs_is_own ON emoji_packs(is_own);
479
480 CREATE TABLE IF NOT EXISTS emoji_pack_items (
481 pack_addr TEXT NOT NULL,
482 shortcode TEXT NOT NULL,
483 url TEXT NOT NULL,
484 sha256 TEXT,
485 position INTEGER NOT NULL DEFAULT 0,
486 PRIMARY KEY (pack_addr, shortcode),
487 FOREIGN KEY (pack_addr) REFERENCES emoji_packs(addr) ON DELETE CASCADE
488 );
489 CREATE INDEX IF NOT EXISTS idx_emoji_pack_items_pack ON emoji_pack_items(pack_addr, position);
490
491 CREATE TABLE IF NOT EXISTS emoji_pack_subscriptions (
492 addr TEXT PRIMARY KEY,
493 subscribed_at INTEGER NOT NULL
494 );"
495 ).map_err(|e| format!("Failed to create emoji pack tables: {}", e))?;
496 Ok(())
497 })?;
498
499 run_atomic_migration(conn, 29, "Add wallpaper columns to chats", |tx| {
507 tx.execute_batch(
508 "ALTER TABLE chats ADD COLUMN wallpaper_path TEXT NOT NULL DEFAULT '';
509 ALTER TABLE chats ADD COLUMN wallpaper_ts INTEGER NOT NULL DEFAULT 0;"
510 ).map_err(|e| format!("Failed to add wallpaper columns: {}", e))?;
511 Ok(())
512 })?;
513
514 run_atomic_migration(conn, 30, "Add wallpaper blur/dim columns to chats", |tx| {
522 tx.execute_batch(
523 "ALTER TABLE chats ADD COLUMN wallpaper_blur INTEGER NOT NULL DEFAULT 0;
524 ALTER TABLE chats ADD COLUMN wallpaper_dim INTEGER NOT NULL DEFAULT 50;"
525 ).map_err(|e| format!("Failed to add wallpaper blur/dim columns: {}", e))?;
526 Ok(())
527 })?;
528
529 run_atomic_migration(conn, 31, "Add wallpaper url/uploader columns to chats", |tx| {
538 tx.execute_batch(
539 "ALTER TABLE chats ADD COLUMN wallpaper_url TEXT NOT NULL DEFAULT '';
540 ALTER TABLE chats ADD COLUMN wallpaper_uploader TEXT NOT NULL DEFAULT '';"
541 ).map_err(|e| format!("Failed to add wallpaper url/uploader columns: {}", e))?;
542 Ok(())
543 })?;
544
545 run_atomic_migration(conn, 32, "Drop mls_event_cursors table", |tx| {
553 tx.execute_batch("DROP TABLE IF EXISTS mls_event_cursors;")
554 .map_err(|e| format!("Failed to drop mls_event_cursors: {}", e))?;
555 Ok(())
556 })?;
557
558 run_atomic_migration(conn, 40, "Create community tables", |tx| {
575 tx.execute_batch(
576 "CREATE TABLE IF NOT EXISTS communities (
577 community_id TEXT PRIMARY KEY,
578 server_root_key BLOB NOT NULL,
579 name TEXT NOT NULL,
580 relays TEXT NOT NULL,
581 created_at INTEGER NOT NULL,
582 description TEXT,
583 icon TEXT,
584 banner TEXT,
585 banlist TEXT NOT NULL DEFAULT '[]',
586 banlist_at INTEGER NOT NULL DEFAULT 0,
587 owner_attestation TEXT,
588 roles TEXT NOT NULL DEFAULT '{}',
589 roles_at INTEGER NOT NULL DEFAULT 0,
590 server_root_epoch INTEGER NOT NULL DEFAULT 0,
591 invite_registry TEXT NOT NULL DEFAULT '[]',
592 read_cut_pending INTEGER NOT NULL DEFAULT 0,
593 read_cut_target_epoch INTEGER NOT NULL DEFAULT 0,
594 dissolved INTEGER NOT NULL DEFAULT 0
595 );
596 CREATE TABLE IF NOT EXISTS community_channels (
597 channel_id TEXT PRIMARY KEY,
598 community_id TEXT NOT NULL,
599 channel_key BLOB NOT NULL,
600 epoch INTEGER NOT NULL,
601 name TEXT NOT NULL,
602 created_at INTEGER NOT NULL,
603 rekeyed_at_server_epoch INTEGER NOT NULL DEFAULT 0
604 );
605 CREATE INDEX IF NOT EXISTS idx_community_channels_community
606 ON community_channels(community_id);
607 CREATE TABLE IF NOT EXISTS community_message_keys (
608 outer_event_id TEXT PRIMARY KEY,
609 ephemeral_secret BLOB NOT NULL,
610 relays TEXT NOT NULL,
611 created_at INTEGER NOT NULL,
612 message_id TEXT
613 );
614 CREATE INDEX IF NOT EXISTS idx_cmk_message_id
615 ON community_message_keys(message_id);
616 CREATE TABLE IF NOT EXISTS pending_community_invites (
617 community_id TEXT PRIMARY KEY,
618 bundle_json TEXT NOT NULL,
619 inviter_npub TEXT NOT NULL,
620 received_at INTEGER NOT NULL
621 );
622 CREATE TABLE IF NOT EXISTS community_public_invites (
623 token TEXT PRIMARY KEY,
624 community_id TEXT NOT NULL,
625 url TEXT NOT NULL,
626 expires_at INTEGER,
627 created_at INTEGER NOT NULL
628 );
629 CREATE INDEX IF NOT EXISTS idx_public_invites_community
630 ON community_public_invites(community_id);
631 CREATE TABLE IF NOT EXISTS community_edition_heads (
632 community_id TEXT NOT NULL,
633 entity_id TEXT NOT NULL,
634 version INTEGER NOT NULL,
635 self_hash BLOB NOT NULL,
636 inner_id BLOB,
637 epoch INTEGER NOT NULL DEFAULT 0,
638 PRIMARY KEY (community_id, entity_id)
639 );
640 CREATE TABLE IF NOT EXISTS community_epoch_keys (
641 community_id TEXT NOT NULL,
642 scope_id TEXT NOT NULL,
643 epoch INTEGER NOT NULL,
644 key BLOB NOT NULL,
645 created_at INTEGER NOT NULL,
646 PRIMARY KEY (community_id, scope_id, epoch)
647 );
648 CREATE TABLE IF NOT EXISTS community_invite_link_sets (
649 community_id TEXT NOT NULL,
650 creator TEXT NOT NULL,
651 locators TEXT NOT NULL DEFAULT '[]',
652 version INTEGER NOT NULL DEFAULT 0,
653 PRIMARY KEY (community_id, creator)
654 );",
655 )
656 .map_err(|e| format!("Failed to create community tables: {}", e))?;
657 Ok(())
658 })?;
659
660 run_atomic_migration(conn, 41, "Purge legacy MLS data", |tx| {
667 tx.execute_batch(
668 "DELETE FROM events WHERE chat_id IN (SELECT id FROM chats WHERE chat_type = 1);
669 DELETE FROM chats WHERE chat_type = 1;
670 DROP TABLE IF EXISTS mls_groups;
671 DROP TABLE IF EXISTS mls_keypackages;
672 DROP TABLE IF EXISTS mls_processed_events;
673 DROP TABLE IF EXISTS mls_wrap_keys;
674 DROP TABLE IF EXISTS mls_pending_events;",
675 )
676 .map_err(|e| format!("Failed to purge legacy MLS data: {}", e))?;
677 Ok(())
678 })?;
679
680 run_atomic_migration(conn, 42, "Add transport discriminator to processed_wrappers", |tx| {
687 tx.execute_batch("ALTER TABLE processed_wrappers ADD COLUMN transport INTEGER NOT NULL DEFAULT 0;")
688 .map_err(|e| format!("Failed to add transport column: {}", e))?;
689 Ok(())
690 })?;
691
692 run_atomic_migration(conn, 43, "Add label to community_public_invites", |tx| {
699 tx.execute_batch("ALTER TABLE community_public_invites ADD COLUMN label TEXT;")
700 .map_err(|e| format!("Failed to add label column: {}", e))?;
701 Ok(())
702 })?;
703
704 run_atomic_migration(conn, 44, "Create emoji_usage table", |tx| {
712 tx.execute_batch(
713 "CREATE TABLE IF NOT EXISTS emoji_usage (
714 kind INTEGER NOT NULL,
715 id TEXT NOT NULL,
716 url TEXT,
717 score REAL NOT NULL,
718 last_used INTEGER NOT NULL,
719 PRIMARY KEY (kind, id)
720 ) WITHOUT ROWID;
721 CREATE INDEX IF NOT EXISTS idx_emoji_usage_score
722 ON emoji_usage(score DESC);",
723 )
724 .map_err(|e| format!("Failed to create emoji_usage table: {}", e))?;
725 Ok(())
726 })?;
727
728 run_atomic_migration(conn, 62, "Repair: ensure label column on community_public_invites", |tx| {
733 let has_label: i64 = tx
734 .query_row(
735 "SELECT COUNT(*) FROM pragma_table_info('community_public_invites') WHERE name = 'label'",
736 [],
737 |r| r.get(0),
738 )
739 .map_err(|e| format!("Failed to inspect community_public_invites columns: {}", e))?;
740 if has_label == 0 {
741 tx.execute_batch("ALTER TABLE community_public_invites ADD COLUMN label TEXT;")
742 .map_err(|e| format!("Failed to add label column: {}", e))?;
743 }
744 Ok(())
745 })?;
746
747 run_atomic_migration(conn, 63, "Add health columns to emoji_packs", |tx| {
756 tx.execute_batch(
757 "ALTER TABLE emoji_packs ADD COLUMN status INTEGER NOT NULL DEFAULT 0;
758 ALTER TABLE emoji_packs ADD COLUMN miss_count INTEGER NOT NULL DEFAULT 0;
759 ALTER TABLE emoji_packs ADD COLUMN first_missed_at INTEGER NOT NULL DEFAULT 0;
760 ALTER TABLE emoji_packs ADD COLUMN last_miss_counted_at INTEGER NOT NULL DEFAULT 0;
761 ALTER TABLE emoji_packs ADD COLUMN status_changed_at INTEGER NOT NULL DEFAULT 0;",
762 )
763 .map_err(|e| format!("Failed to add emoji pack health columns: {}", e))?;
764 Ok(())
765 })?;
766
767 run_atomic_migration(conn, 64, "Drop orphaned pending-id event rows", |tx| {
776 tx.execute(
777 "DELETE FROM events WHERE id LIKE 'pending-%' AND pending = 0 AND failed = 0",
778 [],
779 )
780 .map_err(|e| format!("Failed to drop orphaned pending rows: {}", e))?;
781 Ok(())
782 })?;
783
784 run_atomic_migration(conn, 65, "Add position to emoji pack subscriptions", |tx| {
793 tx.execute_batch(
794 "ALTER TABLE emoji_pack_subscriptions ADD COLUMN position INTEGER NOT NULL DEFAULT 0;
795 UPDATE emoji_pack_subscriptions SET position = (
796 SELECT COUNT(*) FROM emoji_pack_subscriptions s2
797 WHERE s2.rowid < emoji_pack_subscriptions.rowid
798 );",
799 )
800 .map_err(|e| format!("Failed to add position column: {}", e))?;
801 Ok(())
802 })?;
803
804 run_atomic_migration(conn, 66, "Concord v2 dual-stack columns", |tx| {
813 for (table, col, ddl) in [
814 ("communities", "protocol", "INTEGER NOT NULL DEFAULT 1"),
815 ("communities", "owner_pubkey", "TEXT"),
816 ("communities", "owner_salt", "TEXT"),
817 ("community_channels", "private", "INTEGER NOT NULL DEFAULT 0"),
818 ] {
819 let sql = format!("ALTER TABLE {table} ADD COLUMN {col} {ddl}");
821 if let Err(e) = tx.execute(&sql, []) {
822 let msg = e.to_string();
823 if !msg.contains("duplicate column name") {
824 return Err(format!("add {table}.{col}: {msg}"));
825 }
826 }
827 }
828 Ok(())
829 })?;
830
831 run_atomic_migration(conn, 67, "v2 guestbook store", |tx| {
837 tx.execute(
838 "CREATE TABLE IF NOT EXISTS community_guestbook (
839 community_id TEXT PRIMARY KEY,
840 events TEXT NOT NULL,
841 cursor_secs INTEGER NOT NULL DEFAULT 0
842 )",
843 [],
844 )
845 .map_err(|e| format!("create community_guestbook: {e}"))?;
846 Ok(())
847 })?;
848
849 run_atomic_migration(conn, 68, "v2 metadata preservation stash", |tx| {
853 for (table, col) in [("communities", "meta_extra"), ("community_channels", "meta_extra")] {
854 let sql = format!("ALTER TABLE {table} ADD COLUMN {col} TEXT");
855 if let Err(e) = tx.execute(&sql, []) {
856 let msg = e.to_string();
857 if !msg.contains("duplicate column name") {
858 return Err(format!("add {table}.{col}: {msg}"));
859 }
860 }
861 }
862 Ok(())
863 })?;
864
865 run_atomic_migration(conn, 69, "bot manifest store", |tx| {
870 tx.execute(
871 "CREATE TABLE IF NOT EXISTS bot_manifests (
872 pubkey TEXT PRIMARY KEY,
873 manifest TEXT NOT NULL,
874 event_created_at INTEGER NOT NULL,
875 fetched_at INTEGER NOT NULL
876 )",
877 [],
878 )
879 .map_err(|e| format!("create bot_manifests: {e}"))?;
880 Ok(())
881 })?;
882
883 run_atomic_migration(conn, 70, "Retained gift-wrap body for idempotent retry", |tx| {
894 tx.execute_batch(
895 "ALTER TABLE nip17_wrap_keys ADD COLUMN wrap_json TEXT;
896 ALTER TABLE nip17_wrap_keys ADD COLUMN rumor_json TEXT;
897 ALTER TABLE nip17_wrap_keys ADD COLUMN pending_id TEXT;
898 CREATE INDEX IF NOT EXISTS idx_nip17_wrap_keys_pending ON nip17_wrap_keys(pending_id);"
899 ).map_err(|e| format!("Failed to add resend-payload columns: {}", e))?;
900 Ok(())
901 })?;
902
903 run_atomic_migration(conn, 71, "Covering index for unread counts", |tx| {
909 tx.execute_batch(
910 "CREATE INDEX IF NOT EXISTS idx_events_unread ON events(chat_id, mine, kind, created_at);"
911 ).map_err(|e| format!("Failed to create unread covering index: {}", e))?;
912 Ok(())
913 })?;
914
915 run_atomic_migration(conn, 72, "Drop unused events user_id index", |tx| {
922 tx.execute_batch("DROP INDEX IF EXISTS idx_events_user;")
923 .map_err(|e| format!("Failed to drop idx_events_user: {}", e))?;
924 Ok(())
925 })?;
926
927 run_atomic_migration(conn, 73, "Drop legacy messages table", |tx| {
934 tx.execute_batch("DROP TABLE IF EXISTS messages;")
935 .map_err(|e| format!("Failed to drop legacy messages table: {}", e))?;
936 Ok(())
937 })?;
938
939 run_atomic_migration(conn, 74, "Attachments table + backfill", |tx| {
951 tx.execute_batch(
952 "CREATE TABLE IF NOT EXISTS attachments (
953 id INTEGER PRIMARY KEY,
954 event_id TEXT NOT NULL,
955 att_index INTEGER NOT NULL,
956 hash TEXT NOT NULL,
957 key TEXT NOT NULL DEFAULT '',
958 nonce TEXT NOT NULL DEFAULT '',
959 extension TEXT NOT NULL DEFAULT '',
960 name TEXT NOT NULL DEFAULT '',
961 url TEXT NOT NULL DEFAULT '',
962 path TEXT NOT NULL DEFAULT '',
963 size INTEGER NOT NULL DEFAULT 0,
964 img_meta TEXT,
965 downloaded INTEGER NOT NULL DEFAULT 0,
966 webxdc_topic TEXT, group_id TEXT, original_hash TEXT, scheme_version TEXT, mls_filename TEXT,
967 UNIQUE(event_id, att_index),
968 FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE
969 );
970 CREATE INDEX IF NOT EXISTS idx_attachments_hash ON attachments(hash);
971 CREATE INDEX IF NOT EXISTS idx_attachments_downloaded ON attachments(downloaded) WHERE downloaded = 1;"
972 ).map_err(|e| format!("Failed to create attachments table: {}", e))?;
973
974 let events: Vec<(String, String)> = {
976 let mut stmt = tx.prepare("SELECT id, tags FROM events WHERE tags LIKE '%attachments%'")
977 .map_err(|e| format!("prepare attachment backfill: {}", e))?;
978 let mapped = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
979 .map_err(|e| format!("query attachment backfill: {}", e))?;
980 mapped.filter_map(|r| r.ok()).collect()
981 };
982 for (event_id, tags_json) in events {
983 let tags: Vec<Vec<String>> = match serde_json::from_str(&tags_json) {
984 Ok(t) => t,
985 Err(_) => continue,
986 };
987 let att_json = tags.iter()
988 .find(|t| t.first().map(|s| s.as_str()) == Some("attachments"))
989 .and_then(|t| t.get(1));
990 let Some(att_json) = att_json else { continue };
991 let atts: Vec<crate::types::Attachment> = match serde_json::from_str(att_json) {
992 Ok(a) => a,
993 Err(_) => continue,
994 };
995 for (i, a) in atts.iter().enumerate() {
996 let img_meta_json = a.img_meta.as_ref().and_then(|m| serde_json::to_string(m).ok());
997 tx.execute(
998 "INSERT INTO attachments (event_id, att_index, hash, key, nonce, extension, name, url, \
999 path, size, img_meta, downloaded, webxdc_topic, group_id, original_hash) \
1000 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15)",
1001 rusqlite::params![
1002 event_id, i as i64, a.id, a.key, a.nonce, a.extension, a.name, a.url,
1003 a.path, a.size as i64, img_meta_json, a.downloaded as i64,
1004 a.webxdc_topic, a.group_id, a.original_hash,
1005 ],
1006 ).map_err(|e| format!("insert backfilled attachment: {}", e))?;
1007 }
1008 }
1009 Ok(())
1010 })?;
1011
1012 run_atomic_migration(conn, 75, "Strip backfilled attachment tags", |tx| {
1023 let events: Vec<(String, String)> = {
1024 let mut stmt = tx.prepare(
1025 "SELECT id, tags FROM events WHERE tags LIKE '%attachments%' \
1026 AND id IN (SELECT DISTINCT event_id FROM attachments)"
1027 ).map_err(|e| format!("prepare tag strip: {}", e))?;
1028 let mapped = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
1029 .map_err(|e| format!("query tag strip: {}", e))?;
1030 mapped.flatten().collect()
1031 };
1032 for (id, tags_json) in events {
1033 let Ok(mut tags) = serde_json::from_str::<Vec<Vec<String>>>(&tags_json) else { continue };
1034 let before = tags.len();
1035 tags.retain(|t| t.first().map(|s| s.as_str()) != Some("attachments"));
1036 if tags.len() == before {
1037 continue; }
1039 let new_tags = serde_json::to_string(&tags).unwrap_or(tags_json);
1040 tx.execute("UPDATE events SET tags=?1 WHERE id=?2", rusqlite::params![new_tags, id])
1041 .map_err(|e| format!("strip attachments tag: {}", e))?;
1042 }
1043 Ok(())
1044 })?;
1045
1046 run_atomic_migration(conn, 76, "Drop dead attachment columns (mls_filename, scheme_version)", |tx| {
1050 tx.execute("ALTER TABLE attachments DROP COLUMN scheme_version", [])
1051 .map_err(|e| format!("drop scheme_version: {}", e))?;
1052 tx.execute("ALTER TABLE attachments DROP COLUMN mls_filename", [])
1053 .map_err(|e| format!("drop mls_filename: {}", e))?;
1054 Ok(())
1055 })?;
1056
1057 run_atomic_migration(conn, 77, "v1->v2 migration: pointer columns + wizard ledger", |tx| {
1065 tx.execute_batch(
1066 "ALTER TABLE communities ADD COLUMN migrated_to TEXT;
1067 ALTER TABLE communities ADD COLUMN migration_pointer TEXT;
1068 ALTER TABLE communities ADD COLUMN migration_checked INTEGER NOT NULL DEFAULT 0;
1069 CREATE TABLE IF NOT EXISTS community_migrations (
1070 community_id TEXT PRIMARY KEY,
1071 v2_community_id TEXT NOT NULL,
1072 phase INTEGER NOT NULL DEFAULT 0,
1073 twin TEXT NOT NULL DEFAULT '',
1074 updated_at INTEGER NOT NULL DEFAULT 0
1075 );",
1076 )
1077 .map_err(|e| format!("migration 77: {}", e))?;
1078 Ok(())
1079 })?;
1080
1081 run_atomic_migration(conn, 78, "Pending invite expiry (NIP-40)", |tx| {
1086 tx.execute(
1087 "ALTER TABLE pending_community_invites ADD COLUMN expires_at INTEGER NOT NULL DEFAULT 0",
1088 [],
1089 )
1090 .map_err(|e| format!("migration 78: {}", e))?;
1091 Ok(())
1092 })?;
1093
1094 run_atomic_migration(conn, 79, "Per-npub ban marks (phantom-member suppression)", |tx| {
1103 let present: i32 = tx
1107 .query_row("SELECT COUNT(*) FROM pragma_table_info('communities') WHERE name='banlist_marks'", [], |r| r.get(0))
1108 .map_err(|e| format!("migration 79: {}", e))?;
1109 if present == 0 {
1110 tx.execute(
1111 "ALTER TABLE communities ADD COLUMN banlist_marks TEXT NOT NULL DEFAULT '{}'",
1112 [],
1113 )
1114 .map_err(|e| format!("migration 79: {}", e))?;
1115 }
1116 Ok(())
1117 })?;
1118
1119 run_atomic_migration(conn, 80, "Attachment fallback URLs (Blossom mirrors)", |tx| {
1126 tx.execute(
1127 "ALTER TABLE attachments ADD COLUMN fallback_urls TEXT NOT NULL DEFAULT ''",
1128 [],
1129 )
1130 .map_err(|e| format!("migration 80: {}", e))?;
1131 Ok(())
1132 })?;
1133
1134 run_atomic_migration(conn, 81, "processed_wrappers window index", |tx| {
1140 tx.execute(
1141 "CREATE INDEX IF NOT EXISTS idx_processed_wrappers_window \
1142 ON processed_wrappers(transport, wrapper_created_at)",
1143 [],
1144 )
1145 .map_err(|e| format!("migration 81: {}", e))?;
1146 Ok(())
1147 })?;
1148
1149 run_atomic_migration(conn, 82, "Parked private-channel key vends", |tx| {
1159 tx.execute(
1160 "CREATE TABLE IF NOT EXISTS pending_channel_keys (
1161 community_id TEXT NOT NULL,
1162 channel_id TEXT NOT NULL,
1163 epoch INTEGER NOT NULL,
1164 channel_key BLOB NOT NULL,
1165 sender TEXT NOT NULL,
1166 received_at INTEGER NOT NULL,
1167 PRIMARY KEY (community_id, channel_id)
1168 )",
1169 [],
1170 )
1171 .map_err(|e| format!("migration 82: {}", e))?;
1172 Ok(())
1173 })?;
1174
1175 run_atomic_migration(conn, 83, "Parked channel-key vends as candidates", |tx| {
1188 tx.execute("DROP TABLE IF EXISTS pending_channel_keys", [])
1189 .map_err(|e| format!("migration 83: {}", e))?;
1190 tx.execute(
1191 "CREATE TABLE pending_channel_keys (
1192 id INTEGER PRIMARY KEY AUTOINCREMENT,
1193 community_id TEXT NOT NULL,
1194 channel_id TEXT NOT NULL,
1195 epoch INTEGER NOT NULL,
1196 channel_key BLOB NOT NULL,
1197 sender TEXT NOT NULL,
1198 received_at INTEGER NOT NULL
1199 )",
1200 [],
1201 )
1202 .map_err(|e| format!("migration 83: {}", e))?;
1203 tx.execute(
1204 "CREATE INDEX IF NOT EXISTS idx_pending_channel_keys_scope \
1205 ON pending_channel_keys(community_id, channel_id)",
1206 [],
1207 )
1208 .map_err(|e| format!("migration 83: {}", e))?;
1209 Ok(())
1210 })?;
1211
1212 run_atomic_migration(conn, 84, "Per-channel pin lists", |tx| {
1216 tx.execute(
1217 "CREATE TABLE IF NOT EXISTS community_pins (
1218 community_id TEXT NOT NULL,
1219 channel_id TEXT NOT NULL,
1220 content TEXT NOT NULL,
1221 version INTEGER NOT NULL,
1222 PRIMARY KEY (community_id, channel_id)
1223 )",
1224 [],
1225 )
1226 .map_err(|e| format!("migration 84: {}", e))?;
1227 Ok(())
1228 })?;
1229
1230 run_atomic_migration(conn, 85, "Deleted-message tombstones", |tx| {
1235 tx.execute(
1236 "CREATE TABLE IF NOT EXISTS deleted_messages (
1237 event_id TEXT PRIMARY KEY,
1238 deleted_at INTEGER NOT NULL
1239 )",
1240 [],
1241 )
1242 .map_err(|e| format!("migration 85: {}", e))?;
1243 Ok(())
1244 })?;
1245
1246 run_atomic_migration(conn, 86, "Concord v2 control_root split columns", |tx| {
1252 for (col, ddl) in [("control_pk", "TEXT"), ("control_root", "BLOB")] {
1253 let sql = format!("ALTER TABLE communities ADD COLUMN {col} {ddl}");
1255 if let Err(e) = tx.execute(&sql, []) {
1256 let msg = e.to_string();
1257 if !msg.contains("duplicate column name") {
1258 return Err(format!("add communities.{col}: {msg}"));
1259 }
1260 }
1261 }
1262 Ok(())
1263 })?;
1264
1265 run_atomic_migration(conn, 87, "Covering index for negentropy fingerprints", |tx| {
1272 tx.execute(
1273 "CREATE INDEX IF NOT EXISTS idx_processed_wrappers_neg \
1274 ON processed_wrappers(transport, wrapper_created_at, wrapper_id)",
1275 [],
1276 )
1277 .map_err(|e| format!("migration 87: {}", e))?;
1278
1279 tx.execute("DROP INDEX IF EXISTS idx_processed_wrappers_window", [])
1284 .map_err(|e| format!("migration 87 (drop superseded index): {}", e))?;
1285 Ok(())
1286 })?;
1287
1288 run_atomic_migration(conn, 88, "Persist status custom-emoji tags", |tx| {
1289 tx.execute(
1293 "ALTER TABLE profiles ADD COLUMN status_emoji_tags TEXT NOT NULL DEFAULT ''",
1294 [],
1295 )
1296 .map_err(|e| format!("migration 88: {}", e))?;
1297 Ok(())
1298 })?;
1299
1300 run_atomic_migration(conn, 89, "Community policy store", |tx| {
1306 tx.execute(
1307 "CREATE TABLE IF NOT EXISTS community_policies (
1308 community_id TEXT NOT NULL,
1309 policy_id TEXT NOT NULL,
1310 bytes TEXT NOT NULL,
1311 hash TEXT NOT NULL,
1312 enabled INTEGER NOT NULL DEFAULT 1,
1313 updated_at INTEGER NOT NULL DEFAULT 0,
1314 PRIMARY KEY (community_id, policy_id)
1315 )",
1316 [],
1317 )
1318 .map_err(|e| format!("create community_policies: {e}"))?;
1319 Ok(())
1320 })?;
1321
1322 run_atomic_migration(conn, 90, "Queryable community banlist", |tx| {
1332 tx.execute(
1333 "CREATE TABLE IF NOT EXISTS community_bans (
1334 community_id TEXT NOT NULL,
1335 npub TEXT NOT NULL,
1336 PRIMARY KEY (community_id, npub)
1337 )",
1338 [],
1339 )
1340 .map_err(|e| format!("create community_bans: {e}"))?;
1341 tx.execute(
1344 "CREATE INDEX IF NOT EXISTS idx_community_bans_community ON community_bans(community_id)",
1345 [],
1346 )
1347 .map_err(|e| format!("index community_bans: {e}"))?;
1348 Ok(())
1349 })?;
1350
1351 run_atomic_migration(conn, 91, "Drop chats with an empty identifier", |tx| {
1354 tx.execute(
1355 "DELETE FROM events WHERE chat_id IN (SELECT id FROM chats WHERE chat_identifier = '')",
1356 [],
1357 )
1358 .map_err(|e| format!("drop phantom chat events: {e}"))?;
1359 tx.execute("DELETE FROM chats WHERE chat_identifier = ''", [])
1360 .map_err(|e| format!("drop phantom chats: {e}"))?;
1361 Ok(())
1362 })?;
1363
1364 run_atomic_migration(conn, 92, "Create blossom_server_stats table", |tx| {
1365 crate::blossom_stats::migrate(tx)
1366 })?;
1367
1368 run_atomic_migration(conn, 93, "Per-scope notification preferences", |tx| {
1372 tx.execute(
1373 "CREATE TABLE IF NOT EXISTS notify_prefs (
1374 scope_id TEXT PRIMARY KEY,
1375 level INTEGER,
1376 mute_until INTEGER NOT NULL DEFAULT 0,
1377 suppress_everyone INTEGER
1378 )",
1379 [],
1380 )
1381 .map_err(|e| format!("create notify_prefs: {e}"))?;
1382 tx.execute(
1385 "INSERT OR REPLACE INTO notify_prefs (scope_id, level, mute_until, suppress_everyone)
1386 SELECT chat_identifier, NULL, -1, NULL FROM chats WHERE muted = 1 AND chat_identifier != ''",
1387 [],
1388 )
1389 .map_err(|e| format!("seed notify_prefs from mutes: {e}"))?;
1390 Ok(())
1391 })?;
1392
1393 run_atomic_migration(conn, 94, "Chat page index covers received_at and kind", |tx| {
1396 tx.execute_batch(
1397 "DROP INDEX IF EXISTS idx_events_chat_time;
1398 CREATE INDEX IF NOT EXISTS idx_events_chat_page ON events(chat_id, created_at DESC, received_at DESC, kind);",
1399 )
1400 .map_err(|e| format!("rebuild chat page index: {e}"))
1401 })?;
1402
1403 run_atomic_migration(conn, 95, "Per-account key derivation salt", |_tx| Ok(()))?;
1407
1408 run_atomic_migration(conn, 96, "Ledger DM wrappers held only on events rows", |tx| {
1412 backfill_dm_wrapper_ledger(tx).map(|_| ())
1413 })?;
1414
1415 run_atomic_migration(conn, 97, "Profile stream consent", |tx| {
1418 tx.execute("ALTER TABLE profiles ADD COLUMN stream_consent INTEGER NOT NULL DEFAULT 0", [])
1419 .map_err(|e| format!("add profiles.stream_consent: {e}"))?;
1420 Ok(())
1421 })?;
1422
1423 run_atomic_migration(conn, 98, "Chat unread_from marker", |tx| {
1425 tx.execute("ALTER TABLE chats ADD COLUMN unread_from TEXT NOT NULL DEFAULT ''", [])
1426 .map_err(|e| format!("add chats.unread_from: {e}"))?;
1427 Ok(())
1428 })?;
1429
1430 run_atomic_migration(conn, 99, "Persisted inbox relay lists", |tx| crate::inbox_relays::migrate(tx))?;
1431
1432 run_atomic_migration(conn, 100, "Inbox relay list revisions", |tx| crate::inbox_relays::migrate_event_at(tx))?;
1433
1434 run_atomic_migration(conn, 101, "Profile checked_at", |tx| {
1436 tx.execute("ALTER TABLE profiles ADD COLUMN checked_at INTEGER NOT NULL DEFAULT 0", [])
1437 .map_err(|e| format!("add profiles.checked_at: {e}"))?;
1438 Ok(())
1439 })?;
1440
1441 run_atomic_migration(conn, 102, "Mini App package metadata", |tx| {
1444 tx.execute_batch(
1445 "CREATE TABLE IF NOT EXISTS miniapp_meta (
1446 file_hash BLOB PRIMARY KEY,
1447 data TEXT NOT NULL
1448 );
1449 CREATE TABLE IF NOT EXISTS miniapp_files (
1450 path TEXT PRIMARY KEY,
1451 size INTEGER NOT NULL,
1452 modified INTEGER NOT NULL,
1453 file_hash BLOB NOT NULL
1454 );",
1455 )
1456 .map_err(|e| format!("create miniapp_meta: {e}"))
1457 })?;
1458
1459 run_atomic_migration(conn, 103, "Remove Concord v1", |tx| {
1461 let plan = super::v1_purge::plan_v1_purge(tx)?;
1462 super::v1_purge::apply_v1_purge(tx, &plan)
1463 })?;
1464
1465 run_atomic_migration(conn, 104, "Drop Concord v1 columns", |tx| super::v1_purge::drop_v1_columns(tx))?;
1467
1468 run_atomic_migration(conn, 105, "Edition head author", |tx| {
1471 tx.execute("ALTER TABLE community_edition_heads ADD COLUMN author BLOB", [])
1472 .map_err(|e| format!("add community_edition_heads.author: {e}"))?;
1473 Ok(())
1474 })?;
1475
1476 run_atomic_migration(conn, 106, "Edition head family", |tx| {
1479 tx.execute("ALTER TABLE community_edition_heads ADD COLUMN family TEXT", [])
1480 .map_err(|e| format!("add community_edition_heads.family: {e}"))?;
1481 Ok(())
1482 })?;
1483
1484 run_atomic_migration(conn, 107, "Writers ledgers", |tx| {
1486 tx.execute(
1487 "CREATE TABLE IF NOT EXISTS community_writers (
1488 community_id TEXT NOT NULL,
1489 channel_id TEXT NOT NULL,
1490 content TEXT NOT NULL,
1491 version INTEGER NOT NULL,
1492 PRIMARY KEY (community_id, channel_id)
1493 )",
1494 [],
1495 )
1496 .map_err(|e| format!("migration 107: {e}"))?;
1497 Ok(())
1498 })?;
1499
1500 run_atomic_migration(conn, 108, "Held community wraps", |tx| {
1503 tx.execute_batch(
1504 "CREATE TABLE IF NOT EXISTS community_held_wraps (
1505 wrap_id TEXT PRIMARY KEY,
1506 community_id TEXT NOT NULL,
1507 channel_id TEXT NOT NULL,
1508 wrap TEXT NOT NULL,
1509 at_ms INTEGER NOT NULL
1510 );
1511 CREATE INDEX IF NOT EXISTS idx_held_wraps_channel ON community_held_wraps(community_id, channel_id, at_ms);",
1512 )
1513 .map_err(|e| format!("migration 108: {e}"))?;
1514 Ok(())
1515 })?;
1516
1517 run_atomic_migration(conn, 109, "Held wrap authors", |tx| {
1519 tx.execute("ALTER TABLE community_held_wraps ADD COLUMN author TEXT NOT NULL DEFAULT ''", [])
1520 .map_err(|e| format!("migration 109: {e}"))?;
1521 Ok(())
1522 })?;
1523
1524 run_atomic_migration(conn, 110, "Held wrap sizes", |tx| {
1526 tx.execute_batch(
1527 "ALTER TABLE community_held_wraps ADD COLUMN bytes INTEGER NOT NULL DEFAULT 0;
1528 UPDATE community_held_wraps SET bytes = length(wrap);",
1529 )
1530 .map_err(|e| format!("migration 110: {e}"))?;
1531 Ok(())
1532 })?;
1533
1534 run_atomic_migration(conn, 111, "Community audit log", |tx| {
1536 tx.execute_batch(
1537 "CREATE TABLE IF NOT EXISTS community_audit_local (
1538 id TEXT PRIMARY KEY,
1539 community_id TEXT NOT NULL,
1540 at_ms INTEGER NOT NULL,
1541 entry TEXT NOT NULL
1542 );
1543 CREATE INDEX IF NOT EXISTS idx_audit_local_community ON community_audit_local(community_id, at_ms);",
1544 )
1545 .map_err(|e| format!("migration 111: {e}"))?;
1546 Ok(())
1547 })?;
1548
1549 run_atomic_migration(conn, 112, "Pending DM deletions", |tx| {
1552 tx.execute_batch(
1553 "CREATE TABLE IF NOT EXISTS pending_deletions (
1554 target TEXT PRIMARY KEY,
1555 requester TEXT NOT NULL,
1556 expires_at INTEGER NOT NULL
1557 );",
1558 )
1559 .map_err(|e| format!("migration 112: {e}"))?;
1560 Ok(())
1561 })?;
1562
1563 run_atomic_migration(conn, 113, "Community wrap owner keys", |tx| {
1564 tx.execute_batch(
1565 "CREATE TABLE IF NOT EXISTS community_wrap_owners (
1566 outer_event_id TEXT PRIMARY KEY,
1567 message_id TEXT NOT NULL,
1568 owner_secret BLOB NOT NULL,
1569 relays TEXT NOT NULL,
1570 created_at INTEGER NOT NULL
1571 );
1572 CREATE INDEX IF NOT EXISTS idx_cwo_message_id
1573 ON community_wrap_owners(message_id);",
1574 )
1575 .map_err(|e| format!("migration 113: {e}"))?;
1576 Ok(())
1577 })?;
1578
1579 run_atomic_migration(conn, 114, "Community wrap scrub queue", |tx| {
1580 tx.execute_batch(
1581 "CREATE TABLE IF NOT EXISTS community_wrap_scrubs (
1582 message_id TEXT PRIMARY KEY,
1583 community_id TEXT NOT NULL,
1584 queued_at INTEGER NOT NULL
1585 );",
1586 )
1587 .map_err(|e| format!("migration 114: {e}"))?;
1588 Ok(())
1589 })?;
1590
1591 run_atomic_migration(conn, 115, "Held DM wallpapers", |tx| {
1593 tx.execute_batch(
1594 "CREATE TABLE IF NOT EXISTS dm_held_wallpapers (
1595 chat_id TEXT PRIMARY KEY,
1596 created_at INTEGER NOT NULL,
1597 payload TEXT NOT NULL
1598 );",
1599 )
1600 .map_err(|e| format!("migration 115: {e}"))?;
1601 Ok(())
1602 })?;
1603
1604 run_atomic_migration(conn, 116, "Attachment blobs proven to open", |tx| {
1608 tx.execute(
1609 "ALTER TABLE attachments ADD COLUMN verified INTEGER NOT NULL DEFAULT 0",
1610 [],
1611 )
1612 .map_err(|e| format!("migration 116: {e}"))?;
1613 Ok(())
1614 })?;
1615
1616 run_atomic_migration(conn, 117, "Media store", |tx| {
1620 tx.execute_batch(
1621 "CREATE TABLE IF NOT EXISTS media_store (
1622 hash TEXT PRIMARY KEY,
1623 file TEXT NOT NULL,
1624 format TEXT NOT NULL,
1625 key TEXT NOT NULL,
1626 nonce TEXT NOT NULL,
1627 blob_sha256 TEXT NOT NULL,
1628 pt_len INTEGER NOT NULL,
1629 mime TEXT NOT NULL DEFAULT '',
1630 origin TEXT NOT NULL,
1631 created_at INTEGER NOT NULL,
1632 used_at INTEGER NOT NULL,
1633 missing_at INTEGER,
1634 chunk_size INTEGER,
1635 have BLOB
1636 );",
1637 )
1638 .map_err(|e| format!("migration 117: {e}"))?;
1639 Ok(())
1640 })?;
1641
1642 run_atomic_migration(conn, 118, "Saved files", |tx| {
1644 tx.execute_batch("CREATE TABLE IF NOT EXISTS saved_files (path TEXT PRIMARY KEY);")
1645 .map_err(|e| format!("migration 118: {e}"))?;
1646 Ok(())
1647 })?;
1648
1649 run_atomic_migration(conn, 119, "Guestbook events as rows", |tx| {
1654 tx.execute_batch(
1655 "CREATE TABLE IF NOT EXISTS community_guestbook_books (
1656 book INTEGER PRIMARY KEY,
1657 community_id TEXT NOT NULL UNIQUE
1658 );
1659 CREATE TABLE IF NOT EXISTS community_guestbook_events (
1660 seq INTEGER PRIMARY KEY,
1661 book INTEGER NOT NULL,
1662 rumor_id BLOB NOT NULL,
1663 body BLOB NOT NULL,
1664 UNIQUE (book, rumor_id)
1665 );",
1666 )
1667 .map_err(|e| format!("migration 119: {e}"))?;
1668 Ok(())
1669 })?;
1670
1671 run_atomic_migration(conn, 120, "Owed departures as rows", |tx| {
1674 tx.execute_batch(
1675 "CREATE TABLE IF NOT EXISTS community_departures_seen (
1676 seq INTEGER PRIMARY KEY,
1677 book INTEGER NOT NULL,
1678 body BLOB NOT NULL
1679 );
1680 CREATE INDEX IF NOT EXISTS community_departures_seen_book ON community_departures_seen (book);",
1681 )
1682 .map_err(|e| format!("migration 120: {e}"))?;
1683 Ok(())
1684 })?;
1685
1686 run_atomic_migration(conn, 121, "Owed author take-backs sealed", |tx| {
1689 tx.execute_batch(
1690 "CREATE TABLE IF NOT EXISTS community_owed_authors (
1691 seq INTEGER PRIMARY KEY,
1692 book INTEGER NOT NULL,
1693 channel_id TEXT NOT NULL,
1694 body BLOB NOT NULL
1695 );
1696 CREATE INDEX IF NOT EXISTS community_owed_authors_book ON community_owed_authors (book, channel_id);",
1697 )
1698 .map_err(|e| format!("migration 121: {e}"))?;
1699 Ok(())
1700 })?;
1701
1702 run_atomic_migration(conn, 122, "Index posts that are no sign of membership", |tx| {
1705 tx.execute_batch(
1706 "CREATE INDEX IF NOT EXISTS idx_events_unauthorized ON events(chat_id, npub) WHERE instr(tags, '[\"unauthorized\"]') > 0;
1707 CREATE INDEX IF NOT EXISTS idx_events_unauthorized_or_writer ON events(chat_id, npub) WHERE (instr(tags, '[\"unauthorized\"]') > 0 OR instr(tags, '[\"writer\"]') > 0);",
1708 )
1709 .map_err(|e| format!("migration 122: {e}"))?;
1710 Ok(())
1711 })?;
1712
1713 run_atomic_migration(conn, 123, "Index each sign of a post that is no sign of membership", |tx| {
1717 tx.execute_batch(
1718 "DROP INDEX IF EXISTS idx_events_unauthorized_or_writer;
1719 CREATE INDEX IF NOT EXISTS idx_events_writer_post ON events(chat_id, npub) WHERE instr(tags, '[\"writer\"]') > 0;",
1720 )
1721 .map_err(|e| format!("migration 123: {e}"))?;
1722 Ok(())
1723 })?;
1724
1725 run_atomic_migration(conn, 124, "Pending invite wrap ids", |tx| {
1728 tx.execute("ALTER TABLE pending_community_invites ADD COLUMN wrap_ids TEXT NOT NULL DEFAULT ''", [])
1729 .map_err(|e| format!("migration 124: {e}"))?;
1730 Ok(())
1731 })?;
1732
1733 run_atomic_migration(conn, 125, "Pending invite send time", |tx| {
1736 tx.execute("ALTER TABLE pending_community_invites ADD COLUMN sent_at INTEGER NOT NULL DEFAULT 0", [])
1737 .map_err(|e| format!("migration 125: {e}"))?;
1738 Ok(())
1739 })?;
1740
1741 run_atomic_migration(conn, 126, "Control wraps", |tx| {
1744 tx.execute_batch(
1745 "CREATE TABLE IF NOT EXISTS community_control_wraps (
1746 community_id TEXT NOT NULL,
1747 view BLOB NOT NULL,
1748 wrap_id BLOB NOT NULL,
1749 created_at INTEGER NOT NULL,
1750 wrap BLOB,
1751 rules INTEGER NOT NULL,
1752 judged_at INTEGER NOT NULL,
1753 PRIMARY KEY (community_id, view, wrap_id)
1754 );
1755 CREATE INDEX IF NOT EXISTS idx_control_wraps_page
1756 ON community_control_wraps(community_id, view, created_at DESC, wrap_id DESC) WHERE wrap IS NOT NULL;",
1757 )
1758 .map_err(|e| format!("migration 126: {e}"))?;
1759 Ok(())
1760 })?;
1761
1762 run_atomic_migration(conn, 127, "Guestbook wraps", |tx| {
1765 tx.execute_batch(
1766 "CREATE TABLE IF NOT EXISTS community_guestbook_wraps (
1767 community_id TEXT NOT NULL,
1768 plane BLOB NOT NULL,
1769 wrap_id BLOB NOT NULL,
1770 created_at INTEGER NOT NULL,
1771 rules INTEGER NOT NULL,
1772 judged_at INTEGER NOT NULL,
1773 PRIMARY KEY (community_id, plane, wrap_id)
1774 ) WITHOUT ROWID;",
1775 )
1776 .map_err(|e| format!("migration 127: {e}"))?;
1777 Ok(())
1778 })?;
1779
1780 Ok(())
1781}
1782
1783pub(crate) fn backfill_dm_wrapper_ledger(conn: &rusqlite::Connection) -> Result<usize, String> {
1787 let mut read = conn
1788 .prepare(
1789 "SELECT e.wrapper_event_id FROM events e LEFT JOIN chats c ON c.id = e.chat_id \
1790 WHERE e.wrapper_event_id IS NOT NULL AND length(e.wrapper_event_id) = 64 \
1791 AND c.chat_type IS NOT 2",
1792 )
1793 .map_err(|e| format!("prepare wrapper backfill read: {e}"))?;
1794 let mut write = conn
1795 .prepare(
1796 "INSERT OR IGNORE INTO processed_wrappers (wrapper_id, wrapper_created_at, transport) \
1797 VALUES (?1, 0, 0)",
1798 )
1799 .map_err(|e| format!("prepare wrapper backfill write: {e}"))?;
1800 let mut rows = read.query([]).map_err(|e| format!("read wrapper backfill: {e}"))?;
1801 let mut added = 0;
1802 while let Some(row) = rows.next().map_err(|e| format!("read wrapper backfill row: {e}"))? {
1803 let Ok(hex) = row.get_ref(0).and_then(|v| v.as_str().map_err(Into::into)) else {
1804 continue;
1805 };
1806 let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(hex) else {
1807 continue;
1808 };
1809 added += write
1810 .execute(rusqlite::params![&id[..]])
1811 .map_err(|e| format!("write wrapper backfill: {e}"))?;
1812 }
1813 Ok(added)
1814}
1815
1816#[cfg(test)]
1817mod tests {
1818 use super::HIGHEST_MIGRATION_ID;
1819
1820 fn migrated() -> rusqlite::Connection {
1821 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
1822 conn.execute_batch(super::SQL_SCHEMA).unwrap();
1823 super::run_migrations(&mut conn).unwrap();
1824 conn
1825 }
1826
1827 fn hex(b: u8) -> String {
1828 format!("{b:02x}").repeat(32)
1829 }
1830
1831 fn event(conn: &rusqlite::Connection, id: &str, chat: i64, wrapper: Option<&str>) {
1832 conn.execute(
1833 "INSERT INTO events (id, kind, chat_id, content, created_at, received_at, wrapper_event_id) \
1834 VALUES (?1, 14, ?2, '', 1, 1, ?3)",
1835 rusqlite::params![id, chat, wrapper],
1836 )
1837 .unwrap();
1838 }
1839
1840 fn ledger(conn: &rusqlite::Connection) -> Vec<(Vec<u8>, i64, i64)> {
1841 conn.prepare("SELECT wrapper_id, wrapper_created_at, transport FROM processed_wrappers ORDER BY wrapper_id")
1842 .unwrap()
1843 .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
1844 .unwrap()
1845 .map(Result::unwrap)
1846 .collect()
1847 }
1848
1849 #[test]
1851 fn the_wrapper_backfill_ledgers_exactly_the_dm_wrappers() {
1852 let mut conn = migrated();
1853 conn.execute_batch(
1854 "INSERT INTO chats (id, chat_identifier, chat_type, participants, created_at) VALUES
1855 (1, 'npub1dm', 0, '[]', 0), (2, 'channel', 2, '[]', 0);",
1856 )
1857 .unwrap();
1858 conn.execute_batch("PRAGMA foreign_keys = OFF;").unwrap();
1859 event(&conn, "m1", 1, Some(&hex(0x11))); event(&conn, "m2", 1, Some(&hex(0xAB).to_uppercase())); event(&conn, "m3", 1, Some(&hex(0x22))); event(&conn, "m4", 2, Some(&hex(0x33))); event(&conn, "m5", 99, Some(&hex(0x44))); event(&conn, "m6", 1, Some("zz".repeat(32).as_str())); event(&conn, "m7", 1, Some("abc")); event(&conn, "m8", 1, Some("")); event(&conn, "m9", 1, None); event(&conn, "m10", 1, Some(&hex(0x11))); conn.execute(
1870 "INSERT INTO processed_wrappers (wrapper_id, wrapper_created_at, transport) VALUES (?1, 777, 0)",
1871 [&[0x22u8; 32][..]],
1872 )
1873 .unwrap();
1874 conn.execute("DELETE FROM schema_migrations WHERE id = 96", []).unwrap();
1875
1876 super::run_migrations(&mut conn).unwrap();
1877
1878 assert_eq!(
1879 ledger(&conn),
1880 vec![
1881 (vec![0x11; 32], 0, 0),
1882 (vec![0x22; 32], 777, 0),
1883 (vec![0x44; 32], 0, 0),
1884 (vec![0xAB; 32], 0, 0),
1885 ],
1886 );
1887 assert!(super::migration_applied(&conn, 96));
1888
1889 event(&conn, "m11", 1, Some(&hex(0x55)));
1891 super::run_migrations(&mut conn).unwrap();
1892 assert_eq!(ledger(&conn).len(), 4);
1893 }
1894
1895 #[test]
1896 fn the_wrapper_backfill_is_a_no_op_on_a_fresh_database() {
1897 let conn = migrated();
1898 assert!(super::migration_applied(&conn, 96));
1899 assert!(ledger(&conn).is_empty());
1900 assert_eq!(super::backfill_dm_wrapper_ledger(&conn).unwrap(), 0);
1901 }
1902
1903 #[test]
1906 fn a_backfilled_wrapper_is_found_by_the_dedup_lookup() {
1907 let conn = migrated();
1908 conn.execute_batch(
1909 "INSERT INTO chats (id, chat_identifier, chat_type, participants, created_at) VALUES (1, 'npub1dm', 0, '[]', 0);",
1910 )
1911 .unwrap();
1912 let id = [0x5Au8; 32];
1913 event(&conn, "m1", 1, Some(&crate::simd::hex::bytes_to_hex_32(&id)));
1914 assert_eq!(super::backfill_dm_wrapper_ledger(&conn).unwrap(), 1);
1915 let found: bool = conn
1916 .query_row("SELECT EXISTS(SELECT 1 FROM processed_wrappers WHERE wrapper_id = ?1)", [&id[..]], |r| r.get(0))
1917 .unwrap();
1918 assert!(found);
1919 assert_eq!(super::backfill_dm_wrapper_ledger(&conn).unwrap(), 0, "idempotent");
1920 }
1921
1922 #[test]
1926 fn highest_migration_id_matches_the_runner() {
1927 let src = include_str!("schema.rs");
1928 let mut highest = 0u32;
1929 let mut seen = 0usize;
1930
1931 for (at, _) in src.match_indices("run_atomic_migration(") {
1932 let tail = src[at + "run_atomic_migration(".len()..].trim_start();
1933 let Some(args) = tail.strip_prefix("conn,") else {
1935 continue;
1936 };
1937 let id: String = args
1938 .trim_start()
1939 .chars()
1940 .take_while(char::is_ascii_digit)
1941 .collect();
1942 if let Ok(id) = id.parse::<u32>() {
1943 seen += 1;
1944 highest = highest.max(id);
1945 }
1946 }
1947
1948 assert!(seen > 0, "parsed no migrations; the call shape must have changed");
1949 assert_eq!(
1950 HIGHEST_MIGRATION_ID, highest,
1951 "bump HIGHEST_MIGRATION_ID to {highest} when adding a migration"
1952 );
1953 }
1954}