Test customize data type for primary key

This commit is contained in:
Jinzhu 2018-02-12 13:09:37 +08:00
parent 7e2bb3d7fa
commit 30adc80edc
2 changed files with 40 additions and 0 deletions

View File

@ -87,6 +87,37 @@ func TestUIntPrimaryKey(t *testing.T) {
}
}
func TestCustomizedTypePrimaryKey(t *testing.T) {
type ID uint
type CustomizedTypePrimaryKey struct {
ID ID
Name string
}
DB.AutoMigrate(&CustomizedTypePrimaryKey{})
p1 := CustomizedTypePrimaryKey{Name: "p1"}
p2 := CustomizedTypePrimaryKey{Name: "p2"}
p3 := CustomizedTypePrimaryKey{Name: "p3"}
DB.Create(&p1)
DB.Create(&p2)
DB.Create(&p3)
var p CustomizedTypePrimaryKey
if err := DB.First(&p, p2.ID).Error; err == nil {
t.Errorf("Should return error for invalid query condition")
}
if err := DB.First(&p, "id = ?", p2.ID).Error; err != nil {
t.Errorf("No error should happen when querying with customized type for primary key, got err %v", err)
}
if p.Name != "p2" {
t.Errorf("Should find correct value when querying with customized type for primary key")
}
}
func TestStringPrimaryKeyForNumericValueStartingWithZero(t *testing.T) {
type AddressByZipCode struct {
ZipCode string `gorm:"primary_key"`

View File

@ -578,12 +578,21 @@ func (scope *Scope) buildCondition(clause map[string]interface{}, include bool)
case interface{}:
var sqls []string
newScope := scope.New(value)
if len(newScope.Fields()) == 0 {
scope.Err(fmt.Errorf("invalid query condition: %v", value))
return
}
for _, field := range newScope.Fields() {
if !field.IsIgnored && !field.IsBlank {
sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", quotedTableName, scope.Quote(field.DBName), equalSQL, scope.AddToVars(field.Field.Interface())))
}
}
return strings.Join(sqls, " AND ")
default:
scope.Err(fmt.Errorf("invalid query condition: %v", value))
return
}
replacements := []string{}