-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquery.go
69 lines (59 loc) · 1.27 KB
/
query.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
package gitschemalex
import (
"context"
"database/sql"
"fmt"
"io"
"strings"
"github.com/pkg/errors"
)
type query struct {
stmt string
args []interface{}
}
func (q *query) execute(ctx context.Context, db *sql.DB) error {
_, err := db.ExecContext(ctx, q.stmt, q.args...)
return errors.Wrap(err, `failed to execute query`)
}
func (q *query) dump(dst io.Writer) error {
fmt.Fprintf(dst, "%s;", q.stmt)
if len(q.args) > 0 {
fmt.Fprintf(dst, "%v", q.args)
}
fmt.Fprintf(dst, "\n\n")
return nil
}
type queryList []*query
func queryListFromString(stmts string) queryList {
var l queryList
for _, stmt := range strings.Split(stmts, ";") {
stmt = strings.TrimSpace(stmt)
if len(stmt) == 0 {
continue
}
l.AppendStmt(stmt)
}
return l
}
func (l *queryList) AppendStmt(stmt string, args ...interface{}) {
*l = append(*l, &query{
stmt: stmt,
args: args,
})
}
func (l *queryList) dump(dst io.Writer) error {
for i, q := range *l {
if err := q.dump(dst); err != nil {
return errors.Wrapf(err, `failed to dump query %d`, i+1)
}
}
return nil
}
func (l *queryList) execute(ctx context.Context, db *sql.DB) error {
for i, q := range *l {
if err := q.execute(ctx, db); err != nil {
return errors.Wrapf(err, `failed to execute query %d`, i+1)
}
}
return nil
}