1use crate::pg_sql::PgSqlProblem;
22
23pub fn check_statement(sql: &str, passed: Option<usize>) -> Vec<PgSqlProblem> {
27 let mut out = Vec::new();
28 if let Some(message) = syntax_problem(sql) {
29 out.push(PgSqlProblem::Invalid(message));
30 }
31 if let Some(passed) = passed {
32 let expected = placeholder_count(sql);
33 if expected != passed {
34 out.push(PgSqlProblem::ParamCount { expected, passed });
35 }
36 }
37 out
38}
39
40fn syntax_problem(sql: &str) -> Option<String> {
41 use sqlparser::dialect::MySqlDialect;
42 use sqlparser::parser::Parser;
43 match Parser::parse_sql(&MySqlDialect {}, sql) {
44 Err(e) => Some(
45 e.to_string()
46 .strip_prefix("sql parser error: ")
47 .map(str::to_string)
48 .unwrap_or_else(|| e.to_string())
49 .trim()
50 .to_string(),
51 ),
52 Ok(statements) if statements.len() > 1 => Some(
53 "a statement is one command: the driver refuses several, so send each with its own call (or use `transaction`)"
54 .to_string(),
55 ),
56 Ok(_) => None,
57 }
58}
59
60pub fn placeholder_count(sql: &str) -> usize {
62 let b = sql.as_bytes();
63 let (mut count, mut i) = (0usize, 0usize);
64 while i < b.len() {
65 match b[i] {
66 q @ (b'\'' | b'`') => i = skip_quoted(b, i, q),
67 b'-' if b.get(i + 1) == Some(&b'-')
69 && b.get(i + 2)
70 .is_none_or(|c| c.is_ascii_whitespace() || c.is_ascii_control()) =>
71 {
72 i = line_end(b, i)
73 }
74 b'/' if b.get(i + 1) == Some(&b'*') => {
75 i = sql[i + 2..].find("*/").map_or(b.len(), |n| i + 2 + n + 2);
76 }
77 b'?' => {
78 count += 1;
79 i += 1;
80 }
81 _ => i += 1,
82 }
83 }
84 count
85}
86
87fn line_end(b: &[u8], i: usize) -> usize {
88 b[i..]
89 .iter()
90 .position(|&c| c == b'\n')
91 .map_or(b.len(), |n| i + n)
92}
93
94fn skip_quoted(b: &[u8], i: usize, quote: u8) -> usize {
97 let mut j = i + 1;
98 while j < b.len() {
99 match b[j] {
100 b'\\' if quote != b'`' => j += 2,
101 c if c == quote && b.get(j + 1) == Some("e) => j += 2,
102 c if c == quote => return j + 1,
103 _ => j += 1,
104 }
105 }
106 b.len()
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 const COUNTS: &[(&str, usize)] = &[
114 ("select 1", 0),
115 ("select ?", 1),
116 ("select ?, ?, ?", 3),
117 ("select * from t where a = ? and b = ?", 2),
118 ("select '?' from t where a = ?", 1),
119 ("select 'it''s ?', ?", 1),
120 ("select 'it\\'s ?', ?", 1),
121 ("select \"?\" from t where a = ?", 2),
123 ("select 1 # ?\n, ?", 2),
124 ("select `a?b` from t where a = ?", 1),
125 ("select 1 -- ?\n, ?", 1),
126 ("select /* ? */ ?", 1),
127 ("select 5--?", 1),
128 ("select * from t limit ?, ?", 2),
129 (
130 "insert into t (a, b) values (?, ?) on duplicate key update b = values(b)",
131 2,
132 ),
133 ];
134
135 #[test]
136 fn the_scanner_counts_by_mysql_rules() {
137 for (sql, n) in COUNTS {
138 assert_eq!(placeholder_count(sql), *n, "{sql}");
139 }
140 }
141
142 pub(crate) const VALID_MYSQL: &[&str] = &[
144 "insert into orders (name, qty) values (?, ?) on duplicate key update qty = qty + values(qty)",
145 "insert ignore into orders (name) values (?)",
146 "select `id`, `name` from `orders` where `name` like ? limit ?, ?",
147 "update orders set qty = qty - 1 where id = ? limit 1",
148 "delete from orders where id in (select id from old_orders where placed < ?)",
149 "select id, json_extract(doc, '$.name') from events where json_contains(doc, ?)",
150 "with recent as (select * from orders where placed > ?) select count(*) from recent",
151 "select * from orders o join items i on i.order_id = o.id where o.id = ? for update",
152 "create table if not exists t (id bigint unsigned auto_increment primary key, flag tinyint(1) not null default 0, at datetime(3) default current_timestamp(3))",
153 ];
154
155 #[test]
156 fn valid_mysql_has_no_problem() {
157 for sql in VALID_MYSQL {
158 assert_eq!(check_statement(sql, None), vec![], "{sql}");
159 }
160 }
161
162 #[test]
163 fn a_syntax_error_is_invalid_and_a_wrong_count_is_reported() {
164 let got = check_statement("selec 1", Some(0));
165 assert!(
166 matches!(got.as_slice(), [PgSqlProblem::Invalid(_)]),
167 "{got:?}"
168 );
169 assert_eq!(
170 check_statement("select ?, ?", Some(1)),
171 vec![PgSqlProblem::ParamCount {
172 expected: 2,
173 passed: 1
174 }]
175 );
176 assert_eq!(check_statement("select ?, ?", Some(2)), vec![]);
177 assert_eq!(check_statement("select ?, ?", None), vec![]);
178 let several = check_statement("select 1; select 2", Some(0));
179 assert!(
180 matches!(several.as_slice(), [PgSqlProblem::Invalid(m)] if m.contains("one command")),
181 "{several:?}"
182 );
183 }
184}