Support the use of clause.Expression to return conditional statements

This commit is contained in:
demoManito 2022-09-26 17:24:28 +08:00
parent 328f301982
commit 2ee53580ac
2 changed files with 18 additions and 0 deletions

View File

@ -398,6 +398,12 @@ func Expr(expr string, args ...interface{}) clause.Expr {
return clause.Expr{SQL: expr, Vars: args} return clause.Expr{SQL: expr, Vars: args}
} }
// 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...)
}
// SetupJoinTable setup join table schema // SetupJoinTable setup join table schema
func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error { func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error {
var ( var (

View File

@ -357,6 +357,18 @@ func TestFromWithJoins(t *testing.T) {
} }
} }
func TestExprToString(t *testing.T) {
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}),
}
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)
}
}
func TestToSQL(t *testing.T) { func TestToSQL(t *testing.T) {
// By default DB.DryRun should false // By default DB.DryRun should false
if DB.DryRun { if DB.DryRun {