github.com/yongjacky/phoenix-go-orm-builder@v0.3.5/cond_or.go (about)

     1  // Copyright 2016 The Xorm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package builder
     6  
     7  import "fmt"
     8  
     9  type condOr []Cond
    10  
    11  var _ Cond = condOr{}
    12  
    13  // Or sets OR conditions
    14  func Or(conds ...Cond) Cond {
    15  	var result = make(condOr, 0, len(conds))
    16  	for _, cond := range conds {
    17  		if cond == nil || !cond.IsValid() {
    18  			continue
    19  		}
    20  		result = append(result, cond)
    21  	}
    22  	return result
    23  }
    24  
    25  // WriteTo implments Cond
    26  func (o condOr) WriteTo(w Writer) error {
    27  	for i, cond := range o {
    28  		var needQuote bool
    29  		switch cond.(type) {
    30  		case condAnd, expr:
    31  			needQuote = true
    32  		case Eq:
    33  			needQuote = (len(cond.(Eq)) > 1)
    34  		case Neq:
    35  			needQuote = (len(cond.(Neq)) > 1)
    36  		}
    37  
    38  		if needQuote {
    39  			fmt.Fprint(w, "(")
    40  		}
    41  
    42  		err := cond.WriteTo(w)
    43  		if err != nil {
    44  			return err
    45  		}
    46  
    47  		if needQuote {
    48  			fmt.Fprint(w, ")")
    49  		}
    50  
    51  		if i != len(o)-1 {
    52  			fmt.Fprint(w, " OR ")
    53  		}
    54  	}
    55  
    56  	return nil
    57  }
    58  
    59  func (o condOr) And(conds ...Cond) Cond {
    60  	return And(o, And(conds...))
    61  }
    62  
    63  func (o condOr) Or(conds ...Cond) Cond {
    64  	return Or(o, Or(conds...))
    65  }
    66  
    67  func (o condOr) IsValid() bool {
    68  	return len(o) > 0
    69  }