Fix: Where clauses with named arguments may cause generation of unintended queries (#4937)

This commit is contained in:
Emre Güllü 2021-12-21 14:50:00 +03:00 committed by GitHub
parent 24026bf1fe
commit 2c3fc2db28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 0 deletions

View File

@ -60,6 +60,9 @@ func buildExprs(exprs []Expression, builder Builder, joinCond string) {
case Expr: case Expr:
sql := strings.ToLower(v.SQL) sql := strings.ToLower(v.SQL)
wrapInParentheses = strings.Contains(sql, "and") || strings.Contains(sql, "or") wrapInParentheses = strings.Contains(sql, "and") || strings.Contains(sql, "or")
case NamedExpr:
sql := strings.ToLower(v.SQL)
wrapInParentheses = strings.Contains(sql, "and") || strings.Contains(sql, "or")
} }
} }

View File

@ -2,6 +2,7 @@ package tests_test
import ( import (
"database/sql" "database/sql"
"errors"
"testing" "testing"
"gorm.io/gorm" "gorm.io/gorm"
@ -66,4 +67,16 @@ func TestNamedArg(t *testing.T) {
} }
AssertEqual(t, result6, namedUser) AssertEqual(t, result6, namedUser)
var result7 NamedUser
if err := DB.Where("name1 = @name OR name2 = @name", sql.Named("name", "jinzhu-new")).Where("name3 = 'jinzhu-new3'").First(&result7).Error; err == nil || !errors.Is(err, gorm.ErrRecordNotFound) {
t.Errorf("should return record not found error, but got %v", err)
}
DB.Delete(&namedUser)
var result8 NamedUser
if err := DB.Where("name1 = @name OR name2 = @name", map[string]interface{}{"name": "jinzhu-new"}).First(&result8).Error; err == nil || !errors.Is(err, gorm.ErrRecordNotFound) {
t.Errorf("should return record not found error, but got %v", err)
}
} }