-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.go
332 lines (291 loc) · 7.88 KB
/
index.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
package anystore
import (
"bytes"
"context"
"fmt"
"slices"
"strings"
"sync/atomic"
"zombiezen.com/go/sqlite"
"github.com/anyproto/any-store/anyenc"
"github.com/anyproto/any-store/internal/driver"
"github.com/anyproto/any-store/internal/sql"
)
// IndexInfo provides information about an index.
type IndexInfo struct {
// Name is the name of the index. If empty, it will be generated
// based on the fields (e.g., "name,-createdDate").
Name string
// Fields are the fields included in the index. Each field can specify
// ascending (e.g., "name") or descending (e.g., "-createdDate") order.
Fields []string
// Unique indicates whether the index enforces a unique constraint.
Unique bool
// Sparse indicates whether the index is sparse, indexing only documents
// with the specified fields.
Sparse bool
}
func (i IndexInfo) createName() string {
return strings.Join(i.Fields, ",")
}
// Index represents an index on a collection.
type Index interface {
// Info returns the IndexInfo for this index.
Info() IndexInfo
// Len returns the length of the index.
Len(ctx context.Context) (int, error)
}
func newIndex(ctx context.Context, c *collection, info IndexInfo) (idx *index, err error) {
idx = &index{info: info, c: c}
if err = idx.init(ctx); err != nil {
return nil, err
}
return
}
type index struct {
c *collection
sql sql.IndexSql
info IndexInfo
fieldNames []string
fieldPaths [][]string
reverse []bool
keyBuf anyenc.Tuple
keysBuf []anyenc.Tuple
keysBufPrev []anyenc.Tuple
uniqBuf [][]anyenc.Tuple
stmts struct {
insert,
delete *driver.Stmt
}
queries struct {
count string
}
stmtsReady atomic.Bool
driverValuesBuf [][]byte
}
func validateIndexField(s string) (err error) {
if s == "" || s == "-" {
return fmt.Errorf("index field is empty")
}
if strings.HasPrefix(s, "$") {
return fmt.Errorf("invalid index field name: %s", s)
}
return nil
}
func parseIndexField(s string) (fields []string, reverse bool) {
if strings.HasPrefix(s, "-") {
return strings.Split(s[1:], "."), true
}
return strings.Split(s, "."), false
}
func (idx *index) init(ctx context.Context) (err error) {
for _, field := range idx.info.Fields {
fields, reverse := parseIndexField(field)
for _, f := range fields {
if f == "" {
return fmt.Errorf("invalid index field: '%s'", field)
}
}
idx.fieldNames = append(idx.fieldNames, strings.Join(fields, "."))
idx.fieldPaths = append(idx.fieldPaths, fields)
idx.reverse = append(idx.reverse, reverse)
}
idx.uniqBuf = make([][]anyenc.Tuple, len(idx.fieldPaths))
idx.driverValuesBuf = make([][]byte, 0, len(idx.fieldNames))
idx.sql = idx.c.sql.Index(idx.info.Name)
idx.makeQueries()
return nil
}
func (idx *index) makeQueries() {
tableName := idx.sql.TableName()
idx.queries.count = fmt.Sprintf("SELECT COUNT(*) FROM '%s'", tableName)
}
func (idx *index) checkStmts(ctx context.Context, cn *driver.Conn) (err error) {
if idx.stmtsReady.CompareAndSwap(false, true) {
if idx.stmts.insert, err = cn.Prepare(idx.sql.InsertStmt(len(idx.fieldNames))); err != nil {
return err
}
if idx.stmts.delete, err = cn.Prepare(idx.sql.DeleteStmt(len(idx.fieldNames))); err != nil {
return err
}
}
return nil
}
func (idx *index) Info() IndexInfo {
return idx.info
}
func (idx *index) Len(ctx context.Context) (count int, err error) {
err = idx.c.db.doReadTx(ctx, func(cn *driver.Conn) error {
err = cn.ExecCached(ctx, idx.queries.count, nil, func(stmt *sqlite.Stmt) error {
hasRow, stepErr := stmt.Step()
if stepErr != nil {
return stepErr
}
if !hasRow {
return nil
}
count = stmt.ColumnInt(0)
return nil
})
return err
})
return
}
func (idx *index) Drop(ctx context.Context, cn *driver.Conn) (err error) {
if err = cn.ExecNoResult(ctx, idx.sql.Drop()); err != nil {
return
}
if err = idx.c.db.stmt.removeIndex.Exec(ctx, func(stmt *sqlite.Stmt) {
stmt.SetText(":indexName", idx.info.Name)
stmt.SetText(":collName", idx.c.name)
}, driver.StmtExecNoResults); err != nil {
return
}
return
}
func (idx *index) RenameColl(ctx context.Context, cn *driver.Conn, name string) (err error) {
if err = cn.ExecNoResult(ctx, idx.sql.RenameColl(name)); err != nil {
return err
}
idx.sql = idx.c.sql.Index(idx.info.Name)
idx.makeQueries()
idx.closeStmts()
return idx.checkStmts(ctx, cn)
}
func (idx *index) Insert(ctx context.Context, id anyenc.Tuple, it item) error {
idx.fillKeysBuf(it)
return idx.insertBuf(ctx, id)
}
func (idx *index) Update(ctx context.Context, id anyenc.Tuple, prevIt, newIt item) (err error) {
// calc previous index keys
idx.fillKeysBuf(prevIt)
// copy prev keys to second buffer
idx.keysBufPrev = slices.Grow(idx.keysBufPrev, len(idx.keysBuf))[:len(idx.keysBuf)]
for i, k := range idx.keysBuf {
idx.keysBufPrev[i] = append(idx.keysBufPrev[i][:0], k...)
}
// calc new index keys
idx.fillKeysBuf(newIt)
// delete equal keys from both bufs
idx.keysBuf = slices.DeleteFunc(idx.keysBuf, func(k anyenc.Tuple) bool {
for i, pk := range idx.keysBufPrev {
if bytes.Equal(k, pk) {
idx.keysBufPrev = slices.Delete(idx.keysBufPrev, i, i+1)
return true
}
}
return false
})
if err = idx.deleteBuf(ctx, id, idx.keysBufPrev); err != nil {
return err
}
return idx.insertBuf(ctx, id)
}
func (idx *index) Delete(ctx context.Context, id anyenc.Tuple, prevIt item) error {
idx.fillKeysBuf(prevIt)
return idx.deleteBuf(ctx, id, idx.keysBuf)
}
func (idx *index) writeKey() {
nl := len(idx.keysBuf) + 1
idx.keysBuf = slices.Grow(idx.keysBuf, nl)[:nl]
idx.keysBuf[nl-1] = append(idx.keysBuf[nl-1][:0], idx.keyBuf...)
}
func (idx *index) writeValues(d *anyenc.Value, i int) bool {
if i == len(idx.fieldPaths) {
idx.writeKey()
return true
}
v := d.Get(idx.fieldPaths[i]...)
if idx.info.Sparse && (v == nil || v.Type() == anyenc.TypeNull) {
return false
}
k := idx.keyBuf
if v != nil && v.Type() == anyenc.TypeArray {
arr, _ := v.Array()
if len(arr) != 0 {
idx.uniqBuf[i] = idx.uniqBuf[i][:0]
for _, av := range arr {
idx.keyBuf = av.MarshalTo(k)
if idx.isUnique(i, idx.keyBuf) {
if !idx.writeValues(d, i+1) {
return false
}
}
}
}
}
idx.keyBuf = v.MarshalTo(k)
return idx.writeValues(d, i+1)
}
func (idx *index) fillKeysBuf(it item) {
idx.keysBuf = idx.keysBuf[:0]
idx.keyBuf = idx.keyBuf[:0]
idx.resetUnique()
if !idx.writeValues(it.Value(), 0) {
// we got false in case sparse index and nil value - reset the buffer
idx.keysBuf = idx.keysBuf[:0]
}
}
func (idx *index) resetUnique() {
for i := range idx.uniqBuf {
idx.uniqBuf[i] = idx.uniqBuf[i][:0]
}
}
func (idx *index) isUnique(i int, k anyenc.Tuple) bool {
for _, ek := range idx.uniqBuf[i] {
if bytes.Equal(k, ek) {
return false
}
}
nl := len(idx.uniqBuf[i]) + 1
idx.uniqBuf[i] = slices.Grow(idx.uniqBuf[i], nl)[:nl]
idx.uniqBuf[i][nl-1] = append(idx.uniqBuf[i][nl-1][:0], k...)
return true
}
func (idx *index) insertBuf(ctx context.Context, id []byte) (err error) {
for _, k := range idx.keysBuf {
err = idx.stmts.insert.Exec(ctx, func(stmt *sqlite.Stmt) {
stmt.BindBytes(1, id)
var i = 2
_ = k.ReadBytes(func(b []byte) error {
stmt.BindBytes(i, b)
i++
return nil
})
}, driver.StmtExecNoResults)
if err != nil {
return replaceUniqErr(err, ErrUniqueConstraint)
}
}
return
}
func (idx *index) deleteBuf(ctx context.Context, id []byte, buf []anyenc.Tuple) (err error) {
for _, k := range buf {
err = idx.stmts.delete.Exec(ctx, func(stmt *sqlite.Stmt) {
stmt.BindBytes(1, id)
var i = 2
_ = k.ReadBytes(func(b []byte) error {
stmt.BindBytes(i, b)
i++
return nil
})
}, driver.StmtExecNoResults)
if err != nil {
return
}
}
return
}
func (idx *index) closeStmts() {
if idx.stmtsReady.CompareAndSwap(true, false) {
for _, stmt := range []*driver.Stmt{
idx.stmts.insert, idx.stmts.delete,
} {
_ = stmt.Close()
}
}
}
func (idx *index) Close() (err error) {
idx.closeStmts()
return
}