Repository: go-gorm/gorm
Pull request #6771 (2024-01-02 12:57:31)

fix: preload shouldn't overwrite the value of join
<!--
Make sure these boxes checked before submitting your pull request.

For significant changes, please open an issue to make an agreement on an implementation design/plan first before starting it.
-->

- [X] Do only one thing
- [X] Non breaking API changes
- [X] Tested

### What did this pull request do?

<!--
provide a general description of the code changes in your pull request
-->

Fix the issue #6715, preload shouldn't overwrite the value of join.

See https://github.com/go-gorm/gorm/issues/6715#issuecomment-1873581676

### User Case Description

<!-- Your use case -->
```go
type (
	Preload struct {
		ID       uint
		Value    string
		NestedID uint
	}
	Join struct {
		ID       uint
		Value    string
		NestedID uint
	}
	Nested struct {
		ID       uint
		Preloads []*Preload
		Join     Join
		ValueID  uint
	}
	Value struct {
		ID     uint
		Name   string
		Nested Nested
	}
)

DB.Joins("Nested").Joins("Nested.Join").Preload("Nested.Preloads").First(&find)
```




Patch:
diff --git a/callbacks/preload.go b/callbacks/preload.go
index 15669c8..25ecfe7 100644
--- a/callbacks/preload.go
+++ b/callbacks/preload.go
@@ -3,6 +3,7 @@ package callbacks
 import (
 	"fmt"
 	"reflect"
+	"sort"
 	"strings"
 
 	"gorm.io/gorm"
@@ -82,27 +83,80 @@ func embeddedValues(embeddedRelations *schema.Relationships) []string {
 	return names
 }
 
-func preloadEmbedded(tx *gorm.DB, relationships *schema.Relationships, s *schema.Schema, preloads map[string][]interface{}, as []interface{}) error {
-	if relationships == nil {
-		return nil
+// preloadEntryPoint enters layer by layer. It will call real preload if it finds the right entry point.
+// If the current relationship is embedded or joined, current query will be ignored.
+//
+//nolint:cyclop
+func preloadEntryPoint(db *gorm.DB, joins []string, relationships *schema.Relationships, preloads map[string][]interface{}, associationsConds []interface{}) error {
+	preloadMap := parsePreloadMap(db.Statement.Schema, preloads)
+
+	// avoid random traversal of the map
+	preloadNames := make([]string, 0, len(preloadMap))
+	for key := range preloadMap {
+		preloadNames = append(preloadNames, key)
+	}
+	sort.Strings(preloadNames)
+
+	isJoined := func(name string) (joined bool, nestedJoins []string) {
+		for _, join := range joins {
+			if _, ok := relationships.Relations[join]; ok && name == join {
+				joined = true
+				continue
+			}
+			joinNames := strings.SplitN(join, ".", 2)
+			if len(joinNames) == 2 {
+				if _, ok := relationships.Relations[joinNames[0]]; ok && name == joinNames[0] {
+					joined = true
+					nestedJoins = append(nestedJoins, joinNames[1])
+				}
+			}
+		}
+		return joined, nestedJoins
 	}
-	preloadMap := parsePreloadMap(s, preloads)
-	for name := range preloadMap {
-		if embeddedRelations := relationships.EmbeddedRelations[name]; embeddedRelations != nil {
-			if err := preloadEmbedded(tx, embeddedRelations, s, preloadMap[name], as); err != nil {
+
+	for _, name := range preloadNames {
+		if relations := relationships.EmbeddedRelations[name]; relations != nil {
+			if err := preloadEntryPoint(db, joins, relations, preloadMap[name], associationsConds); err != nil {
 				return err
 			}
 		} else if rel := relationships.Relations[name]; rel != nil {
-			if err := preload(tx, rel, append(preloads[name], as), preloadMap[name]); err != nil {
-				return err
+			if joined, nestedJoins := isJoined(name); joined {
+				reflectValue := rel.Field.ReflectValueOf(db.Statement.Context, db.Statement.ReflectValue)
+				tx := preloadDB(db, reflectValue, reflectValue.Interface())
+				if err := preloadEntryPoint(tx, nestedJoins, &tx.Statement.Schema.Relationships, preloadMap[name], associationsConds); err != nil {
+					return err
+				}
+			} else {
+				tx := db.Table("").Session(&gorm.Session{Context: db.Statement.Context, SkipHooks: db.Statement.SkipHooks})
+				tx.Statement.ReflectValue = db.Statement.ReflectValue
+				tx.Statement.Unscoped = db.Statement.Unscoped
+				if err := preload(tx, rel, append(preloads[name], associationsConds...), preloadMap[name]); err != nil {
+					return err
+				}
 			}
 		} else {
-			return fmt.Errorf("%s: %w (embedded) for schema %s", name, gorm.ErrUnsupportedRelation, s.Name)
+			return fmt.Errorf("%s: %w for schema %s", name, gorm.ErrUnsupportedRelation, db.Statement.Schema.Name)
 		}
 	}
 	return nil
 }
 
+func preloadDB(db *gorm.DB, reflectValue reflect.Value, dest interface{}) *gorm.DB {
+	tx := db.Session(&gorm.Session{Context: db.Statement.Context, NewDB: true, SkipHooks: db.Statement.SkipHooks, Initialized: true})
+	db.Statement.Settings.Range(func(k, v interface{}) bool {
+		tx.Statement.Settings.Store(k, v)
+		return true
+	})
+
+	if err := tx.Statement.Parse(dest); err != nil {
+		tx.AddError(err)
+		return tx
+	}
+	tx.Statement.ReflectValue = reflectValue
+	tx.Statement.Unscoped = db.Statement.Unscoped
+	return tx
+}
+
 func preload(tx *gorm.DB, rel *schema.Relationship, conds []interface{}, preloads map[string][]interface{}) error {
 	var (
 		reflectValue     = tx.Statement.ReflectValue
diff --git a/callbacks/query.go b/callbacks/query.go
index e89dd19..2a82eab 100644
--- a/callbacks/query.go
+++ b/callbacks/query.go
@@ -3,7 +3,6 @@ package callbacks
 import (
 	"fmt"
 	"reflect"
-	"sort"
 	"strings"
 
 	"gorm.io/gorm"
@@ -254,7 +253,6 @@ func BuildQuerySQL(db *gorm.DB) {
 			}
 
 			db.Statement.AddClause(fromClause)
-			db.Statement.Joins = nil
 		} else {
 			db.Statement.AddClauseIfNotExists(clause.From{})
 		}
@@ -272,38 +270,23 @@ func Preload(db *gorm.DB) {
 			return
 		}
 
-		preloadMap := parsePreloadMap(db.Statement.Schema, db.Statement.Preloads)
-		preloadNames := make([]string, 0, len(preloadMap))
-		for key := range preloadMap {
-			preloadNames = append(preloadNames, key)
+		joins := make([]string, 0, len(db.Statement.Joins))
+		for _, join := range db.Statement.Joins {
+			joins = append(joins, join.Name)
 		}
-		sort.Strings(preloadNames)
 
-		preloadDB := db.Session(&gorm.Session{Context: db.Statement.Context, NewDB: true, SkipHooks: db.Statement.SkipHooks, Initialized: true})
-		db.Statement.Settings.Range(func(k, v interface{}) bool {
-			preloadDB.Statement.Settings.Store(k, v)
-			return true
-		})
-
-		if err := preloadDB.Statement.Parse(db.Statement.Dest); err != nil {
+		tx := preloadDB(db, db.Statement.ReflectValue, db.Statement.Dest)
+		if tx.Error != nil {
 			return
 		}
-		preloadDB.Statement.ReflectValue = db.Statement.ReflectValue
-		preloadDB.Statement.Unscoped = db.Statement.Unscoped
-
-		for _, name := range preloadNames {
-			if relations := preloadDB.Statement.Schema.Relationships.EmbeddedRelations[name]; relations != nil {
-				db.AddError(preloadEmbedded(preloadDB.Table("").Session(&gorm.Session{Context: db.Statement.Context, SkipHooks: db.Statement.SkipHooks}), relations, db.Statement.Schema, preloadMap[name], db.Statement.Preloads[clause.Associations]))
-			} else if rel := preloadDB.Statement.Schema.Relationships.Relations[name]; rel != nil {
-				db.AddError(preload(preloadDB.Table("").Session(&gorm.Session{Context: db.Statement.Context, SkipHooks: db.Statement.SkipHooks}), rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name]))
-			} else {
-				db.AddError(fmt.Errorf("%s: %w for schema %s", name, gorm.ErrUnsupportedRelation, db.Statement.Schema.Name))
-			}
-		}
+
+		db.AddError(preloadEntryPoint(tx, joins, &tx.Statement.Schema.Relationships, db.Statement.Preloads, db.Statement.Preloads[clause.Associations]))
 	}
 }
 
 func AfterQuery(db *gorm.DB) {
+	// clear the joins after query because preload need it
+	db.Statement.Joins = nil
 	if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind && db.RowsAffected > 0 {
 		callMethod(db, func(value interface{}, tx *gorm.DB) bool {
 			if i, ok := value.(AfterFindInterface); ok {
diff --git a/chainable_api.go b/chainable_api.go
index 3dc7256..1ec9b86 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 a29401c..46d0b31 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/finisher_api.go b/finisher_api.go
index f80aa6c..f97571e 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 b24228b..ae79aa3 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/utils/utils.go b/utils/utils.go
index c8fec5b..a4d8ac2 100644
--- a/utils/utils.go
+++ b/utils/utils.go
@@ -35,7 +35,8 @@ func FileWithLineNum() string {
 	// the second caller usually from gorm internal, so set i start from 2
 	for i := 2; i < 15; i++ {
 		_, file, line, ok := runtime.Caller(i)
-		if ok && (!strings.HasPrefix(file, gormSourceDir) || strings.HasSuffix(file, "_test.go")) {
+		if ok && (!strings.HasPrefix(file, gormSourceDir) || strings.HasSuffix(file, "_test.go")) &&
+			!strings.HasSuffix(file, ".gen.go") {
 			return file + ":" + strconv.FormatInt(int64(line), 10)
 		}
 	}


Test patch:
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 380231b..af471d2 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -30,7 +30,7 @@ jobs:
       uses: actions/checkout@v4
 
     - name: go mod package cache
-      uses: actions/cache@v3
+      uses: actions/cache@v4
       with:
         path: ~/go/pkg/mod
         key: ${{ runner.os }}-go-${{ matrix.go }}-${{ hashFiles('tests/go.mod') }}
@@ -73,7 +73,7 @@ jobs:
       uses: actions/checkout@v4
 
     - name: go mod package cache
-      uses: actions/cache@v3
+      uses: actions/cache@v4
       with:
         path: ~/go/pkg/mod
         key: ${{ runner.os }}-go-${{ matrix.go }}-${{ hashFiles('tests/go.mod') }}
@@ -116,7 +116,7 @@ jobs:
         uses: actions/checkout@v4
 
       - name: go mod package cache
-        uses: actions/cache@v3
+        uses: actions/cache@v4
         with:
           path: ~/go/pkg/mod
           key: ${{ runner.os }}-go-${{ matrix.go }}-${{ hashFiles('tests/go.mod') }}
@@ -159,7 +159,7 @@ jobs:
       uses: actions/checkout@v4
 
     - name: go mod package cache
-      uses: actions/cache@v3
+      uses: actions/cache@v4
       with:
         path: ~/go/pkg/mod
         key: ${{ runner.os }}-go-${{ matrix.go }}-${{ hashFiles('tests/go.mod') }}
@@ -202,7 +202,7 @@ jobs:
       uses: actions/checkout@v4
 
     - name: go mod package cache
-      uses: actions/cache@v3
+      uses: actions/cache@v4
       with:
         path: ~/go/pkg/mod
         key: ${{ runner.os }}-go-${{ matrix.go }}-${{ hashFiles('tests/go.mod') }}
@@ -235,7 +235,7 @@ jobs:
 
 
       - name: go mod package cache
-        uses: actions/cache@v3
+        uses: actions/cache@v4
         with:
           path: ~/go/pkg/mod
           key: ${{ runner.os }}-go-${{ matrix.go }}-${{ hashFiles('tests/go.mod') }}
diff --git a/clause/where_test.go b/clause/where_test.go
index 35e3dbe..aa9d06e 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/tests/go.mod b/tests/go.mod
index 7107905..07fedc4 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/preload_test.go b/tests/preload_test.go
index 3ff8649..26b08d7 100644
--- a/tests/preload_test.go
+++ b/tests/preload_test.go
@@ -307,6 +307,63 @@ func TestNestedPreloadWithUnscoped(t *testing.T) {
 	CheckUserUnscoped(t, *user6, user)
 }
 
+func TestNestedPreloadWithNestedJoin(t *testing.T) {
+	type (
+		Preload struct {
+			ID       uint
+			Value    string
+			NestedID uint
+		}
+		Join struct {
+			ID       uint
+			Value    string
+			NestedID uint
+		}
+		Nested struct {
+			ID       uint
+			Preloads []*Preload
+			Join     Join
+			ValueID  uint
+		}
+		Value struct {
+			ID     uint
+			Name   string
+			Nested Nested
+		}
+	)
+
+	DB.Migrator().DropTable(&Preload{}, &Join{}, &Nested{}, &Value{})
+	DB.Migrator().AutoMigrate(&Preload{}, &Join{}, &Nested{}, &Value{})
+
+	value := Value{
+		Name: "value",
+		Nested: Nested{
+			Preloads: []*Preload{
+				{Value: "p1"}, {Value: "p2"},
+			},
+			Join: Join{Value: "j1"},
+		},
+	}
+	if err := DB.Create(&value).Error; err != nil {
+		t.Errorf("failed to create value, got err: %v", err)
+	}
+
+	var find1 Value
+	err := DB.Joins("Nested").Joins("Nested.Join").Preload("Nested.Preloads").First(&find1).Error
+	if err != nil {
+		t.Errorf("failed to find value, got err: %v", err)
+	}
+	AssertEqual(t, find1, value)
+
+	var find2 Value
+	// Joins will automatically add Nested queries.
+	err = DB.Joins("Nested.Join").Preload("Nested.Preloads").First(&find2).Error
+	if err != nil {
+		t.Errorf("failed to find value, got err: %v", err)
+	}
+	AssertEqual(t, find2, value)
+}
+
 func TestEmbedPreload(t *testing.T) {
 	type Country struct {
 		ID   int `gorm:"primaryKey"`
diff --git a/tests/query_test.go b/tests/query_test.go
index 5728378..cadf716 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 52c6b37..84aeb99 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 022e049..0c204db 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 {