From 4b1643bc4710c2647e6d3c6531e7d16fc7a3dc0b Mon Sep 17 00:00:00 2001 From: Cory McWilliams Date: Sat, 22 Mar 2025 08:58:43 -0400 Subject: [PATCH] ssb: Hook up a busy handler to give checkpointing a chance of working, and fix fundamental bugs with the messages_stats table. How did this ever work? --- src/ssb.db.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/ssb.db.c b/src/ssb.db.c index 6ae5ed80..fe68b6eb 100644 --- a/src/ssb.db.c +++ b/src/ssb.db.c @@ -71,11 +71,17 @@ static bool _tf_ssb_db_has_rows(sqlite3* db, const char* query) return found; } +static int _tf_ssb_db_busy_handler(void* user_data, int count) +{ + return 1; +} + static void _tf_ssb_db_init_internal(sqlite3* db) { sqlite3_extended_result_codes(db, 1); _tf_ssb_db_exec(db, "PRAGMA journal_mode = WAL"); _tf_ssb_db_exec(db, "PRAGMA synchronous = NORMAL"); + sqlite3_busy_handler(db, _tf_ssb_db_busy_handler, db); } void tf_ssb_db_init_reader(sqlite3* db) @@ -119,6 +125,14 @@ void tf_ssb_db_init(tf_ssb_t* ssb) " flags INTEGER," " UNIQUE(author, sequence)" ")"); + if (_tf_ssb_db_has_rows(db, "PRAGMA table_list('messages_stats')")) + { + if (_tf_ssb_db_has_rows(db, "SELECT 1 FROM messages_stats WHERE max_sequence IS NULL LIMIT 1")) + { + tf_printf("Rebuilding messages_stats.\n"); + _tf_ssb_db_exec(db, "DROP TABLE messages_stats"); + } + } if (!_tf_ssb_db_has_rows(db, "PRAGMA table_list('messages_stats')")) { _tf_ssb_db_exec(db, "BEGIN TRANSACTION"); @@ -134,8 +148,8 @@ void tf_ssb_db_init(tf_ssb_t* ssb) } _tf_ssb_db_exec(db, "CREATE TRIGGER IF NOT EXISTS messages_ai_stats AFTER INSERT ON messages BEGIN INSERT INTO messages_stats(author, max_sequence, max_timestamp) VALUES (new.author, " - "new.sequence, new.timestamp) ON CONFLICT DO UPDATE SET max_sequence = MAX(max_sequence, excluded.max_sequence), max_timestamp = MAX(max_timestamp, " - "excluded.max_timestamp); END"); + "new.sequence, new.timestamp) ON CONFLICT DO UPDATE SET max_sequence = MAX(max_sequence, new.sequence), max_timestamp = MAX(max_timestamp, " + "new.timestamp); END"); _tf_ssb_db_exec(db, "CREATE TRIGGER IF NOT EXISTS messages_ad_stats AFTER DELETE ON messages BEGIN UPDATE messages_stats SET max_sequence = (SELECT MAX(messages.sequence) FROM messages WHERE " "messages.author = old.author), max_timestamp = (SELECT MAX(messages.timestamp) FROM messages WHERE messages.author = old.author); END");