forked from godoes/gorm-dameng
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dm.go
286 lines (246 loc) · 7.13 KB
/
dm.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
// 本方言包基于gorm v1.24.2开发,需要配合达梦数据库驱动使用
package dameng
import (
"database/sql"
"fmt"
"strings"
_ "github.com/godoes/gorm-dameng/dm8" // 引入dm数据库驱动包
"gorm.io/gorm" // 引入gorm v2包
"gorm.io/gorm/callbacks"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
"gorm.io/gorm/migrator"
"gorm.io/gorm/schema"
)
type Config struct {
DriverName string
DSN string
Conn gorm.ConnPool
DefaultStringSize uint
VarcharSizeIsCharLength bool // VARCHAR 类型大小是否为字符长度(默认为字节长度)
}
type Dialector struct {
*Config
}
var (
// CreateClauses create clauses
CreateClauses = []string{"INSERT", "VALUES", "ON CONFLICT"}
// QueryClauses query clauses
QueryClauses []string
// UpdateClauses update clauses
UpdateClauses = []string{"UPDATE", "SET", "WHERE", "ORDER BY", "LIMIT"}
// DeleteClauses delete clauses
DeleteClauses = []string{"DELETE", "FROM", "WHERE", "ORDER BY", "LIMIT"}
defaultDatetimePrecision = 3
)
func Open(dsn string) gorm.Dialector {
return &Dialector{Config: &Config{DSN: dsn}}
}
func New(config Config) gorm.Dialector {
return &Dialector{Config: &config}
}
func (d Dialector) Name() string {
return "dm"
}
func (d Dialector) Initialize(db *gorm.DB) (err error) {
if d.DriverName == "" {
d.DriverName = "dm"
}
if d.Conn != nil {
db.ConnPool = d.Conn
} else {
db.ConnPool, err = sql.Open(d.DriverName, d.DSN)
if err != nil {
return
}
}
// register callbacks
callbackConfig := &callbacks.Config{
CreateClauses: CreateClauses,
QueryClauses: QueryClauses,
UpdateClauses: UpdateClauses,
DeleteClauses: DeleteClauses,
}
callbacks.RegisterDefaultCallbacks(db, callbackConfig)
_ = db.Callback().Create().Replace("gorm:create", Create)
return
}
func (d Dialector) DefaultValueOf(*schema.Field) clause.Expression {
// return clause.Expr{SQL: "DEFAULT VALUES"}
// 和gorm v1不一样,gorm v1是 INSERT INTO table_name DEFAULT VALUES;
// gorm v2是 INSERT INTO table_name(C1, C2) VALUES(XX, NULL);
return clause.Expr{SQL: "NULL"}
}
func (d Dialector) Migrator(db *gorm.DB) gorm.Migrator {
return Migrator{
Migrator: migrator.Migrator{
Config: migrator.Config{
DB: db,
Dialector: d,
CreateIndexAfterCreateTable: true,
},
},
Dialector: d,
}
}
func (d Dialector) BindVarTo(writer clause.Writer, _ *gorm.Statement, _ interface{}) {
_ = writer.WriteByte('?')
}
func (d Dialector) QuoteTo(writer clause.Writer, str string) {
var (
underQuoted, selfQuoted bool
continuousBacktick int8
shiftDelimiter int8
)
for _, v := range []byte(str) {
switch v {
case '"':
continuousBacktick++
if continuousBacktick == 2 {
_, _ = writer.WriteString(`""`)
continuousBacktick = 0
}
case '.':
if continuousBacktick > 0 || !selfQuoted {
shiftDelimiter = 0
underQuoted = false
continuousBacktick = 0
_ = writer.WriteByte('"')
}
_ = writer.WriteByte(v)
continue
default:
if shiftDelimiter-continuousBacktick <= 0 && !underQuoted {
_ = writer.WriteByte('"')
underQuoted = true
if selfQuoted = continuousBacktick > 0; selfQuoted {
continuousBacktick -= 1
}
}
for ; continuousBacktick > 0; continuousBacktick -= 1 {
_, _ = writer.WriteString(`""`)
}
_ = writer.WriteByte(v)
}
shiftDelimiter++
}
if continuousBacktick > 0 && !selfQuoted {
_, _ = writer.WriteString(`""`)
}
_ = writer.WriteByte('"')
}
func (d Dialector) Explain(sql string, vars ...interface{}) string {
return logger.ExplainSQL(sql, nil, `'`, vars...)
}
func (d Dialector) DataTypeOf(field *schema.Field) string {
switch field.DataType {
case schema.Bool:
return "BIT"
case schema.Int, schema.Uint:
return d.getSchemaIntAndUnitType(field)
case schema.Float:
return d.getSchemaFloatType(field)
case schema.String:
return d.getSchemaStringType(field)
case schema.Time:
return d.getSchemaTimeType(field)
case schema.Bytes:
return d.getSchemaBytesType(field)
default:
return d.getSchemaCustomType(field)
// what oracle do:
//notNull, _ := field.TagSettings["NOT NULL"]
//unique, _ := field.TagSettings["UNIQUE"]
//additionalType := fmt.Sprintf("%s %s", notNull, unique)
//if value, ok := field.TagSettings["DEFAULT"]; ok {
// additionalType = fmt.Sprintf("%s %s %s%s", "DEFAULT", value, additionalType, func() string {
// if value, ok := field.TagSettings["COMMENT"]; ok {
// return " COMMENT " + value
// }
// return ""
// }())
//}
//sqlType = fmt.Sprintf("%v %v", sqlType, additionalType)
}
}
func (d Dialector) getSchemaIntAndUnitType(field *schema.Field) string {
constraint := func(sqlType string) string {
//if field.NotNull {
// sqlType += " NOT NULL"
//}
if field.AutoIncrement {
sqlType += " IDENTITY(1,1)"
}
return sqlType
}
switch {
case field.Size <= 8:
return constraint("TINYINT")
case field.Size <= 16:
return constraint("SMALLINT")
case field.Size <= 32:
return constraint("INT")
default:
return constraint("BIGINT")
}
}
func (d Dialector) getSchemaFloatType(field *schema.Field) string {
if field.Precision > 0 {
return fmt.Sprintf("DECIMAL(%d, %d)", field.Precision, field.Scale)
}
return "DOUBLE"
}
func (d Dialector) getSchemaStringType(field *schema.Field) string {
size := field.Size
if size == 0 {
if d.DefaultStringSize > 0 {
size = int(d.DefaultStringSize)
} else {
hasIndex := field.TagSettings["INDEX"] != "" || field.TagSettings["UNIQUE"] != ""
// TEXT, GEOMETRY or JSON column can't have a default value
if field.PrimaryKey || field.HasDefaultValue || hasIndex {
size = 255 // mysql:191, dm not support utf8mb4
}
}
}
if size == 0 {
if d.VarcharSizeIsCharLength {
return "VARCHAR(8188 CHAR)" // 字符长度(8188 * 4)
}
return "VARCHAR" // 如果未指定长度,缺省为 8188 字节
} else if size < 0 || size >= 32768 {
return "CLOB" // 长度超过 32767,使用 CLOB(TEXT)
} else {
// VARCHAR 可以指定一个不超过 32767 的正整数作为字节或字符长度
if d.VarcharSizeIsCharLength {
return fmt.Sprintf("VARCHAR(%d CHAR)", size) // 字符长度(size * 4)
}
return fmt.Sprintf("VARCHAR(%d)", size) // 字节长度
}
}
func (d Dialector) getSchemaTimeType(_ *schema.Field) string {
sqlType := "TIMESTAMP WITH TIME ZONE"
//if field.NotNull || field.PrimaryKey {
// sqlType += " NOT NULL"
//}
return sqlType
}
func (d Dialector) getSchemaBytesType(field *schema.Field) string {
if field.Size > 0 && field.Size < 32768 {
return fmt.Sprintf("VARBINARY(%d)", field.Size)
}
return "BLOB"
}
func (d Dialector) getSchemaCustomType(field *schema.Field) string {
sqlType := string(field.DataType)
if field.AutoIncrement && !strings.Contains(strings.ToLower(sqlType), " auto_increment") && !strings.Contains(strings.ToLower(sqlType), " identity") {
sqlType += " IDENTITY(1,1)"
}
return sqlType
}
func (d Dialector) SavePoint(tx *gorm.DB, name string) error {
return tx.Exec("SAVEPOINT " + name).Error
}
func (d Dialector) RollbackTo(tx *gorm.DB, name string) error {
return tx.Exec("ROLLBACK TO SAVEPOINT " + name).Error
}