Skip to main content

quote_literal

Function quote_literal 

Source
pub fn quote_literal(s: &str) -> String
Expand description

Quote a SQL literal string.

This function wraps the string in single quotes and escapes any embedded single quotes by doubling them. This is only for cases where parameterized queries can’t be used (e.g., SET commands).

§Warning

Prefer using parameterized queries with SqlParam instead of this function whenever possible. This function should only be used for SQL constructs that don’t support parameters (like some SET commands).

§Examples

use postrust_sql::quote_literal;

assert_eq!(quote_literal("hello"), "'hello'");
assert_eq!(quote_literal("it's"), "'it''s'");
assert_eq!(quote_literal(r"a\b"), r"E'a\\b'");

A string with a backslash in it is written as an escape string, E'...', with the backslash doubled. A plain '...' literal reads a backslash as itself only while standard_conforming_strings is on: a database, role or server that turns it off reads \' as a quote inside the literal, and the doubled quote after it ends the literal early. An escape string means the same under either setting.