-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_builder.go
More file actions
86 lines (74 loc) · 1.97 KB
/
query_builder.go
File metadata and controls
86 lines (74 loc) · 1.97 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
package querybuilder
import (
"fmt"
"strings"
)
type QueryBuilder struct {
baseQuery string
conditions []string
operators []string
args []any
values []any
argCounter int
limitValue int
offsetValue int
sortFields []SortField
}
type QueryCondition struct {
condition string
value any
placeholder string
isGroup bool
groupConds []QueryCondition
groupOp string
}
type SortField struct {
field string
direction SortDirection
}
func NewQueryBuilder(query string) *QueryBuilder {
return &QueryBuilder{
baseQuery: strings.TrimSpace(query),
conditions: []string{},
operators: []string{},
args: []any{},
values: []any{},
argCounter: 1,
limitValue: -1,
offsetValue: -1,
sortFields: []SortField{},
}
}
func (qb *QueryBuilder) Commit() (string, []any) {
query := qb.baseQuery
if len(qb.conditions) > 0 {
whereClause := " WHERE " + qb.conditions[0]
for i := 1; i < len(qb.conditions); i++ {
whereClause += " " + qb.operators[i] + " " + qb.conditions[i]
}
query += whereClause
}
if len(qb.sortFields) > 0 {
var sortParts []string
for _, field := range qb.sortFields {
sortStr := field.field
if field.direction == SortDesc {
sortStr += " DESC"
}
sortParts = append(sortParts, sortStr)
}
query += " ORDER BY " + strings.Join(sortParts, ", ")
}
// Apply default limit of 10 if offset is set but limit is not
limitToApply := qb.limitValue
if qb.offsetValue >= 0 && qb.limitValue < 0 {
limitToApply = 10
}
if limitToApply >= 0 {
query += fmt.Sprintf(" LIMIT %d", limitToApply)
}
if qb.offsetValue >= 0 {
query += fmt.Sprintf(" OFFSET %d", qb.offsetValue)
}
return query + ";", qb.values
}