diff --git a/src/db-migration.test.ts b/src/db-migration.test.ts new file mode 100644 index 0000000..e26873d --- /dev/null +++ b/src/db-migration.test.ts @@ -0,0 +1,67 @@ +import Database from 'better-sqlite3'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { describe, expect, it, vi } from 'vitest'; + +describe('database migrations', () => { + it('defaults Telegram backfill chats to direct messages', async () => { + const repoRoot = process.cwd(); + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nanoclaw-db-test-')); + + try { + process.chdir(tempDir); + fs.mkdirSync(path.join(tempDir, 'store'), { recursive: true }); + + const dbPath = path.join(tempDir, 'store', 'messages.db'); + const legacyDb = new Database(dbPath); + legacyDb.exec(` + CREATE TABLE chats ( + jid TEXT PRIMARY KEY, + name TEXT, + last_message_time TEXT + ); + `); + legacyDb + .prepare( + `INSERT INTO chats (jid, name, last_message_time) VALUES (?, ?, ?)`, + ) + .run('tg:12345', 'Telegram DM', '2024-01-01T00:00:00.000Z'); + legacyDb + .prepare( + `INSERT INTO chats (jid, name, last_message_time) VALUES (?, ?, ?)`, + ) + .run('tg:-10012345', 'Telegram Group', '2024-01-01T00:00:01.000Z'); + legacyDb + .prepare( + `INSERT INTO chats (jid, name, last_message_time) VALUES (?, ?, ?)`, + ) + .run('room@g.us', 'WhatsApp Group', '2024-01-01T00:00:02.000Z'); + legacyDb.close(); + + vi.resetModules(); + const { initDatabase, getAllChats, _closeDatabase } = + await import('./db.js'); + + initDatabase(); + + const chats = getAllChats(); + expect(chats.find((chat) => chat.jid === 'tg:12345')).toMatchObject({ + channel: 'telegram', + is_group: 0, + }); + expect(chats.find((chat) => chat.jid === 'tg:-10012345')).toMatchObject({ + channel: 'telegram', + is_group: 0, + }); + expect(chats.find((chat) => chat.jid === 'room@g.us')).toMatchObject({ + channel: 'whatsapp', + is_group: 1, + }); + + _closeDatabase(); + } finally { + process.chdir(repoRoot); + } + }); +}); diff --git a/src/db.ts b/src/db.ts index 87dd941..718bc60 100644 --- a/src/db.ts +++ b/src/db.ts @@ -141,7 +141,7 @@ function createSchema(database: Database.Database): void { `UPDATE chats SET channel = 'discord', is_group = 1 WHERE jid LIKE 'dc:%'`, ); database.exec( - `UPDATE chats SET channel = 'telegram', is_group = 1 WHERE jid LIKE 'tg:%'`, + `UPDATE chats SET channel = 'telegram', is_group = 0 WHERE jid LIKE 'tg:%'`, ); } catch { /* columns already exist */ @@ -165,6 +165,11 @@ export function _initTestDatabase(): void { createSchema(db); } +/** @internal - for tests only. */ +export function _closeDatabase(): void { + db.close(); +} + /** * Store chat metadata only (no message content). * Used for all chats to enable group discovery without storing sensitive content.