|
| 1 | +package storage |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "gorm.io/gorm" |
| 9 | +) |
| 10 | + |
| 11 | +// fts5LogsTable is the FTS5 virtual table mirroring `logs.body` and |
| 12 | +// `logs.service_name`. It is an external-content table keyed on `logs.id` so it |
| 13 | +// stores no extra copy of the body — instead, INSERT/DELETE/UPDATE on `logs` |
| 14 | +// are mirrored via the triggers installed in setupSQLiteFTS5. |
| 15 | +const fts5LogsTable = "logs_fts" |
| 16 | + |
| 17 | +// setupSQLiteFTS5 provisions the FTS5 virtual table for log search on SQLite |
| 18 | +// and the AFTER INSERT/DELETE/UPDATE triggers that keep it in sync with the |
| 19 | +// `logs` base table. The implementation is idempotent: it tolerates an |
| 20 | +// existing virtual table left over from a previous boot, repairs missing |
| 21 | +// triggers, and runs an initial backfill via the `rebuild` command so that |
| 22 | +// rows present in `logs` before the FTS table existed (e.g. migrating an |
| 23 | +// older OtelContext.db) are included in the BM25 index. |
| 24 | +// |
| 25 | +// Tokenizer rationale: `porter unicode61 remove_diacritics 2` chosen for: |
| 26 | +// - unicode61: case-insensitive, splits on whitespace+punctuation |
| 27 | +// - remove_diacritics 2: strips accents (latency vs latência both match) |
| 28 | +// - porter: English stemming so "panic" matches "panicked"/"panicking" |
| 29 | +// |
| 30 | +// All three are pure-SQLite — they do not require external linkage and work |
| 31 | +// on the modernc.org/sqlite (glebarez) build used in this project. |
| 32 | +func setupSQLiteFTS5(db *gorm.DB) error { |
| 33 | + create := `CREATE VIRTUAL TABLE IF NOT EXISTS ` + fts5LogsTable + ` USING fts5( |
| 34 | + body, |
| 35 | + service_name, |
| 36 | + content='logs', |
| 37 | + content_rowid='id', |
| 38 | + tokenize='porter unicode61 remove_diacritics 2' |
| 39 | + )` |
| 40 | + if err := db.Exec(create).Error; err != nil { |
| 41 | + // FTS5 is included in the modernc.org/sqlite amalgamation by default; |
| 42 | + // if this fails, the build was compiled without FTS5. Surface the |
| 43 | + // failure so SearchLogs can fall back to LIKE rather than producing |
| 44 | + // a confusing "no such table" error later. |
| 45 | + return fmt.Errorf("create fts5 virtual table: %w", err) |
| 46 | + } |
| 47 | + |
| 48 | + triggers := []struct { |
| 49 | + name string |
| 50 | + ddl string |
| 51 | + }{ |
| 52 | + { |
| 53 | + name: "logs_ai", |
| 54 | + ddl: `CREATE TRIGGER IF NOT EXISTS logs_ai AFTER INSERT ON logs BEGIN |
| 55 | + INSERT INTO ` + fts5LogsTable + `(rowid, body, service_name) VALUES (new.id, new.body, new.service_name); |
| 56 | + END`, |
| 57 | + }, |
| 58 | + { |
| 59 | + name: "logs_ad", |
| 60 | + ddl: `CREATE TRIGGER IF NOT EXISTS logs_ad AFTER DELETE ON logs BEGIN |
| 61 | + INSERT INTO ` + fts5LogsTable + `(` + fts5LogsTable + `, rowid, body, service_name) VALUES ('delete', old.id, old.body, old.service_name); |
| 62 | + END`, |
| 63 | + }, |
| 64 | + { |
| 65 | + name: "logs_au", |
| 66 | + ddl: `CREATE TRIGGER IF NOT EXISTS logs_au AFTER UPDATE ON logs BEGIN |
| 67 | + INSERT INTO ` + fts5LogsTable + `(` + fts5LogsTable + `, rowid, body, service_name) VALUES ('delete', old.id, old.body, old.service_name); |
| 68 | + INSERT INTO ` + fts5LogsTable + `(rowid, body, service_name) VALUES (new.id, new.body, new.service_name); |
| 69 | + END`, |
| 70 | + }, |
| 71 | + } |
| 72 | + for _, tr := range triggers { |
| 73 | + if err := db.Exec(tr.ddl).Error; err != nil { |
| 74 | + return fmt.Errorf("create trigger %s: %w", tr.name, err) |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + // Backfill any rows already present in `logs` but not yet in the FTS index. |
| 79 | + // `rebuild` is a no-op on a fresh DB and cheap on a populated one — FTS5 |
| 80 | + // streams the source rows once. |
| 81 | + if err := db.Exec(`INSERT INTO ` + fts5LogsTable + `(` + fts5LogsTable + `) VALUES ('rebuild')`).Error; err != nil { |
| 82 | + return fmt.Errorf("rebuild fts5 index: %w", err) |
| 83 | + } |
| 84 | + |
| 85 | + log.Println("🔎 SQLite: FTS5 BM25 index ready on logs(body, service_name)") |
| 86 | + return nil |
| 87 | +} |
| 88 | + |
| 89 | +// fts5MatchExpr translates a free-form user search string into an FTS5 MATCH |
| 90 | +// expression that approximates the previous LIKE %query% semantics: |
| 91 | +// |
| 92 | +// - whitespace-separated terms are ANDed together |
| 93 | +// - each term is double-quoted so FTS5 treats internal punctuation as |
| 94 | +// literal token separators rather than query operators |
| 95 | +// - each term is suffixed with `*` for prefix match, so a search for "conn" |
| 96 | +// still hits "connection"; combined with the porter stemmer this also |
| 97 | +// covers inflectional matches like "panic" → "panicked" |
| 98 | +// |
| 99 | +// Returns the empty string for empty/whitespace-only input — the caller is |
| 100 | +// expected to skip the WHERE-clause attachment in that case. |
| 101 | +func fts5MatchExpr(input string) string { |
| 102 | + fields := strings.Fields(input) |
| 103 | + if len(fields) == 0 { |
| 104 | + return "" |
| 105 | + } |
| 106 | + parts := make([]string, 0, len(fields)) |
| 107 | + for _, f := range fields { |
| 108 | + escaped := strings.ReplaceAll(f, `"`, `""`) |
| 109 | + parts = append(parts, `"`+escaped+`"*`) |
| 110 | + } |
| 111 | + return strings.Join(parts, " ") |
| 112 | +} |
| 113 | + |
| 114 | +// fts5Available reports whether the given driver should use the FTS5 path. We |
| 115 | +// only enable FTS5 on SQLite because Postgres has its own pg_trgm GIN path |
| 116 | +// (see factory.go) and MySQL/SQL Server are out of scope. |
| 117 | +func fts5Available(driver string) bool { |
| 118 | + return strings.ToLower(driver) == "sqlite" |
| 119 | +} |
0 commit comments