SQL comment stripping utilities This module provides functionality to strip SQL comments from queries to prevent issues with query parsing and execution. Strip SQL comments from a query Removes both single-line (--) and multi-line (/* */) comments while preserving string literals and their contents.
(query: &str)
| 7 | /// Removes both single-line (--) and multi-line (/* */) comments |
| 8 | /// while preserving string literals and their contents. |
| 9 | pub fn strip_sql_comments(query: &str) -> String { |
| 10 | let mut result = String::with_capacity(query.len()); |
| 11 | let mut chars = query.chars().peekable(); |
| 12 | let mut in_string = false; |
| 13 | let mut string_delimiter = '\0'; |
| 14 | |
| 15 | while let Some(ch) = chars.next() { |
| 16 | match ch { |
| 17 | // Handle string literals |
| 18 | '\'' | '"' if !in_string => { |
| 19 | in_string = true; |
| 20 | string_delimiter = ch; |
| 21 | result.push(ch); |
| 22 | } |
| 23 | ch if ch == string_delimiter && in_string => { |
| 24 | // Check for escaped quotes |
| 25 | if chars.peek() == Some(&ch) { |
| 26 | // Escaped quote, consume both |
| 27 | result.push(ch); |
| 28 | result.push(chars.next().unwrap()); |
| 29 | } else { |
| 30 | // End of string |
| 31 | in_string = false; |
| 32 | string_delimiter = '\0'; |
| 33 | result.push(ch); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Handle comments only outside of strings |
| 38 | '-' if !in_string && chars.peek() == Some(&'-') => { |
| 39 | // Single-line comment, skip to end of line |
| 40 | chars.next(); // consume second '-' |
| 41 | for c in chars.by_ref() { |
| 42 | if c == '\n' { |
| 43 | result.push('\n'); // preserve line break |
| 44 | break; |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | '/' if !in_string && chars.peek() == Some(&'*') => { |
| 49 | // Multi-line comment, skip until */ |
| 50 | chars.next(); // consume '*' |
| 51 | let mut prev_char = '\0'; |
| 52 | for c in chars.by_ref() { |
| 53 | if prev_char == '*' && c == '/' { |
| 54 | break; |
| 55 | } |
| 56 | prev_char = c; |
| 57 | } |
| 58 | // Add a space to prevent token concatenation |
| 59 | result.push(' '); |
| 60 | } |
| 61 | |
| 62 | // Pass through everything else |
| 63 | _ => result.push(ch), |
| 64 | } |
| 65 | } |
| 66 |
no test coverage detected