From 30adc80edc91ab4934e12f33fa1a0b07bfa4da03 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 12 Feb 2018 13:09:37 +0800 Subject: [PATCH] Test customize data type for primary key --- query_test.go | 31 +++++++++++++++++++++++++++++++ scope.go | 9 +++++++++ 2 files changed, 40 insertions(+) diff --git a/query_test.go b/query_test.go index 3c3c74b5..80ebd473 100644 --- a/query_test.go +++ b/query_test.go @@ -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"` diff --git a/scope.go b/scope.go index 1bd32a28..04d549bf 100644 --- a/scope.go +++ b/scope.go @@ -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{}