mirror of https://github.com/go-gorm/gorm.git
58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
|
package tests_test
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"testing"
|
||
|
|
||
|
"gorm.io/gorm"
|
||
|
. "gorm.io/gorm/utils/tests"
|
||
|
)
|
||
|
|
||
|
func TestNamedArg(t *testing.T) {
|
||
|
type NamedUser struct {
|
||
|
gorm.Model
|
||
|
Name1 string
|
||
|
Name2 string
|
||
|
Name3 string
|
||
|
}
|
||
|
|
||
|
DB.Migrator().DropTable(&NamedUser{})
|
||
|
DB.AutoMigrate(&NamedUser{})
|
||
|
|
||
|
namedUser := NamedUser{Name1: "jinzhu1", Name2: "jinzhu2", Name3: "jinzhu3"}
|
||
|
DB.Create(&namedUser)
|
||
|
|
||
|
var result NamedUser
|
||
|
DB.First(&result, "name1 = @name OR name2 = @name OR name3 = @name", sql.Named("name", "jinzhu2"))
|
||
|
|
||
|
AssertEqual(t, result, namedUser)
|
||
|
|
||
|
var result2 NamedUser
|
||
|
DB.Where("name1 = @name OR name2 = @name OR name3 = @name", sql.Named("name", "jinzhu2")).First(&result2)
|
||
|
|
||
|
AssertEqual(t, result2, namedUser)
|
||
|
|
||
|
var result3 NamedUser
|
||
|
DB.Where("name1 = @name OR name2 = @name OR name3 = @name", map[string]interface{}{"name": "jinzhu2"}).First(&result3)
|
||
|
|
||
|
AssertEqual(t, result3, namedUser)
|
||
|
|
||
|
var result4 NamedUser
|
||
|
if err := DB.Raw("SELECT * FROM named_users WHERE name1 = @name OR name2 = @name2 OR name3 = @name", sql.Named("name", "jinzhu-none"), sql.Named("name2", "jinzhu2")).Find(&result4).Error; err != nil {
|
||
|
t.Errorf("failed to update with named arg")
|
||
|
}
|
||
|
|
||
|
AssertEqual(t, result4, namedUser)
|
||
|
|
||
|
if err := DB.Exec("UPDATE named_users SET name1 = @name, name2 = @name2, name3 = @name", sql.Named("name", "jinzhu-new"), sql.Named("name2", "jinzhu-new2")).Error; err != nil {
|
||
|
t.Errorf("failed to update with named arg")
|
||
|
}
|
||
|
|
||
|
var result5 NamedUser
|
||
|
if err := DB.Raw("SELECT * FROM named_users WHERE (name1 = @name AND name3 = @name) AND name2 = @name2", sql.Named("name", "jinzhu-new"), sql.Named("name2", "jinzhu-new2")).Find(&result5).Error; err != nil {
|
||
|
t.Errorf("failed to update with named arg")
|
||
|
}
|
||
|
|
||
|
AssertEqual(t, result4, namedUser)
|
||
|
}
|