callback.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file.
  5. package sqlite3
  6. // You can't export a Go function to C and have definitions in the C
  7. // preamble in the same file, so we have to have callbackTrampoline in
  8. // its own file. Because we need a separate file anyway, the support
  9. // code for SQLite custom functions is in here.
  10. /*
  11. #ifndef USE_LIBSQLITE3
  12. #include "sqlite3-binding.h"
  13. #else
  14. #include <sqlite3.h>
  15. #endif
  16. #include <stdlib.h>
  17. void _sqlite3_result_text(sqlite3_context* ctx, const char* s);
  18. void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l);
  19. */
  20. import "C"
  21. import (
  22. "errors"
  23. "fmt"
  24. "math"
  25. "reflect"
  26. "sync"
  27. "unsafe"
  28. )
  29. //export callbackTrampoline
  30. func callbackTrampoline(ctx *C.sqlite3_context, argc int, argv **C.sqlite3_value) {
  31. args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
  32. fi := lookupHandle(C.sqlite3_user_data(ctx)).(*functionInfo)
  33. fi.Call(ctx, args)
  34. }
  35. //export stepTrampoline
  36. func stepTrampoline(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. ai := lookupHandle(C.sqlite3_user_data(ctx)).(*aggInfo)
  39. ai.Step(ctx, args)
  40. }
  41. //export doneTrampoline
  42. func doneTrampoline(ctx *C.sqlite3_context) {
  43. ai := lookupHandle(C.sqlite3_user_data(ctx)).(*aggInfo)
  44. ai.Done(ctx)
  45. }
  46. //export compareTrampoline
  47. func compareTrampoline(handlePtr unsafe.Pointer, la C.int, a *C.char, lb C.int, b *C.char) C.int {
  48. cmp := lookupHandle(handlePtr).(func(string, string) int)
  49. return C.int(cmp(C.GoStringN(a, la), C.GoStringN(b, lb)))
  50. }
  51. //export commitHookTrampoline
  52. func commitHookTrampoline(handle unsafe.Pointer) int {
  53. callback := lookupHandle(handle).(func() int)
  54. return callback()
  55. }
  56. //export rollbackHookTrampoline
  57. func rollbackHookTrampoline(handle unsafe.Pointer) {
  58. callback := lookupHandle(handle).(func())
  59. callback()
  60. }
  61. //export updateHookTrampoline
  62. func updateHookTrampoline(handle unsafe.Pointer, op int, db *C.char, table *C.char, rowid int64) {
  63. callback := lookupHandle(handle).(func(int, string, string, int64))
  64. callback(op, C.GoString(db), C.GoString(table), rowid)
  65. }
  66. //export authorizerTrampoline
  67. func authorizerTrampoline(handle unsafe.Pointer, op int, arg1 *C.char, arg2 *C.char, arg3 *C.char) int {
  68. callback := lookupHandle(handle).(func(int, string, string, string) int)
  69. return callback(op, C.GoString(arg1), C.GoString(arg2), C.GoString(arg3))
  70. }
  71. //export preUpdateHookTrampoline
  72. func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op int, db *C.char, table *C.char, oldrowid int64, newrowid int64) {
  73. hval := lookupHandleVal(handle)
  74. data := SQLitePreUpdateData{
  75. Conn: hval.db,
  76. Op: op,
  77. DatabaseName: C.GoString(db),
  78. TableName: C.GoString(table),
  79. OldRowID: oldrowid,
  80. NewRowID: newrowid,
  81. }
  82. callback := hval.val.(func(SQLitePreUpdateData))
  83. callback(data)
  84. }
  85. // Use handles to avoid passing Go pointers to C.
  86. type handleVal struct {
  87. db *SQLiteConn
  88. val interface{}
  89. }
  90. var handleLock sync.Mutex
  91. var handleVals = make(map[unsafe.Pointer]handleVal)
  92. func newHandle(db *SQLiteConn, v interface{}) unsafe.Pointer {
  93. handleLock.Lock()
  94. defer handleLock.Unlock()
  95. val := handleVal{db: db, val: v}
  96. var p unsafe.Pointer = C.malloc(C.size_t(1))
  97. if p == nil {
  98. panic("can't allocate 'cgo-pointer hack index pointer': ptr == nil")
  99. }
  100. handleVals[p] = val
  101. return p
  102. }
  103. func lookupHandleVal(handle unsafe.Pointer) handleVal {
  104. handleLock.Lock()
  105. defer handleLock.Unlock()
  106. return handleVals[handle]
  107. }
  108. func lookupHandle(handle unsafe.Pointer) interface{} {
  109. return lookupHandleVal(handle).val
  110. }
  111. func deleteHandles(db *SQLiteConn) {
  112. handleLock.Lock()
  113. defer handleLock.Unlock()
  114. for handle, val := range handleVals {
  115. if val.db == db {
  116. delete(handleVals, handle)
  117. C.free(handle)
  118. }
  119. }
  120. }
  121. // This is only here so that tests can refer to it.
  122. type callbackArgRaw C.sqlite3_value
  123. type callbackArgConverter func(*C.sqlite3_value) (reflect.Value, error)
  124. type callbackArgCast struct {
  125. f callbackArgConverter
  126. typ reflect.Type
  127. }
  128. func (c callbackArgCast) Run(v *C.sqlite3_value) (reflect.Value, error) {
  129. val, err := c.f(v)
  130. if err != nil {
  131. return reflect.Value{}, err
  132. }
  133. if !val.Type().ConvertibleTo(c.typ) {
  134. return reflect.Value{}, fmt.Errorf("cannot convert %s to %s", val.Type(), c.typ)
  135. }
  136. return val.Convert(c.typ), nil
  137. }
  138. func callbackArgInt64(v *C.sqlite3_value) (reflect.Value, error) {
  139. if C.sqlite3_value_type(v) != C.SQLITE_INTEGER {
  140. return reflect.Value{}, fmt.Errorf("argument must be an INTEGER")
  141. }
  142. return reflect.ValueOf(int64(C.sqlite3_value_int64(v))), nil
  143. }
  144. func callbackArgBool(v *C.sqlite3_value) (reflect.Value, error) {
  145. if C.sqlite3_value_type(v) != C.SQLITE_INTEGER {
  146. return reflect.Value{}, fmt.Errorf("argument must be an INTEGER")
  147. }
  148. i := int64(C.sqlite3_value_int64(v))
  149. val := false
  150. if i != 0 {
  151. val = true
  152. }
  153. return reflect.ValueOf(val), nil
  154. }
  155. func callbackArgFloat64(v *C.sqlite3_value) (reflect.Value, error) {
  156. if C.sqlite3_value_type(v) != C.SQLITE_FLOAT {
  157. return reflect.Value{}, fmt.Errorf("argument must be a FLOAT")
  158. }
  159. return reflect.ValueOf(float64(C.sqlite3_value_double(v))), nil
  160. }
  161. func callbackArgBytes(v *C.sqlite3_value) (reflect.Value, error) {
  162. switch C.sqlite3_value_type(v) {
  163. case C.SQLITE_BLOB:
  164. l := C.sqlite3_value_bytes(v)
  165. p := C.sqlite3_value_blob(v)
  166. return reflect.ValueOf(C.GoBytes(p, l)), nil
  167. case C.SQLITE_TEXT:
  168. l := C.sqlite3_value_bytes(v)
  169. c := unsafe.Pointer(C.sqlite3_value_text(v))
  170. return reflect.ValueOf(C.GoBytes(c, l)), nil
  171. default:
  172. return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT")
  173. }
  174. }
  175. func callbackArgString(v *C.sqlite3_value) (reflect.Value, error) {
  176. switch C.sqlite3_value_type(v) {
  177. case C.SQLITE_BLOB:
  178. l := C.sqlite3_value_bytes(v)
  179. p := (*C.char)(C.sqlite3_value_blob(v))
  180. return reflect.ValueOf(C.GoStringN(p, l)), nil
  181. case C.SQLITE_TEXT:
  182. c := (*C.char)(unsafe.Pointer(C.sqlite3_value_text(v)))
  183. return reflect.ValueOf(C.GoString(c)), nil
  184. default:
  185. return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT")
  186. }
  187. }
  188. func callbackArgGeneric(v *C.sqlite3_value) (reflect.Value, error) {
  189. switch C.sqlite3_value_type(v) {
  190. case C.SQLITE_INTEGER:
  191. return callbackArgInt64(v)
  192. case C.SQLITE_FLOAT:
  193. return callbackArgFloat64(v)
  194. case C.SQLITE_TEXT:
  195. return callbackArgString(v)
  196. case C.SQLITE_BLOB:
  197. return callbackArgBytes(v)
  198. case C.SQLITE_NULL:
  199. // Interpret NULL as a nil byte slice.
  200. var ret []byte
  201. return reflect.ValueOf(ret), nil
  202. default:
  203. panic("unreachable")
  204. }
  205. }
  206. func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
  207. switch typ.Kind() {
  208. case reflect.Interface:
  209. if typ.NumMethod() != 0 {
  210. return nil, errors.New("the only supported interface type is interface{}")
  211. }
  212. return callbackArgGeneric, nil
  213. case reflect.Slice:
  214. if typ.Elem().Kind() != reflect.Uint8 {
  215. return nil, errors.New("the only supported slice type is []byte")
  216. }
  217. return callbackArgBytes, nil
  218. case reflect.String:
  219. return callbackArgString, nil
  220. case reflect.Bool:
  221. return callbackArgBool, nil
  222. case reflect.Int64:
  223. return callbackArgInt64, nil
  224. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
  225. c := callbackArgCast{callbackArgInt64, typ}
  226. return c.Run, nil
  227. case reflect.Float64:
  228. return callbackArgFloat64, nil
  229. case reflect.Float32:
  230. c := callbackArgCast{callbackArgFloat64, typ}
  231. return c.Run, nil
  232. default:
  233. return nil, fmt.Errorf("don't know how to convert to %s", typ)
  234. }
  235. }
  236. func callbackConvertArgs(argv []*C.sqlite3_value, converters []callbackArgConverter, variadic callbackArgConverter) ([]reflect.Value, error) {
  237. var args []reflect.Value
  238. if len(argv) < len(converters) {
  239. return nil, fmt.Errorf("function requires at least %d arguments", len(converters))
  240. }
  241. for i, arg := range argv[:len(converters)] {
  242. v, err := converters[i](arg)
  243. if err != nil {
  244. return nil, err
  245. }
  246. args = append(args, v)
  247. }
  248. if variadic != nil {
  249. for _, arg := range argv[len(converters):] {
  250. v, err := variadic(arg)
  251. if err != nil {
  252. return nil, err
  253. }
  254. args = append(args, v)
  255. }
  256. }
  257. return args, nil
  258. }
  259. type callbackRetConverter func(*C.sqlite3_context, reflect.Value) error
  260. func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error {
  261. switch v.Type().Kind() {
  262. case reflect.Int64:
  263. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
  264. v = v.Convert(reflect.TypeOf(int64(0)))
  265. case reflect.Bool:
  266. b := v.Interface().(bool)
  267. if b {
  268. v = reflect.ValueOf(int64(1))
  269. } else {
  270. v = reflect.ValueOf(int64(0))
  271. }
  272. default:
  273. return fmt.Errorf("cannot convert %s to INTEGER", v.Type())
  274. }
  275. C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Interface().(int64)))
  276. return nil
  277. }
  278. func callbackRetFloat(ctx *C.sqlite3_context, v reflect.Value) error {
  279. switch v.Type().Kind() {
  280. case reflect.Float64:
  281. case reflect.Float32:
  282. v = v.Convert(reflect.TypeOf(float64(0)))
  283. default:
  284. return fmt.Errorf("cannot convert %s to FLOAT", v.Type())
  285. }
  286. C.sqlite3_result_double(ctx, C.double(v.Interface().(float64)))
  287. return nil
  288. }
  289. func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error {
  290. if v.Type().Kind() != reflect.Slice || v.Type().Elem().Kind() != reflect.Uint8 {
  291. return fmt.Errorf("cannot convert %s to BLOB", v.Type())
  292. }
  293. i := v.Interface()
  294. if i == nil || len(i.([]byte)) == 0 {
  295. C.sqlite3_result_null(ctx)
  296. } else {
  297. bs := i.([]byte)
  298. C._sqlite3_result_blob(ctx, unsafe.Pointer(&bs[0]), C.int(len(bs)))
  299. }
  300. return nil
  301. }
  302. func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error {
  303. if v.Type().Kind() != reflect.String {
  304. return fmt.Errorf("cannot convert %s to TEXT", v.Type())
  305. }
  306. C._sqlite3_result_text(ctx, C.CString(v.Interface().(string)))
  307. return nil
  308. }
  309. func callbackRetNil(ctx *C.sqlite3_context, v reflect.Value) error {
  310. return nil
  311. }
  312. func callbackRetGeneric(ctx *C.sqlite3_context, v reflect.Value) error {
  313. if v.IsNil() {
  314. C.sqlite3_result_null(ctx)
  315. return nil
  316. }
  317. cb, err := callbackRet(v.Elem().Type())
  318. if err != nil {
  319. return err
  320. }
  321. return cb(ctx, v.Elem())
  322. }
  323. func callbackRet(typ reflect.Type) (callbackRetConverter, error) {
  324. switch typ.Kind() {
  325. case reflect.Interface:
  326. errorInterface := reflect.TypeOf((*error)(nil)).Elem()
  327. if typ.Implements(errorInterface) {
  328. return callbackRetNil, nil
  329. }
  330. if typ.NumMethod() == 0 {
  331. return callbackRetGeneric, nil
  332. }
  333. fallthrough
  334. case reflect.Slice:
  335. if typ.Elem().Kind() != reflect.Uint8 {
  336. return nil, errors.New("the only supported slice type is []byte")
  337. }
  338. return callbackRetBlob, nil
  339. case reflect.String:
  340. return callbackRetText, nil
  341. case reflect.Bool, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
  342. return callbackRetInteger, nil
  343. case reflect.Float32, reflect.Float64:
  344. return callbackRetFloat, nil
  345. default:
  346. return nil, fmt.Errorf("don't know how to convert to %s", typ)
  347. }
  348. }
  349. func callbackError(ctx *C.sqlite3_context, err error) {
  350. cstr := C.CString(err.Error())
  351. defer C.free(unsafe.Pointer(cstr))
  352. C.sqlite3_result_error(ctx, cstr, C.int(-1))
  353. }
  354. // Test support code. Tests are not allowed to import "C", so we can't
  355. // declare any functions that use C.sqlite3_value.
  356. func callbackSyntheticForTests(v reflect.Value, err error) callbackArgConverter {
  357. return func(*C.sqlite3_value) (reflect.Value, error) {
  358. return v, err
  359. }
  360. }