-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvtab.go
404 lines (350 loc) · 8.52 KB
/
vtab.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package vtab
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"text/template"
"go.riyazali.net/sqlite"
)
type Orders uint8
const (
NONE Orders = iota
DESC
ASC
)
type ColumnFilter struct {
Op sqlite.ConstraintOp
OmitCheck bool
}
type Column struct {
Name string
Type string
NotNull bool
Hidden bool
Filters []*ColumnFilter
OrderBy Orders
}
type Constraint struct {
ColIndex int
Op sqlite.ConstraintOp
Value *sqlite.Value
}
type GetIteratorFunc func(constraints []*Constraint, order []*sqlite.OrderBy) (Iterator, error)
type options struct {
earlyOrderByConstraintExit bool
}
type OptFunc func(*options)
// EarlyOrderByConstraintExit tells the table-func to end iteration early, if results are ordered by
// a field that is also in a WHERE clause with one of a >,>=,<,<= that would warrant an early exit.
// This assumes that the column in question has the GT, GE, LT, LE constraints registered.
func EarlyOrderByConstraintExit(value bool) OptFunc {
return func(opts *options) { opts.earlyOrderByConstraintExit = value }
}
func NewTableFunc(name string, columns []Column, newIterator GetIteratorFunc, opts ...OptFunc) sqlite.Module {
opt := &options{}
for _, optFunc := range opts {
optFunc(opt)
}
return &tableFuncModule{name, columns, newIterator, opt}
}
type tableFuncModule struct {
name string
columns []Column
getIterator GetIteratorFunc
options *options
}
type tableFuncTable struct {
*tableFuncModule
}
type tableFuncCursor struct {
*tableFuncTable
iterator Iterator
count int
current Row
order []*sqlite.OrderBy
constraints []*Constraint
}
type Iterator interface {
Next() (Row, error)
}
type Context interface {
ResultInt(v int)
ResultInt64(v int64)
ResultFloat(v float64)
ResultNull()
ResultValue(v sqlite.Value)
ResultZeroBlob(n int64)
ResultText(v string)
ResultError(err error)
ResultPointer(val interface{})
}
type Row interface {
Column(ctx Context, col int) error
}
// createTableSQL produces the SQL to declare a new virtual table
func (m *tableFuncModule) createTableSQL() (string, error) {
// TODO needs to support WITHOUT ROWID, PRIMARY KEY, NOT NULL
const declare = `CREATE TABLE {{ .Name }} (
{{- range $c, $col := .Columns }}
{{ .Name }} {{ .Type }}{{ if .Hidden }} HIDDEN{{ end }}{{ if columnComma $c }},{{ end }}
{{- end }}
)`
// helper to determine whether we're on the last column (and therefore should avoid a comma ",") in the range
fns := template.FuncMap{
"columnComma": func(c int) bool {
return c < len(m.columns)-1
},
}
tmpl, err := template.New(fmt.Sprintf("declare_table_func_%s", m.name)).Funcs(fns).Parse(declare)
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, struct {
Name string
Columns []Column
}{
m.name,
m.columns,
})
if err != nil {
return "", err
}
return buf.String(), nil
}
func (m *tableFuncModule) Connect(_ *sqlite.Conn, _ []string, declare func(string) error) (sqlite.VirtualTable, error) {
str, err := m.createTableSQL()
if err != nil {
return nil, err
}
err = declare(str)
if err != nil {
return nil, err
}
return &tableFuncTable{m}, nil
}
func (m *tableFuncModule) Destroy() error {
return nil
}
func (t *tableFuncTable) Open() (sqlite.VirtualCursor, error) {
return &tableFuncCursor{t, nil, 0, nil, nil, nil}, nil
}
type index struct {
Constraints []*Constraint
Orders []*sqlite.OrderBy
}
func (t *tableFuncTable) BestIndex(input *sqlite.IndexInfoInput) (*sqlite.IndexInfoOutput, error) {
// start with a relatively high cost
cost := 1000.0
usage := make([]*sqlite.ConstraintUsage, len(input.Constraints))
idx := &index{
Constraints: make([]*Constraint, 0, len(input.Constraints)),
Orders: make([]*sqlite.OrderBy, 0),
}
orderByUsed := true
for _, order := range input.OrderBy {
col := t.columns[order.ColumnIndex]
if col.OrderBy&ASC != 0 && !order.Desc {
idx.Orders = append(idx.Orders, order)
continue
}
if col.OrderBy&DESC != 0 && order.Desc {
idx.Orders = append(idx.Orders, order)
continue
}
orderByUsed = false
}
// iterate over constraints
for cst, constraint := range input.Constraints {
usage[cst] = &sqlite.ConstraintUsage{}
if !constraint.Usable {
return nil, sqlite.SQLITE_CONSTRAINT
}
// iterate over the declared constraints the column supports
col := t.columns[constraint.ColumnIndex]
for _, filter := range col.Filters {
// if there's a match, reduce the cost (to prefer usage of this constraint)
if filter.Op == constraint.Op {
cost -= 10
usage[cst].ArgvIndex = len(idx.Constraints) + 1
usage[cst].Omit = filter.OmitCheck
idx.Constraints = append(idx.Constraints, &Constraint{
ColIndex: constraint.ColumnIndex,
Op: filter.Op,
})
}
}
}
idxStr, err := json.Marshal(idx)
if err != nil {
return nil, err
}
return &sqlite.IndexInfoOutput{
EstimatedCost: cost,
IndexString: string(idxStr),
ConstraintUsage: usage,
OrderByConsumed: orderByUsed,
}, nil
}
func (t *tableFuncTable) Disconnect() error {
return t.Destroy()
}
func (t *tableFuncTable) Destroy() error { return nil }
func (c *tableFuncCursor) Filter(idxNum int, idxName string, values ...sqlite.Value) error {
var idx index
err := json.Unmarshal([]byte(idxName), &idx)
if err != nil {
return err
}
for c := range idx.Constraints {
idx.Constraints[c].Value = &values[c]
}
c.order = idx.Orders
c.constraints = idx.Constraints
iter, err := c.getIterator(idx.Constraints, idx.Orders)
if err != nil {
return err
}
c.iterator = iter
row, err := iter.Next()
if err != nil {
if errors.Is(err, io.EOF) {
c.current = nil
return nil
}
return err
}
c.current = row
return nil
}
// earlyOrderByConstraintExit determines if there should be an early exit, based on supplied ORDER BYs
// and any of <, >=, <, or <= constraints on corresponding columns
func (c *tableFuncCursor) earlyOrderByConstraintExit() error {
outer:
for _, order := range c.order {
for _, constraint := range c.constraints {
if order.ColumnIndex == constraint.ColIndex {
// limit := constraint.Value.Blob()
getter := &valueGetter{}
err := c.current.Column(getter, constraint.ColIndex)
if err != nil {
return err
}
var comparison int
switch v := getter.value.(type) {
case int:
limit := constraint.Value.Int()
switch {
case v == limit:
comparison = 0
case v < limit:
comparison = -1
case v > limit:
comparison = 1
}
case int64:
limit := constraint.Value.Int64()
switch {
case v == limit:
comparison = 0
case v < limit:
comparison = -1
case v > limit:
comparison = 1
}
case string:
limit := constraint.Value.Text()
switch {
case v == limit:
comparison = 0
case v < limit:
comparison = -1
case v > limit:
comparison = 1
}
case float64:
limit := constraint.Value.Float()
switch {
case v == limit:
comparison = 0
case v < limit:
comparison = -1
case v > limit:
comparison = 1
}
case []byte:
limit := constraint.Value.Blob()
comparison = bytes.Compare(v, limit)
default:
break outer
}
switch constraint.Op {
case sqlite.INDEX_CONSTRAINT_GT:
if order.Desc {
if comparison <= 0 {
c.current = nil
return nil
}
}
case sqlite.INDEX_CONSTRAINT_GE:
if order.Desc {
if comparison < 0 {
c.current = nil
return nil
}
}
case sqlite.INDEX_CONSTRAINT_LT:
if !order.Desc {
if comparison >= 0 {
c.current = nil
return nil
}
}
case sqlite.INDEX_CONSTRAINT_LE:
if !order.Desc {
if comparison > 0 {
c.current = nil
return nil
}
}
}
}
}
}
return nil
}
func (c *tableFuncCursor) Next() error {
defer func() { c.count++ }()
row, err := c.iterator.Next()
if err != nil {
if errors.Is(err, io.EOF) {
c.current = nil
return nil
}
return err
}
c.current = row
if c.tableFuncModule.options.earlyOrderByConstraintExit {
err := c.earlyOrderByConstraintExit()
if errors.Is(err, io.EOF) {
c.current = nil
return nil
}
return err
}
return nil
}
func (c *tableFuncCursor) Column(ctx *sqlite.VirtualTableContext, col int) error {
return c.current.Column(ctx, col)
}
func (c *tableFuncCursor) Eof() bool {
return c.current == nil
}
func (c *tableFuncCursor) Rowid() (int64, error) {
return int64(c.count), nil
}
func (c *tableFuncCursor) Close() error {
return nil
}