forked from yunionio/sqlchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.go
More file actions
105 lines (86 loc) · 2.16 KB
/
functions.go
File metadata and controls
105 lines (86 loc) · 2.16 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package sqlchemy
import (
"fmt"
"strconv"
"strings"
)
type SFunctionField struct {
fields []IQueryField
function string
alias string
}
func (ff *SFunctionField) Expression() string {
fieldRefs := make([]interface{}, 0)
for _, f := range ff.fields {
fieldRefs = append(fieldRefs, f.Reference())
}
return fmt.Sprintf("%s AS %s", fmt.Sprintf(ff.function, fieldRefs...), ff.Name())
}
func (ff *SFunctionField) Name() string {
return ff.alias
}
func (ff *SFunctionField) Reference() string {
return ff.alias
}
func (ff *SFunctionField) Label(label string) IQueryField {
if len(label) > 0 && label != ff.alias {
ff.alias = label
}
return ff
}
func NewFunctionField(name string, funcexp string, fields ...IQueryField) SFunctionField {
ff := SFunctionField{function: funcexp, alias: name, fields: fields}
return ff
}
func COUNT(name string, field ...IQueryField) IQueryField {
var expr string
if len(field) == 0 {
expr = "COUNT(*)"
} else {
expr = "COUNT(%s)"
}
ff := NewFunctionField(name, expr, field...)
return &ff
}
func MAX(name string, field IQueryField) IQueryField {
ff := NewFunctionField(name, "MAX(%s)", field)
return &ff
}
func SUM(name string, field IQueryField) IQueryField {
ff := NewFunctionField(name, "SUM(%s)", field)
return &ff
}
func DISTINCT(name string, field IQueryField) IQueryField {
ff := NewFunctionField(name, "DISTINCT(%s)", field)
return &ff
}
func GROUP_CONCAT(name string, field IQueryField) IQueryField {
ff := NewFunctionField(name, "GROUP_CONCAT(%s)", field)
return &ff
}
type SStringField struct {
strConst string
}
func (s *SStringField) Expression() string {
return ""
}
func (s *SStringField) Name() string {
return ""
}
func (s *SStringField) Reference() string {
return strconv.Quote(s.strConst)
}
func (s *SStringField) Label(label string) IQueryField {
return s
}
func NewStringField(name string) *SStringField {
return &SStringField{strConst: name}
}
func CONCAT(name string, fields ...IQueryField) IQueryField {
params := []string{}
for i := 0; i < len(fields); i++ {
params = append(params, "%s")
}
ff := NewFunctionField(name, `CONCAT(`+strings.Join(params, ",")+`)`, fields...)
return &ff
}