-
Notifications
You must be signed in to change notification settings - Fork 0
/
tablename_util.go
54 lines (47 loc) · 1.08 KB
/
tablename_util.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
package repo
import (
"fmt"
"reflect"
"strings"
)
var typeTableNameMap = make(map[string]string)
type TableName interface {
TableName() string
}
func registerTableName(tPtr *reflect.Type, tableName string) {
key := obtainTableNameMapKey(tPtr)
typeTableNameMap[key] = tableName
}
func obtainTableNameMapKey(tPtr *reflect.Type) string {
t := *tPtr
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return fmt.Sprintf("%s/%s", t.PkgPath(), t.Name())
}
func ObtainTableNameByEntityPtr(entityPtr interface{}) (tableName string) {
t := reflect.TypeOf(entityPtr).Elem()
tableName = ObtainTableNameByType(&t)
return
}
func ObtainTableNameByType(tPtr *reflect.Type) (tableName string) {
key := obtainTableNameMapKey(tPtr)
name, exists := typeTableNameMap[key]
if exists {
return name
}
t := *tPtr
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
valObj := reflect.New(t)
v, ok := valObj.Interface().(TableName)
if ok {
tableName = v.TableName()
registerTableName(tPtr, v.TableName())
return
}
tableName = strings.ToLower(t.Name())
registerTableName(tPtr, tableName)
return
}