recommended to use magic const strings (#4059)

This commit is contained in:
heige 2021-02-07 10:09:32 +08:00 committed by GitHub
parent 3d3208ed60
commit ef5ef18d4a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 8 deletions

View File

@ -13,6 +13,12 @@ import (
"gorm.io/gorm/utils"
)
const (
tmFmtWithMS = "2006-01-02 15:04:05.999"
tmFmtZero = "0000-00-00 00:00:00"
nullStr = "NULL"
)
func isPrintable(s []byte) bool {
for _, r := range s {
if !unicode.IsPrint(rune(r)) {
@ -34,26 +40,26 @@ func ExplainSQL(sql string, numericPlaceholder *regexp.Regexp, escaper string, a
vars[idx] = strconv.FormatBool(v)
case time.Time:
if v.IsZero() {
vars[idx] = escaper + "0000-00-00 00:00:00" + escaper
vars[idx] = escaper + tmFmtZero + escaper
} else {
vars[idx] = escaper + v.Format("2006-01-02 15:04:05.999") + escaper
vars[idx] = escaper + v.Format(tmFmtWithMS) + escaper
}
case *time.Time:
if v != nil {
if v.IsZero() {
vars[idx] = escaper + "0000-00-00 00:00:00" + escaper
vars[idx] = escaper + tmFmtZero + escaper
} else {
vars[idx] = escaper + v.Format("2006-01-02 15:04:05.999") + escaper
vars[idx] = escaper + v.Format(tmFmtWithMS) + escaper
}
} else {
vars[idx] = "NULL"
vars[idx] = nullStr
}
case fmt.Stringer:
reflectValue := reflect.ValueOf(v)
if v != nil && reflectValue.IsValid() && ((reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil()) || reflectValue.Kind() != reflect.Ptr) {
vars[idx] = escaper + strings.Replace(fmt.Sprintf("%v", v), escaper, "\\"+escaper, -1) + escaper
} else {
vars[idx] = "NULL"
vars[idx] = nullStr
}
case driver.Valuer:
reflectValue := reflect.ValueOf(v)
@ -61,7 +67,7 @@ func ExplainSQL(sql string, numericPlaceholder *regexp.Regexp, escaper string, a
r, _ := v.Value()
convertParams(r, idx)
} else {
vars[idx] = "NULL"
vars[idx] = nullStr
}
case []byte:
if isPrintable(v) {
@ -78,7 +84,7 @@ func ExplainSQL(sql string, numericPlaceholder *regexp.Regexp, escaper string, a
default:
rv := reflect.ValueOf(v)
if v == nil || !rv.IsValid() || rv.Kind() == reflect.Ptr && rv.IsNil() {
vars[idx] = "NULL"
vars[idx] = nullStr
} else if valuer, ok := v.(driver.Valuer); ok {
v, _ = valuer.Value()
convertParams(v, idx)