From da9df86d40f8484694fce3cfc5ef6cdb6083343f Mon Sep 17 00:00:00 2001 From: Brent Schroeter Date: Fri, 21 Nov 2025 08:08:51 +0000 Subject: [PATCH] add test for escape_identifier() --- phono-backends/src/lib.rs | 12 ++---------- phono-backends/src/utils.rs | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) create mode 100644 phono-backends/src/utils.rs diff --git a/phono-backends/src/lib.rs b/phono-backends/src/lib.rs index 4f5635b..74699bf 100644 --- a/phono-backends/src/lib.rs +++ b/phono-backends/src/lib.rs @@ -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; diff --git a/phono-backends/src/utils.rs b/phono-backends/src/utils.rs new file mode 100644 index 0000000..e87aacf --- /dev/null +++ b/phono-backends/src/utils.rs @@ -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""""# + ); + } +}