diff --git a/chainable_api.go b/chainable_api.go index 3dc7256e6..1ec9b865f 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -367,33 +367,12 @@ func (db *DB) Scopes(funcs ...func(*DB) *DB) (tx *DB) { } func (db *DB) executeScopes() (tx *DB) { - tx = db.getInstance() scopes := db.Statement.scopes - if len(scopes) == 0 { - return tx - } - tx.Statement.scopes = nil - - conditions := make([]clause.Interface, 0, 4) - if cs, ok := tx.Statement.Clauses["WHERE"]; ok && cs.Expression != nil { - conditions = append(conditions, cs.Expression.(clause.Interface)) - cs.Expression = nil - tx.Statement.Clauses["WHERE"] = cs - } - + db.Statement.scopes = nil for _, scope := range scopes { - tx = scope(tx) - if cs, ok := tx.Statement.Clauses["WHERE"]; ok && cs.Expression != nil { - conditions = append(conditions, cs.Expression.(clause.Interface)) - cs.Expression = nil - tx.Statement.Clauses["WHERE"] = cs - } - } - - for _, condition := range conditions { - tx.Statement.AddClause(condition) + db = scope(db) } - return tx + return db } // Preload preload associations with given conditions diff --git a/clause/where.go b/clause/where.go index a29401cfe..46d0b3193 100644 --- a/clause/where.go +++ b/clause/where.go @@ -21,6 +21,12 @@ func (where Where) Name() string { // Build build where clause func (where Where) Build(builder Builder) { + if len(where.Exprs) == 1 { + if andCondition, ok := where.Exprs[0].(AndConditions); ok { + where.Exprs = andCondition.Exprs + } + } + // Switch position if the first query expression is a single Or condition for idx, expr := range where.Exprs { if v, ok := expr.(OrConditions); !ok || len(v.Exprs) > 1 { @@ -147,6 +153,11 @@ func Not(exprs ...Expression) Expression { if len(exprs) == 0 { return nil } + if len(exprs) == 1 { + if andCondition, ok := exprs[0].(AndConditions); ok { + exprs = andCondition.Exprs + } + } return NotConditions{Exprs: exprs} } diff --git a/clause/where_test.go b/clause/where_test.go index 35e3dbeeb..aa9d06ebf 100644 --- a/clause/where_test.go +++ b/clause/where_test.go @@ -63,7 +63,7 @@ func TestWhere(t *testing.T) { []clause.Interface{clause.Select{}, clause.From{}, clause.Where{ Exprs: []clause.Expression{clause.And(clause.Eq{Column: "age", Value: 18}, clause.Or(clause.Neq{Column: "name", Value: "jinzhu"}))}, }}, - "SELECT * FROM `users` WHERE (`age` = ? OR `name` <> ?)", + "SELECT * FROM `users` WHERE `age` = ? OR `name` <> ?", []interface{}{18, "jinzhu"}, }, { @@ -94,7 +94,7 @@ func TestWhere(t *testing.T) { clause.And(clause.Expr{SQL: "`score` <= ?", Vars: []interface{}{100}, WithoutParentheses: false})), }, }}, - "SELECT * FROM `users` WHERE (`users`.`id` <> ? AND `score` <= ?)", + "SELECT * FROM `users` WHERE `users`.`id` <> ? AND `score` <= ?", []interface{}{"1", 100}, }, { diff --git a/finisher_api.go b/finisher_api.go index f80aa6c04..f97571ed0 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -376,8 +376,12 @@ func (db *DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB) { } else if len(db.Statement.assigns) > 0 { exprs := tx.Statement.BuildCondition(db.Statement.assigns[0], db.Statement.assigns[1:]...) assigns := map[string]interface{}{} - for _, expr := range exprs { - if eq, ok := expr.(clause.Eq); ok { + for i := 0; i < len(exprs); i++ { + expr := exprs[i] + + if eq, ok := expr.(clause.AndConditions); ok { + exprs = append(exprs, eq.Exprs...) + } else if eq, ok := expr.(clause.Eq); ok { switch column := eq.Column.(type) { case string: assigns[column] = eq.Value diff --git a/statement.go b/statement.go index b24228b2c..ae79aa321 100644 --- a/statement.go +++ b/statement.go @@ -326,7 +326,7 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) [] case *DB: v.executeScopes() - if cs, ok := v.Statement.Clauses["WHERE"]; ok && cs.Expression != nil { + if cs, ok := v.Statement.Clauses["WHERE"]; ok { if where, ok := cs.Expression.(clause.Where); ok { if len(where.Exprs) == 1 { if orConds, ok := where.Exprs[0].(clause.OrConditions); ok { @@ -334,13 +334,9 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) [] } } conds = append(conds, clause.And(where.Exprs...)) - } else { + } else if cs.Expression != nil { conds = append(conds, cs.Expression) } - if v.Statement == stmt { - cs.Expression = nil - stmt.Statement.Clauses["WHERE"] = cs - } } case map[interface{}]interface{}: for i, j := range v { @@ -451,8 +447,9 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) [] if len(values) > 0 { conds = append(conds, clause.IN{Column: clause.PrimaryColumn, Values: values}) + return []clause.Expression{clause.And(conds...)} } - return conds + return nil } } @@ -461,7 +458,10 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) [] } } - return conds + if len(conds) > 0 { + return []clause.Expression{clause.And(conds...)} + } + return nil } // Build build sql with clauses names diff --git a/tests/go.mod b/tests/go.mod index 710790504..07fedc45f 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -3,7 +3,7 @@ module gorm.io/gorm/tests go 1.18 require ( - github.com/google/uuid v1.4.0 + github.com/google/uuid v1.5.0 github.com/jinzhu/now v1.1.5 github.com/lib/pq v1.10.9 gorm.io/driver/mysql v1.5.2 @@ -18,12 +18,12 @@ require ( github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect github.com/golang-sql/sqlexp v0.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect - github.com/jackc/pgx/v5 v5.5.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect + github.com/jackc/pgx/v5 v5.5.1 // indirect github.com/jinzhu/inflection v1.0.0 // indirect - github.com/mattn/go-sqlite3 v1.14.18 // indirect + github.com/mattn/go-sqlite3 v1.14.19 // indirect github.com/microsoft/go-mssqldb v1.6.0 // indirect - golang.org/x/crypto v0.15.0 // indirect + golang.org/x/crypto v0.18.0 // indirect golang.org/x/text v0.14.0 // indirect ) diff --git a/tests/query_test.go b/tests/query_test.go index 5728378dd..cadf7164e 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -1118,12 +1118,12 @@ func TestSearchWithStruct(t *testing.T) { } result = dryRunDB.Where(User{Name: "jinzhu", Age: 18}).Find(&User{}) - if !regexp.MustCompile(`WHERE .users.\..name. = .{1,3} AND .users.\..age. = .{1,3} AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) { + if !regexp.MustCompile(`WHERE \(.users.\..name. = .{1,3} AND .users.\..age. = .{1,3}\) AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) { t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String()) } result = dryRunDB.Where(User{Name: "jinzhu"}, "name", "Age").Find(&User{}) - if !regexp.MustCompile(`WHERE .users.\..name. = .{1,3} AND .users.\..age. = .{1,3} AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) { + if !regexp.MustCompile(`WHERE \(.users.\..name. = .{1,3} AND .users.\..age. = .{1,3}\) AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) { t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String()) } diff --git a/tests/scopes_test.go b/tests/scopes_test.go index 52c6b37b1..84aeb990c 100644 --- a/tests/scopes_test.go +++ b/tests/scopes_test.go @@ -84,7 +84,9 @@ func TestComplexScopes(t *testing.T) { queryFn: func(tx *gorm.DB) *gorm.DB { return tx.Scopes( func(d *gorm.DB) *gorm.DB { return d.Where("a = 1") }, - func(d *gorm.DB) *gorm.DB { return d.Where(d.Or("b = 2").Or("c = 3")) }, + func(d *gorm.DB) *gorm.DB { + return d.Where(DB.Or("b = 2").Or("c = 3")) + }, ).Find(&Language{}) }, expected: `SELECT * FROM "languages" WHERE a = 1 AND (b = 2 OR c = 3)`, @@ -93,7 +95,9 @@ func TestComplexScopes(t *testing.T) { queryFn: func(tx *gorm.DB) *gorm.DB { return tx.Where("z = 0").Scopes( func(d *gorm.DB) *gorm.DB { return d.Where("a = 1") }, - func(d *gorm.DB) *gorm.DB { return d.Or(d.Where("b = 2").Or("c = 3")) }, + func(d *gorm.DB) *gorm.DB { + return d.Or(DB.Where("b = 2").Or("c = 3")) + }, ).Find(&Language{}) }, expected: `SELECT * FROM "languages" WHERE z = 0 AND a = 1 OR (b = 2 OR c = 3)`, @@ -104,7 +108,7 @@ func TestComplexScopes(t *testing.T) { func(d *gorm.DB) *gorm.DB { return d.Model(&Language{}) }, func(d *gorm.DB) *gorm.DB { return d. - Or(d.Scopes( + Or(DB.Scopes( func(d *gorm.DB) *gorm.DB { return d.Where("a = 1") }, func(d *gorm.DB) *gorm.DB { return d.Where("b = 2") }, )). diff --git a/tests/sql_builder_test.go b/tests/sql_builder_test.go index 022e0495e..0c204db49 100644 --- a/tests/sql_builder_test.go +++ b/tests/sql_builder_test.go @@ -388,7 +388,7 @@ func TestToSQL(t *testing.T) { sql = DB.ToSQL(func(tx *gorm.DB) *gorm.DB { return tx.Model(&User{}).Where(&User{Name: "foo", Age: 20}).Limit(10).Offset(5).Order("name ASC").First(&User{}) }) - assertEqualSQL(t, `SELECT * FROM "users" WHERE "users"."name" = 'foo' AND "users"."age" = 20 AND "users"."deleted_at" IS NULL ORDER BY name ASC,"users"."id" LIMIT 1 OFFSET 5`, sql) + assertEqualSQL(t, `SELECT * FROM "users" WHERE ("users"."name" = 'foo' AND "users"."age" = 20) AND "users"."deleted_at" IS NULL ORDER BY name ASC,"users"."id" LIMIT 1 OFFSET 5`, sql) // last and unscoped sql = DB.ToSQL(func(tx *gorm.DB) *gorm.DB {