func.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // Copyright (c) 2018 David Crawshaw <david@zentus.com>
  2. //
  3. // Permission to use, copy, modify, and distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. package sqlite
  15. // #include <stdint.h>
  16. // #include <stdlib.h>
  17. // #include <sqlite3.h>
  18. // #include "wrappers.h"
  19. //
  20. // static int go_sqlite3_create_function_v2(
  21. // sqlite3 *db,
  22. // const char *zFunctionName,
  23. // int nArg,
  24. // int eTextRep,
  25. // uintptr_t pApp,
  26. // void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  27. // void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  28. // void (*xFinal)(sqlite3_context*),
  29. // void(*xDestroy)(void*)
  30. // ) {
  31. // return sqlite3_create_function_v2(
  32. // db,
  33. // zFunctionName,
  34. // nArg,
  35. // eTextRep,
  36. // (void *)pApp,
  37. // xFunc,
  38. // xStep,
  39. // xFinal,
  40. // xDestroy);
  41. // }
  42. import "C"
  43. import (
  44. "sync"
  45. "unsafe"
  46. )
  47. // Context is an *sqlite3_context.
  48. // It is used by custom functions to return result values.
  49. // An SQLite context is in no way related to a Go context.Context.
  50. type Context struct {
  51. ptr *C.sqlite3_context
  52. }
  53. func (ctx Context) UserData() interface{} {
  54. return getxfuncs(ctx.ptr).data
  55. }
  56. func (ctx Context) SetUserData(data interface{}) {
  57. getxfuncs(ctx.ptr).data = data
  58. }
  59. func (ctx Context) ResultInt(v int) { C.sqlite3_result_int(ctx.ptr, C.int(v)) }
  60. func (ctx Context) ResultInt64(v int64) { C.sqlite3_result_int64(ctx.ptr, C.sqlite3_int64(v)) }
  61. func (ctx Context) ResultFloat(v float64) { C.sqlite3_result_double(ctx.ptr, C.double(v)) }
  62. func (ctx Context) ResultNull() { C.sqlite3_result_null(ctx.ptr) }
  63. func (ctx Context) ResultValue(v Value) { C.sqlite3_result_value(ctx.ptr, v.ptr) }
  64. func (ctx Context) ResultZeroBlob(n int64) { C.sqlite3_result_zeroblob64(ctx.ptr, C.sqlite3_uint64(n)) }
  65. func (ctx Context) ResultBlob(v []byte) {
  66. C.sqlite3_result_blob(ctx.ptr, C.CBytes(v), C.int(len(v)), (*[0]byte)(C.cfree))
  67. }
  68. func (ctx Context) ResultText(v string) {
  69. var cv *C.char
  70. if len(v) != 0 {
  71. cv = C.CString(v)
  72. }
  73. C.sqlite3_result_text(ctx.ptr, cv, C.int(len(v)), (*[0]byte)(C.cfree))
  74. }
  75. func (ctx Context) ResultError(err error) {
  76. if err, isError := err.(Error); isError {
  77. C.sqlite3_result_error_code(ctx.ptr, C.int(err.Code))
  78. return
  79. }
  80. errstr := err.Error()
  81. cerrstr := C.CString(errstr)
  82. defer C.free(unsafe.Pointer(cerrstr))
  83. C.sqlite3_result_error(ctx.ptr, cerrstr, C.int(len(errstr)))
  84. }
  85. type Value struct {
  86. ptr *C.sqlite3_value
  87. }
  88. func (v Value) IsNil() bool { return v.ptr == nil }
  89. func (v Value) Int() int { return int(C.sqlite3_value_int(v.ptr)) }
  90. func (v Value) Int64() int64 { return int64(C.sqlite3_value_int64(v.ptr)) }
  91. func (v Value) Float() float64 { return float64(C.sqlite3_value_double(v.ptr)) }
  92. func (v Value) Len() int { return int(C.sqlite3_value_bytes(v.ptr)) }
  93. func (v Value) Type() ColumnType { return ColumnType(C.sqlite3_value_type(v.ptr)) }
  94. func (v Value) Text() string {
  95. ptr := unsafe.Pointer(C.sqlite3_value_text(v.ptr))
  96. n := v.Len()
  97. return C.GoStringN((*C.char)(ptr), C.int(n))
  98. }
  99. func (v Value) Blob() []byte {
  100. ptr := unsafe.Pointer(C.sqlite3_value_blob(v.ptr))
  101. n := v.Len()
  102. return C.GoBytes(ptr, C.int(n))
  103. }
  104. type xfunc struct {
  105. id int
  106. name string
  107. conn *Conn
  108. xFunc func(Context, ...Value)
  109. xStep func(Context, ...Value)
  110. xFinal func(Context)
  111. data interface{}
  112. }
  113. var xfuncs = struct {
  114. mu sync.RWMutex
  115. m map[int]*xfunc
  116. next int
  117. }{
  118. m: make(map[int]*xfunc),
  119. }
  120. // CreateFunction registers a Go function with SQLite
  121. // for use in SQL queries.
  122. //
  123. // To define a scalar function, provide a value for
  124. // xFunc and set xStep/xFinal to nil.
  125. //
  126. // To define an aggregation set xFunc to nil and
  127. // provide values for xStep and xFinal.
  128. //
  129. // State can be stored across function calls by
  130. // using the Context UserData/SetUserData methods.
  131. //
  132. // https://sqlite.org/c3ref/create_function.html
  133. func (conn *Conn) CreateFunction(name string, deterministic bool, numArgs int, xFunc, xStep func(Context, ...Value), xFinal func(Context)) error {
  134. cname := C.CString(name) // TODO: free?
  135. eTextRep := C.int(C.SQLITE_UTF8)
  136. if deterministic {
  137. eTextRep |= C.SQLITE_DETERMINISTIC
  138. }
  139. x := &xfunc{
  140. conn: conn,
  141. name: name,
  142. xFunc: xFunc,
  143. xStep: xStep,
  144. xFinal: xFinal,
  145. }
  146. xfuncs.mu.Lock()
  147. xfuncs.next++
  148. x.id = xfuncs.next
  149. xfuncs.m[x.id] = x
  150. xfuncs.mu.Unlock()
  151. pApp := C.uintptr_t(x.id)
  152. var funcfn, stepfn, finalfn *[0]byte
  153. if xFunc == nil {
  154. stepfn = (*[0]byte)(C.c_step_tramp)
  155. finalfn = (*[0]byte)(C.c_final_tramp)
  156. } else {
  157. funcfn = (*[0]byte)(C.c_func_tramp)
  158. }
  159. res := C.go_sqlite3_create_function_v2(
  160. conn.conn,
  161. cname,
  162. C.int(numArgs),
  163. eTextRep,
  164. pApp,
  165. funcfn,
  166. stepfn,
  167. finalfn,
  168. (*[0]byte)(C.c_destroy_tramp),
  169. )
  170. return conn.reserr("Conn.CreateFunction", name, res)
  171. }
  172. func getxfuncs(ctx *C.sqlite3_context) *xfunc {
  173. id := int(uintptr(C.sqlite3_user_data(ctx)))
  174. xfuncs.mu.RLock()
  175. x := xfuncs.m[id]
  176. xfuncs.mu.RUnlock()
  177. return x
  178. }
  179. //export go_func_tramp
  180. func go_func_tramp(ctx *C.sqlite3_context, n C.int, valarray **C.sqlite3_value) {
  181. x := getxfuncs(ctx)
  182. var vals []Value
  183. if n > 0 {
  184. vals = (*[127]Value)(unsafe.Pointer(valarray))[:n:n]
  185. }
  186. x.xFunc(Context{ptr: ctx}, vals...)
  187. }
  188. //export go_step_tramp
  189. func go_step_tramp(ctx *C.sqlite3_context, n C.int, valarray **C.sqlite3_value) {
  190. x := getxfuncs(ctx)
  191. var vals []Value
  192. if n > 0 {
  193. vals = (*[127]Value)(unsafe.Pointer(valarray))[:n:n]
  194. }
  195. x.xStep(Context{ptr: ctx}, vals...)
  196. }
  197. //export go_final_tramp
  198. func go_final_tramp(ctx *C.sqlite3_context) {
  199. x := getxfuncs(ctx)
  200. x.xFinal(Context{ptr: ctx})
  201. }
  202. //export go_destroy_tramp
  203. func go_destroy_tramp(ptr uintptr) {
  204. id := int(ptr)
  205. xfuncs.mu.Lock()
  206. delete(xfuncs.m, id)
  207. xfuncs.mu.Unlock()
  208. }