From e4bb4e5414dd06712c77337c1c61d46dd0dc5624 Mon Sep 17 00:00:00 2001 From: "brobert (aider)" Date: Sun, 23 Mar 2025 12:15:18 +0100 Subject: [PATCH] fix: Make participants field nullable and improve database error handling --- src/bot/utils/api.ts | 15 +++++++++++++-- src/database/db.ts | 13 ++++++++++--- src/database/schema.sql | 2 +- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/bot/utils/api.ts b/src/bot/utils/api.ts index 99e348e..a1ef3d2 100644 --- a/src/bot/utils/api.ts +++ b/src/bot/utils/api.ts @@ -33,8 +33,19 @@ export async function fetchGroups(communityId: string): Promise> { // Save the group to the database execute( - 'INSERT OR REPLACE INTO groups (id, name, linked_parent) VALUES (?, ?, ?)', - [group.id, group.subject || 'Unnamed Group', group.linkedParent] // Provide a default name if missing + `INSERT INTO groups (id, name, participants, linked_parent, last_updated) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + name = excluded.name, + participants = excluded.participants, + last_updated = excluded.last_updated`, + [ + group.id, + group.subject || 'Unnamed Group', + group.participants ? JSON.stringify(group.participants) : null, + group.linkedParent, + new Date().toISOString() + ] ); } } diff --git a/src/database/db.ts b/src/database/db.ts index e9dfc4f..af72aae 100644 --- a/src/database/db.ts +++ b/src/database/db.ts @@ -12,9 +12,16 @@ if (!fs.existsSync(dbDir)) { const dbPath = path.join(dbDir, 'bot.db'); export const db = new Database(dbPath); -// Run the schema script -const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8'); -db.exec(schema); +// Run the schema script with error handling +try { + const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8'); + db.exec('PRAGMA foreign_keys=OFF;'); // Disable foreign keys during schema changes + db.exec(schema); + db.exec('PRAGMA foreign_keys=ON;'); // Re-enable foreign keys +} catch (error) { + console.error('Error initializing database schema:', error); + process.exit(1); +} // Helper function to query the database export function query(sql: string, params: any[] = []) { diff --git a/src/database/schema.sql b/src/database/schema.sql index 01c0c69..20509bd 100644 --- a/src/database/schema.sql +++ b/src/database/schema.sql @@ -2,7 +2,7 @@ CREATE TABLE IF NOT EXISTS groups ( id TEXT PRIMARY KEY, -- WhatsApp group ID name TEXT NOT NULL DEFAULT 'Unnamed group', - participants TEXT NOT NULL, -- JSON array of phone numbers + participants TEXT DEFAULT NULL, -- JSON array of phone numbers (nullable) linked_parent TEXT, -- Parent community ID last_updated TEXT -- ISO 8601 timestamp of last update );