Skip to main content

bynk_check/
pg_sql.rs

1//! Hyperdrive H4 (#3321, ADR 0799 G): a literal `Postgres` statement's SQL
2//! checked against Postgres' own parser, when the project supplies a
3//! `schema.sql`.
4//!
5//! Bynk does not own the Postgres schema, so there is nothing to prepare a
6//! statement against, as `bynk.d1.sql_invalid` does for D1 (ADR 0763). What can
7//! be checked without one is the text:
8//!
9//! - `bynk.postgres.sql_invalid` (a **warning**): the statement does not parse
10//!   with `sqlparser`'s Postgres dialect, or holds more than one command (a
11//!   prepared statement takes one, so the driver would refuse it);
12//! - `bynk.postgres.sql_param_count` (an error): the statement's highest `$n`
13//!   differs from the number of parameters the call passes.
14//!
15//! `sqlparser` is a pure-Rust parser and is not Postgres' own, so it can refuse
16//! valid Postgres (a newer or rarer form). That is why the syntax finding is a
17//! warning: an advisory check must never block a program that runs. The
18//! parameter count is exact (it is a scanner of this file's own, below, pinned
19//! by tests to Postgres' rules), so a mismatch is an error. `libpg_query`
20//! (`pg_query`) would be exact on syntax too, but needs libclang to build.
21//!
22//! The check is off unless `schema.sql` is at the project root: its presence is
23//! the project saying it keeps a Postgres schema Bynk may take an interest in.
24//! The parser has no C, so it builds on every target, `wasm32` included.
25
26/// What is wrong with a statement's text.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum PgSqlProblem {
29    /// The statement does not parse, or is not one command. Carries the
30    /// parser's own words.
31    Invalid(String),
32    /// The statement uses `expected` parameters and the call passes `passed`.
33    ParamCount { expected: usize, passed: usize },
34}
35
36/// The problems with the literal statement `sql`, given the number of
37/// parameters the call passes when the list is written out (`None` when it is
38/// not, which leaves the count unchecked).
39pub fn check_statement(sql: &str, passed: Option<usize>) -> Vec<PgSqlProblem> {
40    let mut out = Vec::new();
41    if let Some(message) = syntax_problem(sql) {
42        out.push(PgSqlProblem::Invalid(message));
43    }
44    if let Some(passed) = passed {
45        let expected = placeholder_count(sql);
46        if expected != passed {
47            out.push(PgSqlProblem::ParamCount { expected, passed });
48        }
49    }
50    out
51}
52
53fn syntax_problem(sql: &str) -> Option<String> {
54    use sqlparser::dialect::PostgreSqlDialect;
55    use sqlparser::parser::Parser;
56    match Parser::parse_sql(&PostgreSqlDialect {}, sql) {
57        Err(e) => Some(parse_message(&e.to_string())),
58        Ok(statements) if statements.len() > 1 => Some(
59            "a statement is one command: a prepared statement refuses several, so send each with its own call (or use `transaction`)"
60                .to_string(),
61        ),
62        Ok(_) => None,
63    }
64}
65
66/// The parser's message, without the prefix it puts in front of it.
67fn parse_message(text: &str) -> String {
68    text.strip_prefix("sql parser error: ")
69        .unwrap_or(text)
70        .trim()
71        .to_string()
72}
73
74/// The number of parameters a statement uses: its highest `$n`, which is how
75/// many Postgres asks the call for. A `$n` inside a string literal (`'$9'`,
76/// `E'…'`), a quoted identifier, a comment or a dollar-quoted body is text, not a
77/// parameter.
78pub fn placeholder_count(sql: &str) -> usize {
79    let b = sql.as_bytes();
80    let mut highest = 0usize;
81    let mut i = 0;
82    while i < b.len() {
83        match b[i] {
84            b'\'' => i = skip_string(b, i, is_escape_string(b, i)),
85            b'"' => i = skip_quoted(b, i, b'"'),
86            b'-' if b.get(i + 1) == Some(&b'-') => {
87                i = b[i..]
88                    .iter()
89                    .position(|&c| c == b'\n')
90                    .map_or(b.len(), |n| i + n);
91            }
92            b'/' if b.get(i + 1) == Some(&b'*') => i = skip_block_comment(b, i),
93            // A `$` after an identifier byte is part of the name (`price$1`), not a parameter.
94            b'$' if i > 0 && is_ident_byte(b[i - 1]) => i += 1,
95            b'$' => {
96                let digits = b[i + 1..].iter().take_while(|c| c.is_ascii_digit()).count();
97                if digits > 0 {
98                    // Saturating: a number past `usize` is far past any list.
99                    let n = sql[i + 1..i + 1 + digits]
100                        .parse::<usize>()
101                        .unwrap_or(usize::MAX);
102                    highest = highest.max(n);
103                    i += 1 + digits;
104                } else if let Some(end) = dollar_quote_end(b, i) {
105                    i = end;
106                } else {
107                    i += 1;
108                }
109            }
110            _ => i += 1,
111        }
112    }
113    highest
114}
115
116/// Whether `c` can be part of an identifier after its first character: Postgres
117/// allows letters, digits, `_`, `$` and any non-ASCII byte.
118fn is_ident_byte(c: u8) -> bool {
119    c.is_ascii_alphanumeric() || c == b'_' || c == b'$' || c >= 0x80
120}
121
122/// Whether the `'` at `i` opens an escape string (`E'…'`), where a backslash
123/// escapes the next character. The `E` must not be the tail of a longer name.
124fn is_escape_string(b: &[u8], i: usize) -> bool {
125    i > 0
126        && matches!(b[i - 1], b'e' | b'E')
127        && (i == 1 || !(b[i - 2].is_ascii_alphanumeric() || b[i - 2] == b'_' || b[i - 2] == b'$'))
128}
129
130/// The index after the string literal opening at `i`. A doubled `''` is a quote
131/// in it; in an escape string so is a backslash-quote.
132fn skip_string(b: &[u8], i: usize, escapes: bool) -> usize {
133    let mut j = i + 1;
134    while j < b.len() {
135        match b[j] {
136            b'\\' if escapes => j += 2,
137            b'\'' if b.get(j + 1) == Some(&b'\'') => j += 2,
138            b'\'' => return j + 1,
139            _ => j += 1,
140        }
141    }
142    b.len()
143}
144
145/// The index after the quoted identifier opening at `i` (`""` is a quote in it).
146fn skip_quoted(b: &[u8], i: usize, quote: u8) -> usize {
147    let mut j = i + 1;
148    while j < b.len() {
149        if b[j] == quote {
150            if b.get(j + 1) == Some(&quote) {
151                j += 2;
152                continue;
153            }
154            return j + 1;
155        }
156        j += 1;
157    }
158    b.len()
159}
160
161/// The index after the block comment opening at `i`. They nest in Postgres.
162fn skip_block_comment(b: &[u8], i: usize) -> usize {
163    let (mut depth, mut j) = (1usize, i + 2);
164    while j < b.len() && depth > 0 {
165        if b[j] == b'/' && b.get(j + 1) == Some(&b'*') {
166            depth += 1;
167            j += 2;
168        } else if b[j] == b'*' && b.get(j + 1) == Some(&b'/') {
169            depth -= 1;
170            j += 2;
171        } else {
172            j += 1;
173        }
174    }
175    j
176}
177
178/// The index after the dollar-quoted body opening at `i` (`$$…$$`, `$tag$…$tag$`),
179/// or `None` when the `$` opens none. A tag is an identifier that does not start
180/// with a digit, so `$1` is a parameter, never a tag.
181fn dollar_quote_end(b: &[u8], i: usize) -> Option<usize> {
182    let tag_len = b[i + 1..]
183        .iter()
184        .enumerate()
185        .take_while(|(k, c)| {
186            c.is_ascii_alphabetic() || **c == b'_' || (*k > 0 && c.is_ascii_digit())
187        })
188        .count();
189    if b.get(i + 1 + tag_len) != Some(&b'$') {
190        return None;
191    }
192    let tag = &b[i..i + tag_len + 2];
193    let body = i + tag.len();
194    Some(
195        b[body..]
196            .windows(tag.len())
197            .position(|w| w == tag)
198            .map_or(b.len(), |n| body + n + tag.len()),
199    )
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    /// The statements the scanner is held to: the highest `$n`, with text that
207    /// only looks like a parameter.
208    const COUNTS: &[(&str, usize)] = &[
209        ("select 1", 0),
210        ("select $1", 1),
211        ("select $1, $2, $3", 3),
212        ("select $2, $1", 2),
213        ("select * from t where a = $1 and b = $1", 1),
214        ("select '$9'", 0),
215        ("select E'it\\'s $9', $1", 1),
216        ("select 'it''s $9', $2, $1", 2),
217        ("select \"$9\" from t where a = $1", 1),
218        ("select 1 -- $9\n, $1", 1),
219        ("select price$1 from t where a = $2", 2),
220        ("select a$tag$ from t where b = $1", 1),
221        ("select a$1, $2 from t", 2),
222        ("select /* $9 /* nested $8 */ $7 */ $1", 1),
223        ("select $$ $9 $$, $1", 1),
224        ("select $tag$ $9 $tag$, $1, $2", 2),
225        ("select $1::int + $10::int", 10),
226        ("insert into t (a, b) values ($1, $2) returning id", 2),
227        ("select array[$1, $2]", 2),
228        ("select x ilike '%' || $2 || '%' from t", 2),
229    ];
230
231    #[test]
232    fn the_scanner_counts_by_postgres_rules() {
233        for (sql, n) in COUNTS {
234            assert_eq!(placeholder_count(sql), *n, "{sql}");
235        }
236    }
237
238    /// Valid Postgres, in the forms the docs and the tests of this repository
239    /// use: none of them may be reported.
240    pub(crate) const VALID_POSTGRES: &[&str] = &[
241        "select id, data->>'name' as name, data->'tags'->0 from events where data @> $1::jsonb",
242        "insert into orders (name, qty) values ($1, $2) on conflict (name) do update set qty = orders.qty + excluded.qty returning id, qty",
243        "insert into orders (name) values ($1) on conflict do nothing",
244        "update orders set qty = qty - 1 where id = $1 returning *",
245        "delete from orders where id = any($1::int8[])",
246        "select $1::timestamptz, $2::numeric(12, 2), $3::text[]",
247        "with recent as (select * from orders where placed > $1) select count(*) from recent",
248        "select distinct on (name) name, qty from orders order by name, qty desc",
249        "select id from orders where name ilike $1 order by id limit $2 offset $3",
250        "select id, row_number() over (partition by name order by id) from orders",
251        "select * from orders where id = $1 for update skip locked",
252        "select generate_series(1, $1)",
253        "insert into archive select * from orders where placed < $1",
254        "select * from orders o join items i on i.order_id = o.id where o.id = $1",
255        "create table if not exists t (id serial primary key, doc jsonb not null default '{}'::jsonb, at timestamptz default now())",
256    ];
257
258    #[test]
259    fn valid_postgres_has_no_problem() {
260        for sql in VALID_POSTGRES {
261            assert_eq!(check_statement(sql, None), vec![], "{sql}");
262        }
263    }
264
265    #[test]
266    fn a_valid_statement_with_the_right_count_has_no_problem() {
267        assert_eq!(check_statement("select $1, $2", Some(2)), vec![]);
268        assert_eq!(check_statement("select 1", Some(0)), vec![]);
269        // A list that is not written out leaves the count unchecked.
270        assert_eq!(check_statement("select $1, $2", None), vec![]);
271    }
272
273    #[test]
274    fn a_syntax_error_is_invalid() {
275        let got = check_statement("selec 1", Some(0));
276        assert!(
277            matches!(got.as_slice(), [PgSqlProblem::Invalid(_)]),
278            "{got:?}"
279        );
280    }
281
282    #[test]
283    fn several_commands_are_invalid() {
284        let got = check_statement("select 1; select 2", Some(0));
285        assert!(
286            matches!(got.as_slice(), [PgSqlProblem::Invalid(m)] if m.contains("one command")),
287            "{got:?}"
288        );
289    }
290
291    #[test]
292    fn a_wrong_count_is_reported_both_ways() {
293        assert_eq!(
294            check_statement("select $1, $2", Some(1)),
295            vec![PgSqlProblem::ParamCount {
296                expected: 2,
297                passed: 1
298            }]
299        );
300        assert_eq!(
301            check_statement("select $1", Some(3)),
302            vec![PgSqlProblem::ParamCount {
303                expected: 1,
304                passed: 3
305            }]
306        );
307    }
308}