Debian Codegraph @

sqlite3_opt_vtable.go

raw
1 // Copyright (C) 2019 Yasuhiro Matsumoto <[email protected]>.
2 //
3 // Use of this source code is governed by an MIT-style
4 // license that can be found in the LICENSE file.
5
6 //go:build sqlite_vtable || vtable
7 // +build sqlite_vtable vtable
8
9 package sqlite3
10
11 /*
12 #cgo CFLAGS: -std=gnu99
13 #cgo CFLAGS: -DSQLITE_ENABLE_RTREE
14 #cgo CFLAGS: -DSQLITE_THREADSAFE
15 #cgo CFLAGS: -DSQLITE_ENABLE_FTS3
16 #cgo CFLAGS: -DSQLITE_ENABLE_FTS3_PARENTHESIS
17 #cgo CFLAGS: -DSQLITE_ENABLE_FTS4_UNICODE61
18 #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
19 #cgo CFLAGS: -DSQLITE_ENABLE_COLUMN_METADATA=1
20 #cgo CFLAGS: -Wno-deprecated-declarations
21
22 #ifndef USE_LIBSQLITE3
23 #include "sqlite3-binding.h"
24 #else
25 #include <sqlite3.h>
26 #endif
27 #include <stdlib.h>
28 #include <stdint.h>
29 #include <memory.h>
30
31 static inline char *_sqlite3_mprintf(char *zFormat, char *arg) {
32 return sqlite3_mprintf(zFormat, arg);
33 }
34
35 typedef struct goVTab goVTab;
36
37 struct goVTab {
38 sqlite3_vtab base;
39 void *vTab;
40 };
41
42 uintptr_t goMInit(void *db, void *pAux, int argc, char **argv, char **pzErr, int isCreate);
43
44 static int cXInit(sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char **pzErr, int isCreate) {
45 void *vTab = (void *)goMInit(db, pAux, argc, (char**)argv, pzErr, isCreate);
46 if (!vTab || *pzErr) {
47 return SQLITE_ERROR;
48 }
49 goVTab *pvTab = (goVTab *)sqlite3_malloc(sizeof(goVTab));
50 if (!pvTab) {
51 *pzErr = sqlite3_mprintf("%s", "Out of memory");
52 return SQLITE_NOMEM;
53 }
54 memset(pvTab, 0, sizeof(goVTab));
55 pvTab->vTab = vTab;
56
57 *ppVTab = (sqlite3_vtab *)pvTab;
58 *pzErr = 0;
59 return SQLITE_OK;
60 }
61
62 static inline int cXCreate(sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char **pzErr) {
63 return cXInit(db, pAux, argc, argv, ppVTab, pzErr, 1);
64 }
65 static inline int cXConnect(sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char **pzErr) {
66 return cXInit(db, pAux, argc, argv, ppVTab, pzErr, 0);
67 }
68
69 char* goVBestIndex(void *pVTab, void *icp);
70
71 static inline int cXBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *info) {
72 char *pzErr = goVBestIndex(((goVTab*)pVTab)->vTab, info);
73 if (pzErr) {
74 if (pVTab->zErrMsg)
75 sqlite3_free(pVTab->zErrMsg);
76 pVTab->zErrMsg = pzErr;
77 return SQLITE_ERROR;
78 }
79 return SQLITE_OK;
80 }
81
82 char* goVRelease(void *pVTab, int isDestroy);
83
84 static int cXRelease(sqlite3_vtab *pVTab, int isDestroy) {
85 char *pzErr = goVRelease(((goVTab*)pVTab)->vTab, isDestroy);
86 if (pzErr) {
87 if (pVTab->zErrMsg)
88 sqlite3_free(pVTab->zErrMsg);
89 pVTab->zErrMsg = pzErr;
90 return SQLITE_ERROR;
91 }
92 if (pVTab->zErrMsg)
93 sqlite3_free(pVTab->zErrMsg);
94 sqlite3_free(pVTab);
95 return SQLITE_OK;
96 }
97
98 static inline int cXDisconnect(sqlite3_vtab *pVTab) {
99 return cXRelease(pVTab, 0);
100 }
101 static inline int cXDestroy(sqlite3_vtab *pVTab) {
102 return cXRelease(pVTab, 1);
103 }
104
105 typedef struct goVTabCursor goVTabCursor;
106
107 struct goVTabCursor {
108 sqlite3_vtab_cursor base;
109 void *vTabCursor;
110 };
111
112 uintptr_t goVOpen(void *pVTab, char **pzErr);
113
114 static int cXOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) {
115 void *vTabCursor = (void *)goVOpen(((goVTab*)pVTab)->vTab, &(pVTab->zErrMsg));
116 if (!vTabCursor) {
117 return SQLITE_ERROR;
118 }
119 goVTabCursor *pCursor = (goVTabCursor *)sqlite3_malloc(sizeof(goVTabCursor));
120 if (!pCursor) {
121 return SQLITE_NOMEM;
122 }
123 memset(pCursor, 0, sizeof(goVTabCursor));
124 pCursor->vTabCursor = vTabCursor;
125 *ppCursor = (sqlite3_vtab_cursor *)pCursor;
126 return SQLITE_OK;
127 }
128
129 static int setErrMsg(sqlite3_vtab_cursor *pCursor, char *pzErr) {
130 if (pCursor->pVtab->zErrMsg)
131 sqlite3_free(pCursor->pVtab->zErrMsg);
132 pCursor->pVtab->zErrMsg = pzErr;
133 return SQLITE_ERROR;
134 }
135
136 char* goVClose(void *pCursor);
137
138 static int cXClose(sqlite3_vtab_cursor *pCursor) {
139 char *pzErr = goVClose(((goVTabCursor*)pCursor)->vTabCursor);
140 if (pzErr) {
141 return setErrMsg(pCursor, pzErr);
142 }
143 sqlite3_free(pCursor);
144 return SQLITE_OK;
145 }
146
147 char* goVFilter(void *pCursor, int idxNum, char* idxName, int argc, sqlite3_value **argv);
148
149 static int cXFilter(sqlite3_vtab_cursor *pCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv) {
150 char *pzErr = goVFilter(((goVTabCursor*)pCursor)->vTabCursor, idxNum, (char*)idxStr, argc, argv);
151 if (pzErr) {
152 return setErrMsg(pCursor, pzErr);
153 }
154 return SQLITE_OK;
155 }
156
157 char* goVNext(void *pCursor);
158
159 static int cXNext(sqlite3_vtab_cursor *pCursor) {
160 char *pzErr = goVNext(((goVTabCursor*)pCursor)->vTabCursor);
161 if (pzErr) {
162 return setErrMsg(pCursor, pzErr);
163 }
164 return SQLITE_OK;
165 }
166
167 int goVEof(void *pCursor);
168
169 static inline int cXEof(sqlite3_vtab_cursor *pCursor) {
170 return goVEof(((goVTabCursor*)pCursor)->vTabCursor);
171 }
172
173 char* goVColumn(void *pCursor, void *cp, int col);
174
175 static int cXColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *ctx, int i) {
176 char *pzErr = goVColumn(((goVTabCursor*)pCursor)->vTabCursor, ctx, i);
177 if (pzErr) {
178 return setErrMsg(pCursor, pzErr);
179 }
180 return SQLITE_OK;
181 }
182
183 char* goVRowid(void *pCursor, sqlite3_int64 *pRowid);
184
185 static int cXRowid(sqlite3_vtab_cursor *pCursor, sqlite3_int64 *pRowid) {
186 char *pzErr = goVRowid(((goVTabCursor*)pCursor)->vTabCursor, pRowid);
187 if (pzErr) {
188 return setErrMsg(pCursor, pzErr);
189 }
190 return SQLITE_OK;
191 }
192
193 char* goVUpdate(void *pVTab, int argc, sqlite3_value **argv, sqlite3_int64 *pRowid);
194
195 static int cXUpdate(sqlite3_vtab *pVTab, int argc, sqlite3_value **argv, sqlite3_int64 *pRowid) {
196 char *pzErr = goVUpdate(((goVTab*)pVTab)->vTab, argc, argv, pRowid);
197 if (pzErr) {
198 if (pVTab->zErrMsg)
199 sqlite3_free(pVTab->zErrMsg);
200 pVTab->zErrMsg = pzErr;
201 return SQLITE_ERROR;
202 }
203 return SQLITE_OK;
204 }
205
206 static sqlite3_module goModule = {
207 0, // iVersion
208 cXCreate, // xCreate - create a table
209 cXConnect, // xConnect - connect to an existing table
210 cXBestIndex, // xBestIndex - Determine search strategy
211 cXDisconnect, // xDisconnect - Disconnect from a table
212 cXDestroy, // xDestroy - Drop a table
213 cXOpen, // xOpen - open a cursor
214 cXClose, // xClose - close a cursor
215 cXFilter, // xFilter - configure scan constraints
216 cXNext, // xNext - advance a cursor
217 cXEof, // xEof
218 cXColumn, // xColumn - read data
219 cXRowid, // xRowid - read data
220 cXUpdate, // xUpdate - write data
221 // Not implemented
222 0, // xBegin - begin transaction
223 0, // xSync - sync transaction
224 0, // xCommit - commit transaction
225 0, // xRollback - rollback transaction
226 0, // xFindFunction - function overloading
227 0, // xRename - rename the table
228 0, // xSavepoint
229 0, // xRelease
230 0 // xRollbackTo
231 };
232
233 // See https://sqlite.org/vtab.html#eponymous_only_virtual_tables
234 static sqlite3_module goModuleEponymousOnly = {
235 0, // iVersion
236 0, // xCreate - create a table, which here is null
237 cXConnect, // xConnect - connect to an existing table
238 cXBestIndex, // xBestIndex - Determine search strategy
239 cXDisconnect, // xDisconnect - Disconnect from a table
240 cXDestroy, // xDestroy - Drop a table
241 cXOpen, // xOpen - open a cursor
242 cXClose, // xClose - close a cursor
243 cXFilter, // xFilter - configure scan constraints
244 cXNext, // xNext - advance a cursor
245 cXEof, // xEof
246 cXColumn, // xColumn - read data
247 cXRowid, // xRowid - read data
248 cXUpdate, // xUpdate - write data
249 // Not implemented
250 0, // xBegin - begin transaction
251 0, // xSync - sync transaction
252 0, // xCommit - commit transaction
253 0, // xRollback - rollback transaction
254 0, // xFindFunction - function overloading
255 0, // xRename - rename the table
256 0, // xSavepoint
257 0, // xRelease
258 0 // xRollbackTo
259 };
260
261 void goMDestroy(void*);
262
263 static int _sqlite3_create_module(sqlite3 *db, const char *zName, uintptr_t pClientData) {
264 return sqlite3_create_module_v2(db, zName, &goModule, (void*) pClientData, goMDestroy);
265 }
266
267 static int _sqlite3_create_module_eponymous_only(sqlite3 *db, const char *zName, uintptr_t pClientData) {
268 return sqlite3_create_module_v2(db, zName, &goModuleEponymousOnly, (void*) pClientData, goMDestroy);
269 }
270 */
271 import "C"
272
273 import (
274 "fmt"
275 "math"
276 "unsafe"
277 )
278
279 type sqliteModule struct {
280 c *SQLiteConn
281 name string
282 module Module
283 }
284
285 type sqliteVTab struct {
286 module *sqliteModule
287 vTab VTab
288 }
289
290 type sqliteVTabCursor struct {
291 vTab *sqliteVTab
292 vTabCursor VTabCursor
293 }
294
295 // Op is type of operations.
296 type Op uint8
297
298 // Op mean identity of operations.
299 const (
300 OpEQ Op = 2
301 OpGT = 4
302 OpLE = 8
303 OpLT = 16
304 OpGE = 32
305 OpMATCH = 64
306 OpLIKE = 65 /* 3.10.0 and later only */
307 OpGLOB = 66 /* 3.10.0 and later only */
308 OpREGEXP = 67 /* 3.10.0 and later only */
309 OpNE = 68 /* 3.21.0 and later only */
310 OpISNOT = 69 /* 3.21.0 and later */
311 OpISNOTNULL = 70 /* 3.21.0 and later */
312 OpISNULL = 71 /* 3.21.0 and later */
313 OpIS = 72 /* 3.21.0 and later */
314 OpLIMIT = 73 /* 3.38.0 and later */
315 OpOFFSET = 74 /* 3.38.0 and later */
316 OpFUNCTION = 150 /* 3.25.0 and later */
317 OpScanUnique = 1 /* Scan visits at most 1 row */
318 )
319
320 // InfoConstraint give information of constraint.
321 type InfoConstraint struct {
322 Column int
323 Op Op
324 Usable bool
325 }
326
327 // InfoOrderBy give information of order-by.
328 type InfoOrderBy struct {
329 Column int
330 Desc bool
331 }
332
333 func constraints(info *C.sqlite3_index_info) []InfoConstraint {
334 slice := unsafe.Slice(info.aConstraint, int(info.nConstraint))
335
336 cst := make([]InfoConstraint, 0, len(slice))
337 for _, c := range slice {
338 var usable bool
339 if c.usable > 0 {
340 usable = true
341 }
342 cst = append(cst, InfoConstraint{
343 Column: int(c.iColumn),
344 Op: Op(c.op),
345 Usable: usable,
346 })
347 }
348 return cst
349 }
350
351 func orderBys(info *C.sqlite3_index_info) []InfoOrderBy {
352 slice := unsafe.Slice(info.aOrderBy, int(info.nOrderBy))
353
354 ob := make([]InfoOrderBy, 0, len(slice))
355 for _, c := range slice {
356 var desc bool
357 if c.desc > 0 {
358 desc = true
359 }
360 ob = append(ob, InfoOrderBy{
361 Column: int(c.iColumn),
362 Desc: desc,
363 })
364 }
365 return ob
366 }
367
368 // IndexResult is a Go struct representation of what eventually ends up in the
369 // output fields for `sqlite3_index_info`
370 // See: https://www.sqlite.org/c3ref/index_info.html
371 type IndexResult struct {
372 Used []bool // aConstraintUsage
373 IdxNum int
374 IdxStr string
375 AlreadyOrdered bool // orderByConsumed
376 EstimatedCost float64
377 EstimatedRows float64
378 }
379
380 // mPrintf is a utility wrapper around sqlite3_mprintf
381 func mPrintf(format, arg string) *C.char {
382 cf := C.CString(format)
383 defer C.free(unsafe.Pointer(cf))
384 ca := C.CString(arg)
385 defer C.free(unsafe.Pointer(ca))
386 return C._sqlite3_mprintf(cf, ca)
387 }
388
389 //export goMInit
390 func goMInit(db, pClientData unsafe.Pointer, argc C.int, argv **C.char, pzErr **C.char, isCreate C.int) C.uintptr_t {
391 m := lookupHandle(pClientData).(*sqliteModule)
392 if m.c.db != (*C.sqlite3)(db) {
393 *pzErr = mPrintf("%s", "Inconsistent db handles")
394 return 0
395 }
396 args := make([]string, argc)
397 for i, s := range unsafe.Slice(argv, int(argc)) {
398 args[i] = C.GoString(s)
399 }
400 var vTab VTab
401 var err error
402 if isCreate == 1 {
403 vTab, err = m.module.Create(m.c, args)
404 } else {
405 vTab, err = m.module.Connect(m.c, args)
406 }
407
408 if err != nil {
409 *pzErr = mPrintf("%s", err.Error())
410 return 0
411 }
412 vt := sqliteVTab{m, vTab}
413 *pzErr = nil
414 return C.uintptr_t(uintptr(newHandle(m.c, &vt)))
415 }
416
417 //export goVRelease
418 func goVRelease(pVTab unsafe.Pointer, isDestroy C.int) *C.char {
419 vt := lookupHandle(pVTab).(*sqliteVTab)
420 var err error
421 if isDestroy == 1 {
422 err = vt.vTab.Destroy()
423 } else {
424 err = vt.vTab.Disconnect()
425 }
426 if err != nil && isDestroy == 1 {
427 // SQLite retains p->pVtab when xDestroy fails and later calls
428 // xDisconnect on the same object; keep the handle registered so
429 // that call can resolve it (a missing handle panics above).
430 return mPrintf("%s", err.Error())
431 }
432 // On xDisconnect (success or error) SQLite discards the vtab object,
433 // and on successful xDestroy it clears p->pVtab; release the handle
434 // in both cases.
435 deleteHandle(pVTab)
436 if err != nil {
437 return mPrintf("%s", err.Error())
438 }
439 return nil
440 }
441
442 //export goVOpen
443 func goVOpen(pVTab unsafe.Pointer, pzErr **C.char) C.uintptr_t {
444 vt := lookupHandle(pVTab).(*sqliteVTab)
445 vTabCursor, err := vt.vTab.Open()
446 if err != nil {
447 *pzErr = mPrintf("%s", err.Error())
448 return 0
449 }
450 vtc := sqliteVTabCursor{vt, vTabCursor}
451 *pzErr = nil
452 return C.uintptr_t(uintptr(newHandle(vt.module.c, &vtc)))
453 }
454
455 //export goVBestIndex
456 func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
457 vt := lookupHandle(pVTab).(*sqliteVTab)
458 info := (*C.sqlite3_index_info)(icp)
459 csts := constraints(info)
460 res, err := vt.vTab.BestIndex(csts, orderBys(info))
461 if err != nil {
462 return mPrintf("%s", err.Error())
463 }
464 if res == nil {
465 return mPrintf("%s", "BestIndex returned a nil IndexResult")
466 }
467 if len(res.Used) != len(csts) {
468 return mPrintf("Result.Used != expected value", "")
469 }
470
471 // Get a pointer to constraint_usage struct so we can update in place.
472
473 slice := unsafe.Slice(info.aConstraintUsage, int(info.nConstraint))
474 index := 1
475 for i := range slice {
476 // SQLite returns "xBestIndex malfunction" when an argvIndex is
477 // assigned to a constraint it marked as not usable, so ignore
478 // Used for those; they may become usable on a later xBestIndex
479 // invocation for a different plan.
480 if res.Used[i] && csts[i].Usable {
481 slice[i].argvIndex = C.int(index)
482 slice[i].omit = C.uchar(1)
483 index++
484 }
485 }
486
487 info.idxNum = C.int(res.IdxNum)
488 info.idxStr = (*C.char)(C.sqlite3_malloc(C.int(len(res.IdxStr) + 1)))
489 if info.idxStr == nil {
490 // C.malloc and C.CString ordinarily do this for you. See https://golang.org/cmd/cgo/
491 panic("out of memory")
492 }
493 info.needToFreeIdxStr = C.int(1)
494
495 idxStr := unsafe.Slice((*byte)(unsafe.Pointer(info.idxStr)), len(res.IdxStr)+1)
496 copy(idxStr, res.IdxStr)
497 idxStr[len(idxStr)-1] = 0 // null-terminated string
498
499 if res.AlreadyOrdered {
500 info.orderByConsumed = C.int(1)
501 }
502 // SQLite pre-initializes estimatedCost and estimatedRows with sensible
503 // defaults; overwriting them with the Go zero value would make every
504 // candidate plan look free and break query planning, so only pass
505 // values the implementation actually set.
506 if res.EstimatedCost > 0 {
507 info.estimatedCost = C.double(res.EstimatedCost)
508 }
509 if res.EstimatedRows > 0 {
510 var rows int64
511 if res.EstimatedRows >= float64(math.MaxInt64) {
512 rows = math.MaxInt64
513 } else if rows = int64(res.EstimatedRows); rows < 1 {
514 // A positive fractional estimate must not truncate to 0.
515 rows = 1
516 }
517 info.estimatedRows = C.sqlite3_int64(rows)
518 }
519
520 return nil
521 }
522
523 //export goVClose
524 func goVClose(pCursor unsafe.Pointer) *C.char {
525 vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
526 err := vtc.vTabCursor.Close()
527 // The cursor is gone as far as SQLite is concerned regardless of the
528 // callback result, so release the handle either way.
529 deleteHandle(pCursor)
530 if err != nil {
531 return mPrintf("%s", err.Error())
532 }
533 return nil
534 }
535
536 //export goMDestroy
537 func goMDestroy(pClientData unsafe.Pointer) {
538 m := lookupHandle(pClientData).(*sqliteModule)
539 m.module.DestroyModule()
540 deleteHandle(pClientData)
541 }
542
543 //export goVFilter
544 func goVFilter(pCursor unsafe.Pointer, idxNum C.int, idxName *C.char, argc C.int, argv **C.sqlite3_value) *C.char {
545 vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
546 args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
547 vals := make([]any, 0, argc)
548 for _, v := range args {
549 conv, err := callbackArgGeneric(v)
550 if err != nil {
551 return mPrintf("%s", err.Error())
552 }
553
554 // work around for SQLITE_NULL
555 x := conv.Interface()
556 if z, ok := x.([]byte); ok && z == nil {
557 x = nil
558 }
559
560 vals = append(vals, x)
561 }
562 err := vtc.vTabCursor.Filter(int(idxNum), C.GoString(idxName), vals)
563 if err != nil {
564 return mPrintf("%s", err.Error())
565 }
566 return nil
567 }
568
569 //export goVNext
570 func goVNext(pCursor unsafe.Pointer) *C.char {
571 vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
572 err := vtc.vTabCursor.Next()
573 if err != nil {
574 return mPrintf("%s", err.Error())
575 }
576 return nil
577 }
578
579 //export goVEof
580 func goVEof(pCursor unsafe.Pointer) C.int {
581 vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
582 err := vtc.vTabCursor.EOF()
583 if err {
584 return 1
585 }
586 return 0
587 }
588
589 //export goVColumn
590 func goVColumn(pCursor, cp unsafe.Pointer, col C.int) *C.char {
591 vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
592 c := (*SQLiteContext)(cp)
593 err := vtc.vTabCursor.Column(c, int(col))
594 if err != nil {
595 return mPrintf("%s", err.Error())
596 }
597 return nil
598 }
599
600 //export goVRowid
601 func goVRowid(pCursor unsafe.Pointer, pRowid *C.sqlite3_int64) *C.char {
602 vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
603 rowid, err := vtc.vTabCursor.Rowid()
604 if err != nil {
605 return mPrintf("%s", err.Error())
606 }
607 *pRowid = C.sqlite3_int64(rowid)
608 return nil
609 }
610
611 //export goVUpdate
612 func goVUpdate(pVTab unsafe.Pointer, argc C.int, argv **C.sqlite3_value, pRowid *C.sqlite3_int64) *C.char {
613 vt := lookupHandle(pVTab).(*sqliteVTab)
614
615 var tname string
616 if n, ok := vt.vTab.(interface {
617 TableName() string
618 }); ok {
619 tname = n.TableName() + " "
620 }
621
622 err := fmt.Errorf("virtual %s table %sis read-only", vt.module.name, tname)
623 if v, ok := vt.vTab.(VTabUpdater); ok {
624 // convert argv
625 args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
626 vals := make([]any, 0, argc)
627 for _, v := range args {
628 conv, err := callbackArgGeneric(v)
629 if err != nil {
630 return mPrintf("%s", err.Error())
631 }
632
633 // work around for SQLITE_NULL
634 x := conv.Interface()
635 if z, ok := x.([]byte); ok && z == nil {
636 x = nil
637 }
638
639 vals = append(vals, x)
640 }
641
642 switch {
643 case argc == 1:
644 err = v.Delete(vals[0])
645
646 case argc > 1 && vals[0] == nil:
647 var id int64
648 id, err = v.Insert(vals[1], vals[2:])
649 if err == nil {
650 *pRowid = C.sqlite3_int64(id)
651 }
652
653 case argc > 1:
654 // Per the xUpdate contract argv[0] identifies the row being
655 // updated while argv[1] is its new rowid. VTabUpdater has no
656 // way to convey a rowid change, so reject it instead of
657 // silently updating values under the old rowid.
658 if vals[0] != vals[1] {
659 err = fmt.Errorf("virtual %s table %sdoes not support changing the rowid", vt.module.name, tname)
660 } else {
661 err = v.Update(vals[0], vals[2:])
662 }
663 }
664 }
665
666 if err != nil {
667 return mPrintf("%s", err.Error())
668 }
669
670 return nil
671 }
672
673 // Module is a "virtual table module", it defines the implementation of a
674 // virtual tables. See: http://sqlite.org/c3ref/module.html
675 type Module interface {
676 // http://sqlite.org/vtab.html#xcreate
677 Create(c *SQLiteConn, args []string) (VTab, error)
678 // http://sqlite.org/vtab.html#xconnect
679 Connect(c *SQLiteConn, args []string) (VTab, error)
680 // http://sqlite.org/c3ref/create_module.html
681 DestroyModule()
682 }
683
684 // EponymousOnlyModule is a "virtual table module" (as above), but
685 // for defining "eponymous only" virtual tables See: https://sqlite.org/vtab.html#eponymous_only_virtual_tables
686 type EponymousOnlyModule interface {
687 Module
688 EponymousOnlyModule()
689 }
690
691 // VTab describes a particular instance of the virtual table.
692 // See: http://sqlite.org/c3ref/vtab.html
693 type VTab interface {
694 // http://sqlite.org/vtab.html#xbestindex
695 BestIndex([]InfoConstraint, []InfoOrderBy) (*IndexResult, error)
696 // http://sqlite.org/vtab.html#xdisconnect
697 Disconnect() error
698 // http://sqlite.org/vtab.html#sqlite3_module.xDestroy
699 Destroy() error
700 // http://sqlite.org/vtab.html#xopen
701 Open() (VTabCursor, error)
702 }
703
704 // VTabUpdater is a type that allows a VTab to be inserted, updated, or
705 // deleted.
706 // See: https://sqlite.org/vtab.html#xupdate
707 type VTabUpdater interface {
708 Delete(any) error
709 Insert(any, []any) (int64, error)
710 Update(any, []any) error
711 }
712
713 // VTabCursor describes cursors that point into the virtual table and are used
714 // to loop through the virtual table. See: http://sqlite.org/c3ref/vtab_cursor.html
715 type VTabCursor interface {
716 // http://sqlite.org/vtab.html#xclose
717 Close() error
718 // http://sqlite.org/vtab.html#xfilter
719 Filter(idxNum int, idxStr string, vals []any) error
720 // http://sqlite.org/vtab.html#xnext
721 Next() error
722 // http://sqlite.org/vtab.html#xeof
723 EOF() bool
724 // http://sqlite.org/vtab.html#xcolumn
725 Column(c *SQLiteContext, col int) error
726 // http://sqlite.org/vtab.html#xrowid
727 Rowid() (int64, error)
728 }
729
730 // DeclareVTab declares the Schema of a virtual table.
731 // See: http://sqlite.org/c3ref/declare_vtab.html
732 func (c *SQLiteConn) DeclareVTab(sql string) error {
733 zSQL := C.CString(sql)
734 defer C.free(unsafe.Pointer(zSQL))
735 rv := C.sqlite3_declare_vtab(c.db, zSQL)
736 if rv != C.SQLITE_OK {
737 return c.lastError()
738 }
739 return nil
740 }
741
742 // CreateModule registers a virtual table implementation.
743 // See: http://sqlite.org/c3ref/create_module.html
744 func (c *SQLiteConn) CreateModule(moduleName string, module Module) error {
745 mname := C.CString(moduleName)
746 defer C.free(unsafe.Pointer(mname))
747 udm := sqliteModule{c, moduleName, module}
748 switch module.(type) {
749 case EponymousOnlyModule:
750 rv := C._sqlite3_create_module_eponymous_only(c.db, mname, C.uintptr_t(uintptr(newHandle(c, &udm))))
751 if rv != C.SQLITE_OK {
752 return c.lastError()
753 }
754 return nil
755 case Module:
756 rv := C._sqlite3_create_module(c.db, mname, C.uintptr_t(uintptr(newHandle(c, &udm))))
757 if rv != C.SQLITE_OK {
758 return c.lastError()
759 }
760 return nil
761 }
762 return fmt.Errorf("sqlite3: CreateModule requires a non-nil module")
763 }