-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery_builder.go
88 lines (63 loc) · 1.48 KB
/
query_builder.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package sqb
import (
"log"
"strings"
)
// Query struct for QB
type Query struct {
tableName string // Имя таблицы
selectFields string // Выбираемые поля
limit int // Лимит
offset int // Отступ
where []string // Выборка
}
// --------------- PUBLIC ---------------
// NewQuery creates a new query object
func NewQuery(tableName string) *Query {
return &Query{
tableName: tableName,
where: []string{},
}
}
// ----------- STRUCT METHODS -----------
// Select adds a select expression
func (q *Query) Select(expr string) *Query {
q.selectFields = expr
return q
}
// Where adds a where
func (q *Query) Where(whereType string, condition string) *Query {
whereType = strings.ToUpper(whereType)
if whereType != "AND" && whereType != "OR" {
log.Printf("Unknown WHERE type: %v\n", whereType)
return q
}
q.where = append(q.where, whereType+" "+condition)
return q
}
// Limit sets a limit
func (q *Query) Limit(limit int) *Query {
q.limit = limit
return q
}
// Offset sets a offset
func (q *Query) Offset(offset int) *Query {
q.offset = offset
return q
}
// Generate sql statement
func (q *Query) Generate() string {
result := ""
if q.selectFields != "" {
result += "SELECT " + q.selectFields
} else {
result += "SELECT *"
}
result += " FROM " + q.tableName
result += " WHERE 1 = 1"
for _, cond := range q.where {
result += " " + cond
}
return result
}
// --------------- PRIVATE ---------------