@@ -6,6 +6,20 @@ import (
66 q "github.com/loilo-inc/exql/v3/query"
77)
88
9+ type emptyCondition struct {}
10+
11+ func (emptyCondition ) Query () (string , []any , error ) {
12+ return "" , nil , nil
13+ }
14+
15+ func (emptyCondition ) And (string , ... any ) {}
16+
17+ func (emptyCondition ) Or (string , ... any ) {}
18+
19+ func (emptyCondition ) AndCond (q.Condition ) {}
20+
21+ func (emptyCondition ) OrCond (q.Condition ) {}
22+
923func TestQuery (t * testing.T ) {
1024 assertQuery (t , q .V (1 , 2 ), "?,?" , 1 , 2 )
1125 assertQuery (t , q .Vals ([]int {1 , 2 }), "?,?" , 1 , 2 )
@@ -47,12 +61,31 @@ func TestCondition(t *testing.T) {
4761 cond .AndCond (q .Cond ("foo = ?" , "foo" ))
4862 cond .OrCond (q .Cond ("var = ?" , "var" ))
4963 assertQuery (t , cond ,
50- "id = ? AND name = ? OR age in (?,?) AND foo = ? OR var = ?" ,
64+ "id = ? AND name = ? OR age in (?,?) AND ( foo = ?) OR ( var = ?) " ,
5165 1 , "go" , 20 , 21 , "foo" , "var" ,
5266 )
5367 })
68+ t .Run ("nested conditions are grouped" , func (t * testing.T ) {
69+ tenantScoped := q .Cond ("tenant_id = ?" , 1 )
70+ byIDOrEmail := q .Cond ("id = ?" , 10 )
71+ byIDOrEmail .Or ("email = ?" , "user@example.com" )
72+
73+ tenantScoped .AndCond (byIDOrEmail )
74+
75+ assertQuery (t , tenantScoped ,
76+ "tenant_id = ? AND (id = ? OR email = ?)" ,
77+ 1 , 10 , "user@example.com" ,
78+ )
79+ })
80+
5481 t .Run ("should error if query retuerned an error" , func (t * testing.T ) {
5582 cond := q .CondFrom (q .Q ("" ))
5683 assertQueryErr (t , cond , "DANGER: empty query" )
5784 })
85+
86+ t .Run ("should error if grouped condition returned an empty query" , func (t * testing.T ) {
87+ cond := q .Cond ("id = ?" , 1 )
88+ cond .AndCond (emptyCondition {})
89+ assertQueryErr (t , cond , "DANGER: empty query" )
90+ })
5891}
0 commit comments