forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialect_common.go
192 lines (166 loc) · 4.52 KB
/
dialect_common.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
package pop
import (
"bytes"
"database/sql"
"encoding/gob"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"strings"
"github.com/gobuffalo/pop/columns"
"github.com/gobuffalo/pop/logging"
"github.com/gofrs/uuid"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func init() {
gob.Register(uuid.UUID{})
}
type commonDialect struct {
ConnectionDetails *ConnectionDetails
}
func (commonDialect) Lock(fn func() error) error {
return fn()
}
func (commonDialect) Quote(key string) string {
parts := strings.Split(key, ".")
for i, part := range parts {
part = strings.Trim(part, `"`)
part = strings.TrimSpace(part)
parts[i] = fmt.Sprintf(`"%v"`, part)
}
return strings.Join(parts, ".")
}
func genericCreate(s store, model *Model, cols columns.Columns, quoter quotable) error {
keyType := model.PrimaryKeyType()
switch keyType {
case "int", "int64":
var id int64
w := cols.Writeable()
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", quoter.Quote(model.TableName()), w.QuotedString(quoter), w.SymbolizedString())
log(logging.SQL, query)
res, err := s.NamedExec(query, model.Value)
if err != nil {
return err
}
id, err = res.LastInsertId()
if err == nil {
model.setID(id)
}
if err != nil {
return err
}
return nil
case "UUID", "string":
if keyType == "UUID" {
if model.ID() == emptyUUID {
u, err := uuid.NewV4()
if err != nil {
return err
}
model.setID(u)
}
} else if model.ID() == "" {
return fmt.Errorf("missing ID value")
}
w := cols.Writeable()
w.Add("id")
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", quoter.Quote(model.TableName()), w.QuotedString(quoter), w.SymbolizedString())
log(logging.SQL, query)
stmt, err := s.PrepareNamed(query)
if err != nil {
return err
}
_, err = stmt.Exec(model.Value)
if err != nil {
if err := stmt.Close(); err != nil {
return errors.WithMessage(err, "failed to close statement")
}
return err
}
return errors.WithMessage(stmt.Close(), "failed to close statement")
}
return errors.Errorf("can not use %s as a primary key type!", keyType)
}
func genericUpdate(s store, model *Model, cols columns.Columns, quoter quotable) error {
stmt := fmt.Sprintf("UPDATE %s SET %s WHERE %s", quoter.Quote(model.TableName()), cols.Writeable().QuotedUpdateString(quoter), model.whereNamedID())
log(logging.SQL, stmt, model.ID())
_, err := s.NamedExec(stmt, model.Value)
if err != nil {
return err
}
return nil
}
func genericDestroy(s store, model *Model, quoter quotable) error {
stmt := fmt.Sprintf("DELETE FROM %s WHERE %s", quoter.Quote(model.TableName()), model.whereID())
_, err := genericExec(s, stmt, model.ID())
if err != nil {
return err
}
return nil
}
func genericExec(s store, stmt string, args ...interface{}) (sql.Result, error) {
log(logging.SQL, stmt, args...)
res, err := s.Exec(stmt, args...)
return res, err
}
func genericSelectOne(s store, model *Model, query Query) error {
sqlQuery, args := query.ToSQL(model)
log(logging.SQL, sqlQuery, args...)
err := s.Get(model.Value, sqlQuery, args...)
if err != nil {
return err
}
return nil
}
func genericSelectMany(s store, models *Model, query Query) error {
sqlQuery, args := query.ToSQL(models)
log(logging.SQL, sqlQuery, args...)
err := s.Select(models.Value, sqlQuery, args...)
if err != nil {
return err
}
return nil
}
func genericLoadSchema(deets *ConnectionDetails, migrationURL string, r io.Reader) error {
// Open DB connection on the target DB
db, err := sqlx.Open(deets.Dialect, migrationURL)
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("unable to load schema for %s", deets.Database))
}
defer db.Close()
// Get reader contents
contents, err := ioutil.ReadAll(r)
if err != nil {
return err
}
if len(contents) == 0 {
log(logging.Info, "schema is empty for %s, skipping", deets.Database)
return nil
}
_, err = db.Exec(string(contents))
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("unable to load schema for %s", deets.Database))
}
log(logging.Info, "loaded schema for %s", deets.Database)
return nil
}
func genericDumpSchema(deets *ConnectionDetails, cmd *exec.Cmd, w io.Writer) error {
log(logging.SQL, strings.Join(cmd.Args, " "))
bb := &bytes.Buffer{}
mw := io.MultiWriter(w, bb)
cmd.Stdout = mw
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
x := bytes.TrimSpace(bb.Bytes())
if len(x) == 0 {
return errors.Errorf("unable to dump schema for %s", deets.Database)
}
log(logging.Info, "dumped schema for %s", deets.Database)
return nil
}