Debian Codegraph @

schema/naming.go

raw
1 package schema
2
3 import (
4 "crypto/sha1"
5 "encoding/hex"
6 "regexp"
7 "strings"
8 "unicode/utf8"
9
10 "github.com/jinzhu/inflection"
11 "golang.org/x/text/cases"
12 "golang.org/x/text/language"
13 )
14
15 // Namer namer interface
16 type Namer interface {
17 TableName(table string) string
18 SchemaName(table string) string
19 ColumnName(table, column string) string
20 JoinTableName(joinTable string) string
21 RelationshipFKName(Relationship) string
22 CheckerName(table, column string) string
23 IndexName(table, column string) string
24 UniqueName(table, column string) string
25 }
26
27 // Replacer replacer interface like strings.Replacer
28 type Replacer interface {
29 Replace(name string) string
30 }
31
32 var _ Namer = (*NamingStrategy)(nil)
33
34 // NamingStrategy tables, columns naming strategy
35 type NamingStrategy struct {
36 TablePrefix string
37 SingularTable bool
38 NameReplacer Replacer
39 NoLowerCase bool
40 IdentifierMaxLength int
41 }
42
43 // TableName convert string to table name
44 func (ns NamingStrategy) TableName(str string) string {
45 if ns.SingularTable {
46 return ns.TablePrefix + ns.toDBName(str)
47 }
48 return ns.TablePrefix + inflection.Plural(ns.toDBName(str))
49 }
50
51 // SchemaName generate schema name from table name, don't guarantee it is the reverse value of TableName
52 func (ns NamingStrategy) SchemaName(table string) string {
53 table = strings.TrimPrefix(table, ns.TablePrefix)
54
55 if ns.SingularTable {
56 return ns.toSchemaName(table)
57 }
58 return ns.toSchemaName(inflection.Singular(table))
59 }
60
61 // ColumnName convert string to column name
62 func (ns NamingStrategy) ColumnName(table, column string) string {
63 return ns.toDBName(column)
64 }
65
66 // JoinTableName convert string to join table name
67 func (ns NamingStrategy) JoinTableName(str string) string {
68 if !ns.NoLowerCase && strings.ToLower(str) == str {
69 return ns.TablePrefix + str
70 }
71
72 if ns.SingularTable {
73 return ns.TablePrefix + ns.toDBName(str)
74 }
75 return ns.TablePrefix + inflection.Plural(ns.toDBName(str))
76 }
77
78 // RelationshipFKName generate fk name for relation
79 func (ns NamingStrategy) RelationshipFKName(rel Relationship) string {
80 return ns.formatName("fk", rel.Schema.Table, ns.toDBName(rel.Name))
81 }
82
83 // CheckerName generate checker name
84 func (ns NamingStrategy) CheckerName(table, column string) string {
85 return ns.formatName("chk", table, column)
86 }
87
88 // IndexName generate index name
89 func (ns NamingStrategy) IndexName(table, column string) string {
90 return ns.formatName("idx", table, ns.toDBName(column))
91 }
92
93 // UniqueName generate unique constraint name
94 func (ns NamingStrategy) UniqueName(table, column string) string {
95 return ns.formatName("uni", table, ns.toDBName(column))
96 }
97
98 func (ns NamingStrategy) formatName(prefix, table, name string) string {
99 formattedName := strings.ReplaceAll(strings.Join([]string{
100 prefix, table, name,
101 }, "_"), ".", "_")
102
103 if ns.IdentifierMaxLength == 0 {
104 ns.IdentifierMaxLength = 64
105 }
106
107 if utf8.RuneCountInString(formattedName) > ns.IdentifierMaxLength {
108 h := sha1.New()
109 h.Write([]byte(formattedName))
110 bs := h.Sum(nil)
111
112 formattedName = formattedName[0:ns.IdentifierMaxLength-8] + hex.EncodeToString(bs)[:8]
113 }
114 return formattedName
115 }
116
117 var (
118 // https://github.com/golang/lint/blob/master/lint.go#L770
119 commonInitialisms = []string{"API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA", "SMTP", "SSH", "TLS", "TTL", "UID", "UI", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XSRF", "XSS"}
120 commonInitialismsReplacer *strings.Replacer
121 )
122
123 func init() {
124 commonInitialismsForReplacer := make([]string, 0, len(commonInitialisms))
125 for _, initialism := range commonInitialisms {
126 commonInitialismsForReplacer = append(commonInitialismsForReplacer, initialism, cases.Title(language.Und).String(initialism))
127 }
128 commonInitialismsReplacer = strings.NewReplacer(commonInitialismsForReplacer...)
129 }
130
131 func (ns NamingStrategy) toDBName(name string) string {
132 if name == "" {
133 return ""
134 }
135
136 if ns.NameReplacer != nil {
137 tmpName := ns.NameReplacer.Replace(name)
138
139 if tmpName == "" {
140 return name
141 }
142
143 name = tmpName
144 }
145
146 if ns.NoLowerCase {
147 return name
148 }
149
150 var (
151 value = commonInitialismsReplacer.Replace(name)
152 buf strings.Builder
153 lastCase, nextCase, nextNumber bool // upper case == true
154 curCase = value[0] <= 'Z' && value[0] >= 'A'
155 )
156
157 for i, v := range value[:len(value)-1] {
158 nextCase = value[i+1] <= 'Z' && value[i+1] >= 'A'
159 nextNumber = value[i+1] >= '0' && value[i+1] <= '9'
160
161 if curCase {
162 if lastCase && (nextCase || nextNumber) {
163 buf.WriteRune(v + 32)
164 } else {
165 if i > 0 && value[i-1] != '_' && value[i+1] != '_' {
166 buf.WriteByte('_')
167 }
168 buf.WriteRune(v + 32)
169 }
170 } else {
171 buf.WriteRune(v)
172 }
173
174 lastCase = curCase
175 curCase = nextCase
176 }
177
178 if curCase {
179 if !lastCase && len(value) > 1 {
180 buf.WriteByte('_')
181 }
182 buf.WriteByte(value[len(value)-1] + 32)
183 } else {
184 buf.WriteByte(value[len(value)-1])
185 }
186 ret := buf.String()
187 return ret
188 }
189
190 func (ns NamingStrategy) toSchemaName(name string) string {
191 result := strings.ReplaceAll(cases.Title(language.Und, cases.NoLower).String(strings.ReplaceAll(name, "_", " ")), " ", "")
192 for _, initialism := range commonInitialisms {
193 result = regexp.MustCompile(cases.Title(language.Und, cases.NoLower).String(strings.ToLower(initialism))+"([A-Z]|$|_)").ReplaceAllString(result, initialism+"$1")
194 }
195 return result
196 }