forked from chaisql/chai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_test.go
119 lines (96 loc) · 2.31 KB
/
db_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package genji_test
import (
"fmt"
"log"
"testing"
"github.com/genjidb/genji"
"github.com/genjidb/genji/database"
"github.com/genjidb/genji/document"
"github.com/stretchr/testify/require"
)
func ExampleTx() {
db, err := genji.Open(":memory:")
if err != nil {
log.Fatal(err)
}
defer db.Close()
tx, err := db.Begin(true)
if err != nil {
panic(err)
}
defer tx.Rollback()
err = tx.Exec("CREATE TABLE IF NOT EXISTS user")
if err != nil {
log.Fatal(err)
}
err = tx.Exec("INSERT INTO user (id, name, age) VALUES (?, ?, ?)", 10, "foo", 15)
if err != nil {
log.Fatal(err)
}
d, err := tx.QueryDocument("SELECT id, name, age FROM user WHERE name = ?", "foo")
if err != nil {
panic(err)
}
var u User
err = document.StructScan(d, &u)
if err != nil {
panic(err)
}
fmt.Println(u)
var id uint64
var name string
var age uint8
err = document.Scan(d, &id, &name, &age)
if err != nil {
panic(err)
}
fmt.Println(id, name, age)
err = tx.Commit()
if err != nil {
panic(err)
}
// Output: {10 foo 15 { }}
// 10 foo 15
}
func TestQueryDocument(t *testing.T) {
db, err := genji.Open(":memory:")
require.NoError(t, err)
tx, err := db.Begin(true)
require.NoError(t, err)
err = tx.Exec(`
CREATE TABLE test;
INSERT INTO test (a, b) VALUES (1, 'foo'), (2, 'bar')
`)
require.NoError(t, err)
require.NoError(t, tx.Commit())
t.Run("Should return the first document", func(t *testing.T) {
var a int
var b string
r, err := db.QueryDocument("SELECT * FROM test")
require.NoError(t, err)
err = document.Scan(r, &a, &b)
require.NoError(t, err)
require.Equal(t, 1, a)
require.Equal(t, "foo", b)
tx, err := db.Begin(false)
require.NoError(t, err)
defer tx.Rollback()
r, err = tx.QueryDocument("SELECT * FROM test")
require.NoError(t, err)
err = document.Scan(r, &a, &b)
require.NoError(t, err)
require.Equal(t, 1, a)
require.Equal(t, "foo", b)
})
t.Run("Should return an error if no document", func(t *testing.T) {
r, err := db.QueryDocument("SELECT * FROM test WHERE a > 100")
require.Equal(t, database.ErrDocumentNotFound, err)
require.Nil(t, r)
tx, err := db.Begin(false)
require.NoError(t, err)
defer tx.Rollback()
r, err = tx.QueryDocument("SELECT * FROM test WHERE a > 100")
require.Equal(t, database.ErrDocumentNotFound, err)
require.Nil(t, r)
})
}