|
| 1 | +import Database from 'better-sqlite3' |
| 2 | +import { app } from 'electron' |
| 3 | +import path from 'path' |
| 4 | + |
| 5 | +let db: Database.Database | null = null |
| 6 | + |
| 7 | +/** |
| 8 | + * Get or initialize the SQLite database. |
| 9 | + * Creates tables if they don't exist. |
| 10 | + */ |
| 11 | +export function getDatabase(): Database.Database { |
| 12 | + if (db) return db |
| 13 | + |
| 14 | + const dbPath = path.join(app.getPath('userData'), 'tabby.db') |
| 15 | + console.log('[LocalDB] Opening database at:', dbPath) |
| 16 | + |
| 17 | + db = new Database(dbPath) |
| 18 | + |
| 19 | + // Enable WAL mode for better performance |
| 20 | + db.pragma('journal_mode = WAL') |
| 21 | + db.pragma('foreign_keys = ON') |
| 22 | + |
| 23 | + // Create tables |
| 24 | + db.exec(` |
| 25 | + CREATE TABLE IF NOT EXISTS conversations ( |
| 26 | + id TEXT PRIMARY KEY, |
| 27 | + user_id TEXT, |
| 28 | + title TEXT NOT NULL DEFAULT 'New Chat', |
| 29 | + type TEXT NOT NULL DEFAULT 'chat', |
| 30 | + lastContext TEXT, |
| 31 | + created_at TEXT NOT NULL DEFAULT (datetime('now')), |
| 32 | + updated_at TEXT NOT NULL DEFAULT (datetime('now')) |
| 33 | + ); |
| 34 | +
|
| 35 | + CREATE TABLE IF NOT EXISTS messages ( |
| 36 | + id TEXT PRIMARY KEY, |
| 37 | + conversation_id TEXT NOT NULL, |
| 38 | + role TEXT NOT NULL, |
| 39 | + parts TEXT NOT NULL DEFAULT '[]', |
| 40 | + metadata TEXT, |
| 41 | + created_at TEXT NOT NULL DEFAULT (datetime('now')), |
| 42 | + FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE |
| 43 | + ); |
| 44 | +
|
| 45 | + CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id); |
| 46 | + CREATE INDEX IF NOT EXISTS idx_conversations_type ON conversations(type); |
| 47 | + CREATE INDEX IF NOT EXISTS idx_conversations_updated_at ON conversations(updated_at); |
| 48 | + `) |
| 49 | + |
| 50 | + console.log('[LocalDB] Database initialized successfully') |
| 51 | + return db |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Close the database connection gracefully. |
| 56 | + */ |
| 57 | +export function closeDatabase(): void { |
| 58 | + if (db) { |
| 59 | + db.close() |
| 60 | + db = null |
| 61 | + console.log('[LocalDB] Database closed') |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +// ─── Conversation CRUD ─────────────────────────────────────────── |
| 66 | + |
| 67 | +export interface ConversationRow { |
| 68 | + id: string |
| 69 | + user_id: string | null |
| 70 | + title: string |
| 71 | + type: string |
| 72 | + lastContext: string | null |
| 73 | + created_at: string |
| 74 | + updated_at: string |
| 75 | +} |
| 76 | + |
| 77 | +export interface MessageRow { |
| 78 | + id: string |
| 79 | + conversation_id: string |
| 80 | + role: string |
| 81 | + parts: string // JSON string |
| 82 | + metadata: string | null // JSON string |
| 83 | + created_at: string |
| 84 | +} |
| 85 | + |
| 86 | +export function getConversations(type?: string): ConversationRow[] { |
| 87 | + const database = getDatabase() |
| 88 | + if (type) { |
| 89 | + return database |
| 90 | + .prepare('SELECT * FROM conversations WHERE type = ? ORDER BY updated_at DESC') |
| 91 | + .all(type) as ConversationRow[] |
| 92 | + } |
| 93 | + return database |
| 94 | + .prepare('SELECT * FROM conversations ORDER BY updated_at DESC') |
| 95 | + .all() as ConversationRow[] |
| 96 | +} |
| 97 | + |
| 98 | +export function getConversationById(id: string): ConversationRow | undefined { |
| 99 | + const database = getDatabase() |
| 100 | + return database.prepare('SELECT * FROM conversations WHERE id = ?').get(id) as |
| 101 | + | ConversationRow |
| 102 | + | undefined |
| 103 | +} |
| 104 | + |
| 105 | +export function createConversation(conversation: { |
| 106 | + id: string |
| 107 | + title: string |
| 108 | + type?: string |
| 109 | + userId?: string |
| 110 | +}): ConversationRow { |
| 111 | + const database = getDatabase() |
| 112 | + const now = new Date().toISOString() |
| 113 | + database |
| 114 | + .prepare( |
| 115 | + `INSERT INTO conversations (id, user_id, title, type, created_at, updated_at) |
| 116 | + VALUES (?, ?, ?, ?, ?, ?)` |
| 117 | + ) |
| 118 | + .run( |
| 119 | + conversation.id, |
| 120 | + conversation.userId || null, |
| 121 | + conversation.title, |
| 122 | + conversation.type || 'chat', |
| 123 | + now, |
| 124 | + now |
| 125 | + ) |
| 126 | + return getConversationById(conversation.id)! |
| 127 | +} |
| 128 | + |
| 129 | +export function renameConversation(id: string, title: string): void { |
| 130 | + const database = getDatabase() |
| 131 | + database |
| 132 | + .prepare('UPDATE conversations SET title = ?, updated_at = ? WHERE id = ?') |
| 133 | + .run(title, new Date().toISOString(), id) |
| 134 | +} |
| 135 | + |
| 136 | +export function deleteConversation(id: string): void { |
| 137 | + const database = getDatabase() |
| 138 | + // Messages are cascade-deleted via FK |
| 139 | + database.prepare('DELETE FROM conversations WHERE id = ?').run(id) |
| 140 | +} |
| 141 | + |
| 142 | +// ─── Message CRUD ──────────────────────────────────────────────── |
| 143 | + |
| 144 | +export function getMessages(conversationId: string): MessageRow[] { |
| 145 | + const database = getDatabase() |
| 146 | + return database |
| 147 | + .prepare('SELECT * FROM messages WHERE conversation_id = ? ORDER BY created_at ASC') |
| 148 | + .all(conversationId) as MessageRow[] |
| 149 | +} |
| 150 | + |
| 151 | +export function saveMessages( |
| 152 | + messages: Array<{ |
| 153 | + id: string |
| 154 | + conversation_id: string |
| 155 | + role: string |
| 156 | + parts: unknown |
| 157 | + metadata?: unknown |
| 158 | + }> |
| 159 | +): void { |
| 160 | + const database = getDatabase() |
| 161 | + const upsert = database.prepare( |
| 162 | + `INSERT INTO messages (id, conversation_id, role, parts, metadata, created_at) |
| 163 | + VALUES (?, ?, ?, ?, ?, ?) |
| 164 | + ON CONFLICT(id) DO UPDATE SET |
| 165 | + parts = excluded.parts, |
| 166 | + metadata = excluded.metadata` |
| 167 | + ) |
| 168 | + |
| 169 | + const now = new Date().toISOString() |
| 170 | + const transaction = database.transaction(() => { |
| 171 | + for (const msg of messages) { |
| 172 | + upsert.run( |
| 173 | + msg.id, |
| 174 | + msg.conversation_id, |
| 175 | + msg.role, |
| 176 | + JSON.stringify(msg.parts), |
| 177 | + msg.metadata ? JSON.stringify(msg.metadata) : null, |
| 178 | + now |
| 179 | + ) |
| 180 | + } |
| 181 | + }) |
| 182 | + transaction() |
| 183 | + |
| 184 | + // Update conversation timestamp |
| 185 | + if (messages.length > 0) { |
| 186 | + database |
| 187 | + .prepare('UPDATE conversations SET updated_at = ? WHERE id = ?') |
| 188 | + .run(now, messages[0].conversation_id) |
| 189 | + } |
| 190 | +} |
0 commit comments