-
Notifications
You must be signed in to change notification settings - Fork 1
/
function.go
112 lines (96 loc) · 2.13 KB
/
function.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
103
104
105
106
107
108
109
110
111
112
package genorm
import (
"errors"
"fmt"
)
// Aggregate Functions
/*
Avg
if (distinct) {return AVG(DISTINCT expr)}
else {return AVG(expr)}
*/
func Avg[T Table, S ExprType](expr TypedTableExpr[T, S], distinct bool) TypedTableExpr[T, WrappedPrimitive[float64]] {
if expr == nil {
return &ExprStruct[T, WrappedPrimitive[float64]]{
errs: []error{errors.New("avg expr is nil")},
}
}
query, args, errs := expr.Expr()
if len(errs) != 0 {
return &ExprStruct[T, WrappedPrimitive[float64]]{
errs: errs,
}
}
if distinct {
query = fmt.Sprintf("AVG(DISTINCT %s)", query)
} else {
query = fmt.Sprintf("AVG(%s)", query)
}
return &ExprStruct[T, WrappedPrimitive[float64]]{
query: query,
args: args,
}
}
/*
Count
if (distinct) {return COUNT(DISTINCT expr)}
else {return COUNT(expr)}
*/
func Count[T Table, S ExprType](expr TypedTableExpr[T, S], distinct bool) TypedTableExpr[T, WrappedPrimitive[int64]] {
if expr == nil {
return &ExprStruct[T, WrappedPrimitive[int64]]{
errs: []error{errors.New("count expr is nil")},
}
}
query, args, errs := expr.Expr()
if len(errs) != 0 {
return &ExprStruct[T, WrappedPrimitive[int64]]{
errs: errs,
}
}
if distinct {
query = fmt.Sprintf("COUNT(DISTINCT %s)", query)
} else {
query = fmt.Sprintf("COUNT(%s)", query)
}
return &ExprStruct[T, WrappedPrimitive[int64]]{
query: query,
args: args,
}
}
// Max MAX(expr)
func Max[T Table, S ExprType](expr TypedTableExpr[T, S]) TypedTableExpr[T, S] {
if expr == nil {
return &ExprStruct[T, S]{
errs: []error{errors.New("max expr is nil")},
}
}
query, args, errs := expr.Expr()
if len(errs) != 0 {
return &ExprStruct[T, S]{
errs: errs,
}
}
return &ExprStruct[T, S]{
query: fmt.Sprintf("MAX(%s)", query),
args: args,
}
}
// Min MIN(expr)
func Min[T Table, S ExprType](expr TypedTableExpr[T, S]) TypedTableExpr[T, S] {
if expr == nil {
return &ExprStruct[T, S]{
errs: []error{errors.New("max expr is nil")},
}
}
query, args, errs := expr.Expr()
if len(errs) != 0 {
return &ExprStruct[T, S]{
errs: errs,
}
}
return &ExprStruct[T, S]{
query: fmt.Sprintf("MIN(%s)", query),
args: args,
}
}