add test for escape_identifier()

This commit is contained in:
Brent Schroeter 2025-11-21 08:08:51 +00:00
parent 916f9de45f
commit da9df86d40
2 changed files with 27 additions and 10 deletions

View file

@ -22,14 +22,6 @@ pub mod pg_database;
pub mod pg_namespace;
pub mod pg_role;
pub mod rolnames;
mod utils;
/// Given a raw identifier (such as a table name, column name, etc.), format it
/// so that it may be safely interpolated into a SQL query.
pub fn escape_identifier(identifier: &str) -> String {
// Escaping identifiers for Postgres is fairly easy, provided that the input is
// already known to contain no invalid multi-byte sequences. Backslashes may
// remain as-is, and embedded double quotes are escaped simply by doubling
// them (`"` becomes `""`). Refer to the PQescapeInternal() function in
// libpq (fe-exec.c) and Diesel's PgQueryBuilder::push_identifier().
format!("\"{}\"", identifier.replace('"', "\"\""))
}
pub use utils::escape_identifier;

View file

@ -0,0 +1,25 @@
/// Given a raw identifier (such as a table name, column name, etc.), format it
/// so that it may be safely interpolated into a SQL query.
pub fn escape_identifier(identifier: &str) -> String {
// Escaping identifiers for Postgres is fairly easy, provided that the input is
// already known to contain no invalid multi-byte sequences. Backslashes may
// remain as-is, and embedded double quotes are escaped simply by doubling
// them (`"` becomes `""`). Refer to the PQescapeInternal() function in
// libpq (fe-exec.c) and Diesel's PgQueryBuilder::push_identifier().
format!("\"{}\"", identifier.replace('"', "\"\""))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_escape_identifier() {
assert_eq!(escape_identifier("hello"), r#""hello""#);
assert_eq!(escape_identifier("hello world"), r#""hello world""#);
assert_eq!(
escape_identifier(r#""hello" "world""#),
r#""""hello"" ""world""""#
);
}
}