Skip to content

Fix: Unexpected OR Conditions force converted to AND #7512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Riseif
Copy link

@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
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.

2 participants