-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect.go
102 lines (84 loc) · 2.14 KB
/
select.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package gooqu
import (
"fmt"
"strings"
)
type Record map[string]interface{}
type Query struct {
selectClause selectClause
whereClause whereClause
fromClause fromClause
limitClause limitClause
groupBy groupByClause
setWhereClause bool
setGroupByClause bool
setLimitClause bool
}
type selectClause struct {
selectExpressions selectExpressions
}
func (clause selectClause) String() string {
return fmt.Sprintf("SELECT %s", clause.selectExpressions.String())
}
type whereClause struct {
whereCondition expression
}
func (clause whereClause) String() string {
return fmt.Sprintf("WHERE %s", clause.whereCondition.String())
}
type fromClause struct {
tableReferences tableReferences
joinClause joinClause
setJoinClause bool
}
func (clause fromClause) String() string {
if clause.setJoinClause {
return fmt.Sprintf("FROM %s %s", clause.tableReferences, clause.joinClause)
}
return fmt.Sprintf("FROM %s", clause.tableReferences)
}
func Where(record Record) *Query {
var query Query
query.setWhereClause = true
for key, value := range record {
query.whereClause.whereCondition = newExpression(key, value)
}
return &query
}
func Select(exprs ...SelectExpression) *Query {
var q Query
q.selectClause.selectExpressions = newSelectExpressions(exprs...)
return &q
}
func (q *Query) Select(exprs ...SelectExpression) *Query {
q.selectClause.selectExpressions = newSelectExpressions(exprs...)
return q
}
func (q *Query) From(table_name string) *Query {
q.fromClause.tableReferences = newTableReferences(table_name)
return q
}
func (q *Query) GroupBy(columnName string) *Query {
q.setGroupByClause = true
q.groupBy = newGroupByClause(columnName)
return q
}
func (q Query) ToSQL() string {
elements := []fmt.Stringer{
q.selectClause, q.fromClause,
}
if q.setGroupByClause {
elements = append(elements, q.groupBy)
}
if q.setWhereClause {
elements = append(elements, q.whereClause)
}
if q.setLimitClause {
elements = append(elements, q.limitClause)
}
stringElements := []string{}
for _, v := range elements {
stringElements = append(stringElements, v.String())
}
return strings.Join(stringElements, " ") + ";"
}