-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
condition.go
73 lines (61 loc) · 1.64 KB
/
condition.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package qry
import (
"fmt"
"strings"
)
// Condition is a condition that can be used in a where clause.
type Condition interface {
// Build returns an SQL statement and the related args.
Build() (string, []any)
}
// ConditionGroup is a Condition made up of many Conditions separated by an AND or an OR.
type ConditionGroup struct {
Conditions []Condition
Or bool
}
// Build returns an SQL statement and the related args.
// The statement is already wrapped in brackets.
func (group *ConditionGroup) Build() (string, []any) {
if group == nil {
return "", make([]any, 0)
}
parts := make([]string, 0)
args := make([]any, 0)
if len(group.Conditions) == 0 {
return "", args
}
if len(group.Conditions) > 0 {
for _, cs := range group.Conditions {
part, partArgs := cs.Build()
parts = append(parts, part)
args = append(args, partArgs...)
}
}
sep := " AND "
if group.Or {
sep = " OR "
}
return fmt.Sprintf("(%s)", strings.Join(parts, sep)), args
}
// SimpleCondition is a Condition that can be used to make a basic comparison.
// E.g. user_id = "123"
type SimpleCondition struct {
Field Field
Value any
Comparison string
}
// Build returns an SQL statement and the related args.
func (query *SimpleCondition) Build() (string, []any) {
stmt := fmt.Sprintf("%s %s ?", query.Field, query.Comparison)
args := []any{query.Value}
return stmt, args
}
// RawCondition is a Condition that can be used to make more complex comparisons.
type RawCondition struct {
SQL string
Args []any
}
// Build returns an SQL statement and the related args.
func (query *RawCondition) Build() (string, []any) {
return query.SQL, query.Args
}