improve debug sql with arguments auto bound

This commit is contained in:
John 2019-08-26 20:57:37 +08:00
parent b7f67e3162
commit d3a2bef9ba
3 changed files with 26 additions and 9 deletions

View File

@ -135,7 +135,6 @@ type Sql struct {
Error error // 执行结果(nil为成功)
Start int64 // 执行开始时间(毫秒)
End int64 // 执行结束时间(毫秒)
Func string // 执行方法
}
// 返回数据表记录值

View File

@ -79,12 +79,7 @@ func (bs *dbBase) PrintQueriedSqls() {
// 打印SQL对象(仅在debug=true时有效)
func (bs *dbBase) printSql(v *Sql) {
s := fmt.Sprintf("%s, %v, %s, %s, %d ms, %s", v.Sql, v.Args,
gtime.NewFromTimeStamp(v.Start).Format("Y-m-d H:i:s.u"),
gtime.NewFromTimeStamp(v.End).Format("Y-m-d H:i:s.u"),
v.End-v.Start,
v.Func,
)
s := fmt.Sprintf("[%d ms] %s", v.End-v.Start, bindArgsToQuery(v.Sql, v.Args))
if v.Error != nil {
s += "\nError: " + v.Error.Error()
bs.logger.StackWithFilter(gPATH_FILTER_KEY).Error(s)
@ -385,7 +380,7 @@ func (bs *dbBase) doInsert(link dbLink, table string, data interface{}, option i
charL, k, charR,
)
}
updateStr = fmt.Sprintf(" ON DUPLICATE KEY UPDATE %s", updateStr)
updateStr = fmt.Sprintf("ON DUPLICATE KEY UPDATE %s", updateStr)
}
if link == nil {
if link, err = bs.db.Master(); err != nil {
@ -485,7 +480,7 @@ func (bs *dbBase) doBatchInsert(link dbLink, table string, list interface{}, opt
charL, k, charR,
)
}
updateStr = fmt.Sprintf(" ON DUPLICATE KEY UPDATE %s", updateStr)
updateStr = fmt.Sprintf("ON DUPLICATE KEY UPDATE %s", updateStr)
}
// 构造批量写入数据格式(注意map的遍历是无序的)
batchNum := gDEFAULT_BATCH_NUM

View File

@ -169,6 +169,29 @@ func structToMap(obj interface{}) map[string]interface{} {
return data
}
// 将参数绑定到SQL语句中仅用于调试打印。
func bindArgsToQuery(query string, args []interface{}) string {
index := -1
newQuery, _ := gregex.ReplaceStringFunc(`\?`, query, func(s string) string {
index++
if len(args) > index {
rv := reflect.ValueOf(args[index])
kind := rv.Kind()
if kind == reflect.Ptr {
rv = rv.Elem()
kind = rv.Kind()
}
switch kind {
case reflect.String, reflect.Map, reflect.Slice, reflect.Array:
return "'" + gconv.String(args[index]) + "'"
}
return gconv.String(args[index])
}
return s
})
return newQuery
}
// 使用递归的方式将map键值对映射到struct对象上注意参数<pointer>是一个指向struct的指针。
func mapToStruct(data map[string]interface{}, pointer interface{}) error {
return gconv.StructDeep(data, pointer)