/
sql_reflect.go
37 lines (30 loc) · 882 Bytes
/
sql_reflect.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
package crud
import (
"git.rjp.is/rjp/crud/meta"
"github.com/azer/snakecase"
"github.com/jinzhu/inflection"
)
// Find out what given interface should be called in the database. It first looks up
// if a table name was explicitly specified (see "table-name" option), or automatically
// generates a plural name from the name of the struct type.
func SQLTableNameOf(any interface{}) string {
if customTableName, ok := lookupCustomTableName(any); ok {
return customTableName
}
return snakecase.SnakeCase(inflection.Plural(meta.TypeNameOf(any)))
}
func lookupCustomTableName(any interface{}) (string, bool) {
if meta.IsSlice(any) {
any = meta.CreateElement(any).Interface()
}
fields, err := GetFieldsOf(any)
if err != nil {
return "", false
}
for _, f := range fields {
if len(f.SQL.TableName) > 0 {
return f.SQL.TableName, true
}
}
return "", false
}