Skip to content

Commit

Permalink
fix(do): select with field.Expr
Browse files Browse the repository at this point in the history
  • Loading branch information
tr1v3r committed Oct 26, 2021
1 parent 3137ce1 commit a5f54fe
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
18 changes: 12 additions & 6 deletions do.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,8 @@ func (d *DO) Select(columns ...field.Expr) Dao {
if len(columns) == 0 {
return d.getInstance(d.db.Clauses(clause.Select{}))
}
return d.getInstance(d.db.Select(buildExpr(d.db.Statement, columns...)))
query, args := buildExpr(d.db.Statement, columns...)
return d.getInstance(d.db.Select(query, args...))
}

func (d *DO) Where(conds ...Condition) Dao {
Expand Down Expand Up @@ -580,12 +581,17 @@ func buildColumn(stmt *gorm.Statement, cols []field.Expr, opts ...field.BuildOpt
return results
}

func buildExpr(stmt *gorm.Statement, exprs ...field.Expr) []string {
results := make([]string, len(exprs))
for i, e := range exprs {
results[i] = e.Build(stmt).String()
func buildExpr(stmt *gorm.Statement, exprs ...field.Expr) (query string, args []interface{}) {
for _, e := range exprs {
sql, vars := e.BuildWithArgs(stmt)
if query == "" {
query = sql.String()
} else {
query += "," + sql.String()
}
args = append(args, vars...)
}
return results
return query, args
}

func toExpression(exprs ...field.Expr) []clause.Expression {
Expand Down
10 changes: 10 additions & 0 deletions field/expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type Expr interface {
ColumnName() sql
BuildColumn(*gorm.Statement, ...BuildOpt) sql
Build(*gorm.Statement) sql
BuildWithArgs(*gorm.Statement) (query sql, args []interface{})
RawExpr() expression

// implement Condition
Expand Down Expand Up @@ -103,6 +104,15 @@ func (e expr) Build(stmt *gorm.Statement) sql {
return sql(newStmt.SQL.String())
}

func (e expr) BuildWithArgs(stmt *gorm.Statement) (sql, []interface{}) {
if e.e == nil {
return sql(e.BuildColumn(stmt, WithAll)), nil
}
newStmt := &gorm.Statement{DB: stmt.DB, Table: stmt.Table, Schema: stmt.Schema}
e.e.Build(newStmt)
return sql(newStmt.SQL.String()), newStmt.Vars
}

func (e expr) RawExpr() expression {
if e.e == nil {
return e.col
Expand Down
5 changes: 5 additions & 0 deletions field/external_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,11 @@ func TestExpr_Build(t *testing.T) {
ExpectedVars: []interface{}{time.Duration(24 * time.Hour).Microseconds()},
Result: "DATE_SUB(`creatAt`, INTERVAL ? MICROSECOND)",
},
{
Expr: field.NewTime("", "updateAt").DateFormat("%W %M %Y"),
ExpectedVars: []interface{}{"%W %M %Y"},
Result: "DATE_FORMAT(`updateAt`,?)",
},
// ======================== bool ========================
{
Expr: field.NewBool("", "male").Not(),
Expand Down

0 comments on commit a5f54fe

Please sign in to comment.