Skip to content

Commit a3abb5f

Browse files
authoredMar 7, 2021
support named params in Select API (#4142)
* adds support for named arguments in select * changes clause identifies and adds test
1 parent bc34775 commit a3abb5f

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed
 

‎chainable_api.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,12 @@ func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) {
9898
Distinct: db.Statement.Distinct,
9999
Expression: clause.Expr{SQL: v, Vars: args},
100100
})
101-
} else {
101+
} else if strings.Count(v, "@") > 0 && len(args) > 0 {
102+
tx.Statement.AddClause(clause.Select{
103+
Distinct: db.Statement.Distinct,
104+
Expression: clause.NamedExpr{SQL: v, Vars: args},
105+
})
106+
} else {
102107
tx.Statement.Selects = []string{v}
103108

104109
for _, arg := range args {

‎clause/clause.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,9 @@ func (c Clause) Build(builder Builder) {
6262
}
6363

6464
const (
65-
PrimaryKey string = "@@@py@@@" // primary key
66-
CurrentTable string = "@@@ct@@@" // current table
67-
Associations string = "@@@as@@@" // associations
65+
PrimaryKey string = "~~~py~~~" // primary key
66+
CurrentTable string = "~~~ct~~~" // current table
67+
Associations string = "~~~as~~~" // associations
6868
)
6969

7070
var (

‎tests/query_test.go

+6
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,12 @@ func TestSelect(t *testing.T) {
628628
t.Fatalf("Build Select with func, but got %v", r.Statement.SQL.String())
629629
}
630630

631+
// named arguments
632+
r = dryDB.Table("users").Select("COALESCE(age, @default)", sql.Named("default", 42)).Find(&User{})
633+
if !regexp.MustCompile(`SELECT COALESCE\(age,.*\) FROM .*users.*`).MatchString(r.Statement.SQL.String()) {
634+
t.Fatalf("Build Select with func, but got %v", r.Statement.SQL.String())
635+
}
636+
631637
if _, err := DB.Table("users").Select("COALESCE(age,?)", "42").Rows(); err != nil {
632638
t.Fatalf("Failed, got error: %v", err)
633639
}

0 commit comments

Comments
 (0)