Skip to content

Commit 4e6b56d

Browse files
authored
orm: add or_where() method to the builder (fix #24244) (#24250)
1 parent ccb3d5c commit 4e6b56d

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎vlib/orm/orm_func.v‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,28 @@ pub fn (qb_ &QueryBuilder[T]) reset() &QueryBuilder[T] {
4343
return qb
4444
}
4545

46-
// where create a `where` clause
46+
// where create a `where` clause, it will `AND` with previous `where` clause.
4747
// valid token in the `condition` include: `field's names`, `operator`, `(`, `)`, `?`, `AND`, `OR`, `||`, `&&`,
4848
// valid `operator` incldue: `=`, `!=`, `<>`, `>=`, `<=`, `>`, `<`, `LIKE`, `ILIKE`, `IS NULL`, `IS NOT NULL`
4949
// example: `where('(a > ? AND b <= ?) OR (c <> ? AND (x = ? OR y = ?))', a, b, c, x, y)`
5050
pub fn (qb_ &QueryBuilder[T]) where(condition string, params ...Primitive) !&QueryBuilder[T] {
5151
mut qb := unsafe { qb_ }
52+
if qb.where.fields.len > 0 {
53+
// skip first field
54+
qb.where.is_and << true // and
55+
}
56+
qb.parse_conditions(condition, params)!
57+
qb.config.has_where = true
58+
return qb
59+
}
60+
61+
// or_where create a `where` clause, it will `OR` with previous `where` clause.
62+
pub fn (qb_ &QueryBuilder[T]) or_where(condition string, params ...Primitive) !&QueryBuilder[T] {
63+
mut qb := unsafe { qb_ }
64+
if qb.where.fields.len > 0 {
65+
// skip first field
66+
qb.where.is_and << false // or
67+
}
5268
qb.parse_conditions(condition, params)!
5369
qb.config.has_where = true
5470
return qb

‎vlib/orm/orm_func_test.v‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,12 @@ fn test_orm_func_stmts() {
496496
assert selected_users[0].name == 'Silly'
497497
assert selected_users.len == 1
498498

499+
// chain where
500+
and_where := qb.where('salary > ?', 2000)!.where('age > ?', 40)!.query()!
501+
assert and_where.len == 1
502+
or_where := qb.where('salary > ?', 2000)!.or_where('age > ? OR score > ?', 40, 85)!.query()!
503+
assert or_where.len == 9
504+
499505
// chain calls
500506
final_users := qb
501507
.drop()!

0 commit comments

Comments
 (0)