schema_sql_generator/common/sql_string.rs
1/// Escapes `value` for safe interpolation inside a single-quoted SQL string literal, by
2/// doubling any embedded single quote (the standard SQL escaping - understood by
3/// Postgres, SQL Server, and SQLite alike). Every place in this crate that writes a
4/// user-supplied value (identifier, enum code, configured username, ...) inside `'...'`
5/// must go through this first: an unescaped embedded quote breaks the generated SQL at
6/// best, or lets the value's content escape the string literal and inject arbitrary SQL
7/// at worst.
8pub fn escape_sql_literal(value: &str) -> String {
9 value.replace('\'', "''")
10}
11
12#[cfg(test)]
13mod tests {
14 use super::*;
15
16 #[test]
17 fn leaves_plain_text_unchanged() {
18 assert_eq!(escape_sql_literal("hello"), "hello");
19 }
20
21 #[test]
22 fn doubles_embedded_single_quotes() {
23 assert_eq!(escape_sql_literal("O'Brien"), "O''Brien");
24 assert_eq!(escape_sql_literal("it's a 'test'"), "it''s a ''test''");
25 }
26}