| 1 | /* |
| 2 | Copyright (c) 2019, Percona LLC. |
| 3 | All rights reserved. |
| 4 | |
| 5 | Redistribution and use in source and binary forms, with or without |
| 6 | modification, are permitted provided that the following conditions are met: |
| 7 | |
| 8 | * Redistributions of source code must retain the above copyright notice, this |
| 9 | list of conditions and the following disclaimer. |
| 10 | |
| 11 | * Redistributions in binary form must reproduce the above copyright notice, |
| 12 | this list of conditions and the following disclaimer in the documentation |
| 13 | and/or other materials provided with the distribution. |
| 14 | |
| 15 | * Neither the name of the copyright holder nor the names of its |
| 16 | contributors may be used to endorse or promote products derived from |
| 17 | this software without specific prior written permission. |
| 18 | |
| 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
| 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | */ |
| 30 | |
| 31 | // Package query provides functions to transform queries. |
| 32 | package query |
| 33 | |
| 34 | /* |
| 35 | Fingerprint is highly-specialized and operates on a single principle: |
| 36 | |
| 37 | 1. We only replace numbers, quoted strings, and value lists. |
| 38 | |
| 39 | Although we must handle a lot of details, exceptions, and special cases, |
| 40 | that principle distills the problem to its essence which makes it |
| 41 | possible to solve without a true SQL syntax parser (or regex). It means |
| 42 | that we can simply copy and ignore the vast majority of the query because |
| 43 | if it's not a number, quoted string, or value list then there's nothing |
| 44 | to do. With a regex solution we can stop there and simply do transformations |
| 45 | like s/\d+/?/g and s/'[^']*'/?/g but the details, exceptions, and specials |
| 46 | cases make that only a partial, crude solution because, for example, with |
| 47 | col = 'It\s' an escaped quote char.' now the regex needs to handle inner, |
| 48 | escaped quotes so it becomes more complicated and slower. There are many |
| 49 | more difficult problems like this. Consequently, neither regex nor this |
| 50 | solution can be simple, but at least this solution is very fast compared |
| 51 | to regex because it makes a single pass through the query whereas regex |
| 52 | makes as many passes as there are regexes and, worst case, a single regex |
| 53 | can make several passes due to backtracking. To handle problems like these, |
| 54 | this solution is a simple state machine. In the previous example problem, |
| 55 | once the first quote char (') is seen we enter the inQuote state. In this |
| 56 | state, if an escape char (\) is seen, this is remembered and the next char |
| 57 | is ignored. This allows us to correctly detect the real ending quote char: |
| 58 | it's the first unescaped quote char. Consequently, we can simply ignore |
| 59 | everything else in the quoted value. The same basic logic applies to numbers |
| 60 | and value lists. |
| 61 | |
| 62 | With that principle and basic logic in mind, you'll notice three major code |
| 63 | blocks: |
| 64 | 1. Skip parts of the query for certain states. |
| 65 | 2. Change state based on rune and current state. |
| 66 | 3. Copy a slice of the query into the fingerprint. |
| 67 | The order is important because it enforces the basic logic: once we enter |
| 68 | certain states we must process and finish them first because in these states |
| 69 | we ignore everything but whatever ends the state. As mentioned above, the |
| 70 | inQuote state is handled in the first block. When in this state, only the |
| 71 | real ending quote char ends it. Consequently nothing will trick the parser; |
| 72 | for example the quoted value in col="INSERT INTO t VALUES ('no problem')" |
| 73 | will not be mistaken for another query and another quoted value. -- |
| 74 | The second block is primarily where cpFromOffset and cpToOffset are set |
| 75 | which are used by the third block to copy that range of the query into the |
| 76 | fingerprint. The second block stops, switches state, copies, and lets |
| 77 | the code enter the first block which skips through number, quoted value, or |
| 78 | value list that the second block found. |
| 79 | */ |
| 80 | |
| 81 | import ( |
| 82 | "crypto/md5" |
| 83 | "fmt" |
| 84 | "io" |
| 85 | "strings" |
| 86 | ) |
| 87 | |
| 88 | const ( |
| 89 | unknown byte = iota |
| 90 | inWord // \S+ |
| 91 | inNumber // [0-9a-fA-Fx.-] |
| 92 | inSpace // space, tab, \r, \n |
| 93 | inOp // [=<>!] (usually precedes a number) |
| 94 | opOrNumber // + in 2 + 2 or +3e-9 |
| 95 | inQuote // '...' or "..." |
| 96 | subOrOLC // - or start of -- comment |
| 97 | inDash // -- begins a one-line comment if followed by space |
| 98 | inOLC // -- comment (at least one space after dash is required) |
| 99 | divOrMLC // / operator or start of /* comment */ |
| 100 | mlcOrMySQLCode // /* comment */ or /*! MySQL-specific code */ |
| 101 | inMLC // /* comment */ |
| 102 | inValues // VALUES (1), ..., (N) |
| 103 | moreValuesOrUnknown // , (2nd+) or ON DUPLICATE KEY or end of query |
| 104 | orderBy // ORDER BY |
| 105 | onDupeKeyUpdate // ON DUPLICATE KEY UPDATE |
| 106 | inNumberInWord // e.g. db23 |
| 107 | inBackticks // `table-1` |
| 108 | inMySQLCode // /*! MySQL-specific code */ |
| 109 | ) |
| 110 | |
| 111 | var stateName map[byte]string = map[byte]string{ |
| 112 | 0: "unknown", |
| 113 | 1: "inWord", |
| 114 | 2: "inNumber", |
| 115 | 3: "inSpace", |
| 116 | 4: "inOp", |
| 117 | 5: "opOrNumber", |
| 118 | 6: "inQuote", |
| 119 | 7: "subOrOLC", |
| 120 | 8: "inDash", |
| 121 | 9: "inOLC", |
| 122 | 10: "divOrMLC", |
| 123 | 11: "mlcOrMySQLCode", |
| 124 | 12: "inMLC", |
| 125 | 13: "inValues", |
| 126 | 14: "moreValuesOrUnknown", |
| 127 | 15: "orderBy", |
| 128 | 16: "onDupeKeyUpdate", |
| 129 | 17: "inNumberInWord", |
| 130 | 18: "inBackTicks", |
| 131 | 19: "inMySQLCode", |
| 132 | } |
| 133 | |
| 134 | // Debug prints very verbose tracing information to STDOUT. |
| 135 | var Debug bool = false |
| 136 | |
| 137 | // ReplaceNumbersInWords enables replacing numbers in words. For example: |
| 138 | // `SELECT c FROM org235.t` -> `SELECT c FROM org?.t`. For more examples |
| 139 | // look at test query_test.go/TestFingerprintWithNumberInDbName. |
| 140 | var ReplaceNumbersInWords = false |
| 141 | |
| 142 | // Fingerprint returns the canonical form of q. The primary transformations are: |
| 143 | // - Replace values with ? |
| 144 | // - Collapse whitespace |
| 145 | // - Remove comments |
| 146 | // - Lowercase everything |
| 147 | // |
| 148 | // Additional trasnformations are performed which change the syntax of the |
| 149 | // original query without affecting its performance characteristics. For |
| 150 | // example, "ORDER BY col ASC" is the same as "ORDER BY col", so "ASC" in the |
| 151 | // fingerprint is removed. |
| 152 | func Fingerprint(q string) string { |
| 153 | q += " " // need range to run off end of original query |
| 154 | prevWord := "" |
| 155 | f := make([]byte, len(q)) |
| 156 | fi := 0 |
| 157 | pr := rune(0) // previous rune |
| 158 | s := unknown // current state |
| 159 | sqlState := unknown |
| 160 | quoteChar := rune(0) |
| 161 | cpFromOffset := 0 |
| 162 | cpToOffset := 0 |
| 163 | addSpace := false |
| 164 | escape := false |
| 165 | parOpen := 0 |
| 166 | parOpenTotal := 0 |
| 167 | valueNo := 0 |
| 168 | firstPar := 0 |
| 169 | |
| 170 | for qi, r := range q { |
| 171 | if Debug { |
| 172 | fmt.Printf("\n%d:%d %s/%s [%d:%d] %x %q\n", qi, fi, stateName[s], stateName[sqlState], cpFromOffset, cpToOffset, r, r) |
| 173 | } |
| 174 | |
| 175 | /** |
| 176 | * 1. Skip parts of the query for certain states. |
| 177 | */ |
| 178 | |
| 179 | if s == inQuote { |
| 180 | // We're in a 'quoted value' or "quoted value". The quoted value |
| 181 | // ends at the first non-escaped matching quote character (' or "). |
| 182 | if r != quoteChar { |
| 183 | // The only char inside a quoted value we need to track is \, |
| 184 | // the escape char. This allows us to tell that the 2nd ' in |
| 185 | // '\'' is escaped, not the ending quote char. |
| 186 | if escape { |
| 187 | if Debug { |
| 188 | fmt.Println("Ignore quoted literal") |
| 189 | } |
| 190 | escape = false |
| 191 | } else if r == '\\' { |
| 192 | if Debug { |
| 193 | fmt.Println("Escape") |
| 194 | } |
| 195 | escape = true |
| 196 | } else { |
| 197 | if Debug { |
| 198 | fmt.Println("Ignore quoted value") |
| 199 | } |
| 200 | } |
| 201 | } else if escape { |
| 202 | // \' or \" |
| 203 | if Debug { |
| 204 | fmt.Println("Quote literal") |
| 205 | } |
| 206 | escape = false |
| 207 | } else { |
| 208 | // 'foo' -> ? |
| 209 | // "foo" -> ? |
| 210 | if Debug { |
| 211 | fmt.Println("Quote end") |
| 212 | } |
| 213 | escape = false |
| 214 | |
| 215 | // qi = the closing quote char, so +1 to ensure we don't copy |
| 216 | // anything before this, i.e. quoted value is done, move on. |
| 217 | cpFromOffset = qi + 1 |
| 218 | |
| 219 | if sqlState == inValues { |
| 220 | // ('Hello world!', ...) -> VALUES (, ...) |
| 221 | // The inValues state uses this state to skip quoted values, |
| 222 | // so we don't replace them with ?; the inValues blocks will |
| 223 | // replace the entire value list with ?+. |
| 224 | s = inValues |
| 225 | } else { |
| 226 | f[fi] = '?' |
| 227 | fi++ |
| 228 | s = unknown |
| 229 | } |
| 230 | } |
| 231 | continue |
| 232 | } else if s == inBackticks { |
| 233 | if r != '`' { |
| 234 | // The only char inside a quoted value we need to track is \, |
| 235 | // the escape char. This allows us to tell that the 2nd ' in |
| 236 | // '\`' is escaped, not the ending quote char. |
| 237 | if escape { |
| 238 | if Debug { |
| 239 | fmt.Println("Ignore backtick literal") |
| 240 | } |
| 241 | escape = false |
| 242 | } else if r == '\\' { |
| 243 | if Debug { |
| 244 | fmt.Println("Escape") |
| 245 | } |
| 246 | escape = true |
| 247 | } else { |
| 248 | if Debug { |
| 249 | fmt.Println("Ignore quoted value") |
| 250 | } |
| 251 | } |
| 252 | } else if escape { |
| 253 | // \` |
| 254 | if Debug { |
| 255 | fmt.Println("Quote literal") |
| 256 | } |
| 257 | escape = false |
| 258 | } else { |
| 259 | if Debug { |
| 260 | fmt.Println("Quote end") |
| 261 | } |
| 262 | escape = false |
| 263 | |
| 264 | // qi = the closing backtick, so +1 to ensure we don't copy |
| 265 | // anything before this, i.e. quoted value is done, move on. |
| 266 | // cpFromOffset = qi + 1 |
| 267 | cpToOffset = qi + 1 |
| 268 | |
| 269 | s = inWord |
| 270 | } |
| 271 | continue |
| 272 | |
| 273 | } else if s == inNumberInWord { |
| 274 | // Replaces number in words with ? |
| 275 | // e.g. `db37` to `db?` |
| 276 | // Parser can fall into inNumberInWord only if |
| 277 | // option ReplaceNumbersInWords is turned on |
| 278 | if r >= '0' && r <= '9' { |
| 279 | if Debug { |
| 280 | fmt.Println("Ignore digit in word") |
| 281 | } |
| 282 | continue |
| 283 | } |
| 284 | // 123 -> ?, 0xff -> ?, 1e-9 -> ?, etc. |
| 285 | if Debug { |
| 286 | fmt.Println("Number in word end") |
| 287 | } |
| 288 | f[fi] = '?' |
| 289 | fi++ |
| 290 | cpFromOffset = qi |
| 291 | if isSpace(r) { |
| 292 | s = unknown |
| 293 | } else { |
| 294 | s = inWord |
| 295 | } |
| 296 | } else if s == inNumber { |
| 297 | // We're in a number which can be something simple like 123 or |
| 298 | // something trickier like 1e-9 or 0xFF. The pathological case is |
| 299 | // like 12ff: this is valid hex number and a valid ident (e.g. table |
| 300 | // name). We can't detect this; the best we can do is realize that |
| 301 | // 12ffz is not a number because of the z. |
| 302 | if (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F') || r == '.' || r == 'x' || r == '-' { |
| 303 | if Debug { |
| 304 | fmt.Println("Ignore digit") |
| 305 | } |
| 306 | continue |
| 307 | } |
| 308 | if (r >= 'g' && r <= 'z') || (r >= 'G' && r <= 'Z') || r == '_' { |
| 309 | if Debug { |
| 310 | fmt.Println("Not a number") |
| 311 | } |
| 312 | cpToOffset = qi |
| 313 | s = inWord |
| 314 | } else if sqlState == inMySQLCode { |
| 315 | // If we are in /*![version] ... */, keep the version number |
| 316 | cpToOffset = qi |
| 317 | s = inWord |
| 318 | sqlState = unknown |
| 319 | } else { |
| 320 | // 123 -> ?, 0xff -> ?, 1e-9 -> ?, etc. |
| 321 | if Debug { |
| 322 | fmt.Println("Number end") |
| 323 | } |
| 324 | f[fi] = '?' |
| 325 | fi++ |
| 326 | cpFromOffset = qi |
| 327 | cpToOffset = qi |
| 328 | s = unknown |
| 329 | } |
| 330 | } else if s == inValues { |
| 331 | // We're in the (val1),...,(valN) after IN or VALUE[S]. A single |
| 332 | // () value ends when the parenthesis are balanced, but... |
| 333 | if r == ')' { |
| 334 | parOpen-- |
| 335 | parOpenTotal++ |
| 336 | if Debug { |
| 337 | fmt.Println("Close parenthesis", parOpen) |
| 338 | } |
| 339 | } else if r == '(' { |
| 340 | parOpen++ |
| 341 | if Debug { |
| 342 | fmt.Println("Open parenthesis", parOpen) |
| 343 | } |
| 344 | if parOpen == 1 { |
| 345 | firstPar = qi |
| 346 | } |
| 347 | } else if r == '\'' || r == '"' { |
| 348 | // VALUES ('Hello world!') -> enter inQuote state to skip |
| 349 | // the quoted value so ')' in 'This ) is a trick' doesn't |
| 350 | // balance an outer parenthesis. |
| 351 | if Debug { |
| 352 | fmt.Println("Quote begin") |
| 353 | } |
| 354 | s = inQuote |
| 355 | quoteChar = r |
| 356 | continue |
| 357 | } else if isSpace(r) { |
| 358 | if Debug { |
| 359 | fmt.Println("Space") |
| 360 | } |
| 361 | continue |
| 362 | } |
| 363 | if parOpen > 0 { |
| 364 | // Parenthesis are not balanced yet; i.e. haven't reached |
| 365 | // closing ) for this value. |
| 366 | continue |
| 367 | } |
| 368 | if parOpenTotal == 0 { |
| 369 | // SELECT value FROM t |
| 370 | if Debug { |
| 371 | fmt.Println("Literal values not VALUES()") |
| 372 | } |
| 373 | s = inWord |
| 374 | continue |
| 375 | } |
| 376 | // (<anything>) -> (?+) only for first value, but check for subqueries |
| 377 | if Debug { |
| 378 | fmt.Println("Values end") |
| 379 | } |
| 380 | valueNo++ |
| 381 | if valueNo == 1 { |
| 382 | if qi-firstPar > 1 { |
| 383 | // Check if this is a subquery by looking for SELECT keyword |
| 384 | content := strings.ToLower(strings.TrimSpace(q[firstPar+1 : qi])) |
| 385 | if strings.HasPrefix(content, "select") { |
| 386 | // This is a subquery, fingerprint it recursively |
| 387 | subqueryFingerprint := Fingerprint(q[firstPar+1 : qi]) |
| 388 | subqueryResult := "(" + subqueryFingerprint + ")" |
| 389 | if Debug { |
| 390 | fmt.Printf("Subquery detected: %s -> %s\n", q[firstPar+1:qi], subqueryFingerprint) |
| 391 | } |
| 392 | copy(f[fi:fi+len(subqueryResult)], subqueryResult) |
| 393 | fi += len(subqueryResult) |
| 394 | } else { |
| 395 | // Regular value list |
| 396 | copy(f[fi:fi+4], "(?+)") |
| 397 | fi += 4 |
| 398 | } |
| 399 | } else { |
| 400 | // INSERT INTO t VALUES () |
| 401 | copy(f[fi:fi+2], "()") |
| 402 | fi += 2 |
| 403 | } |
| 404 | firstPar = 0 |
| 405 | } |
| 406 | // ... the difficult part is that there may be other values, e.g. |
| 407 | // (1), (2), (3). So we enter the following state. The values list |
| 408 | // ends when the next char is not a comma. |
| 409 | s = moreValuesOrUnknown |
| 410 | pr = r |
| 411 | cpFromOffset = qi + 1 |
| 412 | parOpenTotal = 0 |
| 413 | continue |
| 414 | } else if s == inMLC { |
| 415 | // We're in a /* mutli-line comments */. Skip and ignore it all. |
| 416 | if pr == '*' && r == '/' { |
| 417 | // /* foo */ -> (nothing) |
| 418 | if Debug { |
| 419 | fmt.Printf("Multi-line comment end. pr: %s\n", string(pr)) |
| 420 | } |
| 421 | s = unknown |
| 422 | } else { |
| 423 | pr = r |
| 424 | if Debug { |
| 425 | fmt.Println("Ignore multi-line comment content") |
| 426 | } |
| 427 | } |
| 428 | continue |
| 429 | } else if s == mlcOrMySQLCode { |
| 430 | // We're at the start of either a /* multi-line comment */ or some |
| 431 | // /*![version] some MySQL-specific code */. The ! after the /* |
| 432 | // determines which one. |
| 433 | if r != '!' { |
| 434 | if Debug { |
| 435 | fmt.Println("Multi-line comment") |
| 436 | } |
| 437 | pr = r |
| 438 | s = inMLC |
| 439 | continue |
| 440 | } else { |
| 441 | // /*![version] SQL_NO_CACHE */ -> /*![version] SQL_NO_CACHE */ (no change) |
| 442 | if Debug { |
| 443 | fmt.Println("MySQL-specific code") |
| 444 | } |
| 445 | s = inWord |
| 446 | sqlState = inMySQLCode |
| 447 | } |
| 448 | } else if s == inOLC { |
| 449 | // We're in a -- one line comment. A space after -- is required. |
| 450 | // It ends at the end of the line, but there can be more query after |
| 451 | // it like: |
| 452 | // SELECT * -- comment |
| 453 | // FROM t |
| 454 | // is really "SELECT * FROM t". |
| 455 | if r == 0x0A { // newline |
| 456 | if Debug { |
| 457 | fmt.Println("One-line comment end") |
| 458 | } |
| 459 | s = unknown |
| 460 | } |
| 461 | continue |
| 462 | } else if isSpace(r) && isSpace(pr) { |
| 463 | // All space is collapsed into a single space, so if this char is |
| 464 | // a space and the previous was too, then skip the extra space. |
| 465 | if Debug { |
| 466 | fmt.Println("Skip space") |
| 467 | } |
| 468 | // +1 here ensures we actually skip the extra space in certain |
| 469 | // cases like "select \n-- bar\n foo". When a part of the query |
| 470 | // triggers a copy of preceding chars, if the only preceding char |
| 471 | // is a space then it's incorrectly copied, but +1 sets cpFromOffset |
| 472 | // to the same offset as the trigger char, thus avoiding the copy. |
| 473 | // For example in that ^ query, the offsets are: |
| 474 | // 0 's' |
| 475 | // 1 'e' |
| 476 | // 2 'l' |
| 477 | // 3 'e' |
| 478 | // 4 'c' |
| 479 | // 5 't' |
| 480 | // 6 ' ' |
| 481 | // 7 '\n' |
| 482 | // 8 '-' |
| 483 | // After copying 'select ', we are here @ 7 and intend to skip the |
| 484 | // newline. Next, the '-' @ 8 triggers a copy of any preceding |
| 485 | // chars. So here if we set cpFromOffset = 7 then 7:8 is copied, |
| 486 | // the newline, but setting cpFromOffset = 7 + 1 is 8:8 and so |
| 487 | // nothing is copied as we want. Actually, cpToOffset is still 6 |
| 488 | // in this case, but 8:6 avoids the copy too. |
| 489 | cpFromOffset = qi + 1 |
| 490 | pr = r |
| 491 | continue |
| 492 | } |
| 493 | |
| 494 | /** |
| 495 | * 2. Change state based on rune and current state. |
| 496 | */ |
| 497 | |
| 498 | switch { |
| 499 | case r >= 0x30 && r <= 0x39: // 0-9 |
| 500 | switch s { |
| 501 | case opOrNumber: |
| 502 | if Debug { |
| 503 | fmt.Println("+/-First digit") |
| 504 | } |
| 505 | cpToOffset = qi - 1 |
| 506 | s = inNumber |
| 507 | case inOp: |
| 508 | if Debug { |
| 509 | fmt.Println("First digit after operator") |
| 510 | } |
| 511 | cpToOffset = qi |
| 512 | s = inNumber |
| 513 | case inWord: |
| 514 | if pr == '(' { |
| 515 | if Debug { |
| 516 | fmt.Println("Number in function") |
| 517 | } |
| 518 | cpToOffset = qi |
| 519 | s = inNumber |
| 520 | } else if pr == ',' { |
| 521 | // foo,4 -- 4 may be a number literal or a word/ident |
| 522 | if Debug { |
| 523 | fmt.Println("Number or word") |
| 524 | } |
| 525 | s = inNumber |
| 526 | cpToOffset = qi |
| 527 | } else { |
| 528 | if Debug { |
| 529 | fmt.Println("Number in word") |
| 530 | } |
| 531 | if ReplaceNumbersInWords { |
| 532 | s = inNumberInWord |
| 533 | cpToOffset = qi |
| 534 | } |
| 535 | } |
| 536 | default: |
| 537 | if Debug { |
| 538 | fmt.Println("Number literal") |
| 539 | } |
| 540 | s = inNumber |
| 541 | cpToOffset = qi |
| 542 | } |
| 543 | case isSpace(r): |
| 544 | if s == unknown { |
| 545 | if Debug { |
| 546 | fmt.Println("Lost in space") |
| 547 | } |
| 548 | if fi > 0 && !isSpace(rune(f[fi-1])) { |
| 549 | if Debug { |
| 550 | fmt.Println("Add space") |
| 551 | } |
| 552 | f[fi] = ' ' |
| 553 | fi++ |
| 554 | // This is a common case: a space after skipping something, |
| 555 | // e.g. col = 'foo'<space>. We want only the first space, |
| 556 | // so advance cpFromOffset to whatever is after the space |
| 557 | // and if it's more space then space skipping block will |
| 558 | // handle it. |
| 559 | } |
| 560 | cpFromOffset = qi + 1 |
| 561 | } else if s == inDash { |
| 562 | if Debug { |
| 563 | fmt.Println("One-line comment begin") |
| 564 | } |
| 565 | s = inOLC |
| 566 | if cpToOffset > 2 { |
| 567 | cpToOffset = qi - 2 |
| 568 | } |
| 569 | } else if s == moreValuesOrUnknown { |
| 570 | if Debug { |
| 571 | fmt.Println("Space after values") |
| 572 | } |
| 573 | if valueNo == 1 { |
| 574 | f[fi] = ' ' |
| 575 | fi++ |
| 576 | } |
| 577 | } else { |
| 578 | if Debug { |
| 579 | fmt.Println("Word end") |
| 580 | } |
| 581 | word := strings.ToLower(q[cpFromOffset:qi]) |
| 582 | // Only match USE if it is the first word in the query, otherwise, |
| 583 | // it could be a USE INDEX |
| 584 | if word == "use" && prevWord == "" { |
| 585 | return "use ?" |
| 586 | } else if (word == "null" && (prevWord != "is" && prevWord != "not")) || word == "null," { |
| 587 | if Debug { |
| 588 | fmt.Println("NULL as value") |
| 589 | } |
| 590 | f[fi] = '?' |
| 591 | fi++ |
| 592 | if word[len(word)-1] == ',' { |
| 593 | f[fi] = ',' |
| 594 | fi++ |
| 595 | } |
| 596 | f[fi] = ' ' |
| 597 | fi++ |
| 598 | cpFromOffset = qi + 1 |
| 599 | } else if prevWord == "order" && word == "by" { |
| 600 | if Debug { |
| 601 | fmt.Println("ORDER BY begin") |
| 602 | } |
| 603 | sqlState = orderBy |
| 604 | } else if sqlState == orderBy && wordIn(word, "asc", "asc,", "asc ") { |
| 605 | if Debug { |
| 606 | fmt.Println("ORDER BY ASC") |
| 607 | } |
| 608 | cpFromOffset = qi |
| 609 | if word[len(word)-1] == ',' { |
| 610 | fi-- |
| 611 | f[fi] = ',' |
| 612 | f[fi+1] = ' ' |
| 613 | fi += 2 |
| 614 | } |
| 615 | } else if prevWord == "key" && word == "update" { |
| 616 | if Debug { |
| 617 | fmt.Println("ON DUPLICATE KEY UPDATE begin") |
| 618 | } |
| 619 | sqlState = onDupeKeyUpdate |
| 620 | } |
| 621 | s = inSpace |
| 622 | cpToOffset = qi |
| 623 | addSpace = true |
| 624 | } |
| 625 | case r == '\'' || r == '"': |
| 626 | if pr != '\\' { |
| 627 | if s != inQuote { |
| 628 | if Debug { |
| 629 | fmt.Println("Quote begin") |
| 630 | } |
| 631 | s = inQuote |
| 632 | quoteChar = r |
| 633 | cpToOffset = qi |
| 634 | if pr == 'x' || pr == 'b' { |
| 635 | if Debug { |
| 636 | fmt.Println("Hex/binary value") |
| 637 | } |
| 638 | // We're at the first quote char of x'0F' |
| 639 | // (or b'0101', etc.), so -2 for the quote char and |
| 640 | // the x or b char to copy anything before and up to |
| 641 | // this value. |
| 642 | cpToOffset = -2 |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | case r == '`': |
| 647 | if pr != '\\' { |
| 648 | if s != inBackticks { |
| 649 | if Debug { |
| 650 | fmt.Println("Beckticks begin") |
| 651 | } |
| 652 | s = inBackticks |
| 653 | } |
| 654 | } |
| 655 | case r == '=' || r == '<' || r == '>' || r == '!': |
| 656 | if Debug { |
| 657 | fmt.Println("Operator") |
| 658 | } |
| 659 | if s != inWord && s != inOp { |
| 660 | cpFromOffset = qi |
| 661 | } |
| 662 | s = inOp |
| 663 | case r == '/': |
| 664 | if Debug { |
| 665 | fmt.Println("Op or multi-line comment") |
| 666 | } |
| 667 | s = divOrMLC |
| 668 | case r == '*' && s == divOrMLC: |
| 669 | if Debug { |
| 670 | fmt.Println("Multi-line comment or MySQL-specific code") |
| 671 | } |
| 672 | s = mlcOrMySQLCode |
| 673 | case r == '+': |
| 674 | if Debug { |
| 675 | fmt.Println("Operator or number") |
| 676 | } |
| 677 | s = opOrNumber |
| 678 | case r == '-': |
| 679 | if pr == '-' { |
| 680 | if Debug { |
| 681 | fmt.Println("Dash") |
| 682 | } |
| 683 | s = inDash |
| 684 | } else { |
| 685 | if Debug { |
| 686 | fmt.Println("Operator or number") |
| 687 | } |
| 688 | s = opOrNumber |
| 689 | } |
| 690 | case r == '.': |
| 691 | if s == inNumber || s == inOp { |
| 692 | if Debug { |
| 693 | fmt.Println("Floating point number") |
| 694 | } |
| 695 | s = inNumber |
| 696 | cpToOffset = qi |
| 697 | } |
| 698 | case r == '(': |
| 699 | if prevWord == "call" { |
| 700 | // 'CALL foo(...)' -> 'call foo' |
| 701 | if Debug { |
| 702 | fmt.Println("CALL sp_name") |
| 703 | } |
| 704 | return "call " + q[cpFromOffset:qi] |
| 705 | } else if sqlState != onDupeKeyUpdate && (((s == inSpace || s == moreValuesOrUnknown) && (prevWord == "value" || prevWord == "values" || prevWord == "in")) || wordIn(q[cpFromOffset:qi], "value", "values", "in")) { |
| 706 | // VALUE(, VALUE (, VALUES(, VALUES (, IN(, or IN( |
| 707 | // but not after ON DUPLICATE KEY UPDATE |
| 708 | if Debug { |
| 709 | fmt.Println("Values begin") |
| 710 | } |
| 711 | s = inValues |
| 712 | sqlState = inValues |
| 713 | parOpen = 1 |
| 714 | firstPar = qi |
| 715 | if valueNo == 0 { |
| 716 | cpToOffset = qi |
| 717 | } |
| 718 | } else if s != inWord { |
| 719 | if Debug { |
| 720 | fmt.Println("Random (") |
| 721 | } |
| 722 | valueNo = 0 |
| 723 | cpFromOffset = qi |
| 724 | s = inWord |
| 725 | } |
| 726 | case r == ',' && s == moreValuesOrUnknown: |
| 727 | if Debug { |
| 728 | fmt.Println("More values") |
| 729 | } |
| 730 | case r == ':' && prevWord == "administrator": |
| 731 | // 'administrator command: Init DB' -> 'administrator command: Init DB' (no change) |
| 732 | if Debug { |
| 733 | fmt.Println("Admin cmd") |
| 734 | } |
| 735 | return q[0 : len(q)-1] // original query minus the trailing space we added |
| 736 | case r == '#': |
| 737 | if Debug { |
| 738 | fmt.Println("One-line comment begin") |
| 739 | } |
| 740 | addSpace = false |
| 741 | s = inOLC |
| 742 | default: |
| 743 | if s != inWord && s != inOp { |
| 744 | // If in a word or operator then keep copying the query, else |
| 745 | // previous chars were being ignored for some reason, but now |
| 746 | // we should start copying again, so set cpFromOffset. Example: |
| 747 | // col=NOW(). 'col' will be set to copy, but then '=' will put |
| 748 | // us in inOp state which, if a value follows, will trigger a |
| 749 | // copy of "col=", but "NOW()" is not a value so "N" is caught |
| 750 | // here and since s=inOp still we do not copy yet (this block is |
| 751 | // not entered). |
| 752 | if Debug { |
| 753 | fmt.Println("Random character") |
| 754 | } |
| 755 | valueNo = 0 |
| 756 | cpFromOffset = qi |
| 757 | |
| 758 | if sqlState == inValues { |
| 759 | // Values are comma-separated, so the first random char |
| 760 | // marks the end of the VALUE() or IN() list. |
| 761 | if Debug { |
| 762 | fmt.Println("No more values") |
| 763 | } |
| 764 | sqlState = unknown |
| 765 | } |
| 766 | } |
| 767 | s = inWord |
| 768 | } |
| 769 | |
| 770 | /** |
| 771 | * 3. Copy a slice of the query into the fingerprint. |
| 772 | */ |
| 773 | |
| 774 | if cpToOffset > cpFromOffset { |
| 775 | l := cpToOffset - cpFromOffset |
| 776 | prevWord = strings.ToLower(q[cpFromOffset:cpToOffset]) |
| 777 | if Debug { |
| 778 | fmt.Printf("copy '%s' (%d:%d, %d:%d) %d\n", prevWord, fi, fi+l, cpFromOffset, cpToOffset, l) |
| 779 | } |
| 780 | copy(f[fi:fi+l], prevWord) |
| 781 | fi += l |
| 782 | cpFromOffset = cpToOffset |
| 783 | valueKeywords := []string{"in", "value", "values"} |
| 784 | if wordIn(prevWord, valueKeywords...) && sqlState != onDupeKeyUpdate { |
| 785 | addSpace = false |
| 786 | // since we only consider the keywords if it exists at a top-level (except onDupeKeyUpdate), |
| 787 | // we only do the conversion below if the "keywords" actually open a value list (i.e., before opening a parenthesis). |
| 788 | if r == '(' || (isSpace(r) && qi+1 < len(q) && ((q[qi+1] == '(') || (q[qi+1] == ' '))) { |
| 789 | // IN () -> in(?+) |
| 790 | // VALUES () -> values(?+) |
| 791 | s = inValues |
| 792 | sqlState = inValues |
| 793 | } else { |
| 794 | f[fi] = ' ' |
| 795 | fi++ |
| 796 | cpFromOffset++ |
| 797 | } |
| 798 | } else if addSpace { |
| 799 | if Debug { |
| 800 | fmt.Println("Add space") |
| 801 | } |
| 802 | f[fi] = ' ' |
| 803 | fi++ |
| 804 | cpFromOffset++ |
| 805 | addSpace = false |
| 806 | } |
| 807 | } |
| 808 | pr = r |
| 809 | } |
| 810 | |
| 811 | // Remove trailing spaces. |
| 812 | for fi > 0 && isSpace(rune(f[fi-1])) { |
| 813 | fi-- |
| 814 | } |
| 815 | |
| 816 | // Clean up control characters, and return the fingerprint |
| 817 | return strings.Replace(string(f[0:fi]), "\x00", "", -1) |
| 818 | } |
| 819 | |
| 820 | func isSpace(r rune) bool { |
| 821 | return r == 0x20 || r == 0x09 || r == 0x0D || r == 0x0A |
| 822 | } |
| 823 | |
| 824 | func wordIn(q string, words ...string) bool { |
| 825 | q = strings.ToLower(q) |
| 826 | for _, word := range words { |
| 827 | if q == word { |
| 828 | return true |
| 829 | } |
| 830 | } |
| 831 | return false |
| 832 | } |
| 833 | |
| 834 | // Id returns the right-most 16 characters of the MD5 checksum of fingerprint. |
| 835 | // Query IDs are the shortest way to uniquely identify queries. |
| 836 | func Id(fingerprint string) string { |
| 837 | id := md5.New() |
| 838 | io.WriteString(id, fingerprint) |
| 839 | h := fmt.Sprintf("%x", id.Sum(nil)) |
| 840 | return strings.ToUpper(h[16:32]) |
| 841 | } |