/
sql.go
234 lines (207 loc) · 4.82 KB
/
sql.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
package query
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"github.com/ezbuy/ezorm/v2/internal/generator"
"github.com/iancoleman/strcase"
)
type T uint8
const (
T_PLACEHOLDER T = iota
T_INT
T_STRING
T_ARRAY_STRING
T_ARRAY_INT
T_ANY
)
func (t T) String() string {
switch t {
case T_PLACEHOLDER:
return "?"
case T_INT:
return "int64"
case T_STRING:
return "string"
case T_ARRAY_STRING:
return "[]string"
case T_ARRAY_INT:
return "[]int64"
case T_ANY:
return "any"
}
panic("parser: unknown type")
}
func (t T) BaseType() string {
switch t {
case T_PLACEHOLDER:
return "?"
case T_INT, T_ARRAY_INT:
return "int64"
case T_STRING, T_ARRAY_STRING:
return "string"
case T_ANY:
return "any"
}
panic("parser: unknown type")
}
type QueryField struct {
Name string
Type T
Alias string
IsLike bool
}
var _ fmt.Stringer = (*QueryMetadata)(nil)
type LimitOption struct {
count, offset bool
}
type QueryMetadata struct {
table string
params []*QueryField
result []*QueryField
}
type Table struct {
Name string
Alias string
}
type TableMetadata map[Table]*QueryMetadata
func (t TableMetadata) String() string {
var buffer bytes.Buffer
var tables []Table
for table := range t {
tables = append(tables, table)
}
sort.SliceStable(tables, func(i, j int) bool {
return tables[i].Name < tables[j].Name
})
for _, table := range tables {
if qm, ok := t[table]; ok {
buffer.WriteString(fmt.Sprintf("table: %s\n", table))
buffer.WriteString(qm.String())
}
}
return buffer.String()
}
func (t TableMetadata) AppendParams(table string, params ...*QueryField) {
var key Table
for tb := range t {
if tb.Name == table || tb.Alias == table {
key = tb
}
}
if key.Alias == "" && key.Name == "" {
return
}
if _, ok := t[key]; ok {
t[key].params = append(t[key].params, params...)
}
}
func (t TableMetadata) AppendResult(table string, result ...*QueryField) {
var key Table
for tb := range t {
if tb.Name == table || tb.Alias == table {
key = tb
}
}
if key.Alias == "" && key.Name == "" {
return
}
if _, ok := t[key]; ok {
t[key].result = append(t[key].result, result...)
}
}
func uglify(col string) string {
if strings.Contains(col, ":") {
parts := strings.Split(col, ":")
if len(parts) != 2 {
return col
}
col = parts[1]
}
if strings.Contains(col, ".") {
parts := strings.Split(col, ".")
if len(parts) != 2 {
return col
}
col = parts[1]
}
col = strings.ReplaceAll(col, "`", "")
return col
}
func typeMatch(fromAST T, fromSchema generator.IField) bool {
if strings.Contains(fromAST.BaseType(), "int") && strings.Contains(fromSchema.GetGoType(), "int") {
return true
}
return fromAST.BaseType() == fromSchema.GetGoType()
}
func (tm TableMetadata) Validate(tableRef map[string]map[string]generator.IField) error {
for t, f := range tm {
name := uglify(t.Name)
ff, ok := tableRef[name]
if !ok {
return fmt.Errorf("metadata: table %s not found in tableRef(YAML)", name)
}
for _, p := range f.params {
pName := uglify(p.Name)
pName = strcase.ToLowerCamel(pName)
col, ok := ff[pName]
if !ok && p.Type != T_ANY && p.Name != LIMIT_COUNT && p.Name != LIMIT_OFFSET {
return fmt.Errorf("metadata: param %s not found in table %s", pName, name)
}
if p.Name != LIMIT_COUNT && p.Name != LIMIT_OFFSET && !typeMatch(p.Type, col) && p.Type != T_ANY {
return fmt.Errorf("metadata: param %s type mismatch, expect %s, got %s", pName, col.GetGoType(), p.Type.BaseType())
}
}
for _, r := range f.result {
rName := uglify(r.Name)
rName = strcase.ToLowerCamel(rName)
if _, ok := ff[rName]; !ok && r.Type != T_ANY {
return fmt.Errorf("metadata: result %s not found in table %s", rName, name)
}
}
}
return nil
}
func (qm *QueryMetadata) String() string {
var buffer bytes.Buffer
sort.Slice(qm.params, func(i, j int) bool {
return qm.params[i].Name < qm.params[j].Name
})
for _, p := range qm.params {
buffer.WriteString(fmt.Sprintf("param: name: %s, type: %s\n", p.Name, p.Type))
}
for _, r := range qm.result {
buffer.WriteString(fmt.Sprintf("result: name: %s, type: %s\n", r.Name, r.Type))
}
return buffer.String()
}
type QueryBuilder struct {
*bytes.Buffer
raw *Raw
resultFields []*QueryField
}
func (qb *QueryBuilder) IsQueryIn() bool {
return len(qb.raw.ins) > 0
}
func (qb *QueryBuilder) rebuild() string {
query := qb.String()
i := strings.Index(query, "WHERE")
rebuildQuery := bytes.NewBuffer(nil)
rebuildQuery.WriteString(query[:i])
rebuildQuery.WriteString("%s")
// rebuildQuery.WriteString(query[s:])
return rebuildQuery.String()
}
type LocationOffset struct {
start, end int
}
type Raw struct {
ins map[string]struct{}
}
// RawQueryParser is a parser to extract metedata from sql query
type RawQueryParser interface {
Parse(context.Context, string) (TableMetadata, *QueryBuilder, error)
Flush()
}