github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/sqlutil/condition_test.go (about) 1 package sqlutil 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 ) 8 9 func TestFilter(t *testing.T) { 10 wantClause1 := "a = ? AND b = ? AND ((c = ? AND d = 4) OR (e = ? OR f = 6))" 11 wantString1 := "a = 1 AND b = 2 AND ((c = 3 AND d = 4) OR (e = 5 OR f = 6))" 12 builder1 := And( 13 Cond("a = ?", 1), 14 Cond("b = ?", 2), 15 Or( 16 Cond("c = ?", 3).IfAnd(true, "d = 4"), 17 Cond("e = ?", 5).IfOr(true, "f = 6"), 18 ), 19 ) 20 clause1, args1 := builder1.Build() 21 assert.Equal(t, wantClause1, clause1) 22 assert.Equal(t, wantString1, builder1.String()) 23 assert.Equal(t, []any{1, 2, 3, 5}, args1) 24 25 wantClause2 := "a = ? AND b = ? AND (c = ? OR d = 4) AND (e = ? OR f = 6)" 26 wantString2 := "a = 1 AND b = 2 AND (c = 3 OR d = 4) AND (e = 5 OR f = 6)" 27 builder2 := And( 28 Cond("a = ?", 1), 29 Cond("b = ?", 2), 30 And( 31 Cond("c = ?", 3).Or("d = 4"), 32 Cond("e = ?", 5).Or("f = 6"), 33 ), 34 ) 35 clause2, args2 := builder2.Build() 36 assert.Equal(t, wantClause2, clause2) 37 assert.Equal(t, wantString2, builder2.String()) 38 assert.Equal(t, []any{1, 2, 3, 5}, args2) 39 } 40 41 func TestMisuseOfBrackets(t *testing.T) { 42 want1 := "a = 1 AND (b = 2 Or c = 3)" 43 cond1 := And( 44 Cond("a = 1"), 45 Cond("b = 2 Or c = 3"), 46 ) 47 got1, _ := cond1.Build() 48 assert.Equal(t, want1, got1) 49 50 want2 := "(a = 1 OR (b = 2 AnD c = 3))" 51 cond2 := Or( 52 Cond("a = 1"), 53 Cond("b = 2 AnD c = 3"), 54 ) 55 got2, _ := cond2.Build() 56 assert.Equal(t, want2, got2) 57 58 want3 := "(a = 1 OR ((b = 2) AND (c = 3)))" 59 cond3 := Or( 60 Cond("a = 1"), 61 Cond("(b = 2) AND (c = 3)"), 62 ) 63 got3, _ := cond3.Build() 64 assert.Equal(t, want3, got3) 65 66 want4 := "a = 1 AND ((b = 2) Or (c = 3))" 67 cond4 := And( 68 Cond("a = 1"), 69 Cond("(b = 2) Or (c = 3)"), 70 ) 71 got4, _ := cond4.Build() 72 assert.Equal(t, want4, got4) 73 }