use crate::dialect::Dialect;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Placeholder {
pub name: String,
pub start: usize,
pub end: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Style {
None,
Named,
Positional,
Mixed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Lexed {
pub params: Vec<String>,
pub placeholders: Vec<Placeholder>,
pub style: Style,
pub opaque: Vec<(usize, usize)>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LexError {
pub message: String,
pub offset: usize,
}
impl std::fmt::Display for LexError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} (at byte {})", self.message, self.offset)
}
}
impl std::error::Error for LexError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
Dollar,
Question,
Numbered,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Rewritten {
pub sql: String,
pub order: Vec<String>,
pub spans: Vec<(usize, usize, usize, usize)>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub inserted: Vec<(usize, usize, usize)>,
}
impl Rewritten {
pub fn to_original(&self, pos: usize) -> usize {
let mut delta: isize = 0;
let mut regions = self.spans.clone();
regions.extend(self.inserted.iter().map(|&(at, rs, re)| (at, at, rs, re)));
regions.sort_by_key(|&(_, _, rs, _)| rs);
for (os, oe, rs, re) in regions {
if pos >= re {
delta += (oe - os) as isize - (re - rs) as isize;
} else if pos >= rs {
return os;
} else {
break;
}
}
(pos as isize + delta).max(0) as usize
}
}
fn is_name_start(c: u8) -> bool {
c.is_ascii_alphabetic() || c == b'_'
}
fn is_name_char(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == b'_'
}
fn prev_is_name_char(b: &[u8], i: usize) -> bool {
i > 0 && is_name_char(b[i - 1])
}
fn name_end(b: &[u8], start: usize) -> usize {
let mut j = start;
while j < b.len() && is_name_char(b[j]) {
j += 1;
}
j
}
fn dotted_name_end(b: &[u8], start: usize) -> usize {
let mut j = name_end(b, start);
while b.get(j) == Some(&b'.') && b.get(j + 1).is_some_and(|c| is_name_start(*c)) {
j = name_end(b, j + 1);
}
j
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Last {
Other,
Operand,
Subscript,
}
fn digits_end(b: &[u8], start: usize) -> usize {
let mut j = start;
while j < b.len() && b[j].is_ascii_digit() {
j += 1;
}
j
}
fn dollar_tag_end(b: &[u8], i: usize) -> Option<usize> {
if b.get(i) != Some(&b'$') {
return None;
}
let mut j = i + 1;
if j < b.len() && is_name_start(b[j]) {
j = name_end(b, j);
}
(b.get(j) == Some(&b'$')).then_some(j + 1)
}
fn find_bytes(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
if needle.is_empty() || from >= hay.len() {
return None;
}
hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MysqlText {
pub backslash_escapes: bool,
pub ansi_quotes: bool,
}
impl Default for MysqlText {
fn default() -> Self {
MysqlText { backslash_escapes: true, ansi_quotes: false }
}
}
impl MysqlText {
pub const ALL: [MysqlText; 4] = [
MysqlText { backslash_escapes: true, ansi_quotes: false },
MysqlText { backslash_escapes: false, ansi_quotes: false },
MysqlText { backslash_escapes: true, ansi_quotes: true },
MysqlText { backslash_escapes: false, ansi_quotes: true },
];
pub fn of_mode(mode: &str) -> MysqlText {
let set = |name: &str| mode.split(',').any(|m| m.trim().eq_ignore_ascii_case(name));
MysqlText { backslash_escapes: !set("NO_BACKSLASH_ESCAPES"), ansi_quotes: set("ANSI_QUOTES") }
}
}
fn quoted_end(b: &[u8], i: usize, escapes: bool) -> Option<usize> {
let quote = b[i];
let mut j = i + 1;
loop {
match b.get(j)? {
b'\\' if escapes => j += 2,
&q if q == quote && b.get(j + 1) == Some("e) => j += 2,
&q if q == quote => return Some(j + 1),
_ => j += 1,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Named {
Dialect,
Colon,
}
pub fn lex(sql: &str, dialect: Dialect) -> Result<Lexed, LexError> {
lex_with(sql, dialect, Named::Dialect)
}
pub fn lex_with(sql: &str, dialect: Dialect, named: Named) -> Result<Lexed, LexError> {
lex_text(sql, dialect, named, MysqlText::default())
}
pub fn lex_mysql(sql: &str, named: Named, text: MysqlText) -> Result<Lexed, LexError> {
lex_text(sql, Dialect::Mysql, named, text)
}
fn lex_text(sql: &str, dialect: Dialect, named: Named, text: MysqlText) -> Result<Lexed, LexError> {
let sqlite_named = dialect == Dialect::Sqlite && named == Named::Dialect;
let mysql = dialect == Dialect::Mysql;
let b = sql.as_bytes();
let mut i = 0usize;
let mut last = Last::Other;
let mut params: Vec<String> = Vec::new();
let mut placeholders: Vec<Placeholder> = Vec::new();
let mut opaque: Vec<(usize, usize)> = Vec::new();
let mut largest = 0u64;
let mut first_named: Option<(usize, usize)> = None;
let mut push = |name: String, start: usize, end: usize, params: &mut Vec<String>| {
if !params.contains(&name) {
params.push(name.clone());
}
placeholders.push(Placeholder { name, start, end });
};
let position = |digits: &str, largest: &mut u64| {
let n = digits.trim_start_matches('0');
let n = if n.is_empty() { "0" } else { n };
*largest = (*largest).max(n.parse().unwrap_or(u64::MAX));
n.to_string()
};
while i < b.len() {
let c = b[i];
match c {
b'\'' | b'"' if c == b'\'' || (mysql && !text.ansi_quotes) => {
let Some(end) = quoted_end(b, i, mysql && text.backslash_escapes) else {
return Err(LexError { message: "unterminated string literal".into(), offset: i });
};
opaque.push((i, end));
i = end;
last = Last::Other;
}
b'E' | b'e' if b.get(i + 1) == Some(&b'\'') && !prev_is_name_char(b, i) && !mysql => {
let start = i;
i += 2;
loop {
match b.get(i) {
None => return Err(LexError { message: "unterminated escape string".into(), offset: start }),
Some(b'\\') => i += 2,
Some(b'\'') if b.get(i + 1) == Some(&b'\'') => i += 2,
Some(b'\'') => {
i += 1;
break;
}
Some(_) => i += 1,
}
}
opaque.push((start, i));
last = Last::Other;
}
b'"' | b'`' => {
let Some(end) = quoted_end(b, i, false) else {
return Err(LexError { message: "unterminated quoted identifier".into(), offset: i });
};
opaque.push((i, end));
i = end;
last = Last::Operand;
}
b'-' if b.get(i + 1) == Some(&b'-') && !(mysql && b.get(i + 2).is_some_and(|&n| n > b' ' && n != 0x7f)) => {
let start = i;
while i < b.len() && b[i] != b'\n' {
i += 1;
}
opaque.push((start, i));
}
b'#' if mysql => {
let start = i;
while i < b.len() && b[i] != b'\n' {
i += 1;
}
opaque.push((start, i));
}
b'/' if b.get(i + 1) == Some(&b'*') && mysql => {
let Some(close) = find_bytes(b, b"*/", i + 2) else {
return Err(LexError { message: "unterminated block comment".into(), offset: i });
};
opaque.push((i, close + 2));
i = close + 2;
}
b'/' if b.get(i + 1) == Some(&b'*') => {
let start = i;
let mut depth = 1usize;
i += 2;
while depth > 0 {
match (b.get(i), b.get(i + 1)) {
(Some(b'/'), Some(b'*')) => {
depth += 1;
i += 2;
}
(Some(b'*'), Some(b'/')) => {
depth -= 1;
i += 2;
}
(Some(_), _) => i += 1,
(None, _) => return Err(LexError { message: "unterminated block comment".into(), offset: start }),
}
}
opaque.push((start, i));
}
b':' => {
if b.get(i + 1) == Some(&b':') {
i += 2;
if i < b.len() && is_name_start(b[i]) {
i = name_end(b, i);
}
last = Last::Operand;
continue;
}
match b.get(i + 1) {
_ if last == Last::Subscript && dialect == Dialect::Postgres => {
i += 1;
last = Last::Other;
}
Some(&n) if is_name_start(n) && !prev_is_name_char(b, i) => {
let end = dotted_name_end(b, i + 1);
one_prefix(sql, &mut first_named, i, end)?;
push(sql[i + 1..end].to_string(), i, end, &mut params);
i = end;
last = Last::Operand;
}
_ => {
i += 1;
last = Last::Other;
}
}
}
b'$' => {
if dialect == Dialect::Postgres {
if let Some(tag_end) = dollar_tag_end(b, i) {
let tag = &b[i..tag_end];
match find_bytes(b, tag, tag_end) {
Some(close) => {
opaque.push((i, close + tag.len()));
i = close + tag.len();
last = Last::Other;
continue;
}
None => {
return Err(LexError {
message: format!("unterminated dollar-quoted string {}", sql[i..tag_end].to_string()),
offset: i,
})
}
}
}
}
match b.get(i + 1) {
_ if prev_is_name_char(b, i) => {
i += 1;
last = Last::Operand;
}
Some(&n) if n.is_ascii_digit() && dialect == Dialect::Postgres => {
let end = digits_end(b, i + 1);
push(position(&sql[i + 1..end], &mut largest), i, end, &mut params);
i = end;
last = Last::Operand;
}
Some(&n) if is_name_start(n) && sqlite_named => {
let end = dotted_name_end(b, i + 1);
one_prefix(sql, &mut first_named, i, end)?;
push(sql[i + 1..end].to_string(), i, end, &mut params);
i = end;
last = Last::Operand;
}
Some(&n) if (is_name_start(n) || n.is_ascii_digit()) && dialect != Dialect::Mysql => {
return Err(foreign(sql, i, dialect));
}
_ => {
i += 1;
last = Last::Other;
}
}
}
b'@' => match b.get(i + 1) {
Some(&n) if is_name_start(n) && !prev_is_name_char(b, i) && sqlite_named => {
let end = dotted_name_end(b, i + 1);
one_prefix(sql, &mut first_named, i, end)?;
push(sql[i + 1..end].to_string(), i, end, &mut params);
i = end;
last = Last::Operand;
}
Some(&n) if is_name_start(n) && !prev_is_name_char(b, i) && dialect == Dialect::Sqlite => {
return Err(foreign(sql, i, dialect));
}
_ => {
i += 1;
last = Last::Other;
}
},
b'?' if dialect != Dialect::Postgres => {
if b.get(i + 1).is_some_and(u8::is_ascii_digit) && dialect == Dialect::Mysql {
let end = digits_end(b, i + 1);
return Err(LexError { message: format!("MySQL has no numbered placeholder {}; write ? for each value, or :name", &sql[i..end]), offset: i });
}
if b.get(i + 1).is_some_and(u8::is_ascii_digit) {
let end = digits_end(b, i + 1);
push(position(&sql[i + 1..end], &mut largest), i, end, &mut params);
i = end;
} else {
largest = largest.saturating_add(1);
push(largest.to_string(), i, i + 1, &mut params);
i += 1;
}
last = Last::Operand;
}
_ if c.is_ascii_whitespace() => i += 1,
_ if is_name_char(c) => {
let end = name_end(b, i);
last = if sql[i..end].eq_ignore_ascii_case("array") { Last::Other } else { Last::Operand };
i = end;
}
b')' | b']' => {
i += 1;
last = Last::Operand;
}
b'[' if dialect == Dialect::Sqlite => {
let Some(close) = b[i..].iter().position(|&c| c == b']') else {
return Err(LexError { message: "unterminated quoted identifier".into(), offset: i });
};
opaque.push((i, i + close + 1));
i += close + 1;
last = Last::Operand;
}
b'[' => {
i += 1;
last = if last == Last::Operand { Last::Subscript } else { Last::Other };
}
_ => {
i += 1;
last = Last::Other;
}
}
}
let positional = params.iter().filter(|p| is_positional(p)).count();
let style = match (positional, params.len()) {
(_, 0) => Style::None,
(0, _) => Style::Named,
(p, n) if p == n => Style::Positional,
_ => Style::Mixed,
};
if style == Style::Positional {
params.sort_by_key(|p| p.parse::<u64>().unwrap_or(u64::MAX));
}
Ok(Lexed { params, placeholders, style, opaque })
}
fn one_prefix(sql: &str, first: &mut Option<(usize, usize)>, start: usize, end: usize) -> Result<(), LexError> {
match *first {
None => {
*first = Some((start, end));
Ok(())
}
Some((s, _)) if sql.as_bytes()[s] == sql.as_bytes()[start] => Ok(()),
Some((s, e)) => Err(LexError {
message: format!(
"{} and {} have different prefixes; write every named parameter of a statement with one prefix, here {}{}",
&sql[start..end],
&sql[s..e],
&sql[s..s + 1],
&sql[start + 1..end]
),
offset: start,
}),
}
}
fn foreign(sql: &str, i: usize, dialect: Dialect) -> LexError {
let b = sql.as_bytes();
let digits = b.get(i + 1).is_some_and(u8::is_ascii_digit);
let end = if digits { digits_end(b, i + 1) } else { dotted_name_end(b, i + 1) };
let written = &sql[i..end];
let fix = if digits { format!("?{}", &sql[i + 1..end]) } else { format!(":{}", &sql[i + 1..end]) };
let message = match dialect {
Dialect::Sqlite => format!("SQLite reads {written} as a parameter that Reylo does not bind; write {fix}"),
_ => format!("{written} is not a placeholder here; Reylo's named placeholder is {fix}"),
};
LexError { message, offset: i }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repeated {
pub message: String,
pub start: usize,
pub end: usize,
}
impl From<Repeated> for LexError {
fn from(r: Repeated) -> LexError {
LexError { message: r.message, offset: r.start }
}
}
pub fn repeated(sql: &str, lexed: &Lexed) -> Vec<Repeated> {
let mut seen: Vec<&str> = Vec::new();
let mut out = Vec::new();
for p in &lexed.placeholders {
if !seen.contains(&p.name.as_str()) {
seen.push(&p.name);
continue;
}
let written = &sql[p.start..p.end];
let column = if is_positional(&p.name) { format!("p{}", p.name) } else { p.name.rsplit('.').next().unwrap_or(&p.name).to_string() };
out.push(Repeated {
message: format!(
"The parameter {written} appears more than once; use each parameter once, and select it in a with to read it twice, cast to its type, as in: with input as (select {written}::<type> as {column}) select … from input"
),
start: p.start,
end: p.end,
});
}
out
}
pub fn is_positional(name: &str) -> bool {
!name.is_empty() && name.bytes().all(|c| c.is_ascii_digit())
}
pub fn rewrite(sql: &str, lexed: &Lexed, target: Target) -> Rewritten {
rewrite_with(sql, lexed, target, &|_, rendered| rendered.to_string())
}
pub fn rewrite_with(sql: &str, lexed: &Lexed, target: Target, decorate: &dyn Fn(&str, &str) -> String) -> Rewritten {
let mut out = String::with_capacity(sql.len());
let mut spans = Vec::with_capacity(lexed.placeholders.len());
let mut order: Vec<String> = Vec::new();
let mut last = 0;
for p in &lexed.placeholders {
let rendered = match target {
Target::Dollar => {
if is_positional(&p.name) {
format!("${}", p.name)
} else {
format!("${}", lexed.params.iter().position(|q| q == &p.name).map_or(0, |i| i + 1))
}
}
Target::Question => "?".to_string(),
Target::Numbered => format!("?{}", lexed.params.iter().position(|q| q == &p.name).map_or(0, |i| i + 1)),
};
let rendered = decorate(&p.name, &rendered);
out.push_str(&sql[last..p.start]);
let rs = out.len();
out.push_str(&rendered);
spans.push((p.start, p.end, rs, out.len()));
last = p.end;
if target == Target::Question {
order.push(p.name.clone());
}
}
out.push_str(&sql[last..]);
if target != Target::Question {
order = lexed.params.clone();
}
Rewritten { sql: out, order, spans, inserted: Vec::new() }
}
const NOT_QUERIES: &[&str] = &[
"alter", "analyze", "attach", "begin", "binlog", "cache", "call", "change", "check", "checksum", "clone", "commit", "create", "deallocate",
"describe", "desc", "detach", "do", "drop", "end", "execute", "explain", "flush", "get", "grant", "handler", "help", "import", "install",
"kill", "load", "lock", "optimize", "pragma", "prepare", "purge", "reindex", "release", "rename", "repair", "reset", "resignal", "restart",
"revoke", "rollback", "savepoint", "set", "show", "shutdown", "signal", "start", "stop", "truncate", "uninstall", "unlock", "use",
"vacuum", "xa",
];
const LEAVE_OUT: &str = "so if it is a migration or a schema file, leave it out of the type check with \"exclude\" in tsconfig.json, as in \"exclude\": [\"db/**\"]";
pub fn several_statements() -> String {
format!("A typed .sql file holds one statement and this one holds several, {LEAVE_OUT}.")
}
pub fn refused_command(message: &str) -> String {
format!("{}, {LEAVE_OUT}.", message.trim_end().trim_end_matches('.'))
}
#[derive(Debug, PartialEq, Eq)]
pub enum Statement {
Query,
Command(String),
}
pub fn first_word(sql: &str, lexed: &Lexed) -> String {
let start = past_comments(sql, lexed, 0);
sql[start..].chars().take_while(|c| c.is_ascii_alphabetic()).collect::<String>().to_ascii_lowercase()
}
fn past_comments(sql: &str, lexed: &Lexed, mut i: usize) -> usize {
let bytes = sql.as_bytes();
let is_comment = |start: usize| sql[start..].starts_with("--") || sql[start..].starts_with("/*") || sql[start..].starts_with('#');
loop {
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
match lexed.opaque.iter().find(|&&(start, _)| start == i && is_comment(start)) {
Some(&(_, end)) => i = end,
None => return i,
}
}
}
pub fn one_statement(sql: &str, lexed: &Lexed, kinds: &[&str]) -> Result<Statement, String> {
let bytes = sql.as_bytes();
let in_text = |i: usize| lexed.opaque.iter().any(|&(start, end)| start <= i && i < end);
if let Some(semicolon) = (0..bytes.len()).find(|&i| bytes[i] == b';' && !in_text(i)) {
let mut i = semicolon + 1;
loop {
i = past_comments(sql, lexed, i);
if i < bytes.len() && bytes[i] == b';' {
i += 1;
} else {
break;
}
}
if i < bytes.len() {
return Err(several_statements());
}
}
let word = first_word(sql, lexed);
if kinds.contains(&word.as_str()) || sql[past_comments(sql, lexed, 0)..].starts_with('(') || !NOT_QUERIES.contains(&word.as_str()) {
return Ok(Statement::Query);
}
Ok(Statement::Command(word))
}
#[cfg(test)]
mod tests {
use super::*;
fn names(sql: &str, d: Dialect) -> Vec<String> {
lex(sql, d).unwrap().params
}
#[test]
fn styles() {
assert_eq!(names("select :a, :b, :a", Dialect::Postgres), ["a", "b"]);
assert_eq!(names("select $1, $2, $1", Dialect::Postgres), ["1", "2"]);
assert_eq!(names("select ?, ?", Dialect::Sqlite), ["1", "2"]);
assert_eq!(names("select ?, ?", Dialect::Mysql), ["1", "2"]);
assert_eq!(lex("select :a, $1", Dialect::Postgres).unwrap().style, Style::Mixed);
assert_eq!(lex("select 1", Dialect::Postgres).unwrap().style, Style::None);
}
#[test]
fn skips_text_and_casts() {
let sql = "select ':x' as a, \":y\" as b, e'\\':z' as c, $$:w$$ as d, x::int, arr[1:2], tags ? 'k' -- :c\n /* :d /* :e */ */ from t where id = :id";
assert_eq!(names(sql, Dialect::Postgres), ["id"]);
assert_eq!(names("select json_extract(j, '$.a') = ? and x = :n", Dialect::Sqlite), ["1", "n"]);
assert_eq!(names("select [a'b] as x, :p as p, [c'd?] as y, [n:m] from t", Dialect::Sqlite), ["p"]);
assert_eq!(lex("select [a from t", Dialect::Sqlite).unwrap_err().offset, 7);
assert_eq!(names("select `a:b`, 'x' from t where a = :a", Dialect::Mysql), ["a"]);
}
#[test]
fn one_named_form_and_the_native_positional_one() {
let err = |sql: &str, d: Dialect| lex(sql, d).unwrap_err();
assert_eq!(err("select $name", Dialect::Postgres).message, "$name is not a placeholder here; Reylo's named placeholder is :name");
assert_eq!(err("select 1 where x = $2", Dialect::Sqlite).message, "SQLite reads $2 as a parameter that Reylo does not bind; write ?2");
assert_eq!(err("select ?2", Dialect::Mysql).message, "MySQL has no numbered placeholder ?2; write ? for each value, or :name");
assert_eq!(err("select $name", Dialect::Postgres).offset, 7);
assert!(names("select @x := 1, $col, $1 from t", Dialect::Mysql).is_empty());
assert!(names("select @ -5, a$1, b$c from t", Dialect::Postgres).is_empty());
assert!(names("-- @returns one\nselect 1", Dialect::Postgres).is_empty());
}
#[test]
fn sqlite_named_prefixes() {
for sql in ["select @a.b, @c, @a.b", "select $a.b, $c, $a.b"] {
let l = lex(sql, Dialect::Sqlite).unwrap();
assert_eq!(l.params, ["a.b", "c"]);
assert_eq!(l.style, Style::Named);
assert_eq!(rewrite(sql, &l, Target::Numbered).sql, "select ?1, ?2, ?1");
}
let e = lex("select :a, @b where x = $a", Dialect::Sqlite).unwrap_err();
assert_eq!(e.message, "@b and :a have different prefixes; write every named parameter of a statement with one prefix, here :b");
assert_eq!(e.offset, 11);
assert_eq!(lex("select @a, :a", Dialect::Sqlite).unwrap_err().offset, 11);
assert_eq!(lex("select @a, ?", Dialect::Sqlite).unwrap().style, Style::Mixed);
assert!(names("select a$b, a@b from t", Dialect::Sqlite).is_empty());
assert!(names("select @a from t", Dialect::Postgres).is_empty());
assert!(names("select @a, $b from t", Dialect::Mysql).is_empty());
let colon = |sql: &str| lex_with(sql, Dialect::Sqlite, Named::Colon).unwrap_err().message;
assert_eq!(colon("select @a.b from t"), "SQLite reads @a.b as a parameter that Reylo does not bind; write :a.b");
assert_eq!(colon("select :x, $y"), "SQLite reads $y as a parameter that Reylo does not bind; write :y");
}
#[test]
fn rewrites_and_maps_back() {
let sql = "select * from t where id = :id and name = :name and id = :id";
let l = lex(sql, Dialect::Postgres).unwrap();
let r = rewrite(sql, &l, Target::Dollar);
assert_eq!(r.sql, "select * from t where id = $1 and name = $2 and id = $1");
assert_eq!(r.order, ["id", "name"]);
let third = r.sql.rfind("$1").unwrap();
assert_eq!(r.to_original(third), sql.rfind(":id").unwrap());
assert_eq!(r.to_original(r.sql.len()), sql.len());
let q = rewrite(sql, &l, Target::Question);
assert_eq!(q.sql, "select * from t where id = ? and name = ? and id = ?");
assert_eq!(q.order, ["id", "name", "id"]);
}
#[test]
fn each_parameter_once() {
let at = |sql: &str, d: Dialect| repeated(sql, &lex(sql, d).unwrap()).into_iter().map(|r| (r.start, r.end)).collect::<Vec<_>>();
let sql = "select id, name from users where name like :q or email like :q";
let r = repeated(sql, &lex(sql, Dialect::Postgres).unwrap());
assert_eq!(r.len(), 1);
assert_eq!(&sql[r[0].start..r[0].end], ":q");
assert_eq!(r[0].start, sql.rfind(":q").unwrap());
assert_eq!(
r[0].message,
"The parameter :q appears more than once; use each parameter once, and select it in a with to read it twice, cast to its type, as in: with input as (select :q::<type> as q) select … from input"
);
assert_eq!(at("select :a, :b, :a, :a, :b", Dialect::Postgres), [(15, 17), (19, 21), (23, 25)]);
assert_eq!(at("select $1, $2, $1", Dialect::Postgres), [(15, 17)]);
assert_eq!(at("select ?3, ?3", Dialect::Sqlite), [(11, 13)]);
assert_eq!(at("select @a, @a", Dialect::Sqlite), [(11, 13)]);
assert_eq!(at("select $a, $a", Dialect::Sqlite), [(11, 13)]);
assert_eq!(at("select :a, :a", Dialect::Mysql), [(11, 13)]);
assert_eq!(at("select ?, ?1", Dialect::Sqlite), [(10, 12)]);
let sql = "select * from t where owner = :auth.user_id or author = :auth.user_id";
assert!(repeated(sql, &lex(sql, Dialect::Postgres).unwrap())[0].message.contains("with input as (select :auth.user_id::<type> as user_id)"));
let sql = "select $1::int + $1";
assert!(repeated(sql, &lex(sql, Dialect::Postgres).unwrap())[0].message.starts_with("The parameter $1 appears more than once;"));
assert!(repeated(sql, &lex(sql, Dialect::Postgres).unwrap())[0].message.contains("(select $1::<type> as p1)"));
assert!(at("select ?, ?, ?", Dialect::Mysql).is_empty());
assert!(at("select ?, ?", Dialect::Sqlite).is_empty());
assert!(at("select :a, :b, ':a', x::a -- :a", Dialect::Postgres).is_empty());
assert!(at("with input as (select :q::text as q) select 1 from t, input where a = input.q or b = input.q", Dialect::Postgres).is_empty());
}
#[test]
fn errors() {
assert!(lex("select 'abc", Dialect::Postgres).is_err());
assert!(lex("select $x$abc", Dialect::Postgres).is_err());
assert!(lex("select /* a", Dialect::Postgres).is_err());
assert_eq!(lex("select 'abc", Dialect::Postgres).unwrap_err().to_string(), "unterminated string literal (at byte 7)");
let at = |sql: &str, dialect| lex(sql, dialect).unwrap_err().offset;
assert_eq!(at("select 1, 'abc", Dialect::Sqlite), 10);
assert_eq!(at("select 1, \"abc", Dialect::Postgres), 10);
assert_eq!(at("select 1, `abc\n", Dialect::Sqlite), 10);
assert_eq!(at("select 1, `abc", Dialect::Mysql), 10);
assert_eq!(at("select 1, E'abc", Dialect::Postgres), 10);
assert_eq!(at("select 1, $x$abc", Dialect::Postgres), 10);
assert_eq!(at("select 1, /* a /* b */", Dialect::Postgres), 10);
assert_eq!(at("select 1, /* a", Dialect::Sqlite), 10);
assert_eq!(at("select 1, /* a", Dialect::Mysql), 10);
}
#[test]
fn dotted_names() {
let sql = "select :a.b";
let l = lex(sql, Dialect::Postgres).unwrap();
assert_eq!(l.params, ["a.b"]);
assert_eq!(l.placeholders, [Placeholder { name: "a.b".into(), start: 7, end: 11 }]);
assert_eq!(l.style, Style::Named);
assert_eq!(rewrite(sql, &l, Target::Dollar).sql, "select $1");
assert_eq!(rewrite(sql, &l, Target::Numbered).sql, "select ?1");
assert_eq!(rewrite(sql, &l, Target::Question).sql, "select ?");
assert_eq!(names("select :auth.user_id, :org.name::text, :t.*, :x.1", Dialect::Postgres), ["auth.user_id", "org.name", "t", "x"]);
let sql = "select :a.b, :c";
let l = lex(sql, Dialect::Sqlite).unwrap();
let r = rewrite(sql, &l, Target::Numbered);
assert_eq!(r.sql, "select ?1, ?2");
assert_eq!(r.to_original(r.sql.find("?2").unwrap()), sql.find(":c").unwrap());
assert_eq!(r.to_original(r.sql.len()), sql.len());
}
#[test]
fn numbered_question_is_a_position() {
let l = lex("select ?3, ?3", Dialect::Sqlite).unwrap();
assert_eq!(l.params, ["3"]);
assert_eq!(l.placeholders.iter().map(|p| (p.start, p.end)).collect::<Vec<_>>(), [(7, 9), (11, 13)]);
assert_eq!(l.style, Style::Positional);
assert_eq!(lex("select ?3, :x", Dialect::Sqlite).unwrap().style, Style::Mixed);
assert!(lex("select j ? 'k', 1 ?2", Dialect::Postgres).unwrap().params.is_empty());
}
#[test]
fn array_slices_are_not_placeholders() {
for d in [Dialect::Postgres, Dialect::Sqlite, Dialect::Mysql] {
assert!(lex("select arr[1:2], arr[2:], arr[:3], arr[1:2].x, arr[lo:hi], arr[1:n] from t", d).unwrap().params.is_empty());
}
let slices = "select arr[:hi], arr[ :hi], arr[/* c */:hi], arr[:t.n], \"a\"[:hi], (f(x))[:pg_t.tgnargs], m[1][:hi], arr[1:hi], arr[:hi][:lo] from t where x = :x and y = $1";
let l = lex(slices, Dialect::Postgres).unwrap();
assert_eq!(l.params, ["x", "1"]);
assert_eq!(l.style, Style::Mixed);
assert_eq!(names("select :a[:hi], arr[:hi] from t", Dialect::Postgres), ["a"]);
assert_eq!(names("select arr[(:i)], arr[ : :hi], arr[1 : :b], arr[:i + 0] from t", Dialect::Postgres), ["i", "hi", "b"]);
assert_eq!(names("select array[:a, :b], ARRAY[[:c], [:d]], x = any(array[:e]) from t", Dialect::Postgres), ["a", "b", "c", "d", "e"]);
let l = lex("select tags[:n], tags[ :m], (f(x))[:pg_t.tgnargs], \"q\"[:k], array[:a, :b], tags[(:c)], tags[1::int:d] from t where y = :y", Dialect::Postgres).unwrap();
assert_eq!(l.params, ["a", "b", "c", "y"]);
assert_eq!(l.placeholders.iter().map(|p| (p.start, p.end)).collect::<Vec<_>>(), [(66, 68), (70, 72), (81, 83), (119, 121)]);
assert_eq!(names("select arr[:lo] from t", Dialect::Mysql), ["lo"]);
assert!(names("select arr[:lo] from t", Dialect::Sqlite).is_empty());
}
#[test]
fn colons_that_open_nothing() {
assert!(names("select '{}'::jsonb, :{a}", Dialect::Postgres).is_empty());
assert!(names("select @x := 1", Dialect::Mysql).is_empty());
assert_eq!(names("select 'it''s :not', :yes", Dialect::Postgres), ["yes"]);
assert_eq!(names("select E'\\':nope', $tag$ :nope $tag$, :real", Dialect::Postgres), ["real"]);
}
#[test]
fn opaque_spans() {
let sql = "select 'a''b', \"q\"\"r\", $t$ :x $t$, e'\\'' -- c :y\n/* d /* :z */ */ :w";
let l = lex(sql, Dialect::Postgres).unwrap();
assert_eq!(l.params, ["w"]);
assert_eq!(l.opaque, [(7, 13), (15, 21), (23, 33), (35, 40), (41, 48), (49, 65)]);
let text: Vec<&str> = l.opaque.iter().map(|&(s, e)| &sql[s..e]).collect();
assert_eq!(text, ["'a''b'", "\"q\"\"r\"", "$t$ :x $t$", "e'\\''", "-- c :y", "/* d /* :z */ */"]);
let l = lex("-- @returns one\nselect `a`, 1", Dialect::Mysql).unwrap();
assert_eq!(l.opaque, [(0, 15), (23, 26)]);
}
#[test]
fn numbered_target() {
let sql = "select :a, :b, :a";
let l = lex(sql, Dialect::Sqlite).unwrap();
let r = rewrite(sql, &l, Target::Numbered);
assert_eq!(r.sql, "select ?1, ?2, ?1");
assert_eq!(r.order, ["a", "b"]);
assert_eq!(r.spans, [(7, 9, 7, 9), (11, 13, 11, 13), (15, 17, 15, 17)]);
let sql = "select ?2, ?1, ?2";
let l = lex(sql, Dialect::Sqlite).unwrap();
let r = rewrite(sql, &l, Target::Numbered);
assert_eq!(r.sql, "select ?2, ?1, ?2");
assert_eq!(r.order, ["1", "2"]);
}
#[test]
fn positional_names_are_numbers() {
assert_eq!(names("select ?1, ?2, ?", Dialect::Sqlite), ["1", "2", "3"]);
assert_eq!(names("select ?5, ?, ?2", Dialect::Sqlite), ["2", "5", "6"]);
assert_eq!(names("select $01, $1", Dialect::Postgres), ["1"]);
assert!(is_positional("12") && !is_positional("a1") && !is_positional(""));
let sql = "select $2::int, $1::text";
let l = lex(sql, Dialect::Postgres).unwrap();
assert_eq!(l.params, ["1", "2"]);
let r = rewrite(sql, &l, Target::Dollar);
assert_eq!(r.sql, sql);
assert_eq!(r.order, ["1", "2"]);
let sql = "select ?, ?";
let l = lex(sql, Dialect::Mysql).unwrap();
assert_eq!(rewrite(sql, &l, Target::Question).order, ["1", "2"]);
}
#[test]
fn mysql_text() {
let sql = r#"select 'it\'s :not', 'a\\' as b, :x, "say \":no", 'a\nb' from t where id = :id"#;
assert_eq!(names(sql, Dialect::Mysql), ["x", "id"]);
assert_eq!(names(r"select 'C:\', :x", Dialect::Postgres), ["x"]);
assert_eq!(names(r"select 'C:\', :x", Dialect::Sqlite), ["x"]);
assert_eq!(lex(r"select 'C:\', :x", Dialect::Mysql).unwrap_err().message, "unterminated string literal");
let plain = MysqlText { backslash_escapes: false, ansi_quotes: false };
assert_eq!(lex_mysql(r"select 'C:\', :x", Named::Dialect, plain).unwrap().params, ["x"]);
assert_eq!(lex_mysql(r"select 'a\' as b, :x, 'it''s :not'", Named::Dialect, plain).unwrap().params, ["x"]);
let ansi = MysqlText { backslash_escapes: true, ansi_quotes: true };
assert_eq!(lex_mysql(r#"select "a\" from t where id = :id"#, Named::Dialect, ansi).unwrap().params, ["id"]);
assert!(lex(r#"select "a\" from t where id = :id"#, Dialect::Mysql).is_err());
assert_eq!(names("select :a # :b\n, :c", Dialect::Mysql), ["a", "c"]);
assert_eq!(names("select :a --:b", Dialect::Mysql), ["a", "b"]);
assert_eq!(names("select :a -- :b\n, :c --\t:d\n, 1--", Dialect::Mysql), ["a", "c"]);
assert_eq!(names("select :a --:b", Dialect::Postgres), ["a"]);
assert_eq!(names("select 1 # :b", Dialect::Postgres), ["b"]);
assert_eq!(names("select /* a /* b */ :x", Dialect::Mysql), ["x"]);
assert_eq!(names(r"select `a\`, :x", Dialect::Mysql), ["x"]);
assert_eq!(lex_mysql(r"select e'\', :x", Named::Dialect, plain).unwrap().params, ["x"]);
let sql = "select 'a\\'b'':c', \"c\\\"\", `d`, :e # f\n/* g /* */";
let l = lex(sql, Dialect::Mysql).unwrap();
let text: Vec<&str> = l.opaque.iter().map(|&(s, e)| &sql[s..e]).collect();
assert_eq!(text, ["'a\\'b'':c'", "\"c\\\"\"", "`d`", "# f", "/* g /* */"]);
assert_eq!(l.params, ["e"]);
assert_eq!(one_statement("select 1; # done", &lex("select 1; # done", Dialect::Mysql).unwrap(), &["select"]), Ok(Statement::Query));
assert_eq!(MysqlText::of_mode("STRICT_TRANS_TABLES,NO_BACKSLASH_ESCAPES"), plain);
assert_eq!(MysqlText::of_mode("REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ONLY_FULL_GROUP_BY,ANSI"), ansi);
assert_eq!(MysqlText::of_mode(""), MysqlText::default());
}
#[test]
fn one_statement_of_any_kind() {
const SQLITE: &[&str] = &["select", "with", "values", "insert", "replace", "update", "delete"];
let check = |sql: &str| one_statement(sql, &lex(sql, Dialect::Sqlite).unwrap(), SQLITE);
assert_eq!(check("select 1"), Ok(Statement::Query));
assert_eq!(check("-- the user\n/* by id */ SELECT id from users where id = :id;"), Ok(Statement::Query));
assert_eq!(check("select 1;\n-- a trailing comment\n;\n"), Ok(Statement::Query));
assert_eq!(check("select ';' as a"), Ok(Statement::Query));
assert_eq!(check("with x as (select 1) delete from t where id in (select * from x)"), Ok(Statement::Query));
assert_eq!(check("create table t (id integer primary key)"), Ok(Statement::Command("create".into())));
assert_eq!(check("/* the schema */ PRAGMA table_info(t);"), Ok(Statement::Command("pragma".into())));
let several = "A typed .sql file holds one statement and this one holds several, so if it is a migration or a schema file, leave it out of the type check with \"exclude\" in tsconfig.json, as in \"exclude\": [\"db/**\"].";
assert_eq!(check("select 1; select 2").unwrap_err(), several);
assert_eq!(check("create table t (id integer primary key);\ncreate index i on t (id);").unwrap_err(), several);
assert_eq!(check("selec id from users"), Ok(Statement::Query));
assert_eq!(refused_command("table t already exists"), "table t already exists, so if it is a migration or a schema file, leave it out of the type check with \"exclude\" in tsconfig.json, as in \"exclude\": [\"db/**\"].");
}
}