-
Notifications
You must be signed in to change notification settings - Fork 16
/
mysql.go
79 lines (64 loc) · 1.59 KB
/
mysql.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
package polluter
import (
"database/sql"
"fmt"
"github.com/pkg/errors"
"github.com/romanyx/jwalk"
)
type mysqlEngine struct {
db *sql.DB
}
func (e mysqlEngine) exec(cmds []command) error {
tx, err := e.db.Begin()
if err != nil {
return errors.Wrap(err, "tx begin")
}
for _, c := range cmds {
if _, err := tx.Exec(c.q, c.args...); err != nil {
if rErr := tx.Rollback(); rErr != nil {
err = errors.Wrap(rErr, err.Error())
}
return errors.Wrap(err, "exec")
}
}
return errors.Wrap(tx.Commit(), "commit")
}
func (e mysqlEngine) build(obj jwalk.ObjectWalker) (commands, error) {
cmds := make(commands, 0)
if err := obj.Walk(func(table string, value interface{}) error {
if v, ok := value.(jwalk.ObjectsWalker); ok {
if err := v.Walk(func(obj jwalk.ObjectWalker) error {
values := make([]interface{}, 0)
insert := fmt.Sprintf("INSERT INTO `%s` (", table)
valuesStr := "("
first := true
if err := obj.Walk(func(field string, value interface{}) error {
if v, ok := value.(jwalk.Value); ok {
values = append(values, v.Interface())
if !first {
insert = insert + ", "
valuesStr = valuesStr + ", "
}
insert = fmt.Sprintf("%s`%s`", insert, field)
valuesStr = valuesStr + "?"
}
if first {
first = false
}
return nil
}); err != nil {
return err
}
insert = insert + ") VALUES " + valuesStr + ");"
cmds = append(cmds, command{insert, values})
return nil
}); err != nil {
return err
}
}
return nil
}); err != nil {
return nil, err
}
return cmds, nil
}