-
Notifications
You must be signed in to change notification settings - Fork 27
/
tablenamer.go
81 lines (69 loc) · 1.71 KB
/
tablenamer.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package tablenamer
import (
"unicode"
"sync"
"github.com/samonzeweb/godb/tablenamer/plural"
)
// NamerFn function type is used set table naming function to build table name from struct's name
type NamerFn func(string, bool) string
// sCache is cache for ToSnakeCase function
var sCache = sync.Map{}
// Plural builds table name as plural form of struct's name
func Plural() NamerFn {
return func(name string, done bool) string {
if done {
return name
}
return plural.EnglishPluralization().Plural(name)
}
}
// Same builds table name same as struct's name
func Same() NamerFn {
return func(name string, done bool) string {
if done {
return name
}
return name
}
}
// Snake builds table name from struct's name in snake format
func Snake() NamerFn {
return func(name string, done bool) string {
if done {
return name
}
return ToSnakeCase(name)
}
}
// SnakePlural builds table name from struct's name in plural snake format
func SnakePlural() NamerFn {
return func(name string, done bool) string {
if done {
return name
}
return plural.EnglishPluralization().Plural(ToSnakeCase(name))
}
}
// ToSnakeCase converts a string to snake case, used for converting struct name to snake_case
func ToSnakeCase(s string) string {
if res, ok := sCache.Load(s); ok {
return res.(string)
}
in := []rune(s)
isLower := func(idx int) bool {
return idx >= 0 && idx < len(in) && unicode.IsLower(in[idx])
}
out := make([]rune, 0, len(in)+len(in)/2)
for i, r := range in {
if unicode.IsUpper(r) {
r = unicode.ToLower(r)
if i > 0 && in[i-1] != '_' && (isLower(i-1) || isLower(i+1)) {
out = append(out, '_')
}
}
out = append(out, r)
}
res := string(out)
sCache.Store(s, res)
return res
}