forked from pingcap/parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yy_parser.go
269 lines (238 loc) · 7.78 KB
/
yy_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
// Copyright 2015 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"math"
"regexp"
"strconv"
"unicode"
"github.com/pingcap/errors"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/terror"
)
const (
codeErrParse = terror.ErrCode(mysql.ErrParse)
codeErrSyntax = terror.ErrCode(mysql.ErrSyntax)
codeErrUnknownCharacterSet = terror.ErrCode(mysql.ErrUnknownCharacterSet)
)
var (
// ErrSyntax returns for sql syntax error.
ErrSyntax = terror.ClassParser.New(codeErrSyntax, mysql.MySQLErrName[mysql.ErrSyntax])
// ErrParse returns for sql parse error.
ErrParse = terror.ClassParser.New(codeErrParse, mysql.MySQLErrName[mysql.ErrParse])
// ErrUnknownCharacterSet returns for no character set found error.
ErrUnknownCharacterSet = terror.ClassParser.New(codeErrUnknownCharacterSet, mysql.MySQLErrName[mysql.ErrUnknownCharacterSet])
// SpecFieldPattern special result field pattern
SpecFieldPattern = regexp.MustCompile(`(\/\*!(M?[0-9]{5,6})?|\*\/)`)
specCodePattern = regexp.MustCompile(`\/\*!(M?[0-9]{5,6})?([^*]|\*+[^*/])*\*+\/`)
specCodeStart = regexp.MustCompile(`^\/\*!(M?[0-9]{5,6})?[ \t]*`)
specCodeEnd = regexp.MustCompile(`[ \t]*\*\/$`)
)
func init() {
parserMySQLErrCodes := map[terror.ErrCode]uint16{
codeErrSyntax: mysql.ErrSyntax,
codeErrParse: mysql.ErrParse,
codeErrUnknownCharacterSet: mysql.ErrUnknownCharacterSet,
}
terror.ErrClassToMySQLCodes[terror.ClassParser] = parserMySQLErrCodes
}
// TrimComment trim comment for special comment code of MySQL.
func TrimComment(txt string) string {
txt = specCodeStart.ReplaceAllString(txt, "")
return specCodeEnd.ReplaceAllString(txt, "")
}
// Parser represents a parser instance. Some temporary objects are stored in it to reduce object allocation during Parse function.
type Parser struct {
charset string
collation string
result []ast.StmtNode
src string
lexer Scanner
// the following fields are used by yyParse to reduce allocation.
cache []yySymType
yylval yySymType
yyVAL yySymType
}
type stmtTexter interface {
stmtText() string
}
// New returns a Parser object.
func New() *Parser {
if ast.NewValueExpr == nil ||
ast.NewParamMarkerExpr == nil ||
ast.NewHexLiteral == nil ||
ast.NewBitLiteral == nil {
panic("no parser driver (forgotten import?) https://github.com/pingcap/parser/issues/43")
}
return &Parser{
cache: make([]yySymType, 200),
}
}
// Parse parses a query string to raw ast.StmtNode.
// If charset or collation is "", default charset and collation will be used.
func (parser *Parser) Parse(sql, charset, collation string) (stmt []ast.StmtNode, warns []error, err error) {
if charset == "" {
charset = mysql.DefaultCharset
}
if collation == "" {
collation = mysql.DefaultCollationName
}
parser.charset = charset
parser.collation = collation
parser.src = sql
parser.result = parser.result[:0]
var l yyLexer
parser.lexer.reset(sql)
l = &parser.lexer
yyParse(l, parser)
warns, errs := l.Errors()
if len(warns) > 0 {
warns = append([]error(nil), warns...)
} else {
warns = nil
}
if len(errs) != 0 {
return nil, warns, errors.Trace(errs[0])
}
for _, stmt := range parser.result {
ast.SetFlag(stmt)
}
return parser.result, warns, nil
}
func (parser *Parser) lastErrorAsWarn() {
if len(parser.lexer.errs) == 0 {
return
}
parser.lexer.warns = append(parser.lexer.warns, parser.lexer.errs[len(parser.lexer.errs)-1])
parser.lexer.errs = parser.lexer.errs[:len(parser.lexer.errs)-1]
}
// ParseOneStmt parses a query and returns an ast.StmtNode.
// The query must have one statement, otherwise ErrSyntax is returned.
func (parser *Parser) ParseOneStmt(sql, charset, collation string) (ast.StmtNode, error) {
stmts, _, err := parser.Parse(sql, charset, collation)
if err != nil {
return nil, errors.Trace(err)
}
if len(stmts) != 1 {
return nil, ErrSyntax
}
ast.SetFlag(stmts[0])
return stmts[0], nil
}
// SetSQLMode sets the SQL mode for parser.
func (parser *Parser) SetSQLMode(mode mysql.SQLMode) {
parser.lexer.SetSQLMode(mode)
}
// EnableWindowFunc enables the parser to parse syntax related with window function.
func (parser *Parser) EnableWindowFunc() {
parser.lexer.EnableWindowFunc()
}
// ParseErrorWith returns "You have a syntax error near..." error message compatible with mysql.
func ParseErrorWith(errstr string, lineno int) error {
if len(errstr) > mysql.ErrTextLength {
errstr = errstr[:mysql.ErrTextLength]
}
return ErrParse.GenWithStackByArgs(mysql.MySQLErrName[mysql.ErrSyntax], errstr, lineno)
}
// The select statement is not at the end of the whole statement, if the last
// field text was set from its offset to the end of the src string, update
// the last field text.
func (parser *Parser) setLastSelectFieldText(st *ast.SelectStmt, lastEnd int) {
lastField := st.Fields.Fields[len(st.Fields.Fields)-1]
if lastField.Offset+len(lastField.Text()) >= len(parser.src)-1 {
lastField.SetText(parser.src[lastField.Offset:lastEnd])
}
}
func (parser *Parser) startOffset(v *yySymType) int {
return v.offset
}
func (parser *Parser) endOffset(v *yySymType) int {
offset := v.offset
for offset > 0 && unicode.IsSpace(rune(parser.src[offset-1])) {
offset--
}
return offset
}
func toInt(l yyLexer, lval *yySymType, str string) int {
n, err := strconv.ParseUint(str, 10, 64)
if err != nil {
e := err.(*strconv.NumError)
if e.Err == strconv.ErrRange {
// TODO: toDecimal maybe out of range still.
// This kind of error should be throw to higher level, because truncated data maybe legal.
// For example, this SQL returns error:
// create table test (id decimal(30, 0));
// insert into test values(123456789012345678901234567890123094839045793405723406801943850);
// While this SQL:
// select 1234567890123456789012345678901230948390457934057234068019438509023041874359081325875128590860234789847359871045943057;
// get value 99999999999999999999999999999999999999999999999999999999999999999
return toDecimal(l, lval, str)
}
l.AppendError(l.Errorf("integer literal: %v", err))
return int(unicode.ReplacementChar)
}
switch {
case n < math.MaxInt64:
lval.item = int64(n)
default:
lval.item = n
}
return intLit
}
func toDecimal(l yyLexer, lval *yySymType, str string) int {
dec, err := ast.NewDecimal(str)
if err != nil {
l.AppendError(l.Errorf("decimal literal: %v", err))
}
lval.item = dec
return decLit
}
func toFloat(l yyLexer, lval *yySymType, str string) int {
n, err := strconv.ParseFloat(str, 64)
if err != nil {
l.AppendError(l.Errorf("float literal: %v", err))
return int(unicode.ReplacementChar)
}
lval.item = n
return floatLit
}
// See https://dev.mysql.com/doc/refman/5.7/en/hexadecimal-literals.html
func toHex(l yyLexer, lval *yySymType, str string) int {
h, err := ast.NewHexLiteral(str)
if err != nil {
l.AppendError(l.Errorf("hex literal: %v", err))
return int(unicode.ReplacementChar)
}
lval.item = h
return hexLit
}
// See https://dev.mysql.com/doc/refman/5.7/en/bit-type.html
func toBit(l yyLexer, lval *yySymType, str string) int {
b, err := ast.NewBitLiteral(str)
if err != nil {
l.AppendError(l.Errorf("bit literal: %v", err))
return int(unicode.ReplacementChar)
}
lval.item = b
return bitLit
}
func getUint64FromNUM(num interface{}) uint64 {
switch v := num.(type) {
case int64:
return uint64(v)
case uint64:
return v
}
return 0
}