| 35 | * Processes in batches for memory efficiency. |
| 36 | */ |
| 37 | export function buildFtsIndex(db: DatabaseAdapter): { indexed: number } { |
| 38 | createFtsTable(db) |
| 39 | |
| 40 | const insertFts = db.prepare('INSERT INTO message_fts(rowid, content) VALUES (?, ?)') |
| 41 | |
| 42 | const countRow = db |
| 43 | .prepare("SELECT COUNT(*) as total FROM message WHERE type = 0 AND content IS NOT NULL AND content != ''") |
| 44 | .get() as { total: number } | undefined |
| 45 | const total = countRow?.total ?? 0 |
| 46 | |
| 47 | let indexed = 0 |
| 48 | let offset = 0 |
| 49 | |
| 50 | while (offset < total) { |
| 51 | const rows = db |
| 52 | .prepare( |
| 53 | `SELECT id, content FROM message |
| 54 | WHERE type = 0 AND content IS NOT NULL AND content != '' |
| 55 | ORDER BY id ASC LIMIT ? OFFSET ?` |
| 56 | ) |
| 57 | .all(BATCH_SIZE, offset) as Array<{ id: number; content: string }> |
| 58 | |
| 59 | if (rows.length === 0) break |
| 60 | |
| 61 | db.transaction(() => { |
| 62 | for (const row of rows) { |
| 63 | const tokens = tokenizeForFts(row.content) |
| 64 | if (tokens) { |
| 65 | insertFts.run(row.id, tokens) |
| 66 | } |
| 67 | } |
| 68 | }) |
| 69 | |
| 70 | indexed += rows.length |
| 71 | offset += BATCH_SIZE |
| 72 | } |
| 73 | |
| 74 | return { indexed } |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Rebuild FTS index by dropping and recreating. |