-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
302 lines (269 loc) · 8.64 KB
/
parser.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
/*
Copyright 2019 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sqlparser
import (
"fmt"
"io"
"strconv"
"strings"
"sync"
"github.com/wesql/sqlparser/go/vt/vterrors"
vtrpcpb "github.com/wesql/sqlparser/go/vt/proto/vtrpc"
)
var versionFlagSync sync.Once
// parserPool is a pool for parser objects.
var parserPool = sync.Pool{
New: func() any {
return &yyParserImpl{}
},
}
// zeroParser is a zero-initialized parser to help reinitialize the parser for pooling.
var zeroParser yyParserImpl
// mySQLParserVersion is the version of MySQL that the parser would emulate
var mySQLParserVersion string
// yyParsePooled is a wrapper around yyParse that pools the parser objects. There isn't a
// particularly good reason to use yyParse directly, since it immediately discards its parser.
//
// N.B: Parser pooling means that you CANNOT take references directly to parse stack variables (e.g.
// $$ = &$4) in sql.y rules. You must instead add an intermediate reference like so:
//
// showCollationFilterOpt := $4
// $$ = &Show{Type: string($2), ShowCollationFilterOpt: &showCollationFilterOpt}
func yyParsePooled(yylex yyLexer) int {
parser := parserPool.Get().(*yyParserImpl)
defer func() {
*parser = zeroParser
parserPool.Put(parser)
}()
return parser.Parse(yylex)
}
// Instructions for creating new types: If a type
// needs to satisfy an interface, declare that function
// along with that interface. This will help users
// identify the list of types to which they can assert
// those interfaces.
// If the member of a type has a string with a predefined
// list of values, declare those values as const following
// the type.
// For interfaces that define dummy functions to consolidate
// a set of types, define the function as iTypeName.
// This will help avoid name collisions.
// Parse2 parses the SQL in full and returns a Statement, which
// is the AST representation of the query, and a set of BindVars, which are all the
// bind variables that were found in the original SQL query. If a DDL statement
// is partially parsed but still contains a syntax error, the
// error is ignored and the DDL is returned anyway.
func Parse2(sql string) (Statement, BindVars, error) {
tokenizer := NewStringTokenizer(sql)
if yyParsePooled(tokenizer) != 0 {
if tokenizer.partialDDL != nil {
if typ, val := tokenizer.Scan(); typ != 0 {
return nil, nil, fmt.Errorf("extra characters encountered after end of DDL: '%s'", string(val))
}
switch x := tokenizer.partialDDL.(type) {
case DBDDLStatement:
x.SetFullyParsed(false)
case DDLStatement:
x.SetFullyParsed(false)
}
tokenizer.ParseTree = tokenizer.partialDDL
return tokenizer.ParseTree, tokenizer.BindVars, nil
}
return nil, nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, tokenizer.LastError.Error())
}
if tokenizer.ParseTree == nil {
return nil, nil, ErrEmpty
}
return tokenizer.ParseTree, tokenizer.BindVars, nil
}
// SetParserVersion sets the mysql parser version
func SetParserVersion(version string) {
mySQLParserVersion = version
}
// GetParserVersion returns the version of the mysql parser
func GetParserVersion() string {
return mySQLParserVersion
}
// convertMySQLVersionToCommentVersion converts the MySQL version into comment version format.
func convertMySQLVersionToCommentVersion(version string) (string, error) {
var res = make([]int, 3)
idx := 0
val := ""
for _, c := range version {
if c <= '9' && c >= '0' {
val += string(c)
} else if c == '.' {
v, err := strconv.Atoi(val)
if err != nil {
return "", err
}
val = ""
res[idx] = v
idx++
if idx == 3 {
break
}
} else {
break
}
}
if val != "" {
v, err := strconv.Atoi(val)
if err != nil {
return "", err
}
res[idx] = v
idx++
}
if idx == 0 {
return "", vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "MySQL version not correctly setup - %s.", version)
}
return fmt.Sprintf("%01d%02d%02d", res[0], res[1], res[2]), nil
}
// ParseExpr parses an expression and transforms it to an AST
func ParseExpr(sql string) (Expr, error) {
stmt, err := Parse("select " + sql)
if err != nil {
return nil, err
}
aliasedExpr := stmt.(*Select).SelectExprs[0].(*AliasedExpr)
return aliasedExpr.Expr, err
}
// Parse behaves like Parse2 but does not return a set of bind variables
func Parse(sql string) (Statement, error) {
stmt, _, err := Parse2(sql)
return stmt, err
}
// ParseStrictDDL is the same as Parse except it errors on
// partially parsed DDL statements.
func ParseStrictDDL(sql string) (Statement, error) {
tokenizer := NewStringTokenizer(sql)
if yyParsePooled(tokenizer) != 0 {
return nil, tokenizer.LastError
}
if tokenizer.ParseTree == nil {
return nil, ErrEmpty
}
return tokenizer.ParseTree, nil
}
// ParseTokenizer is a raw interface to parse from the given tokenizer.
// This does not used pooled parsers, and should not be used in general.
func ParseTokenizer(tokenizer *Tokenizer) int {
return yyParse(tokenizer)
}
// ParseNext parses a single SQL statement from the tokenizer
// returning a Statement which is the AST representation of the query.
// The tokenizer will always read up to the end of the statement, allowing for
// the next call to ParseNext to parse any subsequent SQL statements. When
// there are no more statements to parse, a error of io.EOF is returned.
func ParseNext(tokenizer *Tokenizer) (Statement, error) {
return parseNext(tokenizer, false)
}
// ParseNextStrictDDL is the same as ParseNext except it errors on
// partially parsed DDL statements.
func ParseNextStrictDDL(tokenizer *Tokenizer) (Statement, error) {
return parseNext(tokenizer, true)
}
func parseNext(tokenizer *Tokenizer, strict bool) (Statement, error) {
if tokenizer.cur() == ';' {
tokenizer.skip(1)
tokenizer.skipBlank()
}
if tokenizer.cur() == eofChar {
return nil, io.EOF
}
tokenizer.reset()
tokenizer.multi = true
if yyParsePooled(tokenizer) != 0 {
if tokenizer.partialDDL != nil && !strict {
tokenizer.ParseTree = tokenizer.partialDDL
return tokenizer.ParseTree, nil
}
return nil, tokenizer.LastError
}
_, isCommentOnly := tokenizer.ParseTree.(*CommentOnly)
if tokenizer.ParseTree == nil || isCommentOnly {
return ParseNext(tokenizer)
}
return tokenizer.ParseTree, nil
}
// ErrEmpty is a sentinel error returned when parsing empty statements.
var ErrEmpty = vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.EmptyQuery, "Query was empty")
// SplitStatement returns the first sql statement up to either a ; or EOF
// and the remainder from the given buffer
func SplitStatement(blob string) (string, string, error) {
tokenizer := NewStringTokenizer(blob)
tkn := 0
for {
tkn, _ = tokenizer.Scan()
if tkn == 0 || tkn == ';' || tkn == eofChar {
break
}
}
if tokenizer.LastError != nil {
return "", "", tokenizer.LastError
}
if tkn == ';' {
return blob[:tokenizer.Pos-1], blob[tokenizer.Pos:], nil
}
return blob, "", nil
}
// SplitStatementToPieces split raw sql statement that may have multi sql pieces to sql pieces
// returns the sql pieces blob contains; or error if sql cannot be parsed
func SplitStatementToPieces(blob string) (pieces []string, err error) {
// fast path: the vast majority of SQL statements do not have semicolons in them
if blob == "" {
return nil, nil
}
switch strings.IndexByte(blob, ';') {
case -1: // if there is no semicolon, return blob as a whole
return []string{blob}, nil
case len(blob) - 1: // if there's a single semicolon and it's the last character, return blob without it
return []string{blob[:len(blob)-1]}, nil
}
pieces = make([]string, 0, 16)
tokenizer := NewStringTokenizer(blob)
tkn := 0
var stmt string
stmtBegin := 0
emptyStatement := true
loop:
for {
tkn, _ = tokenizer.Scan()
switch tkn {
case ';':
stmt = blob[stmtBegin : tokenizer.Pos-1]
if !emptyStatement {
pieces = append(pieces, stmt)
emptyStatement = true
}
stmtBegin = tokenizer.Pos
case 0, eofChar:
blobTail := tokenizer.Pos - 1
if stmtBegin < blobTail {
stmt = blob[stmtBegin : blobTail+1]
if !emptyStatement {
pieces = append(pieces, stmt)
}
}
break loop
default:
emptyStatement = false
}
}
err = tokenizer.LastError
return
}
func IsMySQL80AndAbove() bool {
return mySQLParserVersion >= "80000"
}