From 77b24cda2682c282f6e49f052729fe7ce60a7136 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Sun, 27 Nov 2022 11:43:16 +0000 Subject: [PATCH] Ensure double quote characters are always escaped properly Closes #1488 --- lib/src/sql/escape.rs | 6 +++--- lib/tests/escape.rs | 39 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/lib/src/sql/escape.rs b/lib/src/sql/escape.rs index a7347f06..ffdd4c88 100644 --- a/lib/src/sql/escape.rs +++ b/lib/src/sql/escape.rs @@ -15,11 +15,11 @@ const BACKTICK: char = '`'; const BACKTICK_ESC: &str = r#"\`"#; #[inline] -pub fn escape_str(s: &str) -> String { +pub fn escape_str(s: &str) -> Cow<'_, str> { if s.contains(SINGLE) { - format!("{}{}{}", DOUBLE, s, DOUBLE) + escape_normal(s, DOUBLE, DOUBLE, DOUBLE_ESC) } else { - format!("{}{}{}", SINGLE, s, SINGLE) + Cow::Owned(format!("{}{}{}", SINGLE, s, SINGLE)) } } diff --git a/lib/tests/escape.rs b/lib/tests/escape.rs index 77762e04..a2837c9b 100644 --- a/lib/tests/escape.rs +++ b/lib/tests/escape.rs @@ -6,7 +6,7 @@ use surrealdb::Error; use surrealdb::Session; #[tokio::test] -async fn complex_string() -> Result<(), Error> { +async fn complex_ids() -> Result<(), Error> { let sql = r#" CREATE person:100 SET test = 'One'; CREATE person:00100; @@ -84,3 +84,40 @@ async fn complex_string() -> Result<(), Error> { // Ok(()) } + +#[tokio::test] +async fn complex_strings() -> Result<(), Error> { + let sql = r#" + RETURN 'String with no complex characters'; + RETURN 'String with some "double quoted" characters'; + RETURN 'String with some \'escaped single quoted\' characters'; + RETURN "String with some \"escaped double quoted\" characters"; + RETURN "String with some 'single' and \"double\" quoted characters"; + "#; + let dbs = Datastore::new("memory").await?; + let ses = Session::for_kv().with_ns("test").with_db("test"); + let res = &mut dbs.execute(&sql, &ses, None, false).await?; + assert_eq!(res.len(), 5); + // + let tmp = res.remove(0).result?; + let val = Value::parse(r#"'String with no complex characters'"#); + assert_eq!(tmp, val); + // + let tmp = res.remove(0).result?; + let val = Value::parse(r#"'String with some "double quoted" characters'"#); + assert_eq!(tmp, val); + // + let tmp = res.remove(0).result?; + let val = Value::parse(r#""String with some 'escaped single quoted' characters""#); + assert_eq!(tmp, val); + // + let tmp = res.remove(0).result?; + let val = Value::parse(r#"'String with some "escaped double quoted" characters'"#); + assert_eq!(tmp, val); + // + let tmp = res.remove(0).result?; + let val = Value::parse(r#""String with some 'single' and \"double\" quoted characters""#); + assert_eq!(tmp, val); + // + Ok(()) +}