-
-
Notifications
You must be signed in to change notification settings - Fork 486
Add escape_identifier() and escape_literal(). #702
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
//! Provides functions for escaping literals and identifiers for use | ||
//! in SQL queries. | ||
//! | ||
//! Prefer parameterized queries where possible; see | ||
//! [`Client::query`](crate::Client::query). Do not escape parameters. | ||
|
||
#[cfg(test)] | ||
mod test; | ||
|
||
/// Escape a literal and surround result with single quotes. Not | ||
/// recommended in most cases. | ||
/// | ||
/// If input contains backslashes, result will be of the form ` | ||
/// E'...'` so it is safe to use regardless of the setting of | ||
/// standard_conforming_strings. | ||
pub fn escape_literal(input: &str) -> String { | ||
escape_internal(input, false) | ||
} | ||
|
||
/// Escape an identifier and surround result with double quotes. | ||
pub fn escape_identifier(input: &str) -> String { | ||
escape_internal(input, true) | ||
} | ||
|
||
// Translation of PostgreSQL libpq's PQescapeInternal(). Does not | ||
// require a connection because input string is known to be valid | ||
// UTF-8. | ||
// | ||
// Escape arbitrary strings. If as_ident is true, we escape the | ||
// result as an identifier; if false, as a literal. The result is | ||
// returned in a newly allocated buffer. If we fail due to an | ||
// encoding violation or out of memory condition, we return NULL, | ||
// storing an error message into conn. | ||
fn escape_internal(input: &str, as_ident: bool) -> String { | ||
let mut num_backslashes = 0; | ||
let mut num_quotes = 0; | ||
let quote_char = if as_ident { '"' } else { '\'' }; | ||
|
||
// Scan the string for characters that must be escaped. | ||
for ch in input.chars() { | ||
if ch == quote_char { | ||
num_quotes += 1; | ||
} else if ch == '\\' { | ||
num_backslashes += 1; | ||
} | ||
} | ||
|
||
// Allocate output String. | ||
let mut result_size = input.len() + num_quotes + 3; // two quotes, plus a NUL | ||
if !as_ident && num_backslashes > 0 { | ||
result_size += num_backslashes + 2; | ||
} | ||
|
||
let mut output = String::with_capacity(result_size); | ||
|
||
// If we are escaping a literal that contains backslashes, we use | ||
// the escape string syntax so that the result is correct under | ||
// either value of standard_conforming_strings. We also emit a | ||
// leading space in this case, to guard against the possibility | ||
// that the result might be interpolated immediately following an | ||
// identifier. | ||
if !as_ident && num_backslashes > 0 { | ||
output.push(' '); | ||
output.push('E'); | ||
} | ||
|
||
// Opening quote. | ||
output.push(quote_char); | ||
|
||
// Use fast path if possible. | ||
// | ||
// We've already verified that the input string is well-formed in | ||
// the current encoding. If it contains no quotes and, in the | ||
// case of literal-escaping, no backslashes, then we can just copy | ||
// it directly to the output buffer, adding the necessary quotes. | ||
// | ||
// If not, we must rescan the input and process each character | ||
// individually. | ||
if num_quotes == 0 && (num_backslashes == 0 || as_ident) { | ||
output.push_str(input); | ||
} else { | ||
for ch in input.chars() { | ||
if ch == quote_char || (!as_ident && ch == '\\') { | ||
output.push(ch); | ||
} | ||
output.push(ch); | ||
} | ||
} | ||
|
||
output.push(quote_char); | ||
|
||
output | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
use crate::escape::{escape_identifier, escape_literal}; | ||
|
||
#[test] | ||
fn test_escape_idenifier() { | ||
assert_eq!(escape_identifier("foo"), String::from("\"foo\"")); | ||
assert_eq!(escape_identifier("f\\oo"), String::from("\"f\\oo\"")); | ||
assert_eq!(escape_identifier("f'oo"), String::from("\"f'oo\"")); | ||
assert_eq!(escape_identifier("f\"oo"), String::from("\"f\"\"oo\"")); | ||
} | ||
|
||
#[test] | ||
fn test_escape_literal() { | ||
assert_eq!(escape_literal("foo"), String::from("'foo'")); | ||
assert_eq!(escape_literal("f\\oo"), String::from(" E'f\\\\oo'")); | ||
assert_eq!(escape_literal("f'oo"), String::from("'f''oo'")); | ||
assert_eq!(escape_literal("f\"oo"), String::from("'f\"oo'")); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we have these return a
Cow<str>
so the no escaping needed case doesn't need to reallocate?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
escape_literal()
follows the semantics ofPQescapeLiteral()
, which always allocates because the result must be surrounded by quote marks. This is different fromPQescapeStringConn()
which has some messy history that I don't think we need to follow because we should be using parameters most of the time anyway. In those cases where we still need it (like utility commands or replication commands), either form will suffice.We could potentially optimize
escape_identifier()
, but it would deviate from libpq. I don't see this as likely to be a hot path, so the trade-off doesn't seem great to me.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah yeah I missed that quotes were always added. The behavior here makes sense in that case.