From 83fa3593b1a146ba700ab1b353b1707dca22df13 Mon Sep 17 00:00:00 2001 From: Agzer0 Date: Tue, 25 Jul 2023 20:13:17 +0800 Subject: [PATCH] fix: orm generate sql wrong, issues #2782 (#2787) --- contrib/drivers/mysql/mysql_issue_test.go | 37 +++++++++++++++++++++++ database/gdb/gdb_model_builder.go | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/contrib/drivers/mysql/mysql_issue_test.go b/contrib/drivers/mysql/mysql_issue_test.go index 08b1779ad..31e129e56 100644 --- a/contrib/drivers/mysql/mysql_issue_test.go +++ b/contrib/drivers/mysql/mysql_issue_test.go @@ -760,3 +760,40 @@ func Test_Issue2439(t *testing.T) { t.Assert(r[0]["name"], "a") }) } + +// https://github.com/gogf/gf/issues/2782 +func Test_Issue2787(t *testing.T) { + table := createTable() + defer dropTable(table) + + gtest.C(t, func(t *gtest.T) { + m := db.Model("user") + + condWhere, _ := m.Builder(). + Where("id", ""). + Where(m.Builder(). + Where("nickname", "foo"). + WhereOr("password", "abc123")). + Where("passport", "pp"). + Build() + t.Assert(condWhere, "(`id`=?) AND (((`nickname`=?) OR (`password`=?))) AND (`passport`=?)") + + condWhere, _ = m.OmitEmpty().Builder(). + Where("id", ""). + Where(m.Builder(). + Where("nickname", "foo"). + WhereOr("password", "abc123")). + Where("passport", "pp"). + Build() + t.Assert(condWhere, "((`nickname`=?) OR (`password`=?)) AND (`passport`=?)") + + condWhere, _ = m.OmitEmpty().Builder(). + Where(m.Builder(). + Where("nickname", "foo"). + WhereOr("password", "abc123")). + Where("id", ""). + Where("passport", "pp"). + Build() + t.Assert(condWhere, "((`nickname`=?) OR (`password`=?)) AND (`passport`=?)") + }) +} diff --git a/database/gdb/gdb_model_builder.go b/database/gdb/gdb_model_builder.go index 47c0fca21..3b378dcaf 100644 --- a/database/gdb/gdb_model_builder.go +++ b/database/gdb/gdb_model_builder.go @@ -115,7 +115,7 @@ func (b *WhereBuilder) convertWhereBuilder(where interface{}, args []interface{} } if builder != nil { conditionWhere, conditionArgs := builder.Build() - if conditionWhere != "" && len(b.whereHolder) == 0 { + if conditionWhere != "" && (len(b.whereHolder) == 0 || len(builder.whereHolder) > 1) { conditionWhere = "(" + conditionWhere + ")" } return conditionWhere, conditionArgs