| 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 |
package sqlite3 |
| 7 |
|
| 8 |
// You can't export a Go function to C and have definitions in the C |
| 9 |
// preamble in the same file, so we have to have callbackTrampoline in |
| 10 |
// its own file. Because we need a separate file anyway, the support |
| 11 |
// code for SQLite custom functions is in here. |
| 12 |
|
| 13 |
/* |
| 14 |
#ifndef USE_LIBSQLITE3 |
| 15 |
#include "sqlite3-binding.h" |
| 16 |
#else |
| 17 |
#include <sqlite3.h> |
| 18 |
#endif |
| 19 |
#include <stdlib.h> |
| 20 |
|
| 21 |
void _sqlite3_result_text(sqlite3_context* ctx, const char* s, int n); |
| 22 |
void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l); |
| 23 |
*/ |
| 24 |
import "C" |
| 25 |
|
| 26 |
import ( |
| 27 |
"errors" |
| 28 |
"fmt" |
| 29 |
"math" |
| 30 |
"reflect" |
| 31 |
"sync" |
| 32 |
"unsafe" |
| 33 |
) |
| 34 |
|
| 35 |
//export callbackTrampoline |
| 36 |
func callbackTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) { |
| 37 |
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)] |
| 38 |
fi := lookupHandle(C.sqlite3_user_data(ctx)).(*functionInfo) |
| 39 |
fi.Call(ctx, args) |
| 40 |
} |
| 41 |
|
| 42 |
//export stepTrampoline |
| 43 |
func stepTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) { |
| 44 |
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)] |
| 45 |
ai := lookupHandle(C.sqlite3_user_data(ctx)).(*aggInfo) |
| 46 |
ai.Step(ctx, args) |
| 47 |
} |
| 48 |
|
| 49 |
//export doneTrampoline |
| 50 |
func doneTrampoline(ctx *C.sqlite3_context) { |
| 51 |
ai := lookupHandle(C.sqlite3_user_data(ctx)).(*aggInfo) |
| 52 |
ai.Done(ctx) |
| 53 |
} |
| 54 |
|
| 55 |
//export compareTrampoline |
| 56 |
func compareTrampoline(handlePtr unsafe.Pointer, la C.int, a *C.char, lb C.int, b *C.char) C.int { |
| 57 |
cmp := lookupHandle(handlePtr).(func(string, string) int) |
| 58 |
return C.int(cmp(C.GoStringN(a, la), C.GoStringN(b, lb))) |
| 59 |
} |
| 60 |
|
| 61 |
//export commitHookTrampoline |
| 62 |
func commitHookTrampoline(handle unsafe.Pointer) C.int { |
| 63 |
callback := lookupHandle(handle).(func() int) |
| 64 |
return C.int(callback()) |
| 65 |
} |
| 66 |
|
| 67 |
//export rollbackHookTrampoline |
| 68 |
func rollbackHookTrampoline(handle unsafe.Pointer) { |
| 69 |
callback := lookupHandle(handle).(func()) |
| 70 |
callback() |
| 71 |
} |
| 72 |
|
| 73 |
//export updateHookTrampoline |
| 74 |
func updateHookTrampoline(handle unsafe.Pointer, op C.int, db *C.char, table *C.char, rowid int64) { |
| 75 |
callback := lookupHandle(handle).(func(int, string, string, int64)) |
| 76 |
callback(int(op), C.GoString(db), C.GoString(table), rowid) |
| 77 |
} |
| 78 |
|
| 79 |
//export authorizerTrampoline |
| 80 |
func authorizerTrampoline(handle unsafe.Pointer, op C.int, arg1 *C.char, arg2 *C.char, arg3 *C.char) C.int { |
| 81 |
callback := lookupHandle(handle).(func(int, string, string, string) int) |
| 82 |
return C.int(callback(int(op), C.GoString(arg1), C.GoString(arg2), C.GoString(arg3))) |
| 83 |
} |
| 84 |
|
| 85 |
//export preUpdateHookTrampoline |
| 86 |
func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op C.int, db *C.char, table *C.char, oldrowid int64, newrowid int64) { |
| 87 |
hval := lookupHandleVal(handle) |
| 88 |
data := SQLitePreUpdateData{ |
| 89 |
Conn: hval.db, |
| 90 |
Op: int(op), |
| 91 |
DatabaseName: C.GoString(db), |
| 92 |
TableName: C.GoString(table), |
| 93 |
OldRowID: oldrowid, |
| 94 |
NewRowID: newrowid, |
| 95 |
} |
| 96 |
callback := hval.val.(func(SQLitePreUpdateData)) |
| 97 |
callback(data) |
| 98 |
} |
| 99 |
|
| 100 |
// Use handles to avoid passing Go pointers to C. |
| 101 |
type handleVal struct { |
| 102 |
db *SQLiteConn |
| 103 |
val any |
| 104 |
} |
| 105 |
|
| 106 |
// handleVals maps unsafe.Pointer handles to handleVal. A sync.Map keeps |
| 107 |
// lookups lock-free on the hot callback path while insertion and removal |
| 108 |
// stay O(1); the previous copy-on-write map made every registration copy |
| 109 |
// the whole table, so opening N connections (each registering several |
| 110 |
// functions) was quadratic in time and allocation. |
| 111 |
var handleVals sync.Map |
| 112 |
|
| 113 |
func newHandle(db *SQLiteConn, v any) unsafe.Pointer { |
| 114 |
var p unsafe.Pointer = C.malloc(C.size_t(1)) |
| 115 |
if p == nil { |
| 116 |
panic("can't allocate 'cgo-pointer hack index pointer': ptr == nil") |
| 117 |
} |
| 118 |
handleVals.Store(p, handleVal{db: db, val: v}) |
| 119 |
return p |
| 120 |
} |
| 121 |
|
| 122 |
func lookupHandleVal(handle unsafe.Pointer) handleVal { |
| 123 |
v, ok := handleVals.Load(handle) |
| 124 |
if !ok { |
| 125 |
return handleVal{} |
| 126 |
} |
| 127 |
return v.(handleVal) |
| 128 |
} |
| 129 |
|
| 130 |
func lookupHandle(handle unsafe.Pointer) any { |
| 131 |
return lookupHandleVal(handle).val |
| 132 |
} |
| 133 |
|
| 134 |
// deleteHandle releases a single handle created by newHandle. It is a no-op |
| 135 |
// if the handle is unknown (e.g. already released). |
| 136 |
func deleteHandle(handle unsafe.Pointer) { |
| 137 |
if _, ok := handleVals.LoadAndDelete(handle); ok { |
| 138 |
C.free(handle) |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
func deleteHandles(db *SQLiteConn) { |
| 143 |
handleVals.Range(func(handle, val any) bool { |
| 144 |
if val.(handleVal).db == db { |
| 145 |
if _, ok := handleVals.LoadAndDelete(handle); ok { |
| 146 |
C.free(handle.(unsafe.Pointer)) |
| 147 |
} |
| 148 |
} |
| 149 |
return true |
| 150 |
}) |
| 151 |
} |
| 152 |
|
| 153 |
// This is only here so that tests can refer to it. |
| 154 |
type callbackArgRaw C.sqlite3_value |
| 155 |
|
| 156 |
type callbackArgConverter func(*C.sqlite3_value) (reflect.Value, error) |
| 157 |
|
| 158 |
type callbackArgCast struct { |
| 159 |
f callbackArgConverter |
| 160 |
typ reflect.Type |
| 161 |
} |
| 162 |
|
| 163 |
func (c callbackArgCast) Run(v *C.sqlite3_value) (reflect.Value, error) { |
| 164 |
val, err := c.f(v) |
| 165 |
if err != nil { |
| 166 |
return reflect.Value{}, err |
| 167 |
} |
| 168 |
if !val.Type().ConvertibleTo(c.typ) { |
| 169 |
return reflect.Value{}, fmt.Errorf("cannot convert %s to %s", val.Type(), c.typ) |
| 170 |
} |
| 171 |
return val.Convert(c.typ), nil |
| 172 |
} |
| 173 |
|
| 174 |
func callbackArgInt64(v *C.sqlite3_value) (reflect.Value, error) { |
| 175 |
if C.sqlite3_value_type(v) != C.SQLITE_INTEGER { |
| 176 |
return reflect.Value{}, fmt.Errorf("argument must be an INTEGER") |
| 177 |
} |
| 178 |
return reflect.ValueOf(int64(C.sqlite3_value_int64(v))), nil |
| 179 |
} |
| 180 |
|
| 181 |
func callbackArgBool(v *C.sqlite3_value) (reflect.Value, error) { |
| 182 |
if C.sqlite3_value_type(v) != C.SQLITE_INTEGER { |
| 183 |
return reflect.Value{}, fmt.Errorf("argument must be an INTEGER") |
| 184 |
} |
| 185 |
i := int64(C.sqlite3_value_int64(v)) |
| 186 |
val := false |
| 187 |
if i != 0 { |
| 188 |
val = true |
| 189 |
} |
| 190 |
return reflect.ValueOf(val), nil |
| 191 |
} |
| 192 |
|
| 193 |
func callbackArgFloat64(v *C.sqlite3_value) (reflect.Value, error) { |
| 194 |
if C.sqlite3_value_type(v) != C.SQLITE_FLOAT { |
| 195 |
return reflect.Value{}, fmt.Errorf("argument must be a FLOAT") |
| 196 |
} |
| 197 |
return reflect.ValueOf(float64(C.sqlite3_value_double(v))), nil |
| 198 |
} |
| 199 |
|
| 200 |
func callbackArgBytes(v *C.sqlite3_value) (reflect.Value, error) { |
| 201 |
switch C.sqlite3_value_type(v) { |
| 202 |
case C.SQLITE_BLOB: |
| 203 |
l := C.sqlite3_value_bytes(v) |
| 204 |
p := C.sqlite3_value_blob(v) |
| 205 |
return reflect.ValueOf(C.GoBytes(p, l)), nil |
| 206 |
case C.SQLITE_TEXT: |
| 207 |
l := C.sqlite3_value_bytes(v) |
| 208 |
c := unsafe.Pointer(C.sqlite3_value_text(v)) |
| 209 |
return reflect.ValueOf(C.GoBytes(c, l)), nil |
| 210 |
default: |
| 211 |
return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT") |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
func callbackArgString(v *C.sqlite3_value) (reflect.Value, error) { |
| 216 |
switch C.sqlite3_value_type(v) { |
| 217 |
case C.SQLITE_BLOB: |
| 218 |
p := (*C.char)(C.sqlite3_value_blob(v)) |
| 219 |
l := C.sqlite3_value_bytes(v) |
| 220 |
return reflect.ValueOf(C.GoStringN(p, l)), nil |
| 221 |
case C.SQLITE_TEXT: |
| 222 |
c := (*C.char)(unsafe.Pointer(C.sqlite3_value_text(v))) |
| 223 |
l := C.sqlite3_value_bytes(v) |
| 224 |
return reflect.ValueOf(C.GoStringN(c, l)), nil |
| 225 |
default: |
| 226 |
return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT") |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
func callbackArgGeneric(v *C.sqlite3_value) (reflect.Value, error) { |
| 231 |
switch C.sqlite3_value_type(v) { |
| 232 |
case C.SQLITE_INTEGER: |
| 233 |
return callbackArgInt64(v) |
| 234 |
case C.SQLITE_FLOAT: |
| 235 |
return callbackArgFloat64(v) |
| 236 |
case C.SQLITE_TEXT: |
| 237 |
return callbackArgString(v) |
| 238 |
case C.SQLITE_BLOB: |
| 239 |
return callbackArgBytes(v) |
| 240 |
case C.SQLITE_NULL: |
| 241 |
// Interpret NULL as a nil byte slice. |
| 242 |
var ret []byte |
| 243 |
return reflect.ValueOf(ret), nil |
| 244 |
default: |
| 245 |
panic("unreachable") |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
// callbackArgConvert returns conv as-is when the parameter type is the |
| 250 |
// canonical type conv produces, and wraps it with a cast for named types |
| 251 |
// (e.g. time.Duration), which reflect.Call would otherwise panic on. |
| 252 |
func callbackArgConvert(conv callbackArgConverter, typ, canonical reflect.Type) callbackArgConverter { |
| 253 |
if typ == canonical { |
| 254 |
return conv |
| 255 |
} |
| 256 |
return callbackArgCast{conv, typ}.Run |
| 257 |
} |
| 258 |
|
| 259 |
func callbackArg(typ reflect.Type) (callbackArgConverter, error) { |
| 260 |
switch typ.Kind() { |
| 261 |
case reflect.Interface: |
| 262 |
if typ.NumMethod() != 0 { |
| 263 |
return nil, errors.New("the only supported interface type is any") |
| 264 |
} |
| 265 |
return callbackArgGeneric, nil |
| 266 |
case reflect.Slice: |
| 267 |
if typ.Elem().Kind() != reflect.Uint8 { |
| 268 |
return nil, errors.New("the only supported slice type is []byte") |
| 269 |
} |
| 270 |
return callbackArgConvert(callbackArgBytes, typ, reflect.TypeOf([]byte(nil))), nil |
| 271 |
case reflect.String: |
| 272 |
return callbackArgConvert(callbackArgString, typ, reflect.TypeOf("")), nil |
| 273 |
case reflect.Bool: |
| 274 |
return callbackArgConvert(callbackArgBool, typ, reflect.TypeOf(false)), nil |
| 275 |
case reflect.Int64: |
| 276 |
return callbackArgConvert(callbackArgInt64, typ, reflect.TypeOf(int64(0))), nil |
| 277 |
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint: |
| 278 |
c := callbackArgCast{callbackArgInt64, typ} |
| 279 |
return c.Run, nil |
| 280 |
case reflect.Float64: |
| 281 |
return callbackArgConvert(callbackArgFloat64, typ, reflect.TypeOf(float64(0))), nil |
| 282 |
case reflect.Float32: |
| 283 |
c := callbackArgCast{callbackArgFloat64, typ} |
| 284 |
return c.Run, nil |
| 285 |
default: |
| 286 |
return nil, fmt.Errorf("don't know how to convert to %s", typ) |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
func callbackConvertArgs(argv []*C.sqlite3_value, converters []callbackArgConverter, variadic callbackArgConverter) ([]reflect.Value, error) { |
| 291 |
var args []reflect.Value |
| 292 |
|
| 293 |
if len(argv) < len(converters) { |
| 294 |
return nil, fmt.Errorf("function requires at least %d arguments", len(converters)) |
| 295 |
} |
| 296 |
|
| 297 |
for i, arg := range argv[:len(converters)] { |
| 298 |
v, err := converters[i](arg) |
| 299 |
if err != nil { |
| 300 |
return nil, err |
| 301 |
} |
| 302 |
args = append(args, v) |
| 303 |
} |
| 304 |
|
| 305 |
if variadic != nil { |
| 306 |
for _, arg := range argv[len(converters):] { |
| 307 |
v, err := variadic(arg) |
| 308 |
if err != nil { |
| 309 |
return nil, err |
| 310 |
} |
| 311 |
args = append(args, v) |
| 312 |
} |
| 313 |
} |
| 314 |
return args, nil |
| 315 |
} |
| 316 |
|
| 317 |
type callbackRetConverter func(*C.sqlite3_context, reflect.Value) error |
| 318 |
|
| 319 |
func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error { |
| 320 |
switch v.Type().Kind() { |
| 321 |
case reflect.Int64: |
| 322 |
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint: |
| 323 |
v = v.Convert(reflect.TypeOf(int64(0))) |
| 324 |
case reflect.Bool: |
| 325 |
if v.Bool() { |
| 326 |
v = reflect.ValueOf(int64(1)) |
| 327 |
} else { |
| 328 |
v = reflect.ValueOf(int64(0)) |
| 329 |
} |
| 330 |
default: |
| 331 |
return fmt.Errorf("cannot convert %s to INTEGER", v.Type()) |
| 332 |
} |
| 333 |
|
| 334 |
C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Int())) |
| 335 |
return nil |
| 336 |
} |
| 337 |
|
| 338 |
func callbackRetFloat(ctx *C.sqlite3_context, v reflect.Value) error { |
| 339 |
switch v.Type().Kind() { |
| 340 |
case reflect.Float64: |
| 341 |
case reflect.Float32: |
| 342 |
v = v.Convert(reflect.TypeOf(float64(0))) |
| 343 |
default: |
| 344 |
return fmt.Errorf("cannot convert %s to FLOAT", v.Type()) |
| 345 |
} |
| 346 |
|
| 347 |
C.sqlite3_result_double(ctx, C.double(v.Float())) |
| 348 |
return nil |
| 349 |
} |
| 350 |
|
| 351 |
func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error { |
| 352 |
if v.Type().Kind() != reflect.Slice || v.Type().Elem().Kind() != reflect.Uint8 { |
| 353 |
return fmt.Errorf("cannot convert %s to BLOB", v.Type()) |
| 354 |
} |
| 355 |
bs := v.Bytes() |
| 356 |
if len(bs) == 0 { |
| 357 |
C.sqlite3_result_null(ctx) |
| 358 |
} else { |
| 359 |
if i64 && len(bs) > math.MaxInt32 { |
| 360 |
C.sqlite3_result_error_toobig(ctx) |
| 361 |
return nil |
| 362 |
} |
| 363 |
C._sqlite3_result_blob(ctx, unsafe.Pointer(&bs[0]), C.int(len(bs))) |
| 364 |
} |
| 365 |
return nil |
| 366 |
} |
| 367 |
|
| 368 |
func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error { |
| 369 |
if v.Type().Kind() != reflect.String { |
| 370 |
return fmt.Errorf("cannot convert %s to TEXT", v.Type()) |
| 371 |
} |
| 372 |
s := v.String() |
| 373 |
if i64 && len(s) > math.MaxInt32 { |
| 374 |
C.sqlite3_result_error_toobig(ctx) |
| 375 |
return nil |
| 376 |
} |
| 377 |
cstr := C.CString(s) |
| 378 |
C._sqlite3_result_text(ctx, cstr, C.int(len(s))) |
| 379 |
return nil |
| 380 |
} |
| 381 |
|
| 382 |
func callbackRetNil(ctx *C.sqlite3_context, v reflect.Value) error { |
| 383 |
return nil |
| 384 |
} |
| 385 |
|
| 386 |
func callbackRetGeneric(ctx *C.sqlite3_context, v reflect.Value) error { |
| 387 |
if v.IsNil() { |
| 388 |
C.sqlite3_result_null(ctx) |
| 389 |
return nil |
| 390 |
} |
| 391 |
|
| 392 |
cb, err := callbackRet(v.Elem().Type()) |
| 393 |
if err != nil { |
| 394 |
return err |
| 395 |
} |
| 396 |
|
| 397 |
return cb(ctx, v.Elem()) |
| 398 |
} |
| 399 |
|
| 400 |
func callbackRet(typ reflect.Type) (callbackRetConverter, error) { |
| 401 |
switch typ.Kind() { |
| 402 |
case reflect.Interface: |
| 403 |
errorInterface := reflect.TypeOf((*error)(nil)).Elem() |
| 404 |
if typ.Implements(errorInterface) { |
| 405 |
return callbackRetNil, nil |
| 406 |
} |
| 407 |
|
| 408 |
if typ.NumMethod() == 0 { |
| 409 |
return callbackRetGeneric, nil |
| 410 |
} |
| 411 |
|
| 412 |
fallthrough |
| 413 |
case reflect.Slice: |
| 414 |
if typ.Elem().Kind() != reflect.Uint8 { |
| 415 |
return nil, errors.New("the only supported slice type is []byte") |
| 416 |
} |
| 417 |
return callbackRetBlob, nil |
| 418 |
case reflect.String: |
| 419 |
return callbackRetText, nil |
| 420 |
case reflect.Bool, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint: |
| 421 |
return callbackRetInteger, nil |
| 422 |
case reflect.Float32, reflect.Float64: |
| 423 |
return callbackRetFloat, nil |
| 424 |
default: |
| 425 |
return nil, fmt.Errorf("don't know how to convert to %s", typ) |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
func callbackError(ctx *C.sqlite3_context, err error) { |
| 430 |
cstr := C.CString(err.Error()) |
| 431 |
defer C.free(unsafe.Pointer(cstr)) |
| 432 |
C.sqlite3_result_error(ctx, cstr, C.int(-1)) |
| 433 |
} |
| 434 |
|
| 435 |
// Test support code. Tests are not allowed to import "C", so we can't |
| 436 |
// declare any functions that use C.sqlite3_value. |
| 437 |
func callbackSyntheticForTests(v reflect.Value, err error) callbackArgConverter { |
| 438 |
return func(*C.sqlite3_value) (reflect.Value, error) { |
| 439 |
return v, err |
| 440 |
} |
| 441 |
} |