/
sql_method.go
247 lines (221 loc) · 5.31 KB
/
sql_method.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package query
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"unicode"
"github.com/ezbuy/ezorm/v2/internal/generator"
"github.com/iancoleman/strcase"
)
type SQL struct {
fieldMap map[string]map[string]generator.IField
RawQueryParser RawQueryParser
}
type SQLFile struct {
GoPackage string
Methods []*SQLMethod
Dir string
}
type SQLMethod struct {
Name string
Fields []*SQLMethodField
Result []*SQLMethodField
Limit *SQLMethodField
Offset *SQLMethodField
OrderBy []*SQLMethodField
SQL string
Assign string
FromFile string
QueryIn bool
}
type SQLMethodField struct {
Name string
Raw string
Type string
FullName string
IsLike bool
IsOrderByDESC bool
}
func NewSQL(objs map[string]generator.IObject) *SQL {
fieldMap := make(map[string]map[string]generator.IField, len(objs))
for table, obj := range objs {
name := camel2name(table)
fieldMap[name] = make(map[string]generator.IField, len(obj.FieldsMap()))
for _, f := range obj.FieldsMap() {
fieldMap[name][f.GetName()] = f
}
}
return &SQL{
fieldMap: fieldMap,
RawQueryParser: NewTiDBParser(),
}
}
func (p *SQL) retypeResult(table string, col string) (string, error) {
t, ok := p.fieldMap[table]
if !ok {
return "", fmt.Errorf("res: retype: table: %s not found", table)
}
col = strcase.ToLowerCamel(col)
f, ok := t[col]
if !ok {
return "", fmt.Errorf("res: retype: field: %s not found", col)
}
return f.GetGoType(), nil
}
func (p *SQL) Read(path string) (*SQLMethod, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
sql := string(data)
ctx := context.Background()
meta, builder, err := p.RawQueryParser.Parse(ctx, sql)
if err != nil {
return nil, err
}
defer p.RawQueryParser.Flush()
// Insert the name to the raw sql as an internal comment.
name := filepath.Base(path)
name = strings.TrimSuffix(name, ".sql")
if name == "" {
return nil, errors.New("parse sql: the filename is empty")
}
name = strcase.ToCamel(name)
result := &SQLMethod{
Name: name,
SQL: sql,
}
// validation: validate if every table and column are defined in yaml file(TableRef).
if err := meta.Validate(p.fieldMap); err != nil {
return nil, err
}
orderBySet := make(map[string]struct{})
for t, f := range meta {
for _, c := range f.params {
parts := strings.Split(c.Name, ":")
if len(parts) != 2 {
fmt.Fprintf(os.Stderr, "invalid param name: %s\n", c.Name)
continue
}
name := c.Alias
if name == "" {
name = uglify(c.Name)
}
switch parts[0] {
case "limit":
switch parts[1] {
case "count":
result.Limit = &SQLMethodField{
Name: "Count",
Raw: name,
Type: c.Type.String(),
}
case "offset":
result.Offset = &SQLMethodField{
Name: "Offset",
Raw: name,
Type: c.Type.String(),
}
}
case "col":
result.Fields = append(result.Fields, &SQLMethodField{
FullName: strings.Split(c.Name, ":")[1],
Name: strcase.ToCamel(name),
Raw: name,
Type: c.Type.String(),
IsLike: c.IsLike,
})
case "orderby-asc":
fname := strings.Split(c.Name, ":")[1]
if _, ok := orderBySet[fname]; ok {
continue
} else {
orderBySet[fname] = struct{}{}
}
result.OrderBy = append(result.OrderBy, &SQLMethodField{
FullName: fname,
Name: strcase.ToCamel(name),
Raw: name,
Type: c.Type.String(),
IsOrderByDESC: false,
})
case "orderby-desc":
fname := strings.Split(c.Name, ":")[1]
if _, ok := orderBySet[fname]; ok {
continue
} else {
orderBySet[fname] = struct{}{}
}
result.OrderBy = append(result.OrderBy, &SQLMethodField{
FullName: fname,
Name: strcase.ToCamel(name),
Raw: name,
Type: c.Type.String(),
IsOrderByDESC: true,
})
}
}
for _, c := range f.result {
name := c.Alias
if name == "" {
name = uglify(c.Name)
}
if c.Type == T_ANY {
result.Result = append(result.Result, &SQLMethodField{
Name: strcase.ToCamel(name),
Type: c.Type.String(),
Raw: name,
})
continue
}
tp, err := p.retypeResult(t.Name, uglify(c.Name))
if err != nil {
return nil, err
}
result.Result = append(result.Result, &SQLMethodField{
Name: strcase.ToCamel(name),
Raw: name,
Type: tp,
})
}
result.QueryIn = builder.IsQueryIn()
}
sort.SliceStable(result.Fields, func(i, j int) bool {
return result.Fields[i].Name < result.Fields[j].Name
})
sort.SliceStable(result.Result, func(i, j int) bool {
return result.Result[i].Name < result.Result[j].Name
})
var scan bytes.Buffer
for _, r := range builder.resultFields {
name := r.Alias
if name == "" {
name = uglify(r.Name)
}
name = strcase.ToCamel(name)
scan.WriteString(fmt.Sprintf("&o.%s, ", name))
}
result.Assign = scan.String()
result.SQL = builder.rebuild()
return result, nil
}
func camel2name(s string) string {
nameBuf := bytes.NewBuffer(nil)
afterSpace := false
for i, c := range s {
if unicode.IsUpper(c) && unicode.IsLetter(c) {
if i > 0 && !afterSpace {
nameBuf.WriteRune('_')
}
c = unicode.ToLower(c)
}
nameBuf.WriteRune(c)
afterSpace = unicode.IsSpace(c)
}
return nameBuf.String()
}