orm: add or_where() method to the builder (fix #24244) (#24250)

This commit is contained in:
kbkpbot 2025-04-17 19:44:07 +08:00 committed by GitHub
parent ccb3d5cfcd
commit 4e6b56dc4a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 1 deletions

View File

@ -43,12 +43,28 @@ pub fn (qb_ &QueryBuilder[T]) reset() &QueryBuilder[T] {
return qb return qb
} }
// where create a `where` clause // where create a `where` clause, it will `AND` with previous `where` clause.
// valid token in the `condition` include: `field's names`, `operator`, `(`, `)`, `?`, `AND`, `OR`, `||`, `&&`, // valid token in the `condition` include: `field's names`, `operator`, `(`, `)`, `?`, `AND`, `OR`, `||`, `&&`,
// valid `operator` incldue: `=`, `!=`, `<>`, `>=`, `<=`, `>`, `<`, `LIKE`, `ILIKE`, `IS NULL`, `IS NOT NULL` // valid `operator` incldue: `=`, `!=`, `<>`, `>=`, `<=`, `>`, `<`, `LIKE`, `ILIKE`, `IS NULL`, `IS NOT NULL`
// example: `where('(a > ? AND b <= ?) OR (c <> ? AND (x = ? OR y = ?))', a, b, c, x, y)` // example: `where('(a > ? AND b <= ?) OR (c <> ? AND (x = ? OR y = ?))', a, b, c, x, y)`
pub fn (qb_ &QueryBuilder[T]) where(condition string, params ...Primitive) !&QueryBuilder[T] { pub fn (qb_ &QueryBuilder[T]) where(condition string, params ...Primitive) !&QueryBuilder[T] {
mut qb := unsafe { qb_ } mut qb := unsafe { qb_ }
if qb.where.fields.len > 0 {
// skip first field
qb.where.is_and << true // and
}
qb.parse_conditions(condition, params)!
qb.config.has_where = true
return qb
}
// or_where create a `where` clause, it will `OR` with previous `where` clause.
pub fn (qb_ &QueryBuilder[T]) or_where(condition string, params ...Primitive) !&QueryBuilder[T] {
mut qb := unsafe { qb_ }
if qb.where.fields.len > 0 {
// skip first field
qb.where.is_and << false // or
}
qb.parse_conditions(condition, params)! qb.parse_conditions(condition, params)!
qb.config.has_where = true qb.config.has_where = true
return qb return qb

View File

@ -496,6 +496,12 @@ fn test_orm_func_stmts() {
assert selected_users[0].name == 'Silly' assert selected_users[0].name == 'Silly'
assert selected_users.len == 1 assert selected_users.len == 1
// chain where
and_where := qb.where('salary > ?', 2000)!.where('age > ?', 40)!.query()!
assert and_where.len == 1
or_where := qb.where('salary > ?', 2000)!.or_where('age > ? OR score > ?', 40, 85)!.query()!
assert or_where.len == 9
// chain calls // chain calls
final_users := qb final_users := qb
.drop()! .drop()!