forked from DataDog/go-sqllexer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqllexer_utils.go
More file actions
374 lines (331 loc) · 7.92 KB
/
sqllexer_utils.go
File metadata and controls
374 lines (331 loc) · 7.92 KB
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
package sqllexer
import (
"strings"
"unicode"
)
type DBMSType string
const (
// DBMSSQLServer is a MS SQL
DBMSSQLServer DBMSType = "mssql"
DBMSSQLServerAlias1 DBMSType = "sql-server" // .Net tracer
DBMSSQLServerAlias2 DBMSType = "sqlserver" // Java tracer
// DBMSPostgres is a PostgreSQL Server
DBMSPostgres DBMSType = "postgresql"
DBMSPostgresAlias1 DBMSType = "postgres" // Ruby, JavaScript tracers
// DBMSMySQL is a MySQL Server
DBMSMySQL DBMSType = "mysql"
// DBMSOracle is a Oracle Server
DBMSOracle DBMSType = "oracle"
// DBMSSnowflake is a Snowflake Server
DBMSSnowflake DBMSType = "snowflake"
)
var dbmsAliases = map[DBMSType]DBMSType{
DBMSSQLServerAlias1: DBMSSQLServer,
DBMSSQLServerAlias2: DBMSSQLServer,
DBMSPostgresAlias1: DBMSPostgres,
}
func getDBMSFromAlias(alias DBMSType) DBMSType {
if canonical, exists := dbmsAliases[alias]; exists {
return canonical
}
return alias
}
var commands = []string{
"SELECT",
"INSERT",
"UPDATE",
"DELETE",
"CREATE",
"ALTER",
"DROP",
"JOIN",
"GRANT",
"REVOKE",
"COMMIT",
"BEGIN",
"TRUNCATE",
"MERGE",
"EXECUTE",
"EXEC",
"EXPLAIN",
"STRAIGHT_JOIN",
"USE",
"CLONE",
}
var tableIndicatorCommands = []string{
"JOIN",
"UPDATE",
"STRAIGHT_JOIN", // MySQL
"CLONE", // Snowflake
}
var tableIndicatorKeywords = []string{
"FROM",
"INTO",
"TABLE",
"EXISTS", // Drop Table If Exists
"ONLY", // PostgreSQL
}
var keywords = []string{
"ADD",
"ALL",
"AND",
"ANY",
"ASC",
"BETWEEN",
"BY",
"CASE",
"CHECK",
"COLUMN",
"CONSTRAINT",
"DATABASE",
"DECLARE",
"DEFAULT",
"DESC",
"DISTINCT",
"ELSE",
"END",
"ESCAPE",
"EXISTS",
"FOREIGN",
"FROM",
"GROUP",
"HAVING",
"IN",
"INDEX",
"INNER",
"INTO",
"IS",
"KEY",
"LEFT",
"LIKE",
"LIMIT",
"NOT",
"ON",
"OR",
"ORDER",
"OUT",
"OUTER",
"PRIMARY",
"PROCEDURE",
"REPLACE",
"RETURNS",
"RIGHT",
"ROLLBACK",
"ROWNUM",
"SET",
"SOME",
"TABLE",
"TOP",
"UNION",
"UNIQUE",
"VALUES",
"VIEW",
"WHERE",
"CUBE",
"ROLLUP",
"LITERAL",
"WINDOW",
"VACCUM",
"ANALYZE",
"ILIKE",
"USING",
"ASSERTION",
"DOMAIN",
"CLUSTER",
"COPY",
"PLPGSQL",
"TRIGGER",
"TEMPORARY",
"UNLOGGED",
"RECURSIVE",
"RETURNING",
"OFFSET",
"OF",
"SKIP",
"IF",
"ONLY",
}
var (
// Pre-defined constants for common values
booleanValues = []string{
"TRUE",
"FALSE",
}
nullValues = []string{
"NULL",
}
procedureNames = []string{
"PROCEDURE",
"PROC",
}
ctes = []string{
"WITH",
}
alias = []string{
"AS",
}
)
// trieNode represents a node in the keyword trie.
type trieNode struct {
children [27]*trieNode // 0-25 for A-Z, 26 for underscore
isEnd bool
tokenType TokenType
isTableIndicator bool
}
// trieIndex returns the array index for a character (0-25 for A-Z, 26 for underscore).
// Returns -1 for invalid characters.
func trieIndex(ch rune) int {
if ch >= 'A' && ch <= 'Z' {
return int(ch - 'A')
}
if ch == '_' {
return 26
}
return -1
}
// buildCombinedTrie combines all types of SQL keywords into a single trie
// This trie is used for efficient case-insensitive keyword matching during lexing
func buildCombinedTrie() *trieNode {
root := &trieNode{}
// Add all types of keywords
addToTrie(root, commands, COMMAND, false)
addToTrie(root, keywords, KEYWORD, false)
addToTrie(root, tableIndicatorCommands, COMMAND, true)
addToTrie(root, tableIndicatorKeywords, KEYWORD, true)
addToTrie(root, booleanValues, BOOLEAN, false)
addToTrie(root, nullValues, NULL, false)
addToTrie(root, procedureNames, PROC_INDICATOR, false)
addToTrie(root, ctes, CTE_INDICATOR, false)
addToTrie(root, alias, ALIAS_INDICATOR, false)
return root
}
func addToTrie(root *trieNode, words []string, tokenType TokenType, isTableIndicator bool) {
for _, word := range words {
node := root
// Convert to uppercase for case-insensitive matching
for _, ch := range strings.ToUpper(word) {
idx := trieIndex(ch)
if idx < 0 {
// Skip characters that aren't valid trie indices
continue
}
if next := node.children[idx]; next != nil {
node = next
} else {
next := &trieNode{}
node.children[idx] = next
node = next
}
}
node.isEnd = true
node.tokenType = tokenType
node.isTableIndicator = isTableIndicator
}
}
var keywordRoot = buildCombinedTrie()
// TODO: Optimize these functions to work with rune positions instead of string operations
// They are currently used by obfuscator and normalizer, which we'll optimize later
func replaceDigits(token *Token, placeholder string) string {
var replacedToken strings.Builder
replacedToken.Grow(len(token.Value))
var lastWasDigit bool
for _, r := range token.Value {
if isDigit(r) {
if !lastWasDigit {
replacedToken.WriteString(placeholder)
lastWasDigit = true
}
} else {
replacedToken.WriteRune(r)
lastWasDigit = false
}
}
return replacedToken.String()
}
func trimQuotes(token *Token) string {
var trimmedToken strings.Builder
trimmedToken.Grow(len(token.Value))
for _, r := range token.Value {
if isDoubleQuote(r) || r == '[' || r == ']' || r == '`' {
// trimmedToken.WriteString(placeholder)
} else {
trimmedToken.WriteRune(r)
}
}
token.hasQuotes = false
return trimmedToken.String()
}
// isDigit checks if a rune is a digit (0-9)
func isDigit(ch rune) bool {
return ch >= '0' && ch <= '9'
}
// isLeadingDigit checks if a rune is + or -
func isLeadingSign(ch rune) bool {
return ch == '+' || ch == '-'
}
// isExponent checks if a rune is an exponent (e or E)
func isExpontent(ch rune) bool {
return ch == 'e' || ch == 'E'
}
// isSpace checks if a rune is a space or newline
func isSpace(ch rune) bool {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
}
// isAsciiLetter checks if a rune is an ASCII letter (a-z or A-Z)
func isAsciiLetter(ch rune) bool {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
}
// isLetter checks if a rune is an ASCII letter (a-z or A-Z) or unicode letter
func isLetter(ch rune) bool {
return isAsciiLetter(ch) || ch == '_' ||
(ch > 127 && unicode.IsLetter(ch))
}
// isAlphaNumeric checks if a rune is an ASCII letter (a-z or A-Z), digit (0-9), or unicode number
func isAlphaNumeric(ch rune) bool {
return isLetter(ch) || isDigit(ch) ||
(ch > 127 && unicode.IsNumber(ch))
}
// isDoubleQuote checks if a rune is a double quote (")
func isDoubleQuote(ch rune) bool {
return ch == '"'
}
// isSingleQuote checks if a rune is a single quote (')
func isSingleQuote(ch rune) bool {
return ch == '\''
}
// isOperator checks if a rune is an operator
func isOperator(ch rune) bool {
return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=' || ch == '<' || ch == '>' ||
ch == '!' || ch == '&' || ch == '|' || ch == '^' || ch == '%' || ch == '~' || ch == '?' ||
ch == '@' || ch == ':' || ch == '#'
}
// isWildcard checks if a rune is a wildcard (*)
func isWildcard(ch rune) bool {
return ch == '*'
}
// isSinglelineComment checks if two runes are a single line comment (--)
func isSingleLineComment(ch rune, nextCh rune) bool {
return ch == '-' && nextCh == '-'
}
// isMultiLineComment checks if two runes are a multi line comment (/*)
func isMultiLineComment(ch rune, nextCh rune) bool {
return ch == '/' && nextCh == '*'
}
// isPunctuation checks if a rune is a punctuation character
func isPunctuation(ch rune) bool {
return ch == '(' || ch == ')' || ch == ',' || ch == ';' || ch == '.' || ch == ':' ||
ch == '[' || ch == ']' || ch == '{' || ch == '}'
}
// isEOF checks if a rune is EOF (end of file)
func isEOF(ch rune) bool {
return ch == 0
}
// isIdentifier checks if a rune is an identifier
func isIdentifier(ch rune) bool {
return ch == '"' || ch == '.' || ch == '?' || ch == '$' || ch == '#' || ch == '/' || ch == '@' || ch == '!' || isLetter(ch) || isDigit(ch)
}
// isValueToken checks if a token is a value token
// A value token is a token that is not a space, comment, or EOF
func isValueToken(token *Token) bool {
return token.Type != EOF && token.Type != SPACE && token.Type != COMMENT && token.Type != MULTILINE_COMMENT
}