-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdb.go
341 lines (287 loc) · 7.94 KB
/
db.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
336
337
338
339
340
341
package entity
import (
"context"
"database/sql"
"fmt"
"strings"
"sync"
"github.com/jmoiron/sqlx"
)
const (
commandSelect = "select"
commandInsert = "insert"
commandUpdate = "update"
commandDelete = "delete"
driverMysql = "mysql"
driverPostgres = "postgres"
driverSqlite3 = "sqlite3"
)
var (
selectStatements = &sync.Map{}
insertStatements = &sync.Map{}
updateStatements = &sync.Map{}
deleteStatements = &sync.Map{}
driverAlias = map[string]string{
"pgx": driverPostgres,
"sqlite": driverSqlite3,
}
// interface assert
_ DB = (*sqlx.DB)(nil)
_ DB = (*sqlx.Tx)(nil)
)
// DB 数据库接口
// sqlx.DB 和 sqlx.Tx 公共方法
type DB interface {
sqlx.Queryer
sqlx.QueryerContext
sqlx.Execer
sqlx.ExecerContext
sqlx.Preparer
sqlx.PreparerContext
Get(dest interface{}, query string, args ...interface{}) error
GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
Select(dest interface{}, query string, args ...interface{}) error
SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
NamedExec(query string, arg interface{}) (sql.Result, error)
NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
NamedQuery(query string, arg interface{}) (*sqlx.Rows, error)
PrepareNamed(query string) (*sqlx.NamedStmt, error)
PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)
Preparex(query string) (*sqlx.Stmt, error)
PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, error)
DriverName() string
Rebind(string) string
BindNamed(string, interface{}) (string, []interface{}, error)
}
func dbDriver(db DB) string {
dv := db.DriverName()
if v, ok := driverAlias[dv]; ok {
return v
}
return dv
}
func isConflictError(err error, driver string) bool {
s := err.Error()
switch driver {
case driverPostgres:
return strings.Contains(s, "duplicate key value violates unique constraint")
case driverMysql:
return strings.Contains(s, "Duplicate entry")
case driverSqlite3:
return strings.Contains(s, "UNIQUE constraint failed")
}
return false
}
func doLoad(ctx context.Context, ent Entity, db DB) error {
md, err := getMetadata(ent)
if err != nil {
return fmt.Errorf("get metadata, %w", err)
}
stmt := getStatement(commandSelect, md, dbDriver(db))
rows, err := sqlx.NamedQueryContext(ctx, db, stmt, ent)
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return sql.ErrNoRows
}
if err := rows.StructScan(ent); err != nil {
return fmt.Errorf("scan struct, %w", err)
}
return rows.Err()
}
func doInsert(ctx context.Context, ent Entity, db DB) (int64, error) {
md, err := getMetadata(ent)
if err != nil {
return 0, fmt.Errorf("get metadata, %w", err)
}
stmt := getStatement(commandInsert, md, dbDriver(db))
if md.hasReturningInsert {
rows, err := sqlx.NamedQueryContext(ctx, db, stmt, ent)
if err != nil {
return 0, err
}
defer rows.Close()
if !rows.Next() {
return 0, sql.ErrNoRows
}
if err := rows.StructScan(ent); err != nil {
return 0, fmt.Errorf("scan struct, %w", err)
}
return 0, rows.Err()
}
result, err := db.NamedExecContext(ctx, stmt, ent)
if err != nil {
return 0, err
}
// postgresql不支持LastInsertId特性
if dbDriver(db) == driverPostgres {
return 0, nil
}
lastID, err := result.LastInsertId()
if err != nil {
return 0, fmt.Errorf("get last insert id, %w", err)
}
return lastID, nil
}
func doUpdate(ctx context.Context, ent Entity, db DB) error {
md, err := getMetadata(ent)
if err != nil {
return fmt.Errorf("get metadata, %w", err)
}
stmt := getStatement(commandUpdate, md, dbDriver(db))
if md.hasReturningUpdate {
rows, err := sqlx.NamedQueryContext(ctx, db, stmt, ent)
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return sql.ErrNoRows
}
if err := rows.StructScan(ent); err != nil {
return fmt.Errorf("scan struct, %w", err)
}
return rows.Err()
}
_, err = db.NamedExecContext(ctx, stmt, ent)
return err
}
func doDelete(ctx context.Context, ent Entity, db DB) error {
md, err := getMetadata(ent)
if err != nil {
return fmt.Errorf("get metadata, %w", err)
}
stmt := getStatement(commandDelete, md, dbDriver(db))
_, err = db.NamedExecContext(ctx, stmt, ent)
return err
}
func getStatement(cmd string, md *Metadata, driver string) string {
var (
m *sync.Map
fn func(*Metadata, string) string
)
switch cmd {
case commandSelect:
m = selectStatements
fn = newSelectStatement
case commandInsert:
m = insertStatements
fn = newInsertStatement
case commandUpdate:
m = updateStatements
fn = newUpdateStatement
case commandDelete:
m = deleteStatements
fn = newDeleteStatement
default:
panic(fmt.Errorf("unimplemented command %q", cmd))
}
if v, ok := m.Load(md.Type); ok {
return v.(string)
}
stmt := fn(md, driver)
m.Store(md.Type, stmt)
return stmt
}
func newSelectStatement(md *Metadata, driver string) string {
columns := []string{}
for _, col := range md.Columns {
columns = append(columns, quoteColumn(col.DBField, driver))
}
stmt := fmt.Sprintf("SELECT %s FROM %s WHERE", strings.Join(columns, ", "), quoteIdentifier(md.TableName, driver))
for i, col := range md.PrimaryKeys {
if i == 0 {
stmt += fmt.Sprintf(" %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
} else {
stmt += fmt.Sprintf(" AND %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
}
}
stmt += " LIMIT 1"
return stmt
}
func newInsertStatement(md *Metadata, driver string) string {
columns := []string{}
returnings := []string{}
placeholder := []string{}
for _, col := range md.Columns {
c := quoteColumn(col.DBField, driver)
if col.ReturningInsert {
returnings = append(returnings, c)
} else if !col.AutoIncrement {
columns = append(columns, c)
placeholder = append(placeholder, fmt.Sprintf(":%s", col.DBField))
}
}
stmt := fmt.Sprintf(
"INSERT INTO %s (%s) VALUES (%s)",
quoteIdentifier(md.TableName, driver),
strings.Join(columns, ", "),
strings.Join(placeholder, ", "),
)
if len(returnings) > 0 {
stmt += fmt.Sprintf(" RETURNING %s", strings.Join(returnings, ", "))
}
return stmt
}
func newUpdateStatement(md *Metadata, driver string) string {
returnings := []string{}
stmt := fmt.Sprintf("UPDATE %s SET", quoteIdentifier(md.TableName, driver))
set := false
for _, col := range md.Columns {
if col.ReturningUpdate {
returnings = append(returnings, quoteColumn(col.DBField, driver))
} else if !col.RefuseUpdate {
if set {
stmt += fmt.Sprintf(", %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
} else {
stmt += fmt.Sprintf(" %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
set = true
}
}
}
for i, col := range md.PrimaryKeys {
if i == 0 {
stmt += fmt.Sprintf(" WHERE %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
} else {
stmt += fmt.Sprintf(" AND %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
}
}
if len(returnings) > 0 {
stmt += fmt.Sprintf(" RETURNING %s", strings.Join(returnings, ", "))
}
return stmt
}
func newDeleteStatement(md *Metadata, driver string) string {
stmt := fmt.Sprintf("DELETE FROM %s WHERE", quoteIdentifier(md.TableName, driver))
for i, col := range md.PrimaryKeys {
if i == 0 {
stmt += fmt.Sprintf(" %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
} else {
stmt += fmt.Sprintf(" AND %s = :%s", quoteColumn(col.DBField, driver), col.DBField)
}
}
return stmt
}
func quoteColumn(name string, driver string) string {
if driver == driverMysql {
return fmt.Sprintf("`%s`", name)
}
return fmt.Sprintf("%q", name)
}
func quoteIdentifier(name string, driver string) string {
symbol := `"`
if driver == driverMysql {
symbol = "`"
}
result := []string{}
name = strings.ReplaceAll(name, symbol, "")
for _, s := range strings.Split(name, ".") {
if s != "*" {
s = fmt.Sprintf("%s%s%s", symbol, s, symbol)
}
result = append(result, s)
}
return strings.Join(result, ".")
}