-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqllexer.go
396 lines (360 loc) · 9.71 KB
/
sqllexer.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package sqllexer
type TokenType int
const (
ERROR TokenType = iota
EOF
WS // whitespace
STRING // string literal
INCOMPLETE_STRING // illegal string literal so that we can obfuscate it, e.g. 'abc
NUMBER // number literal
IDENT // identifier
OPERATOR // operator
WILDCARD // wildcard *
COMMENT // comment
MULTILINE_COMMENT // multiline comment
PUNCTUATION // punctuation
DOLLAR_QUOTED_FUNCTION // dollar quoted function
DOLLAR_QUOTED_STRING // dollar quoted string
NUMBERED_PARAMETER // numbered parameter
UNKNOWN // unknown token
)
// Token represents a SQL token with its type and value.
type Token struct {
Type TokenType
Value string
}
// SQL Lexer inspired from Rob Pike's talk on Lexical Scanning in Go
type SQLLexer struct {
src string // the input src string
cursor int // the current position of the cursor
start int // the start position of the current token
}
func NewSQLLexer(input string) *SQLLexer {
return &SQLLexer{src: input}
}
// ScanAll scans the entire input string and returns a slice of tokens.
func (s *SQLLexer) ScanAll() []Token {
var tokens []Token
for {
token := s.Scan()
if token.Type == EOF {
// don't include EOF token in the result
break
}
tokens = append(tokens, token)
}
return tokens
}
// ScanAllTokens scans the entire input string and returns a channel of tokens.
// Use this if you want to process the tokens as they are scanned.
func (s *SQLLexer) ScanAllTokens() <-chan *Token {
tokenCh := make(chan *Token)
go func() {
defer close(tokenCh)
for {
token := s.Scan()
if token.Type == EOF {
// don't include EOF token in the result
break
}
tokenCh <- &token
}
}()
return tokenCh
}
// Scan scans the next token and returns it.
func (s *SQLLexer) Scan() Token {
ch := s.peek()
switch {
case isWhitespace(ch):
return s.scanWhitespace()
case isLetter(ch):
return s.scanIdentifier()
case isDoubleQuote(ch):
return s.scanDoubleQuotedIdentifier()
case isSingleQuote(ch):
return s.scanString()
case isSingleLineComment(ch, s.lookAhead(1)):
return s.scanSingleLineComment()
case isMultiLineComment(ch, s.lookAhead(1)):
return s.scanMultiLineComment()
case isLeadingSign(ch):
// if the leading sign is followed by a digit,
// and preceded by whitespace, then it's a number
// although this is not strictly true, it's good enough for our purposes
if (isDigit(s.lookAhead(1)) || s.lookAhead(1) == '.') && isWhitespace(s.lookAhead(-1)) {
return s.scanNumber()
}
return s.scanOperator()
case isDigit(ch):
return s.scanNumber()
case isWildcard(ch):
return s.scanWildcard()
case ch == '$':
if isDigit(s.lookAhead(1)) {
// if the dollar sign is followed by a digit, then it's a numbered parameter
return s.scanNumberedParameter()
}
if isDollarQuotedFunction(s.peekBy(6)) {
// check for dollar quoted function
// dollar quoted function will be obfuscated as a SQL query
return s.scanDollarQuotedFunction()
}
return s.scanDollarQuotedString()
case isOperator(ch):
return s.scanOperator()
case isPunctuation(ch):
return s.scanPunctuation()
case isEOF(ch):
return Token{EOF, ""}
default:
return s.scanUnknown()
}
}
// lookAhead returns the rune n positions ahead of the cursor.
func (s *SQLLexer) lookAhead(n int) rune {
if s.cursor+n >= len(s.src) || s.cursor+n < 0 {
return 0
}
return rune(s.src[s.cursor+n])
}
// peekBy returns a slice of runes n positions ahead of the cursor.
func (s *SQLLexer) peekBy(n int) []rune {
if s.cursor+n >= len(s.src) || s.cursor+n < 0 {
return []rune{}
}
return []rune(s.src[s.cursor : s.cursor+n])
}
// peek returns the rune at the cursor position.
func (s *SQLLexer) peek() rune {
return s.lookAhead(0)
}
// nextBy advances the cursor by n positions and returns the rune at the cursor position.
func (s *SQLLexer) nextBy(n int) rune {
// advance the cursor by n and return the rune at the cursor position
if s.cursor+n > len(s.src) {
return 0
}
s.cursor += n
if s.cursor == len(s.src) {
return 0
}
return rune(s.src[s.cursor])
}
// next advances the cursor by 1 position and returns the rune at the cursor position.
func (s *SQLLexer) next() rune {
return s.nextBy(1)
}
func (s *SQLLexer) scanNumber() Token {
s.start = s.cursor
ch := s.peek()
nextCh := s.lookAhead(1)
// check for hex or octal number
if ch == '0' {
if nextCh == 'x' || nextCh == 'X' {
return s.scanHexNumber()
} else if nextCh >= '0' && nextCh <= '7' {
return s.scanOctalNumber()
}
}
// optional leading sign e.g. +1, -1
if isLeadingSign(ch) {
ch = s.next()
}
// scan digits
for isDigit(ch) || ch == '.' || isExpontent(ch) {
if isExpontent(ch) {
ch = s.next()
if isLeadingSign(ch) {
ch = s.next()
}
} else {
ch = s.next()
}
}
return Token{NUMBER, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanHexNumber() Token {
s.start = s.cursor
s.nextBy(2) // consume the leading 0x
for digitVal(s.peek()) < 16 {
s.next()
}
return Token{NUMBER, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanOctalNumber() Token {
s.start = s.cursor
s.next() // consume the leading 0
for digitVal(s.peek()) < 8 {
s.next()
}
return Token{NUMBER, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanString() Token {
s.start = s.cursor
s.next() // consume the opening quote
for {
ch := s.peek()
if ch == '\'' {
// encountered the closing quote
break
}
if ch == '\\' {
// Encountered an escape character, look ahead the next character
// If it's a single quote or a backslash, consume the escape character
nextCh := s.lookAhead(1)
if nextCh == '\'' || nextCh == '\\' {
s.next()
}
}
if isEOF(ch) {
// encountered EOF before closing quote
// this usually happens when the string is truncated
return Token{INCOMPLETE_STRING, s.src[s.start:s.cursor]}
}
s.next()
}
s.next() // consume the closing quote
return Token{STRING, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanIdentifier() Token {
// NOTE: this func does not distinguish between SQL keywords and identifiers
s.start = s.cursor
ch := s.peek()
for isLetter(ch) || isDigit(ch) || ch == '.' || ch == '?' {
ch = s.next()
}
// return the token as uppercase so that we can do case insensitive matching
return Token{IDENT, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanDoubleQuotedIdentifier() Token {
s.start = s.cursor
s.next() // consume the opening quote
for {
ch := s.peek()
// encountered the closing quote
// BUT if it's followed by .", then we should keep going
// e.g. postgre "foo"."bar"
if ch == '"' {
if string(s.peekBy(3)) == `"."` {
s.nextBy(3) // consume the "."
continue
}
break
}
if isEOF(ch) {
return Token{ERROR, s.src[s.start:s.cursor]}
}
s.next()
}
s.next() // consume the closing quote
return Token{IDENT, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanWhitespace() Token {
// scan whitespace, tab, newline, carriage return
s.start = s.cursor
for isWhitespace(s.peek()) {
s.next()
}
return Token{WS, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanOperator() Token {
s.start = s.cursor
for isOperator(s.peek()) {
s.next()
}
return Token{OPERATOR, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanWildcard() Token {
s.start = s.cursor
s.next()
return Token{WILDCARD, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanSingleLineComment() Token {
s.start = s.cursor
for s.peek() != '\n' && !isEOF(s.peek()) {
s.next()
}
return Token{COMMENT, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanMultiLineComment() Token {
s.start = s.cursor
s.nextBy(2) // consume the opening slash and asterisk
for {
ch := s.peek()
if ch == '*' && s.lookAhead(1) == '/' {
break
}
if ch == 0 {
// encountered EOF before closing comment
// this usually happens when the comment is truncated
return Token{ERROR, s.src[s.start:s.cursor]}
}
s.next()
}
s.nextBy(2) // consume the closing asterisk and slash
return Token{MULTILINE_COMMENT, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanPunctuation() Token {
s.start = s.cursor
s.next()
return Token{PUNCTUATION, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanDollarQuotedFunction() Token {
s.start = s.cursor
s.nextBy(6) // consume the opening dollar and the function name
for {
ch := s.peek()
if ch == '$' && isDollarQuotedFunction(s.peekBy(6)) {
break
}
if isEOF(ch) {
return Token{ERROR, s.src[s.start:s.cursor]}
}
s.next()
}
s.nextBy(6) // consume the closing dollar quoted function
return Token{DOLLAR_QUOTED_FUNCTION, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanDollarQuotedString() Token {
s.start = s.cursor
s.next() // consume the dollar sign
dollars := 1
for {
ch := s.peek()
if ch == '$' {
// keep track of the number of dollar signs we've seen
// a valid dollar quoted string is either $$string$$ or $tag$string$tag$
// we technically should see 4 dollar signs
// this is a bit of a hack because we don't want to keep track of the tag
// but it's good enough for our purposes of tokenization and obfuscation
dollars += 1
}
if isEOF(ch) {
break
}
s.next()
}
if dollars != 4 {
return Token{UNKNOWN, s.src[s.start:s.cursor]}
}
return Token{DOLLAR_QUOTED_STRING, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanNumberedParameter() Token {
s.start = s.cursor
s.next() // consume the dollar sign
for {
ch := s.peek()
if !isDigit(ch) {
break
}
s.next()
}
return Token{NUMBERED_PARAMETER, s.src[s.start:s.cursor]}
}
func (s *SQLLexer) scanUnknown() Token {
// When we see an unknown token, we advance the cursor until we see something that looks like a token boundary.
s.start = s.cursor
s.next()
return Token{UNKNOWN, s.src[s.start:s.cursor]}
}