Skip to content

Commit 35a21f8

Browse files
committed
Add test for sqliteconn.Raw()
Note that you can't call cgo from within a test file; so in order to test the functionality, create new package, .../internal/sqlite3test, to define the callback. Then in the main sqlite3 package, add a test file which includes this package and calls the callback. As with the previous commit, the idea and the basic code was written by @rittneje; I massaged it so that it compiled and passed with Go 1.9, and wrote this commit message and the comments. NB that Golang 1.9 doesn't have sql.OpenDB, so we have to register a new database driver. Signed-off-by: George Dunlap <[email protected]> v4: - Refactor to get rid of sql.OpenDB call, which only appeared in Go 1.10 v3: - New
1 parent 823c1f6 commit 35a21f8

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

internal/sqlite3test/raw.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package sqlite3test
2+
3+
/*
4+
#cgo CFLAGS: -DUSE_LIBSQLITE3
5+
#cgo linux LDFLAGS: -lsqlite3
6+
#cgo darwin LDFLAGS: -L/usr/local/opt/sqlite/lib -lsqlite3
7+
#cgo darwin CFLAGS: -I/usr/local/opt/sqlite/include
8+
#cgo openbsd LDFLAGS: -lsqlite3
9+
#cgo solaris LDFLAGS: -lsqlite3
10+
#include <stdlib.h>
11+
#include <sqlite3.h>
12+
13+
static void one(sqlite3_context* ctx, int n, sqlite3_value** vals) {
14+
sqlite3_result_int(ctx, 1);
15+
}
16+
17+
static inline int _create_function(sqlite3* c) {
18+
return sqlite3_create_function(c, "one", 0, SQLITE_UTF8|SQLITE_DETERMINISTIC, NULL, one, NULL, NULL);
19+
}
20+
*/
21+
import "C"
22+
import (
23+
sqlite3 "github.com/mattn/go-sqlite3"
24+
"unsafe"
25+
)
26+
27+
func RegisterFunction(conn *sqlite3.SQLiteConn) error {
28+
return conn.Raw(func(raw unsafe.Pointer) error {
29+
rawConn := (*C.sqlite3)(raw)
30+
if ret := C._create_function(rawConn); ret != C.SQLITE_OK {
31+
return sqlite3.ErrNo(ret)
32+
}
33+
return nil
34+
})
35+
}

raw_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package sqlite3_test
2+
3+
import (
4+
"database/sql"
5+
"testing"
6+
7+
sqlite3 "github.com/mattn/go-sqlite3"
8+
"github.com/mattn/go-sqlite3/internal/sqlite3test"
9+
)
10+
11+
func TestRaw(t *testing.T) {
12+
sql.Register("sqlite3_rawtest", &sqlite3.SQLiteDriver{
13+
ConnectHook: func(c *sqlite3.SQLiteConn) error {
14+
return sqlite3test.RegisterFunction(c)
15+
},
16+
})
17+
18+
db, err := sql.Open("sqlite3_rawtest", "...")
19+
if err != nil {
20+
t.Fatal(err)
21+
}
22+
23+
defer db.Close()
24+
25+
if err := db.Ping(); err != nil {
26+
t.Fatal(err)
27+
}
28+
29+
var result int
30+
if err := db.QueryRow(`SELECT one()`).Scan(&result); err != nil {
31+
t.Fatal(err)
32+
}
33+
34+
if result != 1 {
35+
t.Errorf("expected custom one() function to return 1, but got %d", result)
36+
}
37+
}

0 commit comments

Comments
 (0)