Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@Riseif
Copy link
Contributor

@Riseif Riseif commented Jul 11, 2025

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

Fix a bug I found.

User Case Description

  • When there is only one OR clause inside a where clause, we want ignore the OR condition and just make it AND.

However, current implementation didn't check when actually there are multi expressions inside OR condition, these expressions are not expected to be modified to AND.

Check the demo below.

package main

import (
	"fmt"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type User struct {
	ID   uint
	Name string
	Age  int
}

func main() {
	db, _ := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
	db.AutoMigrate(&User{})

	// insert data
	db.Create(&User{Name: "Alice", Age: 30})
	db.Create(&User{Name: "Bob", Age: 25})

	sub := db.Clauses(clause.Where{
		Exprs: []clause.Expression{
			clause.OrConditions{
				Exprs: []clause.Expression{
					clause.Expr{SQL: "name = ?", Vars: []interface{}{"Alice"}},
					clause.Expr{SQL: "age = ?", Vars: []interface{}{25}},
				},
			},
		},
	})

	db = db.Debug().Model(&User{})
	var users []User
	db.Where(sub).Find(&users)

	fmt.Println("result:")
	for _, u := range users {
		fmt.Printf("ID=%d Name=%s Age=%d\n", u.ID, u.Name, u.Age)
	}
}

Before

[0.012ms] [rows:0] SELECT * FROM `users` WHERE name = "Alice" AND age = 25
result:

After

[0.018ms] [rows:2] SELECT * FROM `users` WHERE (name = "Alice" OR age = 25)
result:
ID=1 Name=Alice Age=30
ID=2 Name=Bob Age=25

@Riseif Riseif changed the title Unexpected OR Conditions forced converted to AND Unexpected OR Conditions force converted to AND Jul 11, 2025
@Riseif Riseif changed the title Unexpected OR Conditions force converted to AND Fix: Unexpected OR Conditions force converted to AND Jul 11, 2025
@jinzhu jinzhu merged commit 985940f into go-gorm:master Jul 21, 2025
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants