Debian Codegraph @

sqlite3_opt_unlock_notify.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 cgo && sqlite_unlock_notify
7 // +build cgo,sqlite_unlock_notify
8
9 package sqlite3
10
11 /*
12 #cgo CFLAGS: -DSQLITE_ENABLE_UNLOCK_NOTIFY
13
14 #include <stdlib.h>
15 #ifndef USE_LIBSQLITE3
16 #include "sqlite3-binding.h"
17 #else
18 #include <sqlite3.h>
19 #endif
20
21 extern void unlock_notify_callback(void *arg, int argc);
22 */
23 import "C"
24
25 import (
26 "fmt"
27 "math"
28 "sync"
29 "unsafe"
30 )
31
32 type unlock_notify_table struct {
33 sync.Mutex
34 seqnum uint
35 table map[uint]chan struct{}
36 }
37
38 var unt unlock_notify_table = unlock_notify_table{table: make(map[uint]chan struct{})}
39
40 func (t *unlock_notify_table) add(c chan struct{}) uint {
41 t.Lock()
42 defer t.Unlock()
43 h := t.seqnum
44 t.table[h] = c
45 t.seqnum++
46 return h
47 }
48
49 func (t *unlock_notify_table) remove(h uint) {
50 t.Lock()
51 defer t.Unlock()
52 delete(t.table, h)
53 }
54
55 func (t *unlock_notify_table) get(h uint) chan struct{} {
56 t.Lock()
57 defer t.Unlock()
58 c, ok := t.table[h]
59 if !ok {
60 panic(fmt.Sprintf("Non-existent key for unlcok-notify channel: %d", h))
61 }
62 return c
63 }
64
65 //export unlock_notify_callback
66 func unlock_notify_callback(argv unsafe.Pointer, argc C.int) {
67 for i := 0; i < int(argc); i++ {
68 parg := ((*(*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.uint)(nil))]*[1]uint)(argv))[i])
69 arg := *parg
70 h := arg[0]
71 c := unt.get(h)
72 c <- struct{}{}
73 }
74 }
75
76 //export unlock_notify_wait
77 func unlock_notify_wait(db *C.sqlite3) C.int {
78 // It has to be a bufferred channel to not block in sqlite_unlock_notify
79 // as sqlite_unlock_notify could invoke the callback before it returns.
80 c := make(chan struct{}, 1)
81 defer close(c)
82
83 h := unt.add(c)
84 defer unt.remove(h)
85
86 pargv := C.malloc(C.size_t(unsafe.Sizeof(uint(0))))
87 defer C.free(pargv)
88
89 argv := (*[1]uint)(pargv)
90 argv[0] = h
91 if rv := C.sqlite3_unlock_notify(db, (*[0]byte)(C.unlock_notify_callback), unsafe.Pointer(pargv)); rv != C.SQLITE_OK {
92 return rv
93 }
94
95 <-c
96
97 return C.SQLITE_OK
98 }