-
Notifications
You must be signed in to change notification settings - Fork 0
/
execute.go
302 lines (281 loc) · 7.46 KB
/
execute.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
package db
import (
"context"
"database/sql"
"fmt"
"github.com/team-ide/go-dialect/dialect"
"github.com/team-ide/go-dialect/worker"
"github.com/team-ide/go-tool/util"
"go.uber.org/zap"
"strings"
"time"
)
type ExecuteOptions struct {
SelectDataMax int `json:"selectDataMax"`
}
type executeTask struct {
config Config
databaseType *DatabaseType
dia dialect.Dialect
*Param
ownerName string
*ExecuteOptions
}
func (this_ *executeTask) run(sqlContent string) (executeList []map[string]interface{}, errStr string, err error) {
var executeData map[string]interface{}
var query func(query string, args ...any) (*sql.Rows, error)
var exec func(query string, args ...any) (sql.Result, error)
workDb, err := newWorkDb(this_.databaseType, this_.config, this_.ExecUsername, this_.ExecPassword, this_.ownerName)
if err != nil {
util.Logger.Error("ExecuteSQL new db pool error", zap.Error(err))
return
}
defer func() {
_ = workDb.Close()
}()
cxt := context.Background()
conn, err := workDb.Conn(cxt)
if err != nil {
util.Logger.Error("ExecuteSQL Conn error", zap.Error(err))
return
}
defer func() {
_ = conn.Close()
}()
var hasError bool
if this_.OpenTransaction {
var tx *sql.Tx
tx, err = conn.BeginTx(cxt, nil)
if err != nil {
util.Logger.Error("ExecuteSQL BeginTx error", zap.Error(err))
return
}
defer func() {
if hasError {
err = tx.Rollback()
} else {
err = tx.Commit()
if err != nil && strings.Contains(err.Error(), "Not in transaction") {
err = nil
}
}
}()
query = tx.Query
exec = tx.Exec
} else {
query = func(query string, args ...any) (*sql.Rows, error) {
return conn.QueryContext(cxt, query, args...)
}
exec = func(query string, args ...any) (sql.Result, error) {
return conn.ExecContext(cxt, query, args...)
}
}
sqlList := this_.dia.SqlSplit(sqlContent)
for _, executeSql := range sqlList {
executeData, err = this_.execExecuteSQL(executeSql, query, exec)
executeList = append(executeList, executeData)
if err != nil {
util.Logger.Error("ExecuteSQL execExecuteSQL error", zap.Any("executeSql", executeSql), zap.Error(err))
errStr = err.Error()
hasError = true
if !this_.ErrorContinue {
return
}
err = nil
}
}
return
}
func (this_ *executeTask) execExecuteSQL(executeSql string,
query func(query string, args ...any) (*sql.Rows, error),
exec func(query string, args ...any) (sql.Result, error),
) (executeData map[string]interface{}, err error) {
executeData = map[string]interface{}{}
var startTime = util.GetNow()
executeData["sql"] = executeSql
executeData["startTime"] = util.GetFormatByTime(startTime)
// 如果 是 mysql 开启 profiling
if this_.dia.DialectType() == dialect.TypeMysql {
_, _ = exec("SET profiling = 1")
}
defer func() {
var endTime = time.Now()
executeData["endTime"] = util.GetFormatByTime(endTime)
executeData["isEnd"] = true
executeData["useTime"] = util.GetMilliByTime(endTime) - util.GetMilliByTime(startTime)
if err != nil {
executeData["error"] = err.Error()
}
// 如果 是 mysql 关闭 profiling
if this_.dia.DialectType() == dialect.TypeMysql {
executeData["profiling"], _ = queryProfiling(query)
_, _ = exec("SET profiling = 0")
}
}()
str := strings.ToLower(executeSql)
if strings.HasPrefix(str, "select") ||
strings.HasPrefix(str, "show") ||
strings.HasPrefix(str, "desc") ||
strings.HasPrefix(str, "explain") {
executeData["isSelect"] = true
// 查询
var rows *sql.Rows
rows, err = query(executeSql)
if err != nil {
return
}
defer func() {
_ = rows.Close()
}()
var columnList []map[string]interface{}
var dataList []map[string]interface{}
var dataSize int
dataSize, columnList, dataList, err = RowsToListMap(rows, this_.SelectDataMax)
if err != nil {
return
}
executeData["columnList"] = columnList
executeData["dataSize"] = dataSize
executeData["dataList"] = dataList
} else if strings.HasPrefix(str, "insert") {
executeData["isInsert"] = true
var result sql.Result
result, err = exec(executeSql)
if err != nil {
return
}
executeData["rowsAffected"], _ = result.RowsAffected()
} else if strings.HasPrefix(str, "update") {
executeData["isUpdate"] = true
var result sql.Result
result, err = exec(executeSql)
if err != nil {
return
}
executeData["rowsAffected"], _ = result.RowsAffected()
} else if strings.HasPrefix(str, "delete") {
executeData["isDelete"] = true
var result sql.Result
result, err = exec(executeSql)
if err != nil {
return
}
executeData["rowsAffected"], _ = result.RowsAffected()
} else {
executeData["isExec"] = true
var result sql.Result
result, err = exec(executeSql)
if err != nil {
return
}
executeData["rowsAffected"], _ = result.RowsAffected()
}
return
}
func queryProfiling(query func(query string, args ...any) (*sql.Rows, error)) (profilingData map[string]interface{}, err error) {
profilingData = map[string]interface{}{}
var columnList []map[string]interface{}
var dataList []map[string]interface{}
// 查询
var rows *sql.Rows
rows, err = query("SHOW PROFILES")
if err != nil {
return
}
_, columnList, dataList, err = RowsToListMap(rows, 0)
_ = rows.Close()
if err != nil {
return
}
profilingData["profilesColumnList"] = columnList
profilingData["profilesDataList"] = dataList
for _, data := range dataList {
if data == nil || data["Query_ID"] == nil {
continue
}
rows, err = query("SHOW PROFILE CPU, BLOCK IO FOR QUERY " + util.GetStringValue(data["Query_ID"]))
if err != nil {
continue
}
_, columnList, dataList, err = RowsToListMap(rows, 0)
_ = rows.Close()
if err != nil {
return
}
data["profileColumnList"] = columnList
data["profileDataList"] = dataList
}
return
}
func RowsToListMap(rows *sql.Rows, selectDataMax int) (dataSize int, columnList []map[string]interface{}, dataList []map[string]interface{}, err error) {
var columnTypes []*sql.ColumnType
columnTypes, err = rows.ColumnTypes()
if err != nil {
return
}
if len(columnTypes) > 0 {
for _, columnType := range columnTypes {
column := map[string]interface{}{}
column["name"] = columnType.Name()
column["type"] = columnType.DatabaseTypeName()
columnList = append(columnList, column)
}
}
for rows.Next() {
if selectDataMax > 0 && dataSize >= selectDataMax {
dataSize++
continue
}
dataSize++
cache := worker.GetSqlValueCache(columnTypes) //临时存储每行数据
err = rows.Scan(cache...)
if err != nil {
return
}
item := make(map[string]interface{})
for index, data := range cache {
name := columnTypes[index].Name()
var v interface{}
switch tV := data.(type) {
case time.Time:
if tV.IsZero() {
v = nil
} else {
v = util.GetMilliByTime(tV)
}
default:
v = worker.GetSqlValue(columnTypes[index], data)
}
if v == nil {
item[name] = v
} else {
switch tV := v.(type) {
case time.Time:
if tV.IsZero() {
item[name] = nil
} else {
item[name] = util.GetMilliByTime(tV)
}
case float64:
if tV >= float64(9007199254740991) || tV <= float64(-9007199254740991) {
item[name] = fmt.Sprintf("%f", tV)
} else {
item[name] = tV
}
case int64:
if tV >= int64(9007199254740991) || tV <= int64(-9007199254740991) {
item[name] = fmt.Sprintf("%d", tV)
} else {
item[name] = tV
}
case int, int8, int16, int32:
item[name] = tV
default:
item[name] = fmt.Sprint(tV)
}
}
}
dataList = append(dataList, item)
}
return
}