-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmysql.go
172 lines (150 loc) · 4.74 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
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
// Package mysql wraps mysql driver as an adapter for REL.
//
// Usage:
//
// // open mysql connection.
// // note: `clientFoundRows=true` is required for update and delete to works correctly.
// adapter, err := mysql.Open("root@(127.0.0.1:3306)/rel_test?clientFoundRows=true&charset=utf8&parseTime=True&loc=Local")
// if err != nil {
// panic(err)
// }
// defer adapter.Close()
//
// // initialize REL's repo.
// repo := rel.New(adapter)
package mysql
import (
db "database/sql"
"fmt"
"strings"
"github.com/go-rel/rel"
"github.com/go-rel/sql"
"github.com/go-rel/sql/builder"
)
// MySQL adapter.
type MySQL struct {
sql.SQL
}
// Name of database type this adapter implements.
const Name string = "mysql"
// New mysql adapter using existing connection.
// Existing connection needs to be created with `clientFoundRows=true` options for update and delete to works correctly.
func New(database *db.DB) rel.Adapter {
var (
bufferFactory = builder.BufferFactory{ArgumentPlaceholder: "?", BoolTrueValue: "true", BoolFalseValue: "false", Quoter: Quote{}, ValueConverter: ValueConvert{}}
filterBuilder = builder.Filter{}
queryBuilder = builder.Query{BufferFactory: bufferFactory, Filter: filterBuilder}
onConflictBuilder = builder.OnConflict{Statement: "ON DUPLICATE KEY", UpdateStatement: "UPDATE", UseValues: true}
InsertBuilder = builder.Insert{BufferFactory: bufferFactory, InsertDefaultValues: true, OnConflict: onConflictBuilder}
insertAllBuilder = builder.InsertAll{BufferFactory: bufferFactory, OnConflict: onConflictBuilder}
updateBuilder = builder.Update{BufferFactory: bufferFactory, Query: queryBuilder, Filter: filterBuilder}
deleteBuilder = builder.Delete{BufferFactory: bufferFactory, Query: queryBuilder, Filter: filterBuilder}
ddlBufferFactory = builder.BufferFactory{InlineValues: true, BoolTrueValue: "true", BoolFalseValue: "false", Quoter: Quote{}, ValueConverter: ValueConvert{}}
ddlQueryBuilder = builder.Query{BufferFactory: ddlBufferFactory, Filter: filterBuilder}
tableBuilder = builder.Table{BufferFactory: ddlBufferFactory, ColumnMapper: columnMapper, ColumnOptionsMapper: sql.ColumnOptionsMapper, DropKeyMapper: dropKeyMapper}
indexBuilder = builder.Index{BufferFactory: ddlBufferFactory, Query: ddlQueryBuilder, Filter: filterBuilder, DropIndexOnTable: true}
)
return &MySQL{
SQL: sql.SQL{
QueryBuilder: queryBuilder,
InsertBuilder: InsertBuilder,
InsertAllBuilder: insertAllBuilder,
UpdateBuilder: updateBuilder,
DeleteBuilder: deleteBuilder,
TableBuilder: tableBuilder,
IndexBuilder: indexBuilder,
Increment: getIncrement(database),
ErrorMapper: errorMapper,
DB: database,
},
}
}
var dbOpen = db.Open
// Open mysql connection using dsn.
func Open(dsn string) (rel.Adapter, error) {
database, err := dbOpen("mysql", rewriteDsn(dsn))
return New(database), err
}
func rewriteDsn(dsn string) string {
// force clientFoundRows=true
// this allows not found record check when updating a record.
if strings.ContainsRune(dsn, '?') {
return dsn + "&clientFoundRows=true"
}
return dsn + "?clientFoundRows=true"
}
// MustOpen mysql connection using dsn.
func MustOpen(dsn string) rel.Adapter {
adapter, err := Open(dsn)
if err != nil {
panic(err)
}
return adapter
}
// Name of database adapter.
func (MySQL) Name() string {
return Name
}
func getIncrement(database *db.DB) int {
var (
variable string
increment int
)
if database != nil {
err := database.QueryRow("SHOW VARIABLES LIKE 'auto_increment_increment';").Scan(&variable, &increment)
if err != nil {
panic(err)
}
}
return increment
}
func errorMapper(err error) error {
if err == nil {
return nil
}
var (
msg = err.Error()
errCodeSep = ':'
errCodeIndex = strings.IndexRune(msg, errCodeSep)
errStateSep = '('
errStateIndex = -1
)
if errCodeIndex < 0 {
errCodeIndex = 0
}
errStateIndex = strings.IndexRune(msg[:errCodeIndex], errStateSep)
errStateIndex--
if errStateIndex < 0 {
errStateIndex = errCodeIndex
}
switch (msg[:errCodeIndex])[:errStateIndex] {
case "Error 1062":
return rel.ConstraintError{
Key: sql.ExtractString(msg, "key '", "'"),
Type: rel.UniqueConstraint,
Err: err,
}
case "Error 1451", "Error 1452":
return rel.ConstraintError{
Key: sql.ExtractString(msg, "CONSTRAINT `", "`"),
Type: rel.ForeignKeyConstraint,
Err: err,
}
default:
return err
}
}
func columnMapper(column *rel.Column) (string, int, int) {
switch column.Type {
case rel.JSON:
return "JSON", 0, 0
default:
return sql.ColumnMapper(column)
}
}
func dropKeyMapper(typ rel.KeyType) string {
if typ == rel.ForeignKey {
return "FOREIGN KEY"
}
panic(fmt.Sprintf("drop key: unsupported key type `%s`", typ))
}