Do not call TableName function via interface{}.

If scope.Value impelemts table interface,
DefaultTableNameHandler is never called.
But, if scope.Value is a slice of Model,
DefaultTableNameHandler is called.
DefaultTableNameHandler should always be called.
This commit is contained in:
Masaki Yoshida 2017-11-22 11:25:55 +09:00
parent 3a9e91ab37
commit 1f896a6e82
2 changed files with 34 additions and 8 deletions

View File

@ -8,6 +8,7 @@ import (
"path/filepath" "path/filepath"
"reflect" "reflect"
"strconv" "strconv"
"sync"
"testing" "testing"
"time" "time"
@ -23,6 +24,7 @@ import (
var ( var (
DB *gorm.DB DB *gorm.DB
t1, t2, t3, t4, t5 time.Time t1, t2, t3, t4, t5 time.Time
mu sync.RWMutex
) )
func init() { func init() {
@ -262,6 +264,38 @@ func TestTableName(t *testing.T) {
DB.SingularTable(false) DB.SingularTable(false)
} }
func TestTableNameWithTableNameHandler(t *testing.T) {
mu.Lock()
orig := gorm.DefaultTableNameHandler
defer func() {
mu.Unlock()
gorm.DefaultTableNameHandler = orig
}()
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return "renamed_" + defaultTableName
}
if DB.NewScope(Cart{}).TableName() != "renamed_shopping_cart" {
t.Errorf("Cart's table name should be renamed_shopping_cart")
}
if DB.NewScope(&Cart{}).TableName() != "renamed_shopping_cart" {
t.Errorf("&Cart's table name should be renamed_shopping_cart")
}
var cart interface{}
cart = Cart{}
if DB.NewScope(cart).TableName() != "renamed_shopping_cart" {
t.Errorf("interface{}'s table name should be renamed_shopping_cart")
}
cart = &Cart{}
if DB.NewScope(cart).TableName() != "renamed_shopping_cart" {
t.Errorf("interface{}'s table name should be renamed_shopping_cart")
}
}
func TestNullValues(t *testing.T) { func TestNullValues(t *testing.T) {
DB.DropTable(&NullValue{}) DB.DropTable(&NullValue{})
DB.AutoMigrate(&NullValue{}) DB.AutoMigrate(&NullValue{})

View File

@ -314,14 +314,6 @@ func (scope *Scope) TableName() string {
return scope.Search.tableName return scope.Search.tableName
} }
if tabler, ok := scope.Value.(tabler); ok {
return tabler.TableName()
}
if tabler, ok := scope.Value.(dbTabler); ok {
return tabler.TableName(scope.db)
}
return scope.GetModelStruct().TableName(scope.db.Model(scope.Value)) return scope.GetModelStruct().TableName(scope.db.Model(scope.Value))
} }