forked from mirror/gorm
Test customize data type for primary key
This commit is contained in:
parent
7e2bb3d7fa
commit
30adc80edc
|
@ -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) {
|
func TestStringPrimaryKeyForNumericValueStartingWithZero(t *testing.T) {
|
||||||
type AddressByZipCode struct {
|
type AddressByZipCode struct {
|
||||||
ZipCode string `gorm:"primary_key"`
|
ZipCode string `gorm:"primary_key"`
|
||||||
|
|
9
scope.go
9
scope.go
|
@ -578,12 +578,21 @@ func (scope *Scope) buildCondition(clause map[string]interface{}, include bool)
|
||||||
case interface{}:
|
case interface{}:
|
||||||
var sqls []string
|
var sqls []string
|
||||||
newScope := scope.New(value)
|
newScope := scope.New(value)
|
||||||
|
|
||||||
|
if len(newScope.Fields()) == 0 {
|
||||||
|
scope.Err(fmt.Errorf("invalid query condition: %v", value))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for _, field := range newScope.Fields() {
|
for _, field := range newScope.Fields() {
|
||||||
if !field.IsIgnored && !field.IsBlank {
|
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())))
|
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 ")
|
return strings.Join(sqls, " AND ")
|
||||||
|
default:
|
||||||
|
scope.Err(fmt.Errorf("invalid query condition: %v", value))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
replacements := []string{}
|
replacements := []string{}
|
||||||
|
|
Loading…
Reference in New Issue