(db: Database.Database)
| 202 | } |
| 203 | |
| 204 | private migrateDatabase(db: Database.Database): void { |
| 205 | try { |
| 206 | const hasLegacyConversationTable = this.tableExists(db, 'ai_conversation') |
| 207 | |
| 208 | if (hasLegacyConversationTable) { |
| 209 | const convColumns = this.getTableColumns(db, 'ai_conversation') |
| 210 | if (!convColumns.includes('assistant_id')) { |
| 211 | db.exec(`ALTER TABLE ai_conversation ADD COLUMN assistant_id TEXT DEFAULT '${DEFAULT_GENERAL_ID}'`) |
| 212 | } |
| 213 | if (!convColumns.includes('active_message_id')) { |
| 214 | db.exec('ALTER TABLE ai_conversation ADD COLUMN active_message_id TEXT') |
| 215 | } |
| 216 | |
| 217 | db.exec(` |
| 218 | INSERT OR IGNORE INTO ai_chat ( |
| 219 | id, session_id, title, assistant_id, active_message_id, created_at, updated_at |
| 220 | ) |
| 221 | SELECT id, session_id, title, COALESCE(assistant_id, '${DEFAULT_GENERAL_ID}'), |
| 222 | active_message_id, created_at, updated_at |
| 223 | FROM ai_conversation |
| 224 | `) |
| 225 | } |
| 226 | |
| 227 | this.ensureMessageMigrationColumns(db, 'ai_message') |
| 228 | |
| 229 | const messageColumns = this.getTableColumns(db, 'ai_message') |
| 230 | const hadLegacyConversationId = messageColumns.includes('conversation_id') |
| 231 | const needsMessageTreeBackfill = |
| 232 | !messageColumns.includes('parent_id') || |
| 233 | !messageColumns.includes('sibling_group_id') || |
| 234 | !messageColumns.includes('branch_index') || |
| 235 | hadLegacyConversationId |
| 236 | |
| 237 | if (hadLegacyConversationId && !messageColumns.includes('ai_chat_id')) { |
| 238 | db.exec(` |
| 239 | DROP INDEX IF EXISTS idx_ai_message_conversation; |
| 240 | ALTER TABLE ai_message RENAME TO ai_message_legacy; |
| 241 | |
| 242 | CREATE TABLE ai_message ( |
| 243 | id TEXT PRIMARY KEY, |
| 244 | ai_chat_id TEXT NOT NULL, |
| 245 | role TEXT NOT NULL, |
| 246 | content TEXT NOT NULL, |
| 247 | timestamp INTEGER NOT NULL, |
| 248 | data_keywords TEXT, |
| 249 | data_message_count INTEGER, |
| 250 | content_blocks TEXT, |
| 251 | parent_id TEXT, |
| 252 | sibling_group_id TEXT, |
| 253 | branch_index INTEGER DEFAULT 0, |
| 254 | debug_context TEXT, |
| 255 | token_usage TEXT, |
| 256 | FOREIGN KEY(ai_chat_id) REFERENCES ai_chat(id) ON DELETE CASCADE |
| 257 | ); |
| 258 | |
| 259 | INSERT INTO ai_message ( |
| 260 | id, ai_chat_id, role, content, timestamp, data_keywords, data_message_count, |
| 261 | content_blocks, parent_id, sibling_group_id, branch_index, debug_context, token_usage |
no test coverage detected