use crate::error::PostgresProjectionStoreError;
pub(crate) fn highest_placeholder(sql: &str) -> usize {
let bytes = sql.as_bytes();
let mut highest = 0_usize;
let mut at = 0_usize;
while let Some(&byte) = bytes.get(at) {
let next = at.saturating_add(1);
at = match byte {
b'\'' => skip_quoted(bytes, next, b'\'', Backslash::Literal),
b'"' => skip_quoted(bytes, next, b'"', Backslash::Literal),
b'-' if bytes.get(next) == Some(&b'-') => skip_line_comment(bytes, next),
b'/' if bytes.get(next) == Some(&b'*') => {
skip_block_comment(bytes, next.saturating_add(1))
}
b'$' => match parameter(bytes, next) {
Some((value, end)) => {
highest = highest.max(value);
end
}
None => dollar_quote_end(sql, at).unwrap_or(next),
},
_ if is_identifier_start(byte) => skip_identifier(bytes, at),
_ => next,
};
}
highest
}
pub(crate) fn check_parameter_count(
statement: usize,
sql: &str,
supplied: usize,
) -> Result<(), PostgresProjectionStoreError> {
let declared = highest_placeholder(sql);
if declared == supplied {
Ok(())
} else {
Err(PostgresProjectionStoreError::ParameterCount {
statement,
declared,
supplied,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Backslash {
Literal,
Escapes,
}
const fn is_identifier_start(byte: u8) -> bool {
byte.is_ascii_alphabetic() || byte == b'_' || byte >= 0x80
}
const fn is_identifier_continue(byte: u8) -> bool {
is_identifier_start(byte) || byte.is_ascii_digit() || byte == b'$'
}
const fn is_tag_continue(byte: u8) -> bool {
is_identifier_start(byte) || byte.is_ascii_digit()
}
fn run_end(bytes: &[u8], from: usize, keep: impl Fn(u8) -> bool) -> usize {
bytes
.get(from..)
.and_then(|rest| rest.iter().position(|&byte| !keep(byte)))
.map_or(bytes.len(), |offset| from.saturating_add(offset))
}
fn skip_identifier(bytes: &[u8], start: usize) -> usize {
let end = run_end(bytes, start.saturating_add(1), is_identifier_continue);
let one_byte = end == start.saturating_add(1);
let prefix = bytes
.get(start)
.copied()
.map(|byte| byte.to_ascii_lowercase());
let after = |offset: usize| bytes.get(end.saturating_add(offset)).copied();
match (one_byte, prefix, after(0), after(1)) {
(true, Some(b'e'), Some(b'\''), _) => {
skip_quoted(bytes, end.saturating_add(1), b'\'', Backslash::Escapes)
}
(true, Some(b'u'), Some(b'&'), Some(quote @ (b'\'' | b'"'))) => {
skip_quoted(bytes, end.saturating_add(2), quote, Backslash::Literal)
}
_ => end,
}
}
fn skip_quoted(bytes: &[u8], from: usize, quote: u8, backslash: Backslash) -> usize {
let mut at = from;
while let Some(&byte) = bytes.get(at) {
let next = at.saturating_add(1);
if byte == b'\\' && backslash == Backslash::Escapes {
at = next.saturating_add(1);
} else if byte == quote {
if bytes.get(next) == Some("e) {
at = next.saturating_add(1);
} else if let Some(reopened) = continuation(bytes, next).filter(|_| quote == b'\'') {
at = reopened.saturating_add(1);
} else {
return next;
}
} else {
at = next;
}
}
bytes.len()
}
const fn is_horizontal_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | 0x0b | 0x0c)
}
const fn is_newline(byte: u8) -> bool {
matches!(byte, b'\n' | b'\r')
}
fn continuation(bytes: &[u8], from: usize) -> Option<usize> {
let mut at = from;
let mut crossed_newline = false;
while let Some(&byte) = bytes.get(at) {
let next = at.saturating_add(1);
at = match byte {
b'\'' if crossed_newline => return Some(at),
_ if is_horizontal_space(byte) => next,
_ if is_newline(byte) => {
crossed_newline = true;
next
}
b'-' if bytes.get(next) == Some(&b'-') => {
let end = skip_line_comment(bytes, next);
if crossed_newline && !bytes.get(end).copied().is_some_and(is_newline) {
return None;
}
end
}
_ => return None,
};
}
None
}
fn skip_line_comment(bytes: &[u8], from: usize) -> usize {
run_end(bytes, from, |byte| byte != b'\n' && byte != b'\r')
}
fn skip_block_comment(bytes: &[u8], from: usize) -> usize {
let mut depth = 1_usize;
let mut at = from;
while let Some(&byte) = bytes.get(at) {
let next = at.saturating_add(1);
match (byte, bytes.get(next)) {
(b'/', Some(b'*')) => {
depth = depth.saturating_add(1);
at = next.saturating_add(1);
}
(b'*', Some(b'/')) => {
depth = depth.saturating_sub(1);
at = next.saturating_add(1);
if depth == 0 {
return at;
}
}
_ => at = next,
}
}
bytes.len()
}
fn parameter(bytes: &[u8], from: usize) -> Option<(usize, usize)> {
let end = run_end(bytes, from, |byte| byte.is_ascii_digit());
let digits = bytes.get(from..end).filter(|digits| !digits.is_empty())?;
let value = digits.iter().fold(0_usize, |value, &digit| {
value
.saturating_mul(10)
.saturating_add(usize::from(digit.saturating_sub(b'0')))
});
Some((value, end))
}
fn dollar_quote_end(sql: &str, start: usize) -> Option<usize> {
let bytes = sql.as_bytes();
let tag_start = start.saturating_add(1);
let tag_end = match bytes.get(tag_start) {
Some(b'$') => tag_start,
Some(&byte) if is_identifier_start(byte) => {
run_end(bytes, tag_start.saturating_add(1), is_tag_continue)
}
_ => return None,
};
if bytes.get(tag_end) != Some(&b'$') {
return None;
}
let body = tag_end.saturating_add(1);
let delimiter = sql.get(start..body)?;
let rest = sql.get(body..)?;
Some(rest.find(delimiter).map_or(sql.len(), |offset| {
body.saturating_add(offset).saturating_add(delimiter.len())
}))
}
#[cfg(test)]
mod tests {
use super::{check_parameter_count, highest_placeholder};
use crate::error::PostgresProjectionStoreError;
fn declares(sql: &str, expected: usize) {
assert_eq!(
highest_placeholder(sql),
expected,
"the scan read the wrong highest placeholder from {sql:?}"
);
}
#[test]
fn a_statement_without_placeholders_declares_none() {
declares("DELETE FROM t", 0);
declares("", 0);
}
#[test]
fn the_highest_placeholder_is_reported_not_the_number_of_uses() {
declares("DELETE FROM t WHERE k = $1", 1);
declares("INSERT INTO t VALUES ($1, $2)", 2);
declares("DELETE FROM t WHERE k = $1 OR j = $1", 1);
declares("INSERT INTO t VALUES ($2, $1)", 2);
declares("SELECT $3", 3);
declares("SELECT $12", 12);
declares("SELECT $01", 1);
}
#[test]
fn placeholders_inside_string_literals_are_not_counted() {
declares("SELECT $1, '$2'", 1);
declares("SELECT $1, 'it''s $2'", 1);
declares("SELECT $1, B'$2'", 1);
declares("SELECT $1, X'$2'", 1);
declares("SELECT $1, N'$2'", 1);
declares("SELECT $1, U&'$2'", 1);
declares(r"SELECT '\', $2", 2);
}
#[test]
fn an_escape_string_honours_backslash_escapes() {
declares(r"SELECT E'\'$2', $1", 1);
declares(r"SELECT e'\\', $2", 2);
declares(r"SELECT e'it''s $3', $1", 1);
declares(r"SELECT somee'\', $2", 2);
}
#[test]
fn a_continued_escape_string_keeps_honouring_backslashes() {
declares("SELECT E'x'\n'\\' $2', $1::text", 1);
declares("SELECT E''\n'\\'', $2::text, $1::text", 2);
declares("SELECT E'x' -- c\n -- d\n'\\' $2', $1::text", 1);
declares("SELECT e'x' \t\r\n\n '\\' $2', $1", 1);
declares("SELECT E'x', '\\', $2::text, $1::text", 2);
declares("SELECT 'a'\n'\\', $1::text", 1);
declares("SELECT U&'a'\n'$2', $1::text", 1);
}
#[test]
fn placeholders_inside_quoted_identifiers_are_not_counted() {
declares(r#"SELECT $1 AS "col$2""#, 1);
declares(r#"SELECT $1 AS "a""$2""#, 1);
declares(r#"SELECT $1 AS U&"$2""#, 1);
}
#[test]
fn placeholders_inside_dollar_quoted_bodies_are_not_counted() {
declares("SELECT $$ $2 $$, $1", 1);
declares("SELECT $tag$ $2 $other$ $tag$, $1", 1);
declares("SELECT $_t9$ $2 $_t9$, $1", 1);
declares("SELECT $1, $$ unterminated $2", 1);
declares("SELECT $1$$ $2 $$", 1);
declares("SELECT $1::text||$a1$ $2 $a1$", 1);
}
#[test]
fn placeholders_inside_comments_are_not_counted() {
declares("SELECT $1 -- $2\n", 1);
declares("SELECT $1 -- $3\r, $2", 2);
declares("SELECT $1 /* $2 */", 1);
declares("SELECT /* /* */ $2 */ $1", 1);
declares("SELECT $1 /* unterminated $2", 1);
}
#[test]
fn a_dollar_inside_an_identifier_is_not_a_placeholder() {
declares("SELECT a$1", 0);
declares("SELECT $1 AS a$2", 1);
declares("SELECT _x$3, $1", 1);
declares("SELECT $1::text AS é$2", 1);
declares("SELECT café$1", 0);
}
#[test]
fn a_placeholder_directly_after_an_operator_is_counted() {
declares("SELECT 1 WHERE k=$1", 1);
declares("SELECT -$1::int", 1);
declares("SELECT 1--$1", 0);
}
#[test]
fn the_scan_is_total() {
const ALPHABET: [char; 18] = [
'$', '1', '9', '\'', '"', '-', '/', '*', 'e', 'E', 'u', 'U', '_', '\\', '\n', '\r',
' ', '&',
];
let mut scanned = 0_usize;
let mut texts: Vec<String> = vec![String::new()];
for _ in 0..4 {
texts = texts
.iter()
.flat_map(|prefix| {
ALPHABET
.iter()
.map(move |symbol| format!("{prefix}{symbol}"))
})
.collect();
for text in &texts {
let highest = highest_placeholder(text);
assert!(highest <= 999, "{text:?} declared {highest}");
scanned += 1;
}
}
assert_eq!(scanned, 18 + 18 * 18 + 18 * 18 * 18 + 18 * 18 * 18 * 18);
let absurd = format!("SELECT ${}", "9".repeat(25));
assert_eq!(
highest_placeholder(&absurd),
usize::MAX,
"{absurd} saturates"
);
}
#[test]
fn check_parameter_count_refuses_both_directions() {
assert!(matches!(
check_parameter_count(0, "DELETE FROM t WHERE k = $1 OR k = $2", 1),
Err(PostgresProjectionStoreError::ParameterCount {
statement: 0,
declared: 2,
supplied: 1,
})
));
assert!(matches!(
check_parameter_count(3, "DELETE FROM t WHERE k = $1", 2),
Err(PostgresProjectionStoreError::ParameterCount {
statement: 3,
declared: 1,
supplied: 2,
})
));
assert!(matches!(
check_parameter_count(0, "DELETE FROM t WHERE k = $1", 1),
Ok(())
));
}
}