From 2ee53580ac03e252c9e4d75335e8e27ebe23f9d2 Mon Sep 17 00:00:00 2001 From: demoManito <1430482733@qq.com> Date: Mon, 26 Sep 2022 17:24:28 +0800 Subject: [PATCH] Support the use of clause.Expression to return conditional statements --- gorm.go | 6 ++++++ tests/sql_builder_test.go | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/gorm.go b/gorm.go index 81b6e2af..043f76b9 100644 --- a/gorm.go +++ b/gorm.go @@ -398,6 +398,12 @@ func Expr(expr string, args ...interface{}) clause.Expr { 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 func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error { var ( diff --git a/tests/sql_builder_test.go b/tests/sql_builder_test.go index a9b920dc..526e2bf0 100644 --- a/tests/sql_builder_test.go +++ b/tests/sql_builder_test.go @@ -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) { // By default DB.DryRun should false if DB.DryRun {