Debian Codegraph @

comments.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 import (
20 "strconv"
21 "strings"
22 "unicode"
23 )
24
25 const (
26 // DirectiveMultiShardAutocommit is the query comment directive to allow
27 // single round trip autocommit with a multi-shard statement.
28 DirectiveMultiShardAutocommit = "MULTI_SHARD_AUTOCOMMIT"
29 // DirectiveSkipQueryPlanCache skips query plan cache when set.
30 DirectiveSkipQueryPlanCache = "SKIP_QUERY_PLAN_CACHE"
31 // DirectiveQueryTimeout sets a query timeout in vtgate. Only supported for SELECTS.
32 DirectiveQueryTimeout = "QUERY_TIMEOUT_MS"
33 )
34
35 func isNonSpace(r rune) bool {
36 return !unicode.IsSpace(r)
37 }
38
39 // leadingCommentEnd returns the first index after all leading comments, or
40 // 0 if there are no leading comments.
41 func leadingCommentEnd(text string) (end int) {
42 hasComment := false
43 pos := 0
44 for pos < len(text) {
45 // Eat up any whitespace. Trailing whitespace will be considered part of
46 // the leading comments.
47 nextVisibleOffset := strings.IndexFunc(text[pos:], isNonSpace)
48 if nextVisibleOffset < 0 {
49 break
50 }
51 pos += nextVisibleOffset
52 remainingText := text[pos:]
53
54 // Found visible characters. Look for '/*' at the beginning
55 // and '*/' somewhere after that.
56 if len(remainingText) < 4 || remainingText[:2] != "/*" {
57 break
58 }
59 commentLength := 4 + strings.Index(remainingText[2:], "*/")
60 if commentLength < 4 {
61 // Missing end comment :/
62 break
63 }
64
65 hasComment = true
66 pos += commentLength
67 }
68
69 if hasComment {
70 return pos
71 }
72 return 0
73 }
74
75 // trailingCommentStart returns the first index of trailing comments.
76 // If there are no trailing comments, returns the length of the input string.
77 func trailingCommentStart(text string) (start int) {
78 hasComment := false
79 reducedLen := len(text)
80 for reducedLen > 0 {
81 // Eat up any whitespace. Leading whitespace will be considered part of
82 // the trailing comments.
83 nextReducedLen := strings.LastIndexFunc(text[:reducedLen], isNonSpace) + 1
84 if nextReducedLen == 0 {
85 break
86 }
87 reducedLen = nextReducedLen
88 if reducedLen < 4 || text[reducedLen-2:reducedLen] != "*/" {
89 break
90 }
91
92 // Find the beginning of the comment
93 startCommentPos := strings.LastIndex(text[:reducedLen-2], "/*")
94 if startCommentPos < 0 {
95 // Badly formatted sql :/
96 break
97 }
98
99 hasComment = true
100 reducedLen = startCommentPos
101 }
102
103 if hasComment {
104 return reducedLen
105 }
106 return len(text)
107 }
108
109 // MarginComments holds the leading and trailing comments that surround a query.
110 type MarginComments struct {
111 Leading string
112 Trailing string
113 }
114
115 // SplitMarginComments pulls out any leading or trailing comments from a raw sql query.
116 // This function also trims leading (if there's a comment) and trailing whitespace.
117 func SplitMarginComments(sql string) (query string, comments MarginComments) {
118 trailingStart := trailingCommentStart(sql)
119 leadingEnd := leadingCommentEnd(sql[:trailingStart])
120 comments = MarginComments{
121 Leading: strings.TrimLeftFunc(sql[:leadingEnd], unicode.IsSpace),
122 Trailing: strings.TrimRightFunc(sql[trailingStart:], unicode.IsSpace),
123 }
124 return strings.TrimFunc(sql[leadingEnd:trailingStart], unicode.IsSpace), comments
125 }
126
127 // StripLeadingComments trims the SQL string and removes any leading comments
128 func StripLeadingComments(sql string) string {
129 sql = strings.TrimFunc(sql, unicode.IsSpace)
130
131 for hasCommentPrefix(sql) {
132 switch sql[0] {
133 case '/':
134 // Multi line comment
135 index := strings.Index(sql, "*/")
136 if index <= 1 {
137 return sql
138 }
139 // don't strip /*! ... */ or /*!50700 ... */
140 if len(sql) > 2 && sql[2] == '!' {
141 return sql
142 }
143 sql = sql[index+2:]
144 case '-':
145 // Single line comment
146 index := strings.Index(sql, "\n")
147 if index == -1 {
148 return sql
149 }
150 sql = sql[index+1:]
151 }
152
153 sql = strings.TrimFunc(sql, unicode.IsSpace)
154 }
155
156 return sql
157 }
158
159 func hasCommentPrefix(sql string) bool {
160 return len(sql) > 1 && ((sql[0] == '/' && sql[1] == '*') || (sql[0] == '-' && sql[1] == '-'))
161 }
162
163 // ExtractMysqlComment extracts the version and SQL from a comment-only query
164 // such as /*!50708 sql here */
165 func ExtractMysqlComment(sql string) (version string, innerSQL string) {
166 sql = sql[3 : len(sql)-2]
167
168 digitCount := 0
169 endOfVersionIndex := strings.IndexFunc(sql, func(c rune) bool {
170 digitCount++
171 return !unicode.IsDigit(c) || digitCount == 6
172 })
173 version = sql[0:endOfVersionIndex]
174 innerSQL = strings.TrimFunc(sql[endOfVersionIndex:], unicode.IsSpace)
175
176 return version, innerSQL
177 }
178
179 const commentDirectivePreamble = "/*vt+"
180
181 // CommentDirectives is the parsed representation for execution directives
182 // conveyed in query comments
183 type CommentDirectives map[string]interface{}
184
185 // ExtractCommentDirectives parses the comment list for any execution directives
186 // of the form:
187 //
188 // /*vt+ OPTION_ONE=1 OPTION_TWO OPTION_THREE=abcd */
189 //
190 // It returns the map of the directive values or nil if there aren't any.
191 func ExtractCommentDirectives(comments Comments) CommentDirectives {
192 if comments == nil {
193 return nil
194 }
195
196 var vals map[string]interface{}
197
198 for _, comment := range comments {
199 commentStr := string(comment)
200 if commentStr[0:5] != commentDirectivePreamble {
201 continue
202 }
203
204 if vals == nil {
205 vals = make(map[string]interface{})
206 }
207
208 // Split on whitespace and ignore the first and last directive
209 // since they contain the comment start/end
210 directives := strings.Fields(commentStr)
211 for i := 1; i < len(directives)-1; i++ {
212 directive := directives[i]
213 sep := strings.IndexByte(directive, '=')
214
215 // No value is equivalent to a true boolean
216 if sep == -1 {
217 vals[directive] = true
218 continue
219 }
220
221 strVal := directive[sep+1:]
222 directive = directive[:sep]
223
224 intVal, err := strconv.Atoi(strVal)
225 if err == nil {
226 vals[directive] = intVal
227 continue
228 }
229
230 boolVal, err := strconv.ParseBool(strVal)
231 if err == nil {
232 vals[directive] = boolVal
233 continue
234 }
235
236 vals[directive] = strVal
237 }
238 }
239 return vals
240 }
241
242 // IsSet checks the directive map for the named directive and returns
243 // true if the directive is set and has a true/false or 0/1 value
244 func (d CommentDirectives) IsSet(key string) bool {
245 if d == nil {
246 return false
247 }
248
249 val, ok := d[key]
250 if !ok {
251 return false
252 }
253
254 boolVal, ok := val.(bool)
255 if ok {
256 return boolVal
257 }
258
259 intVal, ok := val.(int)
260 if ok {
261 return intVal == 1
262 }
263 return false
264 }
265
266 // SkipQueryPlanCacheDirective returns true if skip query plan cache directive is set to true in query.
267 func SkipQueryPlanCacheDirective(stmt Statement) bool {
268 switch stmt := stmt.(type) {
269 case *Select:
270 directives := ExtractCommentDirectives(stmt.Comments)
271 if directives.IsSet(DirectiveSkipQueryPlanCache) {
272 return true
273 }
274 case *Insert:
275 directives := ExtractCommentDirectives(stmt.Comments)
276 if directives.IsSet(DirectiveSkipQueryPlanCache) {
277 return true
278 }
279 case *Update:
280 directives := ExtractCommentDirectives(stmt.Comments)
281 if directives.IsSet(DirectiveSkipQueryPlanCache) {
282 return true
283 }
284 case *Delete:
285 directives := ExtractCommentDirectives(stmt.Comments)
286 if directives.IsSet(DirectiveSkipQueryPlanCache) {
287 return true
288 }
289 default:
290 return false
291 }
292 return false
293 }