db/util.go

96 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-04-12 15:58:25 +08:00
package db
import (
"reflect"
"regexp"
"strings"
)
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func ToSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
func ExtractStruct(target interface{}) map[string]interface{} {
tv := reflect.Indirect(reflect.ValueOf(target))
tt := tv.Type()
result := make(map[string]interface{}, tv.NumField())
for i := 0; i < tv.NumField(); i++ {
key := ToSnakeCase(tt.Field(i).Name)
result[key] = tv.Field(i).Interface()
}
return result
}
func InterfaceToSlice(param interface{}) []interface{} {
if p, ok := param.([]interface{}); ok {
return p
}
tv := reflect.Indirect(reflect.ValueOf(param))
var res []interface{}
if tv.Type().Kind() == reflect.Slice {
for i := 0; i < tv.Len(); i++ {
res = append(res, tv.Index(i).Interface())
}
} else {
panic("not slice")
}
return res
}
// addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。
// 预定义字符是:
// 单引号('
// 双引号("
// 反斜杠(\
func Addslashes(str string) string {
tmpRune := []rune{}
strRune := []rune(str)
for _, ch := range strRune {
switch ch {
case []rune{'\\'}[0], []rune{'"'}[0], []rune{'\''}[0]:
tmpRune = append(tmpRune, []rune{'\\'}[0])
tmpRune = append(tmpRune, ch)
default:
tmpRune = append(tmpRune, ch)
}
}
return string(tmpRune)
}
// stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。
func Stripslashes(str string) string {
dstRune := []rune{}
strRune := []rune(str)
strLenth := len(strRune)
for i := 0; i < strLenth; i++ {
if strRune[i] == []rune{'\\'}[0] {
i++
}
dstRune = append(dstRune, strRune[i])
}
return string(dstRune)
}
func MysqlRealEscapeString(value string) string {
var sb strings.Builder
for i := 0; i < len(value); i++ {
c := value[i]
switch c {
case '\\', 0, '\n', '\r', '\'', '"':
sb.WriteByte('\\')
sb.WriteByte(c)
case '\032':
sb.WriteByte('\\')
sb.WriteByte('Z')
default:
sb.WriteByte(c)
}
}
return sb.String()
}