Debian Codegraph @

analyzer.go

raw symbols SCIP
1 /*
2 Copyright 2017 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package sqlparser
18
19 // analyzer.go contains utility analysis functions.
20
21 import (
22 "errors"
23 "fmt"
24 "strconv"
25 "strings"
26 "unicode"
27
28 "github.com/xwb1989/sqlparser/dependency/sqltypes"
29 )
30
31 // These constants are used to identify the SQL statement type.
32 const (
33 StmtSelect = iota
34 StmtStream
35 StmtInsert
36 StmtReplace
37 StmtUpdate
38 StmtDelete
39 StmtDDL
40 StmtBegin
41 StmtCommit
42 StmtRollback
43 StmtSet
44 StmtShow
45 StmtUse
46 StmtOther
47 StmtUnknown
48 StmtComment
49 )
50
51 // Preview analyzes the beginning of the query using a simpler and faster
52 // textual comparison to identify the statement type.
53 func Preview(sql string) int {
54 trimmed := StripLeadingComments(sql)
55
56 firstWord := trimmed
57 if end := strings.IndexFunc(trimmed, unicode.IsSpace); end != -1 {
58 firstWord = trimmed[:end]
59 }
60 firstWord = strings.TrimLeftFunc(firstWord, func(r rune) bool { return !unicode.IsLetter(r) })
61 // Comparison is done in order of priority.
62 loweredFirstWord := strings.ToLower(firstWord)
63 switch loweredFirstWord {
64 case "select":
65 return StmtSelect
66 case "stream":
67 return StmtStream
68 case "insert":
69 return StmtInsert
70 case "replace":
71 return StmtReplace
72 case "update":
73 return StmtUpdate
74 case "delete":
75 return StmtDelete
76 }
77 // For the following statements it is not sufficient to rely
78 // on loweredFirstWord. This is because they are not statements
79 // in the grammar and we are relying on Preview to parse them.
80 // For instance, we don't want: "BEGIN JUNK" to be parsed
81 // as StmtBegin.
82 trimmedNoComments, _ := SplitMarginComments(trimmed)
83 switch strings.ToLower(trimmedNoComments) {
84 case "begin", "start transaction":
85 return StmtBegin
86 case "commit":
87 return StmtCommit
88 case "rollback":
89 return StmtRollback
90 }
91 switch loweredFirstWord {
92 case "create", "alter", "rename", "drop", "truncate":
93 return StmtDDL
94 case "set":
95 return StmtSet
96 case "show":
97 return StmtShow
98 case "use":
99 return StmtUse
100 case "analyze", "describe", "desc", "explain", "repair", "optimize":
101 return StmtOther
102 }
103 if strings.Index(trimmed, "/*!") == 0 {
104 return StmtComment
105 }
106 return StmtUnknown
107 }
108
109 // StmtType returns the statement type as a string
110 func StmtType(stmtType int) string {
111 switch stmtType {
112 case StmtSelect:
113 return "SELECT"
114 case StmtStream:
115 return "STREAM"
116 case StmtInsert:
117 return "INSERT"
118 case StmtReplace:
119 return "REPLACE"
120 case StmtUpdate:
121 return "UPDATE"
122 case StmtDelete:
123 return "DELETE"
124 case StmtDDL:
125 return "DDL"
126 case StmtBegin:
127 return "BEGIN"
128 case StmtCommit:
129 return "COMMIT"
130 case StmtRollback:
131 return "ROLLBACK"
132 case StmtSet:
133 return "SET"
134 case StmtShow:
135 return "SHOW"
136 case StmtUse:
137 return "USE"
138 case StmtOther:
139 return "OTHER"
140 default:
141 return "UNKNOWN"
142 }
143 }
144
145 // IsDML returns true if the query is an INSERT, UPDATE or DELETE statement.
146 func IsDML(sql string) bool {
147 switch Preview(sql) {
148 case StmtInsert, StmtReplace, StmtUpdate, StmtDelete:
149 return true
150 }
151 return false
152 }
153
154 // GetTableName returns the table name from the SimpleTableExpr
155 // only if it's a simple expression. Otherwise, it returns "".
156 func GetTableName(node SimpleTableExpr) TableIdent {
157 if n, ok := node.(TableName); ok && n.Qualifier.IsEmpty() {
158 return n.Name
159 }
160 // sub-select or '.' expression
161 return NewTableIdent("")
162 }
163
164 // IsColName returns true if the Expr is a *ColName.
165 func IsColName(node Expr) bool {
166 _, ok := node.(*ColName)
167 return ok
168 }
169
170 // IsValue returns true if the Expr is a string, integral or value arg.
171 // NULL is not considered to be a value.
172 func IsValue(node Expr) bool {
173 switch v := node.(type) {
174 case *SQLVal:
175 switch v.Type {
176 case StrVal, HexVal, IntVal, ValArg:
177 return true
178 }
179 }
180 return false
181 }
182
183 // IsNull returns true if the Expr is SQL NULL
184 func IsNull(node Expr) bool {
185 switch node.(type) {
186 case *NullVal:
187 return true
188 }
189 return false
190 }
191
192 // IsSimpleTuple returns true if the Expr is a ValTuple that
193 // contains simple values or if it's a list arg.
194 func IsSimpleTuple(node Expr) bool {
195 switch vals := node.(type) {
196 case ValTuple:
197 for _, n := range vals {
198 if !IsValue(n) {
199 return false
200 }
201 }
202 return true
203 case ListArg:
204 return true
205 }
206 // It's a subquery
207 return false
208 }
209
210 // NewPlanValue builds a sqltypes.PlanValue from an Expr.
211 func NewPlanValue(node Expr) (sqltypes.PlanValue, error) {
212 switch node := node.(type) {
213 case *SQLVal:
214 switch node.Type {
215 case ValArg:
216 return sqltypes.PlanValue{Key: string(node.Val[1:])}, nil
217 case IntVal:
218 n, err := sqltypes.NewIntegral(string(node.Val))
219 if err != nil {
220 return sqltypes.PlanValue{}, fmt.Errorf("%v", err)
221 }
222 return sqltypes.PlanValue{Value: n}, nil
223 case StrVal:
224 return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, node.Val)}, nil
225 case HexVal:
226 v, err := node.HexDecode()
227 if err != nil {
228 return sqltypes.PlanValue{}, fmt.Errorf("%v", err)
229 }
230 return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, v)}, nil
231 }
232 case ListArg:
233 return sqltypes.PlanValue{ListKey: string(node[2:])}, nil
234 case ValTuple:
235 pv := sqltypes.PlanValue{
236 Values: make([]sqltypes.PlanValue, 0, len(node)),
237 }
238 for _, val := range node {
239 innerpv, err := NewPlanValue(val)
240 if err != nil {
241 return sqltypes.PlanValue{}, err
242 }
243 if innerpv.ListKey != "" || innerpv.Values != nil {
244 return sqltypes.PlanValue{}, errors.New("unsupported: nested lists")
245 }
246 pv.Values = append(pv.Values, innerpv)
247 }
248 return pv, nil
249 case *NullVal:
250 return sqltypes.PlanValue{}, nil
251 }
252 return sqltypes.PlanValue{}, fmt.Errorf("expression is too complex '%v'", String(node))
253 }
254
255 // StringIn is a convenience function that returns
256 // true if str matches any of the values.
257 func StringIn(str string, values ...string) bool {
258 for _, val := range values {
259 if str == val {
260 return true
261 }
262 }
263 return false
264 }
265
266 // SetKey is the extracted key from one SetExpr
267 type SetKey struct {
268 Key string
269 Scope string
270 }
271
272 // ExtractSetValues returns a map of key-value pairs
273 // if the query is a SET statement. Values can be bool, int64 or string.
274 // Since set variable names are case insensitive, all keys are returned
275 // as lower case.
276 func ExtractSetValues(sql string) (keyValues map[SetKey]interface{}, scope string, err error) {
277 stmt, err := Parse(sql)
278 if err != nil {
279 return nil, "", err
280 }
281 setStmt, ok := stmt.(*Set)
282 if !ok {
283 return nil, "", fmt.Errorf("ast did not yield *sqlparser.Set: %T", stmt)
284 }
285 result := make(map[SetKey]interface{})
286 for _, expr := range setStmt.Exprs {
287 scope := SessionStr
288 key := expr.Name.Lowered()
289 switch {
290 case strings.HasPrefix(key, "@@global."):
291 scope = GlobalStr
292 key = strings.TrimPrefix(key, "@@global.")
293 case strings.HasPrefix(key, "@@session."):
294 key = strings.TrimPrefix(key, "@@session.")
295 case strings.HasPrefix(key, "@@"):
296 key = strings.TrimPrefix(key, "@@")
297 }
298
299 if strings.HasPrefix(expr.Name.Lowered(), "@@") {
300 if setStmt.Scope != "" && scope != "" {
301 return nil, "", fmt.Errorf("unsupported in set: mixed using of variable scope")
302 }
303 _, out := NewStringTokenizer(key).Scan()
304 key = string(out)
305 }
306
307 setKey := SetKey{
308 Key: key,
309 Scope: scope,
310 }
311
312 switch expr := expr.Expr.(type) {
313 case *SQLVal:
314 switch expr.Type {
315 case StrVal:
316 result[setKey] = strings.ToLower(string(expr.Val))
317 case IntVal:
318 num, err := strconv.ParseInt(string(expr.Val), 0, 64)
319 if err != nil {
320 return nil, "", err
321 }
322 result[setKey] = num
323 default:
324 return nil, "", fmt.Errorf("invalid value type: %v", String(expr))
325 }
326 case BoolVal:
327 var val int64
328 if expr {
329 val = 1
330 }
331 result[setKey] = val
332 case *ColName:
333 result[setKey] = expr.Name.String()
334 case *NullVal:
335 result[setKey] = nil
336 case *Default:
337 result[setKey] = "default"
338 default:
339 return nil, "", fmt.Errorf("invalid syntax: %s", String(expr))
340 }
341 }
342 return result, strings.ToLower(setStmt.Scope), nil
343 }