You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

callback.go 11KB

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