github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/builder/builder_condition.go (about) 1 package builder 2 3 import "context" 4 5 type SqlConditionMarker interface { 6 asCondition() 7 } 8 9 type SqlCondition interface { 10 SqlExpr 11 SqlConditionMarker 12 13 And(SqlCondition) SqlCondition 14 Or(SqlCondition) SqlCondition 15 Xor(SqlCondition) SqlCondition 16 } 17 18 var EmptyCondition SqlCondition = (*Condition)(nil) 19 20 type Condition struct { 21 expr SqlExpr 22 SqlConditionMarker 23 } 24 25 func (c *Condition) IsNil() bool { return c == nil || c.expr == nil } 26 27 func (c *Condition) Ex(ctx context.Context) *Ex { 28 if IsNilExpr(c.expr) { 29 return nil 30 } 31 return c.expr.Ex(ctx) 32 } 33 34 func (c *Condition) And(cond SqlCondition) SqlCondition { 35 if IsNilExpr(cond) { 36 return c 37 } 38 return And(c, cond) 39 } 40 41 func (c *Condition) Or(cond SqlCondition) SqlCondition { 42 if IsNilExpr(cond) { 43 return c 44 } 45 return Or(c, cond) 46 } 47 48 func (c *Condition) Xor(cond SqlCondition) SqlCondition { 49 if IsNilExpr(cond) { 50 return c 51 } 52 return Xor(c, cond) 53 } 54 55 func And(conds ...SqlCondition) SqlCondition { 56 return ComposeConditions("AND", conds...) 57 } 58 59 func Or(conds ...SqlCondition) SqlCondition { 60 return ComposeConditions("OR", conds...) 61 } 62 63 func Xor(conds ...SqlCondition) SqlCondition { 64 return ComposeConditions("XOR", conds...) 65 } 66 67 type CondCompose struct { 68 SqlConditionMarker 69 70 op string 71 conds []SqlCondition 72 } 73 74 func ComposeConditions(op string, conds ...SqlCondition) *CondCompose { 75 c := &CondCompose{op: op} 76 for i := range conds { 77 cond := conds[i] 78 if IsNilExpr(cond) { 79 continue 80 } 81 c.conds = append(c.conds, cond) 82 } 83 return c 84 } 85 86 func (c *CondCompose) IsNil() bool { 87 if c == nil || c.op == "" { 88 return true 89 } 90 for i := range c.conds { 91 if !IsNilExpr(c.conds[i]) { 92 return false 93 } 94 } 95 return true 96 } 97 98 func (c *CondCompose) Ex(ctx context.Context) *Ex { 99 e := Expr("") 100 for i := range c.conds { 101 if i > 0 { 102 e.WriteQueryByte(' ') 103 e.WriteQuery(c.op) 104 e.WriteQueryByte(' ') 105 } 106 e.WriteGroup(func(e *Ex) { 107 e.WriteExpr(c.conds[i]) 108 }) 109 } 110 return e.Ex(ctx) 111 } 112 113 func (c *CondCompose) And(cond SqlCondition) SqlCondition { return And(c, cond) } 114 115 func (c *CondCompose) Or(cond SqlCondition) SqlCondition { return Or(c, cond) } 116 117 func (c *CondCompose) Xor(cond SqlCondition) SqlCondition { return Xor(c, cond) } 118 119 func AsCond(e SqlExpr) *Condition { return &Condition{expr: e} }