This commit is contained in:
demoManito 2022-09-26 18:31:01 +08:00
parent 2ee53580ac
commit 1dfd1b3ae5
2 changed files with 20 additions and 3 deletions

View File

@ -400,8 +400,12 @@ func Expr(expr string, args ...interface{}) clause.Expr {
// ExprToString clause.Expression Build to SQL String
func (db *DB) ExprToString(expr clause.Expression) string {
expr.Build(db.Statement)
return db.Dialector.Explain(db.Statement.SQL.String(), db.Statement.Vars...)
stmt := &Statement{
DB: db,
Clauses: map[string]clause.Clause{},
}
expr.Build(stmt)
return db.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
}
// SetupJoinTable setup join table schema

View File

@ -365,7 +365,20 @@ func TestExprToString(t *testing.T) {
wantSQL := "((`age` > 10 AND `age` < 18) AND (`age` > 18 AND `age` < 21))"
gotSQL := DB.ExprToString(clause.And(exprs...))
if wantSQL != gotSQL {
t.Errorf("want: %s \n, got: %s", wantSQL, gotSQL)
t.Fatalf("want: %s \n, got: %s", wantSQL, gotSQL)
}
sql := DB.ToSQL(func(tx *gorm.DB) *gorm.DB {
exprs := []clause.Expression{
clause.And(clause.Gt{Column: "age", Value: 10}, clause.Lt{Column: "age", Value: 18}),
clause.And(clause.Gt{Column: "age", Value: 18}, clause.Lt{Column: "age", Value: 21}),
}
gotSQL := tx.ExprToString(clause.And(exprs...))
return tx.Where("name LIKE ?", "jesse*").Where(gotSQL).Find(&[]User{})
})
wantSQL = "SELECT * FROM `users` WHERE name LIKE \"jesse*\" AND (((`age` > 10 AND `age` < 18) AND (`age` > 18 AND `age` < 21))) AND `users`.`deleted_at` IS NULL"
if wantSQL != sql {
t.Fatalf("want: %s \n, got: %s", wantSQL, sql)
}
}