add Smap comment and modify testcase

This commit is contained in:
theoneLee 2019-10-15 11:38:35 +08:00
parent 6fe19d9611
commit d87621ff2c
2 changed files with 35 additions and 41 deletions

View File

@ -66,6 +66,7 @@ func ToColumnName(name string) string {
return TheNamingStrategy.ColumnName(name)
}
// mapping cache map
var Smap = newSafeMap()
func defaultNamer(name string) string {

View File

@ -32,11 +32,40 @@ func TestTheNamingStrategy(t *testing.T) {
func TestAddNamingStrategy(t *testing.T) {
// users can set their custom namer
custom := &gorm.NamingStrategy{
Column: CustomNamer,
}
gorm.AddNamingStrategy(custom)
// users can set their custom namer and use `Smap` to cache result
gorm.AddNamingStrategy(&gorm.NamingStrategy{
Column: func(name string) string {
// set `smap` public access and users can use it to cache
if v := gorm.Smap.Get(name); v != "" {
return v
}
const (
//lower = false
upper = true
)
var (
value = name
buf = bytes.NewBufferString("")
currCase bool
)
for i, v := range value {
currCase = bool(value[i] >= 'A' && value[i] <= 'Z')
if i == 0 && currCase == upper {
buf.WriteRune(v + 32)
} else {
buf.WriteRune(v)
}
}
s := buf.String()
gorm.Smap.Set(name, s)
return s
},
})
// test
cases := []struct {
@ -44,10 +73,6 @@ func TestAddNamingStrategy(t *testing.T) {
namer gorm.Namer
expected string
}{
{name: "auth", expected: "auth", namer: gorm.TheNamingStrategy.DB},
{name: "userRestrictions", expected: "user_restrictions", namer: gorm.TheNamingStrategy.Table},
{name: "clientID", expected: "clientID", namer: gorm.TheNamingStrategy.Column},
{name: "Client0ID", expected: "client0ID", namer: gorm.TheNamingStrategy.Column},
{name: "_Client_ID_", expected: "_Client_ID_", namer: gorm.TheNamingStrategy.Column},
}
@ -63,38 +88,6 @@ func TestAddNamingStrategy(t *testing.T) {
}
func CustomNamer(name string) string {
// set `smap` public access and users can use it to cache
if v := gorm.Smap.Get(name); v != "" {
return v
}
const (
lower = false
upper = true
)
var (
value = name
buf = bytes.NewBufferString("")
currCase bool
)
for i, v := range value {
currCase = bool(value[i] >= 'A' && value[i] <= 'Z')
if i == 0 && currCase == upper {
buf.WriteRune(v + 32)
} else {
buf.WriteRune(v)
}
}
s := buf.String()
gorm.Smap.Set(name, s)
return s
}
func TestNamingStrategy(t *testing.T) {
dbNameNS := func(name string) string {