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:
Ratan Phayade 2021-03-07 08:29:00 +05:30 committed by GitHub
parent bc347758e5
commit a3abb5fedf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 4 deletions

View File

@ -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 {

View File

@ -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 (

View File

@ -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)
}