This repository has been archived by the owner on Nov 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert_test.go
111 lines (92 loc) · 1.86 KB
/
insert_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
package chem
import (
"database/sql"
"reflect"
"testing"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/assert"
)
type Tweet struct {
Text string
Likes uint
}
type TweetRow struct {
Id int
Tweet
}
type TweetTableType struct {
Id IntegerColumn
Text StringColumn
Likes IntegerColumn
}
func (_ TweetTableType) Name() string {
return "tweet"
}
func (_ TweetTableType) Type() reflect.Type {
return reflect.TypeOf(Tweet{})
}
func (t TweetTableType) Columns() []Column {
return []Column{
t.Id,
t.Text,
t.Likes,
}
}
var tweetTable = TweetTableType{
Id: IntegerColumn{
BaseColumn{
Container: TweetTableType{},
Name: "id",
},
},
Text: StringColumn{
BaseColumn{
Container: TweetTableType{},
Name: "text",
},
},
Likes: IntegerColumn{
BaseColumn{
Container: TweetTableType{},
Name: "likes",
},
},
}
const tweetTableDef = `
CREATE TABLE tweet (
id INTEGER PRIMARY KEY,
text TEXT NOT NULL,
likes INTEGER NOT NULL DEFAULT 0
);`
func setupDB() *sql.DB {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
_, err = db.Exec(tweetTableDef)
if err != nil {
panic(err)
}
return db
}
func TestInsertStmtValues(t *testing.T) {
db := setupDB()
stmt := Insert(tweetTable)
tx, err := db.Begin()
assert.NoError(t, err)
result, err := stmt.Values(tx, Tweet{Text: "test tweet"})
assert.NoError(t, err)
err = tx.Commit()
assert.NoError(t, err)
id, err := result.LastInsertId()
assert.NoError(t, err)
assert.Equal(t, int64(1), id)
rowsAffected, err := result.RowsAffected()
assert.NoError(t, err)
assert.Equal(t, int64(1), rowsAffected)
row := db.QueryRow("SELECT text, likes FROM tweet WHERE text = ?", "test tweet")
dbtweet := Tweet{}
err = row.Scan(&dbtweet.Text, &dbtweet.Likes)
assert.NoError(t, err)
assert.Equal(t, Tweet{Text: "test tweet", Likes: 0}, dbtweet)
}