Skip to main content

bynk_check/
mysql_sql.rs

1//! Hyperdrive H5 (#3322): a literal `MySql` statement's SQL checked against a
2//! MySQL parser, when the project supplies a `schema.sql`. It is H4's check
3//! (see [`crate::pg_sql`]) with `sqlparser`'s `MySqlDialect`:
4//!
5//! - `bynk.mysql.sql_invalid` (a **warning**): the statement does not parse, or
6//!   holds more than one command (the driver is not configured for several, so
7//!   it would refuse it);
8//! - `bynk.mysql.sql_param_count` (an error): the number of `?` placeholders
9//!   differs from the number of parameters the call passes.
10//!
11//! `sqlparser` is not MySQL's own parser, so the syntax finding is a warning,
12//! for the reason H4 gives: an advisory check must never block a program that
13//! runs. The placeholder count follows the driver, not the SQL standard, since
14//! what matters is how many values mysql2's `query` will consume: a `?` is a
15//! parameter unless it is inside a single-quoted string (where a backslash
16//! escapes and a doubled quote is a quote), a backtick name, or a comment
17//! (`-- ` and `/* … */`). mysql2 (through `sql-escaper`) does **not** treat a
18//! double-quoted string or a `#` comment as quoting, so a `?` in either is
19//! counted, as it is substituted; write string literals with single quotes.
20
21use crate::pg_sql::PgSqlProblem;
22
23/// The problems with the literal statement `sql`, given the number of
24/// parameters the call passes when the list is written out (`None` leaves the
25/// count unchecked).
26pub 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
60/// The number of `?` placeholders a statement uses, by MySQL's lexical rules.
61pub 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            // `--` is a comment only when whitespace (or the end) follows.
68            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
94/// The index after the quoted run opening at `i`. A doubled quote is a quote in
95/// it; in a string (`'`) a backslash escapes the next byte.
96fn 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(&quote) => 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        // mysql2 substitutes inside a double-quoted string and after `#`.
122        ("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    /// Valid MySQL, in the forms its users write: none may be reported.
143    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}