-
Notifications
You must be signed in to change notification settings - Fork 2
/
sqlx_test.go
86 lines (70 loc) · 1.44 KB
/
sqlx_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
package sqlx
import (
"context"
"testing"
"time"
_ "modernc.org/sqlite"
)
var schema = `
CREATE TABLE IF NOT EXISTS users (
id integer primary key,
age integer,
name varchar(30),
created datetime default CURRENT_TIMESTAMP
)
`
type user struct {
ID int
Name string
Age int
Created time.Time
}
func (u *user) TableName() string { return "users" }
func (u *user) KeyName() string { return "id" }
func TestCRUD(t *testing.T) {
ctx := context.Background()
db := MustConnect("sqlite", ":memory:")
db.MustExecContext(ctx, schema)
now := time.Now()
u1 := &user{Name: "foo", Age: 18, Created: now}
result, err := db.Insert(u1)
if err != nil {
t.Fatal(err)
}
id, _ := result.LastInsertId()
var u2 user
err = db.Get(&u2, "select * from users where id = ?", id)
if err != nil {
t.Fatal(err)
}
if u2.Name != "foo" || u2.Age != 18 || !u2.Created.Equal(now) {
t.Fatal("invalid user", u2)
}
u2.Name = "bar"
_, err = db.Update(&u2)
if err != nil {
t.Fatal(err)
}
var u3 user
err = db.Get(&u3, "select * from users where id = ?", id)
if err != nil {
t.Fatal(err)
}
if u3.Name != "bar" || u3.Age != 18 || !u3.Created.Equal(now) {
t.Fatal("invalid user", u3)
}
u4 := *u1
u4.ID = 10
_, err = db.Insert(&u4)
if err != nil {
t.Fatal(err)
}
var u5 user
err = db.Get(&u5, "select * from users where id = ?", u4.ID)
if err != nil {
t.Fatal(err)
}
if u5.ID != u4.ID {
t.Fatal("invalid user", u5)
}
}