-
Notifications
You must be signed in to change notification settings - Fork 14
/
executor_test.go
335 lines (301 loc) · 7.54 KB
/
executor_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
package sqlf_test
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"testing"
"time"
"github.com/leporo/sqlf"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/require"
)
type dbEnv struct {
driver string
db *sql.DB
sqlf *sqlf.Dialect
}
type dbConfig struct {
driver string
envVar string
defDSN string
dialect *sqlf.Dialect
}
var dbList = []dbConfig{
{
driver: "sqlite3",
envVar: "SQLF_SQLITE_DSN",
defDSN: ":memory:",
dialect: sqlf.NoDialect,
},
}
var envs = make([]dbEnv, 0, len(dbList))
func init() {
connect()
}
func connect() {
// Connect to databases
for _, config := range dbList {
dsn := os.Getenv(config.envVar)
if dsn == "" {
dsn = config.defDSN
}
if dsn == "" || dsn == "skip" {
fmt.Printf("Skipping %s tests.", config.driver)
continue
}
db, err := sql.Open(config.driver, dsn)
if err != nil {
log.Fatalf("Invalid %s DSN: %v", config.driver, err)
}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
err = db.PingContext(ctx)
cancel()
if err != nil {
log.Fatalf("Unable to connect to %s: %v", config.driver, err)
}
envs = append(envs, dbEnv{
driver: config.driver,
db: db,
sqlf: config.dialect,
})
}
}
func execScript(db *sql.DB, script []string) (err error) {
for _, stmt := range script {
_, err = db.Exec(stmt)
if err != nil {
break
}
}
return err
}
func forEveryDB(t *testing.T, test func(ctx context.Context, env *dbEnv)) {
for _, ctx := range []context.Context{nil, context.Background()} {
for n := range envs {
env := &envs[n]
// Create schema
err := execScript(env.db, sqlSchemaCreate)
if err != nil {
t.Errorf("Failed to create a %s schema: %v", env.driver, err)
} else {
err = execScript(env.db, sqlFillDb)
if err != nil {
t.Errorf("Failed to populate a %s database: %v", env.driver, err)
} else {
// Execute a test
test(ctx, env)
}
}
err = execScript(env.db, sqlSchemaDrop)
if err != nil {
t.Errorf("Failed to drop a %s schema: %v", env.driver, err)
}
}
}
}
func TestQueryRow(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
var name string
q := env.sqlf.From("users").
Select("name").To(&name).
Where("id = ?", 1)
err := q.QueryRow(ctx, env.db)
q.Close()
require.NoError(t, err, "Failed to execute a query: %v", err)
require.Equal(t, "User 1", name)
})
}
func TestQueryRowAndClose(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
var name string
err := env.sqlf.From("users").
Select("name").To(&name).
Where("id = ?", 1).
QueryRowAndClose(ctx, env.db)
require.NoError(t, err, "Failed to execute a query: %v", err)
require.Equal(t, "User 1", name)
})
}
func TestBind(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
var u struct {
ID int64 `db:"id"`
Name string `db:"name"`
}
err := env.sqlf.From("users").
Bind(&u).
Where("id = ?", 2).
QueryRowAndClose(ctx, env.db)
require.NoError(t, err, "Failed to execute a query: %v", err)
require.Equal(t, "User 2", u.Name)
require.EqualValues(t, 2, u.ID)
})
}
func TestBindNested(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
type Parent struct {
ID int64 `db:"id"`
}
var u struct {
Parent
Name string `db:"name"`
}
err := env.sqlf.From("users").
Bind(&u).
Where("id = ?", 2).
QueryRowAndClose(ctx, env.db)
require.NoError(t, err, "Failed to execute a query: %v", err)
require.Equal(t, "User 2", u.Name)
require.EqualValues(t, 2, u.ID)
})
}
func TestExec(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
var (
userId int
count int
)
q := env.sqlf.From("users").
Select("count(*)").To(&count).
Select("min(id)").To(&userId)
defer q.Close()
q.QueryRow(ctx, env.db)
require.Equal(t, 3, count)
_, err := env.sqlf.DeleteFrom("users").
Where("id = ?", userId).
ExecAndClose(ctx, env.db)
require.NoError(t, err, "Failed to delete a row. %s error: %v", env.driver, err)
// Re-check the number of remaining rows
count = 0
q.QueryRow(ctx, env.db)
require.Equal(t, 2, count)
})
}
func TestPagination(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
type Income struct {
Id int64 `db:"id"`
UserId int64 `db:"user_id"`
FromUserId int64 `db:"from_user_id"`
Amount float64 `db:"amount"`
}
type PaginatedIncomes struct {
Count int64
Data []Income
}
var (
result PaginatedIncomes
o Income
err error
)
// Create a base query, apply filters
qs := sqlf.From("incomes").Where("amount > ?", 100)
// Clone a statement and retrieve the record count
err = qs.Clone().
Select("count(id)").To(&result.Count).
QueryRowAndClose(ctx, env.db)
if err != nil {
return
}
// Retrieve page data
err = qs.Bind(&o).
OrderBy("id desc").
Paginate(1, 2).
QueryAndClose(ctx, env.db, func(rows *sql.Rows) {
result.Data = append(result.Data, o)
})
if err != nil {
return
}
require.EqualValues(t, 4, result.Count)
require.Len(t, result.Data, 2)
})
}
func TestQuery(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
var (
nRows int = 0
userTo string
userFrom string
amount float64
)
q := env.sqlf.
From("incomes").
From("users ut").Where("ut.id = user_id").
From("users uf").Where("uf.id = from_user_id").
Select("ut.name").To(&userTo).
Select("uf.name").To(&userFrom).
Select("sum(amount) as got").To(&amount).
GroupBy("ut.name, uf.name").
OrderBy("got DESC")
defer q.Close()
err := q.Query(ctx, env.db, func(rows *sql.Rows) {
nRows++
})
if err != nil {
t.Errorf("Failed to execute a query: %v", err)
} else {
require.Equal(t, 4, nRows)
q.Limit(1)
nRows = 0
err := q.Query(ctx, env.db, func(rows *sql.Rows) {
nRows++
})
if err != nil {
t.Errorf("Failed to execute a query: %v", err)
} else {
require.Equal(t, 1, nRows)
require.Equal(t, "User 3", userTo)
require.Equal(t, "User 1", userFrom)
require.Equal(t, 500.0, amount)
}
}
})
}
func TestQueryAndClose(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
var (
nRows int = 0
total float64 = 0.0
amount float64
)
err := env.sqlf.
From("incomes").
Select("sum(amount) as got").To(&amount).
GroupBy("user_id, from_user_id").
OrderBy("got DESC").
QueryAndClose(ctx, env.db, func(rows *sql.Rows) {
nRows++
total += amount
})
require.NoError(t, err, "Failed to execute a query. %s error: %v", env.driver, err)
require.Equal(t, 4, nRows)
require.Equal(t, 1550.0, total)
})
}
var sqlSchemaCreate = []string{
`CREATE TABLE users (
id int IDENTITY PRIMARY KEY,
name varchar(128) NOT NULL)`,
`CREATE TABLE incomes (
id int IDENTITY PRIMARY KEY,
user_id int REFERENCES users(id),
from_user_id int REFERENCES users(id),
amount money)`,
}
var sqlFillDb = []string{
`INSERT INTO users (id, name) VALUES (1, "User 1")`,
`INSERT INTO users (id, name) VALUES (2, "User 2")`,
`INSERT INTO users (id, name) VALUES (3, "User 3")`,
`INSERT INTO incomes (user_id, from_user_id, amount) VALUES (1, 2, 100)`,
`INSERT INTO incomes (user_id, from_user_id, amount) VALUES (1, 2, 200)`,
`INSERT INTO incomes (user_id, from_user_id, amount) VALUES (1, 3, 350)`,
`INSERT INTO incomes (user_id, from_user_id, amount) VALUES (2, 3, 400)`,
`INSERT INTO incomes (user_id, from_user_id, amount) VALUES (3, 1, 500)`,
}
var sqlSchemaDrop = []string{
`DROP TABLE incomes`,
`DROP TABLE users`,
}