changes clause identifies and adds test

This commit is contained in:
ratanphayade 2021-03-05 22:46:24 +05:30
parent 5ad4e6ee98
commit e30ba8dafd
3 changed files with 16 additions and 10 deletions

View File

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