forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
356 lines (328 loc) · 9.07 KB
/
ast.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sqlparser
import (
"bytes"
"fmt"
"github.com/youtube/vitess/go/sqltypes"
)
type ParserError struct {
Message string
}
func NewParserError(format string, args ...interface{}) ParserError {
return ParserError{fmt.Sprintf(format, args...)}
}
func (err ParserError) Error() string {
return err.Message
}
func handleError(err *error) {
if x := recover(); x != nil {
*err = x.(ParserError)
}
}
type Node struct {
Type int
Value []byte
Sub []*Node
}
func Parse(sql string) (*Node, error) {
tokenizer := NewStringTokenizer(sql)
if yyParse(tokenizer) != 0 {
return nil, NewParserError("%s", tokenizer.LastError)
}
return tokenizer.ParseTree, nil
}
func NewSimpleParseNode(Type int, value string) *Node {
return &Node{Type: Type, Value: []byte(value)}
}
func NewParseNode(Type int, value []byte) *Node {
return &Node{Type: Type, Value: value}
}
func (node *Node) PushTwo(left *Node, right *Node) *Node {
node.Push(left)
return node.Push(right)
}
func (node *Node) Push(value *Node) *Node {
if node.Sub == nil {
node.Sub = make([]*Node, 0, 2)
}
node.Sub = append(node.Sub, value)
return node
}
func (node *Node) Pop() *Node {
node.Sub = node.Sub[:len(node.Sub)-1]
return node
}
func (node *Node) At(index int) *Node {
return node.Sub[index]
}
func (node *Node) Set(index int, val *Node) {
node.Sub[index] = val
}
func (node *Node) Len() int {
return len(node.Sub)
}
func (node *Node) LowerCase() {
node.Value = bytes.ToLower(node.Value)
}
func (node *Node) String() (out string) {
buf := NewTrackedBuffer(nil)
buf.Fprintf("%v", node)
return buf.String()
}
func (node *Node) TreeString() string {
buf := bytes.NewBuffer(make([]byte, 0, 8))
node.NodeString(0, buf)
return buf.String()
}
func (node *Node) NodeString(level int, buf *bytes.Buffer) {
for i := 0; i < level; i++ {
buf.WriteString("|-")
}
buf.Write(node.Value)
buf.WriteByte('\n')
for i := 0; i < node.Len(); i++ {
node.At(i).NodeString(level+1, buf)
}
}
// FormatNode is the standard node formatter that
// generates the SQL statement from the AST.
func FormatNode(buf *TrackedBuffer, node *Node) {
switch node.Type {
case SELECT:
buf.Fprintf("select %v%v%v from %v%v%v%v%v%v%v",
node.At(SELECT_COMMENT_OFFSET),
node.At(SELECT_DISTINCT_OFFSET),
node.At(SELECT_EXPR_OFFSET),
node.At(SELECT_FROM_OFFSET),
node.At(SELECT_WHERE_OFFSET),
node.At(SELECT_GROUP_OFFSET),
node.At(SELECT_HAVING_OFFSET),
node.At(SELECT_ORDER_OFFSET),
node.At(SELECT_LIMIT_OFFSET),
node.At(SELECT_LOCK_OFFSET),
)
case INSERT:
buf.Fprintf("insert %vinto %v%v %v%v",
node.At(INSERT_COMMENT_OFFSET),
node.At(INSERT_TABLE_OFFSET),
node.At(INSERT_COLUMN_LIST_OFFSET),
node.At(INSERT_VALUES_OFFSET),
node.At(INSERT_ON_DUP_OFFSET),
)
case UPDATE:
buf.Fprintf("update %v%v set %v%v%v%v",
node.At(UPDATE_COMMENT_OFFSET),
node.At(UPDATE_TABLE_OFFSET),
node.At(UPDATE_LIST_OFFSET),
node.At(UPDATE_WHERE_OFFSET),
node.At(UPDATE_ORDER_OFFSET),
node.At(UPDATE_LIMIT_OFFSET),
)
case DELETE:
buf.Fprintf("delete %vfrom %v%v%v%v",
node.At(DELETE_COMMENT_OFFSET),
node.At(DELETE_TABLE_OFFSET),
node.At(DELETE_WHERE_OFFSET),
node.At(DELETE_ORDER_OFFSET),
node.At(DELETE_LIMIT_OFFSET),
)
case SET:
buf.Fprintf("set %v%v", node.At(0), node.At(1))
case CREATE, ALTER, DROP:
buf.Fprintf("%s table %v", node.Value, node.At(0))
case RENAME:
buf.Fprintf("%s table %v %v", node.Value, node.At(0), node.At(1))
case TABLE_EXPR:
buf.Fprintf("%v", node.At(0))
if node.At(1).Len() == 1 {
buf.Fprintf(" as %v", node.At(1).At(0))
}
buf.Fprintf("%v", node.At(2))
case USE, FORCE:
if node.Len() != 0 {
buf.Fprintf(" %s index %v", node.Value, node.At(0))
}
case WHERE, HAVING:
if node.Len() > 0 {
buf.Fprintf(" %s %v", node.Value, node.At(0))
}
case ORDER, GROUP:
if node.Len() > 0 {
buf.Fprintf(" %s by %v", node.Value, node.At(0))
}
case LIMIT:
if node.Len() > 0 {
buf.Fprintf(" %s %v", node.Value, node.At(0))
if node.Len() > 1 {
buf.Fprintf(", %v", node.At(1))
}
}
case COLUMN_LIST, INDEX_LIST:
if node.Len() > 0 {
buf.Fprintf("(%v", node.At(0))
for i := 1; i < node.Len(); i++ {
buf.Fprintf(", %v", node.At(i))
}
buf.WriteByte(')')
}
case NODE_LIST:
if node.Len() > 0 {
buf.Fprintf("%v", node.At(0))
for i := 1; i < node.Len(); i++ {
buf.Fprintf(", %v", node.At(i))
}
}
case COMMENT_LIST:
if node.Len() > 0 {
for i := 0; i < node.Len(); i++ {
buf.Fprintf("%v", node.At(i))
}
}
case WHEN_LIST:
buf.Fprintf("%v", node.At(0))
for i := 1; i < node.Len(); i++ {
buf.Fprintf(" %v", node.At(i))
}
case JOIN, STRAIGHT_JOIN, LEFT, RIGHT, CROSS, NATURAL:
buf.Fprintf("%v %s %v", node.At(0), node.Value, node.At(1))
if node.Len() > 2 {
buf.Fprintf(" on %v", node.At(2))
}
case DUPLICATE:
if node.Len() != 0 {
buf.Fprintf(" on duplicate key update %v", node.At(0))
}
case NUMBER, NULL, SELECT_STAR, NO_DISTINCT, COMMENT, NO_LOCK, FOR_UPDATE, LOCK_IN_SHARE_MODE, TABLE:
buf.Fprintf("%s", node.Value)
case ID:
if _, ok := keywords[string(node.Value)]; ok {
buf.Fprintf("`%s`", node.Value)
} else {
buf.Fprintf("%s", node.Value)
}
case VALUE_ARG:
buf.WriteArg(string(node.Value[1:]))
case STRING:
s := sqltypes.MakeString(node.Value)
s.EncodeSql(buf)
case '+', '-', '*', '/', '%', '&', '|', '^', '.':
buf.Fprintf("%v%s%v", node.At(0), node.Value, node.At(1))
case CASE_WHEN:
buf.Fprintf("case %v end", node.At(0))
case CASE:
buf.Fprintf("case %v %v end", node.At(0), node.At(1))
case WHEN:
buf.Fprintf("when %v then %v", node.At(0), node.At(1))
case ELSE:
buf.Fprintf("else %v", node.At(0))
case '=', '>', '<', GE, LE, NE, NULL_SAFE_EQUAL, AS, AND, OR, UNION, UNION_ALL, MINUS, EXCEPT, INTERSECT, LIKE, NOT_LIKE, IN, NOT_IN:
buf.Fprintf("%v %s %v", node.At(0), node.Value, node.At(1))
case '(':
buf.Fprintf("(%v)", node.At(0))
case EXISTS:
buf.Fprintf("%s (%v)", node.Value, node.At(0))
case FUNCTION:
if node.Len() == 2 { // DISTINCT
buf.Fprintf("%s(%v%v)", node.Value, node.At(0), node.At(1))
} else {
buf.Fprintf("%s(%v)", node.Value, node.At(0))
}
case UPLUS, UMINUS, '~':
buf.Fprintf("%s%v", node.Value, node.At(0))
case NOT, VALUES:
buf.Fprintf("%s %v", node.Value, node.At(0))
case ASC, DESC, IS_NULL, IS_NOT_NULL:
buf.Fprintf("%v %s", node.At(0), node.Value)
case BETWEEN, NOT_BETWEEN:
buf.Fprintf("%v %s %v and %v", node.At(0), node.Value, node.At(1), node.At(2))
case DISTINCT:
buf.Fprintf("%s ", node.Value)
default:
buf.Fprintf("Unknown: %s", node.Value)
}
}
// AnonymizedFormatNode is just like FormatNode except that
// it anonymizes all values in the SQL.
func AnonymizedFormatNode(buf *TrackedBuffer, node *Node) {
switch node.Type {
case STRING, NUMBER:
buf.Fprintf("?")
default:
FormatNode(buf, node)
}
}
// TrackedBuffer is used to rebuild a query from the ast.
// bindLocations keeps track of locations in the buffer that
// use bind variables for efficient future substitutions.
// nodeFormatter is the formatting function the buffer will
// use to format a node. By default(nil), it's FormatNode.
// But you can supply a different formatting function if you
// want to generate a query that's different from the default.
type TrackedBuffer struct {
*bytes.Buffer
bindLocations []BindLocation
nodeFormatter func(buf *TrackedBuffer, node *Node)
}
func NewTrackedBuffer(nodeFormatter func(buf *TrackedBuffer, node *Node)) *TrackedBuffer {
if nodeFormatter == nil {
nodeFormatter = FormatNode
}
buf := &TrackedBuffer{
Buffer: bytes.NewBuffer(make([]byte, 0, 128)),
bindLocations: make([]BindLocation, 0, 4),
nodeFormatter: nodeFormatter,
}
return buf
}
// Fprintf mimics fmt.Fprintf, but limited to Node(%v), Node.Value(%s) and string(%s).
// It also allows a %a for a value argument, in which case it adds tracking info for
// future substitutions.
func (buf *TrackedBuffer) Fprintf(format string, values ...interface{}) {
end := len(format)
fieldnum := 0
for i := 0; i < end; {
lasti := i
for i < end && format[i] != '%' {
i++
}
if i > lasti {
buf.WriteString(format[lasti:i])
}
if i >= end {
break
}
i++ // '%'
switch format[i] {
case 's':
switch v := values[fieldnum].(type) {
case []byte:
buf.Write(v)
case string:
buf.WriteString(v)
default:
panic(fmt.Sprintf("unexpected type %T", v))
}
case 'v':
node := values[fieldnum].(*Node)
buf.nodeFormatter(buf, node)
case 'a':
buf.WriteArg(values[fieldnum].(string))
default:
panic("unexpected")
}
fieldnum++
i++
}
}
// WriteArg writes a value argument into the buffer. arg should not contain
// the ':' prefix. It also adds tracking info for future substitutions.
func (buf *TrackedBuffer) WriteArg(arg string) {
buf.bindLocations = append(buf.bindLocations, BindLocation{buf.Len(), len(arg) + 1})
buf.WriteString(":")
buf.WriteString(arg)
}
func (buf *TrackedBuffer) ParsedQuery() *ParsedQuery {
return &ParsedQuery{buf.String(), buf.bindLocations}
}