cond.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. package builder
  5. import (
  6. "bytes"
  7. "io"
  8. )
  9. // Writer defines the interface
  10. type Writer interface {
  11. io.Writer
  12. Append(...interface{})
  13. }
  14. var _ Writer = NewWriter()
  15. // BytesWriter implments Writer and save SQL in bytes.Buffer
  16. type BytesWriter struct {
  17. writer *bytes.Buffer
  18. buffer []byte
  19. args []interface{}
  20. }
  21. // NewWriter creates a new string writer
  22. func NewWriter() *BytesWriter {
  23. w := &BytesWriter{}
  24. w.writer = bytes.NewBuffer(w.buffer)
  25. return w
  26. }
  27. // Write writes data to Writer
  28. func (s *BytesWriter) Write(buf []byte) (int, error) {
  29. return s.writer.Write(buf)
  30. }
  31. // Append appends args to Writer
  32. func (s *BytesWriter) Append(args ...interface{}) {
  33. s.args = append(s.args, args...)
  34. }
  35. // Cond defines an interface
  36. type Cond interface {
  37. WriteTo(Writer) error
  38. And(...Cond) Cond
  39. Or(...Cond) Cond
  40. IsValid() bool
  41. }
  42. type condEmpty struct{}
  43. var _ Cond = condEmpty{}
  44. // NewCond creates an empty condition
  45. func NewCond() Cond {
  46. return condEmpty{}
  47. }
  48. func (condEmpty) WriteTo(w Writer) error {
  49. return nil
  50. }
  51. func (condEmpty) And(conds ...Cond) Cond {
  52. return And(conds...)
  53. }
  54. func (condEmpty) Or(conds ...Cond) Cond {
  55. return Or(conds...)
  56. }
  57. func (condEmpty) IsValid() bool {
  58. return false
  59. }
  60. func condToSQL(cond Cond) (string, []interface{}, error) {
  61. if cond == nil || !cond.IsValid() {
  62. return "", nil, nil
  63. }
  64. w := NewWriter()
  65. if err := cond.WriteTo(w); err != nil {
  66. return "", nil, err
  67. }
  68. return w.writer.String(), w.args, nil
  69. }