forked from mirror/gorm
support named params in Select API (#4142)
* adds support for named arguments in select * changes clause identifies and adds test
This commit is contained in:
parent
bc347758e5
commit
a3abb5fedf
|
@ -98,7 +98,12 @@ func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) {
|
|||
Distinct: db.Statement.Distinct,
|
||||
Expression: clause.Expr{SQL: v, Vars: args},
|
||||
})
|
||||
} else {
|
||||
} else if strings.Count(v, "@") > 0 && len(args) > 0 {
|
||||
tx.Statement.AddClause(clause.Select{
|
||||
Distinct: db.Statement.Distinct,
|
||||
Expression: clause.NamedExpr{SQL: v, Vars: args},
|
||||
})
|
||||
} else {
|
||||
tx.Statement.Selects = []string{v}
|
||||
|
||||
for _, arg := range args {
|
||||
|
|
|
@ -62,9 +62,9 @@ func (c Clause) Build(builder Builder) {
|
|||
}
|
||||
|
||||
const (
|
||||
PrimaryKey string = "@@@py@@@" // primary key
|
||||
CurrentTable string = "@@@ct@@@" // current table
|
||||
Associations string = "@@@as@@@" // associations
|
||||
PrimaryKey string = "~~~py~~~" // primary key
|
||||
CurrentTable string = "~~~ct~~~" // current table
|
||||
Associations string = "~~~as~~~" // associations
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
|
@ -628,6 +628,12 @@ func TestSelect(t *testing.T) {
|
|||
t.Fatalf("Build Select with func, but got %v", r.Statement.SQL.String())
|
||||
}
|
||||
|
||||
// named arguments
|
||||
r = dryDB.Table("users").Select("COALESCE(age, @default)", sql.Named("default", 42)).Find(&User{})
|
||||
if !regexp.MustCompile(`SELECT COALESCE\(age,.*\) FROM .*users.*`).MatchString(r.Statement.SQL.String()) {
|
||||
t.Fatalf("Build Select with func, but got %v", r.Statement.SQL.String())
|
||||
}
|
||||
|
||||
if _, err := DB.Table("users").Select("COALESCE(age,?)", "42").Rows(); err != nil {
|
||||
t.Fatalf("Failed, got error: %v", err)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue