| 1 | import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; |
| 2 | import { RETRIEVAL_PARAMS } from "../util/parameters"; |
| 3 | import { getUriPathBasename } from "../util/uri"; |
| 4 | |
| 5 | import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; |
| 6 | import { DatabaseConnection, SqliteDb } from "./refreshIndex"; |
| 7 | import { |
| 8 | IndexResultType, |
| 9 | MarkCompleteCallback, |
| 10 | RefreshIndexResults, |
| 11 | type CodebaseIndex, |
| 12 | } from "./types"; |
| 13 | import { tagToString } from "./utils"; |
| 14 | |
| 15 | export interface RetrieveConfig { |
| 16 | tags: BranchAndDir[]; |
| 17 | text: string; |
| 18 | n: number; |
| 19 | directory?: string; |
| 20 | filterPaths?: string[]; |
| 21 | bm25Threshold?: number; |
| 22 | } |
| 23 | |
| 24 | export class FullTextSearchCodebaseIndex implements CodebaseIndex { |
| 25 | relativeExpectedTime: number = 0.2; |
| 26 | static artifactId = "sqliteFts"; |
| 27 | artifactId: string = FullTextSearchCodebaseIndex.artifactId; |
| 28 | pathWeightMultiplier = 10.0; |
| 29 | |
| 30 | private async _createTables(db: DatabaseConnection) { |
| 31 | await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( |
| 32 | path, |
| 33 | content, |
| 34 | tokenize = 'trigram' |
| 35 | )`); |
| 36 | |
| 37 | await db.exec(`CREATE TABLE IF NOT EXISTS fts_metadata ( |
| 38 | id INTEGER PRIMARY KEY, |
| 39 | path TEXT NOT NULL, |
| 40 | cacheKey TEXT NOT NULL, |
| 41 | chunkId INTEGER NOT NULL, |
| 42 | FOREIGN KEY (chunkId) REFERENCES chunks (id), |
| 43 | FOREIGN KEY (id) REFERENCES fts (rowid) |
| 44 | )`); |
| 45 | } |
| 46 | |
| 47 | async *update( |
| 48 | tag: IndexTag, |
| 49 | results: RefreshIndexResults, |
| 50 | markComplete: MarkCompleteCallback, |
| 51 | repoName: string | undefined, |
| 52 | ): AsyncGenerator<IndexingProgressUpdate, any, unknown> { |
| 53 | const db = await SqliteDb.get(); |
| 54 | await this._createTables(db); |
| 55 | |
| 56 | for (let i = 0; i < results.compute.length; i++) { |
| 57 | const item = results.compute[i]; |
| 58 | // Insert chunks |
| 59 | const chunks = await db.all( |
| 60 | "SELECT * FROM chunks WHERE path = ? AND cacheKey = ?", |
| 61 | [item.path, item.cacheKey], |
| 62 | ); |
| 63 | |
| 64 | for (const chunk of chunks) { |
| 65 | const { lastID } = await db.run( |
| 66 | "INSERT INTO fts (path, content) VALUES (?, ?)", |
| 67 | [item.path, chunk.content], |
| 68 | ); |
| 69 | await db.run( |
| 70 | `INSERT INTO fts_metadata (id, path, cacheKey, chunkId) |
| 71 | VALUES (?, ?, ?, ?) |
| 72 | ON CONFLICT(id) DO UPDATE SET |
| 73 | path = excluded.path, |
| 74 | cacheKey = excluded.cacheKey, |
| 75 | chunkId = excluded.chunkId`, |
| 76 | [lastID, item.path, item.cacheKey, chunk.id], |
| 77 | ); |
| 78 | } |
| 79 | |
| 80 | yield { |
| 81 | progress: i / results.compute.length, |
| 82 | desc: `Indexing ${getUriPathBasename(item.path)}`, |
| 83 | status: "indexing", |
| 84 | }; |
| 85 | await markComplete([item], IndexResultType.Compute); |
| 86 | } |
| 87 | |
| 88 | // Add tag |
| 89 | for (const item of results.addTag) { |
| 90 | await markComplete([item], IndexResultType.AddTag); |
| 91 | } |
| 92 | |
| 93 | // Remove tag |
| 94 | for (const item of results.removeTag) { |
| 95 | await markComplete([item], IndexResultType.RemoveTag); |
| 96 | } |
| 97 | |
| 98 | // Delete |
| 99 | for (const item of results.del) { |
| 100 | await db.run( |
| 101 | ` |
| 102 | DELETE FROM fts WHERE rowid IN ( |
| 103 | SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ? |
| 104 | ) |
| 105 | `, |
| 106 | [item.path, item.cacheKey], |
| 107 | ); |
| 108 | await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [ |
| 109 | item.path, |
| 110 | item.cacheKey, |
| 111 | ]); |
| 112 | await markComplete([item], IndexResultType.Delete); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | async retrieve(config: RetrieveConfig): Promise<Chunk[]> { |
| 117 | const db = await SqliteDb.get(); |
| 118 | |
| 119 | const query = this.buildRetrieveQuery(config); |
| 120 | const parameters = this.getRetrieveQueryParameters(config); |
| 121 | |
| 122 | let results = await db.all(query, parameters); |
| 123 | |
| 124 | results = results.filter( |
| 125 | (result) => |
| 126 | result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold), |
| 127 | ); |
| 128 | |
| 129 | const chunks = await db.all( |
| 130 | `SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`, |
| 131 | results.map((result) => result.chunkId), |
| 132 | ); |
| 133 | |
| 134 | return chunks.map((chunk) => ({ |
| 135 | filepath: chunk.path, |
| 136 | index: chunk.index, |
| 137 | startLine: chunk.startLine, |
| 138 | endLine: chunk.endLine, |
| 139 | content: chunk.content, |
| 140 | digest: chunk.cacheKey, |
| 141 | })); |
| 142 | } |
| 143 | |
| 144 | private buildTagFilter(tags: BranchAndDir[]): string { |
| 145 | const tagStrings = this.convertTags(tags); |
| 146 | |
| 147 | return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`; |
| 148 | } |
| 149 | |
| 150 | private buildPathFilter(filterPaths: string[] | undefined): string { |
| 151 | if (!filterPaths || filterPaths.length === 0) { |
| 152 | return ""; |
| 153 | } |
| 154 | return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`; |
| 155 | } |
| 156 | |
| 157 | private buildRetrieveQuery(config: RetrieveConfig): string { |
| 158 | return ` |
| 159 | SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank |
| 160 | FROM fts |
| 161 | JOIN fts_metadata ON fts.rowid = fts_metadata.id |
| 162 | JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId |
| 163 | WHERE fts MATCH ? |
| 164 | ${this.buildTagFilter(config.tags)} |
| 165 | ${this.buildPathFilter(config.filterPaths)} |
| 166 | ORDER BY bm25(fts, ${this.pathWeightMultiplier}) |
| 167 | LIMIT ? |
| 168 | `; |
| 169 | } |
| 170 | |
| 171 | private getRetrieveQueryParameters(config: RetrieveConfig) { |
| 172 | const { text, tags, filterPaths, n } = config; |
| 173 | const tagStrings = this.convertTags(tags); |
| 174 | |
| 175 | return [ |
| 176 | text.replace(/\?/g, ""), |
| 177 | ...tagStrings, |
| 178 | ...(filterPaths || []), |
| 179 | Math.ceil(n), |
| 180 | ]; |
| 181 | } |
| 182 | |
| 183 | private convertTags(tags: BranchAndDir[]): string[] { |
| 184 | // Notice that the "chunks" artifactId is used because of linking between tables |
| 185 | return tags.map((tag) => |
| 186 | tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }), |
| 187 | ); |
| 188 | } |
| 189 | } |