-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
select.go
93 lines (76 loc) · 1.67 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
package qry
import (
"fmt"
)
func Select() SelectQuery {
return SelectQuery{}
}
// SelectQuery is a Query.
type SelectQuery struct {
Fields []Field
Table string
Condition Condition
Join []Join
OrderBy []OrderBy
Limit int64
Offset int64
}
type Join struct {
Table string
On Condition
Type string
}
func (j Join) Build() (string, []any) {
var kind = j.Type
if kind != "" {
kind = kind + " "
}
conditionsStmt, conditionArgs := j.On.Build()
return fmt.Sprintf(
"%sJOIN %s ON %s",
kind,
j.Table,
conditionsStmt,
), conditionArgs
}
func (query SelectQuery) Build() (string, []any) {
stmt := fmt.Sprintf(
"SELECT %s FROM %s",
genericJoin(query.Fields, ", "),
query.Table,
)
args := make([]any, 0)
if len(query.Join) > 0 {
for _, join := range query.Join {
joinStmt, joinArgs := join.Build()
stmt += fmt.Sprintf(" %s", joinStmt)
args = append(args, joinArgs...)
}
}
if query.Condition != nil {
if conditionsStmt, conditionArgs := query.Condition.Build(); len(conditionsStmt) > 0 {
stmt += fmt.Sprintf(" WHERE %s", conditionsStmt)
args = append(args, conditionArgs...)
}
}
if len(query.OrderBy) > 0 {
stmt += fmt.Sprintf(" ORDER BY %s", genericJoin(query.OrderBy, ", "))
}
if query.Limit > 0 {
stmt += fmt.Sprintf(" LIMIT %d", query.Limit)
}
if query.Offset > 0 {
stmt += fmt.Sprintf(" OFFSET %d", query.Offset)
}
return stmt, args
}
type TypedSelectQuery[T any] struct {
SelectQuery
FieldReferences func(target *T) []any
}
func (query TypedSelectQuery[T]) Prepare() SelectQuery {
return query.SelectQuery
}
func (query TypedSelectQuery[T]) Build() (string, []any) {
return query.Prepare().Build()
}