-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
282 lines (253 loc) · 6.44 KB
/
engine.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
package rorm
import (
"errors"
"log"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/kodekoding/rorm/lib"
"github.com/jmoiron/sqlx"
)
func (re *Engine) SetDB(db *sqlx.DB) {
re.db = db
}
func (re *Engine) GetDB() *sqlx.DB {
return re.db
}
func (re *Engine) GetPreparedValues() []interface{} {
return re.preparedValue
}
func (re *Engine) GetMultiPreparedValues() [][]interface{} {
return re.multiPreparedValue
}
func (re *Engine) Clear() {
re.clearField()
}
func (re *Engine) SetIsMultiRows(state bool) {
re.isMultiRows = state
}
// // New - init new RORM Engine
// func New(dbDriver, connectionURL string, tbPrefix ...string) *Engine {
// re := &Engine{}
// if err := re.Connect(dbDriver, connectionURL, tbPrefix...); err != nil {
// return nil
// }
// return re
// }
// New - init new RORM Engine
func New(cfg *DbConfig) (*Engine, error) {
var err error
re := &Engine{
config: cfg,
options: &DbOptions{},
}
re.connectionString, err = generateConnectionString(cfg)
if err != nil {
return nil, err
}
if err := re.Connect(cfg.Driver, re.connectionString); err != nil {
log.Println("Cannot Connect to DB: ", err.Error())
return nil, err
}
// set default for table case format
re.options.tbFormat = "snake"
re.syntaxQuote = "`"
if cfg.Driver != "mysql" {
re.syntaxQuote = "\""
}
return re, nil
}
func (re *Engine) GetConnectionString() string {
return re.connectionString
}
func generateConnectionString(cfg *DbConfig) (connectionString string, err error) {
if strings.TrimSpace(cfg.Driver) == "" || strings.TrimSpace(cfg.Host) == "" || strings.TrimSpace(cfg.Username) == "" || strings.TrimSpace(cfg.DbName) == "" {
err = errors.New("Config is not set correctly")
return
}
dbURL := &url.URL{
Scheme: cfg.Driver,
User: url.UserPassword(cfg.Username, cfg.Password),
Host: cfg.Host,
}
query := url.Values{}
dbURL.Path = cfg.DbName
switch cfg.Driver {
case "postgres":
query.Add("sslmode", "disable")
query.Add("search_path", "public")
if cfg.DbScheme != "" {
query.Set("search_path", cfg.DbScheme)
}
dbURL.Host += ":5432"
if cfg.Port != "" {
dbURL.Host = cfg.Host + ":" + cfg.Port
}
case "mysql":
if cfg.Protocol == "" {
cfg.Protocol = "tcp"
}
dbURL.Host += ":3306"
if cfg.Port != "" {
dbURL.Host = cfg.Host + ":" + cfg.Port
}
replacedStr := "@" + cfg.Protocol + "($1:$2)/"
rgx := regexp.MustCompile(`@([a-zA-Z0-9]+):([0-9]+)/`)
res := rgx.ReplaceAllString(dbURL.String(), replacedStr)
res = res[8:]
connectionString = res
return
case "sqlserver":
dbURL.Path = ""
if cfg.DbInstance != "" {
dbURL.Path = cfg.DbInstance
}
query.Add("database", cfg.DbName)
}
dbURL.RawQuery = query.Encode()
connectionString = dbURL.String()
return
}
func (re *Engine) extractTableName(data interface{}) reflect.Value {
dValue := reflect.ValueOf(data).Elem()
sdValue := dValue
if dValue.Kind() == reflect.Slice {
re.isMultiRows = true
re.multiPreparedValue = nil
for i := 0; i < dValue.Len(); i++ {
sdValue = dValue.Index(i)
re.preparedValue = nil
if i == dValue.Len()-1 {
break
}
if sdValue.Kind() == reflect.Ptr {
sdValue = sdValue.Elem()
}
for x := 0; x < sdValue.NumField(); x++ {
if _, valid := re.getAndValidateTag(sdValue, x); !valid {
continue
}
field := sdValue.Field(x)
re.preparedValue = append(re.preparedValue, field.Interface())
}
re.multiPreparedValue = append(re.multiPreparedValue, re.preparedValue)
}
}
tblName := ""
switch sdValue.Kind() {
case reflect.Ptr:
sdValue = sdValue.Elem()
tblName = sdValue.Type().Name()
case reflect.Slice:
sdType := dValue.Type()
re.tmpStruct = reflect.New(sdType.Elem()).Interface()
strName := sdType.String()
tblName = strName[strings.Index(strName, ".")+1:]
default:
sdType := sdValue.Type()
re.tmpStruct = reflect.New(sdType).Interface()
tblName = sdType.Name()
}
if re.options.tbFormat == "snake" {
re.tableName = lib.CamelToSnakeCase(tblName)
} else {
re.tableName = lib.SnakeToCamelCase(tblName)
}
// re.tableName = re.syntaxQuote + re.tableName + re.syntaxQuote
return sdValue
}
// Connect - connect to db Driver
func (re *Engine) Connect(dbDriver, connectionURL string) error {
var err error
re.db, err = sqlx.Open(dbDriver, connectionURL)
return err
}
func (re *Engine) getAndValidateTag(field reflect.Value, keyIndex int) (string, bool) {
fieldType := field.Type().Field(keyIndex)
fieldValue := field.Field(keyIndex)
colNameTag := ""
var valid bool
if colNameTag, valid = re.checkStructTag(fieldType.Tag, fieldValue); !valid {
return "", false
}
if colNameTag == "" {
colNameTag = fieldType.Name
}
return colNameTag, true
}
func (re *Engine) checkStructTag(tagField reflect.StructTag, fieldVal reflect.Value) (string, bool) {
colName := ""
if tagField.Get("json") == "" {
return colName, false
}
colName = strings.Split(tagField.Get("json"), ",")[0]
identifierTagArr := strings.Split(tagField.Get("rorm"), " ")
for _, val := range identifierTagArr {
switch val {
case "pk", "ai":
return colName, false
case "date":
if fieldVal.String() == "" {
return colName, false
}
}
}
return identifierTagArr[0], true
}
func (re *Engine) clearField() {
re.conditionBuilder = strings.Builder{}
re.columnBuilder = strings.Builder{}
re.orderByBuilder = strings.Builder{}
re.tableName = ""
re.limitBuilder = strings.Builder{}
re.joinBuilder = strings.Builder{}
re.isRaw = false
re.isBulk = false
re.isMultiRows = false
re.preparedValue = nil
re.multiPreparedValue = nil
re.counter = 0
re.bulkCounter = 0
re.updatedCol = nil
re.tmpStruct = nil
if re.stmt != nil {
re.stmt.Close()
}
}
func (re *Engine) StartBulkOptimized() {
re.bulkOptimized = true
re.bulkCounter = 0
}
func (re *Engine) StopBulkOptimized() {
re.bulkOptimized = false
re.clearField()
}
func (re *Engine) buildString() {
}
func (re *Engine) SetTableOptions(tbCaseFormat, tbPrefix string) {
re.options.tbFormat = tbCaseFormat
re.options.tbPrefix = tbPrefix
}
func (re *Engine) adjustPreparedParam(old string) string {
if strings.TrimSpace(re.config.Driver) != "mysql" {
replacement := ""
switch re.config.Driver {
case "postgres":
replacement = POSTGRES_PREPARED_PARAM
case "sqlserver":
replacement = MSSQL_PREPARED_PARAM
default:
replacement = ORACLE_PREPARED_PARAM
}
for {
if strings.Index(old, "?") == -1 {
break
}
re.counter++
old = strings.Replace(old, "?", replacement+strconv.Itoa(re.counter), 1)
}
}
return old
}