-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
345 lines (288 loc) · 8.13 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package main
import (
"bytes"
"context"
"database/sql"
"encoding/binary"
"fmt"
"os"
"path/filepath"
sqlite_vec "github.com/asg017/sqlite-vec/bindings/go/cgo"
"github.com/mattn/go-sqlite3"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog/log"
"go.lsp.dev/protocol"
"go.lsp.dev/uri"
)
// #cgo LDFLAGS: -L${SRCDIR}/third_party/lib -Wl,-undefined,dynamic_lookup
import "C"
func serializeFloat32(vector []float32) ([]byte, error) {
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.LittleEndian, vector)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
type Execer interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
type DB struct {
Execer
db *sql.DB
}
type DBTX struct {
DB
Execer
tx *sql.Tx
}
func openDB(wd string) (*DB, error) {
sqlite_vec.Auto()
configDir := getDbsDir()
dbDir := filepath.Join(configDir, wd)
dbPath := filepath.Join(dbDir, "index.db")
err := os.MkdirAll(dbDir, 0755)
if err != nil {
return nil, fmt.Errorf("Error creating directory %s: %w", dbDir, err)
}
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
return nil, fmt.Errorf("Error opening db %s: %w", dbPath, err)
}
var sqliteVersion, vecVersion string
err = db.QueryRow("select sqlite_version(), vec_version()").Scan(&sqliteVersion, &vecVersion)
if err != nil {
return nil, err
}
log.Debug().Str("sqlite_version", sqliteVersion).Str("vec_version", vecVersion).Msg("Initialized DB")
result := &DB{
Execer: db,
db: db,
}
return result, result.Init()
}
func (db *DB) Close() error {
return db.db.Close()
}
func (db *DB) Begin() (*DBTX, error) {
tx, err := db.db.BeginTx(context.TODO(), &sql.TxOptions{})
if err != nil {
return nil, err
}
return &DBTX{
DB: DB{
Execer: tx,
db: db.db,
},
Execer: tx,
tx: tx,
}, nil
}
func (dbtx *DBTX) Rollback() error {
return dbtx.tx.Rollback()
}
func (dbtx *DBTX) Commit() error {
return dbtx.tx.Commit()
}
func (db *DB) Init() error {
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS file (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
md5 TEXT NOT NULL
);`)
if err != nil {
return fmt.Errorf("Error creating file table: %w", err)
}
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS symbol (
id INTEGER PRIMARY KEY,
kind REAL NOT NULL,
name TEXT NOT NULL,
path TEXT NOT NULL,
start_line INTEGER NOT NULL,
start_col INTEGER NOT NULL,
end_line INTEGER NOT NULL,
end_col INTEGER NOT NULL,
file_id INTEGER NOT NULL,
FOREIGN KEY(file_id) REFERENCES file(id)
);`)
if err != nil {
return fmt.Errorf("Error creating symbol table: %w", err)
}
// TODO: handle different vector dimension sizes
_, err = db.Exec(`CREATE VIRTUAL TABLE IF NOT EXISTS symbol_embedding USING vec0(embedding float[768]);`)
if err != nil {
return fmt.Errorf("Error creating symbol embeddings table: %w", err)
}
// _, err = db.Exec("CREATE VIRTUAL TABLE IF NOT EXISTS symbol_fts USING fts5(name, content=symbol, content_rowid=id);")
// if err != nil {
// return fmt.Errorf("Error creating symbol fts table: %w", err)
// }
// _, err = db.Exec(`
// CREATE TRIGGER IF NOT EXISTS symbol_ai AFTER INSERT ON symbol BEGIN
// INSERT INTO symbol_fts(rowid, name) VALUES (new.id, new.name);
// END;
// CREATE TRIGGER IF NOT EXISTS symbol_ad AFTER DELETE ON symbol BEGIN
// INSERT INTO symbol_fts(fts_idx, rowid, name) VALUES('delete', old.id, old.name);
// END;
// CREATE TRIGGER IF NOT EXISTS symbol_au AFTER UPDATE ON symbol BEGIN
// INSERT INTO symbol_fts(fts_idx, rowid, name) VALUES('delete', old.id, old.name);
// INSERT INTO symbol_fts(rowid, name) VALUES (new.id, new.name);
// END;
// `)
// if err != nil {
// return fmt.Errorf("Error creating symbol : %w", err)
// }
return nil
}
func (db *DB) InsertFile(path, md5 string) (int64, error) {
result, err := db.Exec("INSERT INTO file (path, md5) VALUES (?, ?) RETURNING id;", path, md5)
if err != nil {
return 0, err
}
return result.LastInsertId()
}
func (db *DB) DeleteFileInfo(id int64) error {
_, err := db.Exec("DELETE FROM symbol WHERE file_id = ?;", id)
if err != nil {
return err
}
_, err = db.Exec("DELETE FROM file WHERE id = ?;", id)
return err
}
func (db *DB) DeleteFileInfoByPath(path string) error {
idRows, err := db.Query("SELECT id FROM file WHERE path = ?;", path)
if err != nil && err != sql.ErrNoRows {
return err
}
for idRows.Next() {
var fileId int64
err = idRows.Scan(&fileId)
if err != nil {
return err
}
_, err = db.Exec("DELETE FROM symbol WHERE file_id = ?", fileId)
if err != nil {
return err
}
}
if err := idRows.Err(); err != nil {
return err
}
_, err = db.Exec("DELETE FROM file WHERE path = ?;", path)
return err
}
func (db *DB) GetFile(path, md5 string) (int64, bool, error) {
result, err := db.Query("SELECT id FROM file WHERE path = ? AND md5 = ?;", path, md5)
if err != nil {
return 0, false, err
}
defer result.Close()
var id int64
// We know there's at least one row
ok := result.Next()
if !ok {
return 0, false, nil
}
err = result.Scan(&id)
if err != nil {
return 0, false, err
}
return id, true, nil
}
func (db *DB) float64ArrayToFloat32(embedding []float64) []float32 {
// XXX: this might be super bad. There's an open issue to support f64 which we should track
//
var embedding32 []float32 = make([]float32, len(embedding))
for i, v := range embedding {
embedding32[i] = float32(v)
}
return embedding32
}
func (db *DB) InsertSymbol(fileId int64, kind float64, name, path string, startL, startC, endL, endC int, embedding []float64) (int64, error) {
serialized, err := serializeFloat32(db.float64ArrayToFloat32(embedding))
if err != nil {
return 0, err
}
result, err := db.Exec(
"INSERT INTO symbol (file_id, kind, name, path, start_line, start_col, end_line, end_col) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id;",
fileId, kind, name, path, startL, startC, endL, endC,
)
if err != nil {
return 0, err
}
symbolId, err := result.LastInsertId()
if err != nil {
return 0, err
}
_, err = db.Exec("INSERT INTO symbol_embedding (rowid, embedding) VALUES (?, ?);", symbolId, serialized)
if err != nil {
return 0, err
}
return symbolId, nil
}
func (db *DB) FindSymbolByEmbedding(embedding []float64) ([]protocol.SymbolInformation, error) {
serialized, err := serializeFloat32(db.float64ArrayToFloat32(embedding))
if err != nil {
return nil, err
}
rows, err := db.Query(`SELECT kind, name, path, start_line, start_col, end_line, end_col FROM symbol WHERE id IN (SELECT rowid FROM symbol_embedding WHERE embedding MATCH ? ORDER BY distance LIMIT 10);`, serialized)
if err != nil {
sqliteErr, ok := err.(sqlite3.Error)
if ok {
fmt.Println(sqliteErr.Code, sqliteErr.ExtendedCode, sqliteErr.ExtendedCode.Error())
}
return nil, err
}
var syms []protocol.SymbolInformation
for rows.Next() {
info, err := db.scanSymbolRow(rows)
if err != nil {
return nil, err
}
syms = append(syms, *info)
}
return syms, nil
}
func (db *DB) scanSymbolRow(rows *sql.Rows) (*protocol.SymbolInformation, error) {
var name, path string
var kind float64
var startLine, startCol, endLine, endCol uint32
err := rows.Scan(&kind, &name, &path, &startLine, &startCol, &endLine, &endCol)
if err != nil {
return nil, err
}
return &protocol.SymbolInformation{
Name: name,
Kind: protocol.SymbolKind(kind),
Location: protocol.Location{
URI: uri.File(path),
Range: protocol.Range{
Start: protocol.Position{
Line: startLine,
Character: startCol,
},
End: protocol.Position{
Line: endLine,
Character: endCol,
},
},
},
}, nil
}
func (db *DB) FindSymbolByPrefix(prefix string) ([]protocol.SymbolInformation, error) {
rows, err := db.Query(`SELECT kind, name, path, start_line, start_col, end_line, end_col FROM symbol WHERE name LIKE ? LIMIT 100`, fmt.Sprintf("%s%%", prefix))
if err != nil {
return nil, err
}
result := []protocol.SymbolInformation{}
for rows.Next() {
info, err := db.scanSymbolRow(rows)
if err != nil {
return nil, err
}
result = append(result, *info)
}
return result, nil
}