forked from gocraft/dbr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbr_test.go
316 lines (269 loc) · 8.02 KB
/
dbr_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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package dbr
import (
"bytes"
"context"
"database/sql"
"fmt"
"log"
"os"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/gocraft/dbr/dialect"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/assert"
)
//
// Test helpers
//
var (
currID int64 = 256
)
// create id
func nextID() int64 {
currID++
return currID
}
const (
mysqlDSN = "root@unix(/tmp/mysql.sock)/uservoice_test?charset=utf8"
postgresDSN = "postgres://postgres@localhost:5432/uservoice_test?sslmode=disable"
sqlite3DSN = ":memory:"
)
func createSession(driver, dsn string) *Session {
var testDSN string
switch driver {
case "mysql":
testDSN = os.Getenv("DBR_TEST_MYSQL_DSN")
case "postgres":
testDSN = os.Getenv("DBR_TEST_POSTGRES_DSN")
case "sqlite3":
testDSN = os.Getenv("DBR_TEST_SQLITE3_DSN")
}
if testDSN != "" {
dsn = testDSN
}
conn, err := Open(driver, dsn, nil)
if err != nil {
log.Fatal(err)
}
sess := conn.NewSession(nil)
reset(sess)
return sess
}
var (
mysqlSession = createSession("mysql", mysqlDSN)
postgresSession = createSession("postgres", postgresDSN)
postgresBinarySession = createSession("postgres", postgresDSN+"&binary_parameters=yes")
sqlite3Session = createSession("sqlite3", sqlite3DSN)
// all test sessions should be here
testSession = []*Session{mysqlSession, postgresSession, sqlite3Session}
)
type dbrPerson struct {
Id int64
Name string
Email string
}
type nullTypedRecord struct {
Id int64
StringVal NullString
Int64Val NullInt64
Float64Val NullFloat64
TimeVal NullTime
BoolVal NullBool
}
func reset(sess *Session) {
var autoIncrementType string
switch sess.Dialect {
case dialect.MySQL:
autoIncrementType = "serial PRIMARY KEY"
case dialect.PostgreSQL:
autoIncrementType = "serial PRIMARY KEY"
case dialect.SQLite3:
autoIncrementType = "integer PRIMARY KEY"
}
for _, v := range []string{
`DROP TABLE IF EXISTS dbr_people`,
fmt.Sprintf(`CREATE TABLE dbr_people (
id %s,
name varchar(255) NOT NULL,
email varchar(255)
)`, autoIncrementType),
`DROP TABLE IF EXISTS null_types`,
fmt.Sprintf(`CREATE TABLE null_types (
id %s,
string_val varchar(255) NULL,
int64_val integer NULL,
float64_val float NULL,
time_val timestamp NULL ,
bool_val bool NULL
)`, autoIncrementType),
} {
_, err := sess.Exec(v)
if err != nil {
log.Fatalf("Failed to execute statement: %s, Got error: %s", v, err)
}
}
}
func BenchmarkByteaNoBinaryEncode(b *testing.B) {
benchmarkBytea(b, postgresSession)
}
func BenchmarkByteaBinaryEncode(b *testing.B) {
benchmarkBytea(b, postgresBinarySession)
}
func benchmarkBytea(b *testing.B, sess *Session) {
data := bytes.Repeat([]byte("0123456789"), 1000)
for _, v := range []string{
`DROP TABLE IF EXISTS bytea_table`,
`CREATE TABLE bytea_table (
val bytea
)`,
} {
_, err := sess.Exec(v)
assert.NoError(b, err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := sess.InsertInto("bytea_table").Pair("val", data).Exec()
assert.NoError(b, err)
}
}
func TestBasicCRUD(t *testing.T) {
for _, sess := range testSession {
jonathan := dbrPerson{
Name: "jonathan",
Email: "[email protected]",
}
insertColumns := []string{"name", "email"}
if sess.Dialect == dialect.PostgreSQL {
jonathan.Id = nextID()
insertColumns = []string{"id", "name", "email"}
}
// insert
result, err := sess.InsertInto("dbr_people").Columns(insertColumns...).Record(&jonathan).Exec()
assert.NoError(t, err)
rowsAffected, err := result.RowsAffected()
assert.NoError(t, err)
assert.EqualValues(t, 1, rowsAffected)
assert.True(t, jonathan.Id > 0)
// select
var people []dbrPerson
count, err := sess.Select("*").From("dbr_people").Where(Eq("id", jonathan.Id)).LoadStructs(&people)
assert.NoError(t, err)
if assert.Equal(t, 1, count) {
assert.Equal(t, jonathan.Id, people[0].Id)
assert.Equal(t, jonathan.Name, people[0].Name)
assert.Equal(t, jonathan.Email, people[0].Email)
}
// select id
ids, err := sess.Select("id").From("dbr_people").ReturnInt64s()
assert.NoError(t, err)
assert.Equal(t, 1, len(ids))
// select id limit
ids, err = sess.Select("id").From("dbr_people").Limit(1).ReturnInt64s()
assert.NoError(t, err)
assert.Equal(t, 1, len(ids))
// update
result, err = sess.Update("dbr_people").Where(Eq("id", jonathan.Id)).Set("name", "jonathan1").Exec()
assert.NoError(t, err)
rowsAffected, err = result.RowsAffected()
assert.NoError(t, err)
assert.EqualValues(t, 1, rowsAffected)
var n NullInt64
sess.Select("count(*)").From("dbr_people").Where("name = ?", "jonathan1").LoadValue(&n)
assert.EqualValues(t, 1, n.Int64)
// delete
result, err = sess.DeleteFrom("dbr_people").Where(Eq("id", jonathan.Id)).Exec()
assert.NoError(t, err)
rowsAffected, err = result.RowsAffected()
assert.NoError(t, err)
assert.EqualValues(t, 1, rowsAffected)
// select id
ids, err = sess.Select("id").From("dbr_people").ReturnInt64s()
assert.NoError(t, err)
assert.Equal(t, 0, len(ids))
}
}
func TestPostgresReturning(t *testing.T) {
sess := postgresSession
var person dbrPerson
err := sess.InsertInto("dbr_people").Columns("name").Record(&person).
Returning("id").Load(&person.Id)
assert.NoError(t, err)
assert.True(t, person.Id > 0)
}
func TestTimeout(t *testing.T) {
for _, sess := range []*Session{
createSession("mysql", mysqlDSN),
createSession("postgres", postgresDSN),
createSession("sqlite3", sqlite3DSN),
} {
// session op timeout
sess.Timeout = time.Nanosecond
var people []dbrPerson
_, err := sess.Select("*").From("dbr_people").Load(&people)
assert.EqualValues(t, context.DeadlineExceeded, err)
_, err = sess.InsertInto("dbr_people").Columns("name", "email").Values("test", "[email protected]").Exec()
assert.EqualValues(t, context.DeadlineExceeded, err)
_, err = sess.Update("dbr_people").Set("name", "test1").Exec()
assert.EqualValues(t, context.DeadlineExceeded, err)
_, err = sess.DeleteFrom("dbr_people").Exec()
assert.EqualValues(t, context.DeadlineExceeded, err)
// tx timeout
_, err = sess.Begin()
assert.EqualValues(t, context.DeadlineExceeded, err)
// tx op timeout
sess.Timeout = 0
tx, err := sess.Begin()
assert.NoError(t, err)
defer tx.RollbackUnlessCommitted()
tx.Timeout = time.Nanosecond
_, err = tx.Select("*").From("dbr_people").Load(&people)
assert.EqualValues(t, context.DeadlineExceeded, err)
_, err = tx.InsertInto("dbr_people").Columns("name", "email").Values("test", "[email protected]").Exec()
assert.EqualValues(t, context.DeadlineExceeded, err)
_, err = tx.Update("dbr_people").Set("name", "test1").Exec()
assert.EqualValues(t, context.DeadlineExceeded, err)
_, err = tx.DeleteFrom("dbr_people").Exec()
assert.EqualValues(t, context.DeadlineExceeded, err)
// tx commit timeout
sess.Timeout = time.Second
tx, err = sess.Begin()
assert.NoError(t, err)
defer tx.RollbackUnlessCommitted()
time.Sleep(2 * time.Second)
err = tx.Commit()
assert.EqualValues(t, sql.ErrTxDone, err)
}
}
type stringSliceWithSqlScanner []string
func (ss *stringSliceWithSqlScanner) Scan(src interface{}) error {
*ss = append(*ss, "called")
return nil
}
func TestSliceWithSQLScannerSelect(t *testing.T) {
for _, sess := range []*Session{
createSession("mysql", mysqlDSN),
createSession("postgres", postgresDSN),
createSession("sqlite3", sqlite3DSN),
} {
_, err := sess.InsertInto("dbr_people").
Columns("name", "email").
Values("test1", "[email protected]").
Values("test2", "[email protected]").
Values("test3", "[email protected]").
Exec()
//plain string slice (original behavour)
var stringSlice []string
cnt, err := sess.Select("name").From("dbr_people").Load(&stringSlice)
assert.NoError(t, err)
assert.Equal(t, cnt, 3)
assert.Len(t, stringSlice, 3)
//string slice with sql.Scanner implemented, should act as a single record
var sliceScanner stringSliceWithSqlScanner
cnt, err = sess.Select("name").From("dbr_people").Load(&sliceScanner)
assert.NoError(t, err)
assert.Equal(t, cnt, 1)
assert.Len(t, sliceScanner, 1)
}
}