stripStringsAndComments returns statement with the contents of string literals ('...', "..."), line comments (-- , #), and block comments (/* */) replaced by spaces, preserving byte length (newlines kept) so caret offsets stay valid. Backtick-quoted identifiers are left intact. This lets the lexical
(statement string)
| 436 | // above ignore backticks and database names that appear inside literals or |
| 437 | // comments rather than as real SQL tokens. |
| 438 | func stripStringsAndComments(statement string) string { |
| 439 | out := []byte(statement) |
| 440 | n := len(out) |
| 441 | blank := func(i int) { |
| 442 | if out[i] != '\n' { |
| 443 | out[i] = ' ' |
| 444 | } |
| 445 | } |
| 446 | i := 0 |
| 447 | for i < n { |
| 448 | switch c := out[i]; { |
| 449 | case c == '\'' || c == '"': |
| 450 | q := c |
| 451 | blank(i) |
| 452 | i++ |
| 453 | for i < n { |
| 454 | if out[i] == '\\' && i+1 < n { // backslash escape |
| 455 | blank(i) |
| 456 | blank(i + 1) |
| 457 | i += 2 |
| 458 | continue |
| 459 | } |
| 460 | if out[i] == q { |
| 461 | if i+1 < n && out[i+1] == q { // doubled-quote escape |
| 462 | blank(i) |
| 463 | blank(i + 1) |
| 464 | i += 2 |
| 465 | continue |
| 466 | } |
| 467 | blank(i) |
| 468 | i++ |
| 469 | break |
| 470 | } |
| 471 | blank(i) |
| 472 | i++ |
| 473 | } |
| 474 | case c == '#': |
| 475 | for i < n && out[i] != '\n' { |
| 476 | out[i] = ' ' |
| 477 | i++ |
| 478 | } |
| 479 | case c == '-' && i+1 < n && out[i+1] == '-' && (i+2 >= n || isSpaceByte(out[i+2])): |
| 480 | for i < n && out[i] != '\n' { |
| 481 | out[i] = ' ' |
| 482 | i++ |
| 483 | } |
| 484 | case c == '/' && i+1 < n && out[i+1] == '*': |
| 485 | blank(i) |
| 486 | blank(i + 1) |
| 487 | i += 2 |
| 488 | for i < n { |
| 489 | if out[i] == '*' && i+1 < n && out[i+1] == '/' { |
| 490 | blank(i) |
| 491 | blank(i + 1) |
| 492 | i += 2 |
| 493 | break |
| 494 | } |
| 495 | blank(i) |
no test coverage detected