forked from go-ozzo/ozzo-dbx
-
Notifications
You must be signed in to change notification settings - Fork 31
/
db_test.go
380 lines (342 loc) · 8.99 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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package dbx
import (
"context"
"database/sql"
"errors"
"io/ioutil"
"strings"
"testing"
// @todo change to sqlite
_ "github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/assert"
)
const (
TestDSN = "travis:@/pocketbase_dbx_test?parseTime=true"
FixtureFile = "testdata/mysql.sql"
)
func TestDB_NewFromDB(t *testing.T) {
sqlDB, err := sql.Open("mysql", TestDSN)
if assert.Nil(t, err) {
db := NewFromDB(sqlDB, "mysql")
assert.NotNil(t, db.sqlDB)
assert.NotNil(t, db.FieldMapper)
}
}
func TestDB_Open(t *testing.T) {
db, err := Open("mysql", TestDSN)
assert.Nil(t, err)
if assert.NotNil(t, db) {
assert.NotNil(t, db.sqlDB)
assert.NotNil(t, db.FieldMapper)
db2 := db.Clone()
assert.NotEqual(t, db, db2)
assert.Equal(t, db.driverName, db2.driverName)
ctx := context.Background()
db3 := db.WithContext(ctx)
assert.Equal(t, ctx, db3.ctx)
assert.Equal(t, ctx, db3.Context())
assert.NotEqual(t, db, db3)
}
_, err = Open("xyz", TestDSN)
assert.NotNil(t, err)
}
func TestDB_MustOpen(t *testing.T) {
_, err := MustOpen("mysql", TestDSN)
assert.Nil(t, err)
_, err = MustOpen("mysql", "unknown:x@/test")
assert.NotNil(t, err)
}
func TestDB_Close(t *testing.T) {
db := getDB()
assert.Nil(t, db.Close())
}
func TestDB_DriverName(t *testing.T) {
db := getDB()
assert.Equal(t, "mysql", db.DriverName())
}
func TestDB_QuoteTableName(t *testing.T) {
tests := []struct {
input, output string
}{
{"users", "`users`"},
{"`users`", "`users`"},
{"(select)", "(select)"},
{"{{users}}", "{{users}}"},
{"public.db1.users", "`public`.`db1`.`users`"},
}
db := getDB()
for _, test := range tests {
result := db.QuoteTableName(test.input)
assert.Equal(t, test.output, result, test.input)
}
}
func TestDB_QuoteColumnName(t *testing.T) {
tests := []struct {
input, output string
}{
{"*", "*"},
{"users.*", "`users`.*"},
{"name", "`name`"},
{"`name`", "`name`"},
{"(select)", "(select)"},
{"{{name}}", "{{name}}"},
{"[[name]]", "[[name]]"},
{"public.db1.users", "`public`.`db1`.`users`"},
}
db := getDB()
for _, test := range tests {
result := db.QuoteColumnName(test.input)
assert.Equal(t, test.output, result, test.input)
}
}
func TestDB_ProcessSQL(t *testing.T) {
tests := []struct {
tag string
sql string // original SQL
mysql string // expected MySQL version
postgres string // expected PostgreSQL version
oci8 string // expected OCI version
params []string // expected params
}{
{
"normal case",
`INSERT INTO employee (id, name, age) VALUES ({:id}, {:name}, {:age})`,
`INSERT INTO employee (id, name, age) VALUES (?, ?, ?)`,
`INSERT INTO employee (id, name, age) VALUES ($1, $2, $3)`,
`INSERT INTO employee (id, name, age) VALUES (:p1, :p2, :p3)`,
[]string{"id", "name", "age"},
},
{
"the same placeholder is used twice",
`SELECT * FROM employee WHERE first_name LIKE {:keyword} OR last_name LIKE {:keyword}`,
`SELECT * FROM employee WHERE first_name LIKE ? OR last_name LIKE ?`,
`SELECT * FROM employee WHERE first_name LIKE $1 OR last_name LIKE $2`,
`SELECT * FROM employee WHERE first_name LIKE :p1 OR last_name LIKE :p2`,
[]string{"keyword", "keyword"},
},
{
"non-matching placeholder",
`SELECT * FROM employee WHERE first_name LIKE "{:key?word}" OR last_name LIKE {:keyword}`,
`SELECT * FROM employee WHERE first_name LIKE "{:key?word}" OR last_name LIKE ?`,
`SELECT * FROM employee WHERE first_name LIKE "{:key?word}" OR last_name LIKE $1`,
`SELECT * FROM employee WHERE first_name LIKE "{:key?word}" OR last_name LIKE :p1`,
[]string{"keyword"},
},
{
"quote table/column names",
`SELECT * FROM {{public.user}} WHERE [[user.id]]=1`,
"SELECT * FROM `public`.`user` WHERE `user`.`id`=1",
"SELECT * FROM \"public\".\"user\" WHERE \"user\".\"id\"=1",
"SELECT * FROM \"public\".\"user\" WHERE \"user\".\"id\"=1",
nil,
},
}
mysqlDB := getDB()
mysqlDB.Builder = NewMysqlBuilder(nil, nil)
pgsqlDB := getDB()
pgsqlDB.Builder = NewPgsqlBuilder(nil, nil)
ociDB := getDB()
ociDB.Builder = NewOciBuilder(nil, nil)
for _, test := range tests {
s1, names := mysqlDB.processSQL(test.sql)
assert.Equal(t, test.mysql, s1, test.tag)
s2, _ := pgsqlDB.processSQL(test.sql)
assert.Equal(t, test.postgres, s2, test.tag)
s3, _ := ociDB.processSQL(test.sql)
assert.Equal(t, test.oci8, s3, test.tag)
assert.Equal(t, test.params, names, test.tag)
}
}
func TestDB_Begin(t *testing.T) {
tests := []struct {
makeTx func(db *DB) *Tx
desc string
}{
{
makeTx: func(db *DB) *Tx {
tx, _ := db.Begin()
return tx
},
desc: "Begin",
},
{
makeTx: func(db *DB) *Tx {
sqlTx, _ := db.DB().Begin()
return db.Wrap(sqlTx)
},
desc: "Wrap",
},
{
makeTx: func(db *DB) *Tx {
tx, _ := db.BeginTx(context.Background(), nil)
return tx
},
desc: "BeginTx",
},
}
db := getPreparedDB()
var (
lastID int
name string
tx *Tx
)
db.NewQuery("SELECT MAX(id) FROM item").Row(&lastID)
for _, test := range tests {
t.Log(test.desc)
tx = test.makeTx(db)
_, err1 := tx.Insert("item", Params{
"name": "name1",
}).Execute()
_, err2 := tx.Insert("item", Params{
"name": "name2",
}).Execute()
if err1 == nil && err2 == nil {
tx.Commit()
} else {
t.Errorf("Unexpected TX rollback: %v, %v", err1, err2)
tx.Rollback()
}
q := db.NewQuery("SELECT name FROM item WHERE id={:id}")
q.Bind(Params{"id": lastID + 1}).Row(&name)
assert.Equal(t, "name1", name)
q.Bind(Params{"id": lastID + 2}).Row(&name)
assert.Equal(t, "name2", name)
tx = test.makeTx(db)
_, err3 := tx.NewQuery("DELETE FROM item WHERE id=7").Execute()
_, err4 := tx.NewQuery("DELETE FROM items WHERE id=7").Execute()
if err3 == nil && err4 == nil {
t.Error("Unexpected TX commit")
tx.Commit()
} else {
tx.Rollback()
}
}
}
func TestDB_Transactional(t *testing.T) {
db := getPreparedDB()
var (
lastID int
name string
)
db.NewQuery("SELECT MAX(id) FROM item").Row(&lastID)
err := db.Transactional(func(tx *Tx) error {
_, err := tx.Insert("item", Params{
"name": "name1",
}).Execute()
if err != nil {
return err
}
_, err = tx.Insert("item", Params{
"name": "name2",
}).Execute()
if err != nil {
return err
}
return nil
})
if assert.Nil(t, err) {
q := db.NewQuery("SELECT name FROM item WHERE id={:id}")
q.Bind(Params{"id": lastID + 1}).Row(&name)
assert.Equal(t, "name1", name)
q.Bind(Params{"id": lastID + 2}).Row(&name)
assert.Equal(t, "name2", name)
}
err = db.Transactional(func(tx *Tx) error {
_, err := tx.NewQuery("DELETE FROM item WHERE id=2").Execute()
if err != nil {
return err
}
_, err = tx.NewQuery("DELETE FROM items WHERE id=2").Execute()
if err != nil {
return err
}
return nil
})
if assert.NotNil(t, err) {
db.NewQuery("SELECT name FROM item WHERE id=2").Row(&name)
assert.Equal(t, "Go in Action", name)
}
// Rollback called within Transactional and return error
err = db.Transactional(func(tx *Tx) error {
_, err := tx.NewQuery("DELETE FROM item WHERE id=2").Execute()
if err != nil {
return err
}
_, err = tx.NewQuery("DELETE FROM items WHERE id=2").Execute()
if err != nil {
tx.Rollback()
return err
}
return nil
})
if assert.NotNil(t, err) {
db.NewQuery("SELECT name FROM item WHERE id=2").Row(&name)
assert.Equal(t, "Go in Action", name)
}
// Rollback called within Transactional without returning error
err = db.Transactional(func(tx *Tx) error {
_, err := tx.NewQuery("DELETE FROM item WHERE id=2").Execute()
if err != nil {
return err
}
_, err = tx.NewQuery("DELETE FROM items WHERE id=2").Execute()
if err != nil {
tx.Rollback()
return nil
}
return nil
})
if assert.Nil(t, err) {
db.NewQuery("SELECT name FROM item WHERE id=2").Row(&name)
assert.Equal(t, "Go in Action", name)
}
}
func TestErrors_Error(t *testing.T) {
errs := Errors{}
assert.Equal(t, "", errs.Error())
errs = Errors{errors.New("a")}
assert.Equal(t, "a", errs.Error())
errs = Errors{errors.New("a"), errors.New("b")}
assert.Equal(t, "a\nb", errs.Error())
}
func getDB() *DB {
db, err := Open("mysql", TestDSN)
if err != nil {
panic(err)
}
return db
}
func getPreparedDB() *DB {
db := getDB()
s, err := ioutil.ReadFile(FixtureFile)
if err != nil {
panic(err)
}
lines := strings.Split(string(s), ";")
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
if _, err := db.NewQuery(line).Execute(); err != nil {
panic(err)
}
}
return db
}
// Naming according to issue 49 ( https://github.com/pocketbase/dbx/issues/49 )
type ArtistDAO struct {
nickname string
}
func (ArtistDAO) TableName() string {
return "artists"
}
func Test_TableNameWithPrefix(t *testing.T) {
db := NewFromDB(nil, "mysql")
db.TableMapper = func(a interface{}) string {
return "tbl_" + GetTableName(a)
}
assert.Equal(t, "tbl_artists", db.TableMapper(ArtistDAO{}))
}