-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathexecutor_test.go
256 lines (228 loc) · 5.74 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
package sqlf_test
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"testing"
"time"
"github.com/leporo/sqlf"
"github.com/stretchr/testify/assert"
_ "github.com/mattn/go-sqlite3"
)
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{
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()
assert.NoError(t, err, "Failed to execute a query: %v", err)
assert.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)
assert.NoError(t, err, "Failed to execute a query: %v", err)
assert.Equal(t, "User 1", name)
})
}
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)
assert.Equal(t, 3, count)
_, err := env.sqlf.DeleteFrom("users").
Where("id = ?", userId).
ExecAndClose(ctx, env.db)
assert.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)
assert.Equal(t, 2, count)
})
}
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 {
assert.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 {
assert.Equal(t, 1, nRows)
assert.Equal(t, "User 3", userTo)
assert.Equal(t, "User 1", userFrom)
assert.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
})
assert.NoError(t, err, "Failed to execute a query. %s error: %v", env.driver, err)
assert.Equal(t, 4, nRows)
assert.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`,
}