Fix SELECT with sql expression in some cases, close #3889

This commit is contained in:
Jinzhu 2020-12-28 10:40:30 +08:00
parent ad8a5c0d1a
commit ade0bd6d60
2 changed files with 6 additions and 2 deletions

View File

@ -93,7 +93,7 @@ func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) {
} }
delete(tx.Statement.Clauses, "SELECT") delete(tx.Statement.Clauses, "SELECT")
case string: case string:
if (strings.Contains(v, " ?") || strings.Contains(v, "(?")) && len(args) > 0 { if strings.Count(v, "?") >= len(args) && len(args) > 0 {
tx.Statement.AddClause(clause.Select{ tx.Statement.AddClause(clause.Select{
Distinct: db.Statement.Distinct, Distinct: db.Statement.Distinct,
Expression: clause.Expr{SQL: v, Vars: args}, Expression: clause.Expr{SQL: v, Vars: args},

View File

@ -612,11 +612,15 @@ func TestSelect(t *testing.T) {
t.Fatalf("Build Select with slice, but got %v", r.Statement.SQL.String()) t.Fatalf("Build Select with slice, but got %v", r.Statement.SQL.String())
} }
// SELECT COALESCE(age,'42') FROM users;
r = dryDB.Table("users").Select("COALESCE(age,?)", 42).Find(&User{}) r = dryDB.Table("users").Select("COALESCE(age,?)", 42).Find(&User{})
if !regexp.MustCompile(`SELECT COALESCE\(age,.*\) FROM .*users.*`).MatchString(r.Statement.SQL.String()) { 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()) t.Fatalf("Build Select with func, but got %v", r.Statement.SQL.String())
} }
// SELECT COALESCE(age,'42') FROM users;
if _, err := DB.Table("users").Select("COALESCE(age,?)", "42").Rows(); err != nil {
t.Fatalf("Failed, got error: %v", err)
}
r = dryDB.Select("u.*").Table("users as u").First(&User{}, user.ID) r = dryDB.Select("u.*").Table("users as u").First(&User{}, user.ID)
if !regexp.MustCompile(`SELECT u\.\* FROM .*users.*`).MatchString(r.Statement.SQL.String()) { if !regexp.MustCompile(`SELECT u\.\* FROM .*users.*`).MatchString(r.Statement.SQL.String()) {