Skip to content

Commit

Permalink
Fix tests doesn't follow https://gorm.io/docs/method_chaining.html co…
Browse files Browse the repository at this point in the history
…nvention
  • Loading branch information
jinzhu committed Jan 12, 2024
1 parent 87decce commit 940358e
Show file tree
Hide file tree
Showing 9 changed files with 45 additions and 47 deletions.
27 changes: 3 additions & 24 deletions chainable_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions clause/where.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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}
}

Expand Down
4 changes: 2 additions & 2 deletions clause/where_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
},
{
Expand Down Expand Up @@ -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},
},
{
Expand Down
8 changes: 6 additions & 2 deletions finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 8 additions & 8 deletions statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,21 +326,17 @@ 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 {
where.Exprs[0] = clause.AndConditions(orConds)
}
}
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 {
Expand Down Expand Up @@ -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
}
}

Expand All @@ -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
Expand Down
10 changes: 5 additions & 5 deletions tests/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
)

Expand Down
4 changes: 2 additions & 2 deletions tests/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}

Expand Down
10 changes: 7 additions & 3 deletions tests/scopes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)`,
Expand All @@ -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)`,
Expand All @@ -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") },
)).
Expand Down
2 changes: 1 addition & 1 deletion tests/sql_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 940358e

Please sign in to comment.