sqlx_core_guts/postgres/message/
parse.rs

1use std::i16;
2
3use crate::io::{BufMutExt, Encode};
4use crate::postgres::io::PgBufMutExt;
5use crate::postgres::types::Oid;
6
7#[derive(Debug)]
8pub struct Parse<'a> {
9    /// The ID of the destination prepared statement.
10    pub statement: Oid,
11
12    /// The query string to be parsed.
13    pub query: &'a str,
14
15    /// The parameter data types specified (could be zero). Note that this is not an
16    /// indication of the number of parameters that might appear in the query string,
17    /// only the number that the frontend wants to pre-specify types for.
18    pub param_types: &'a [Oid],
19}
20
21impl Encode<'_> for Parse<'_> {
22    fn encode_with(&self, buf: &mut Vec<u8>, _: ()) {
23        buf.push(b'P');
24
25        buf.put_length_prefixed(|buf| {
26            buf.put_statement_name(self.statement);
27
28            buf.put_str_nul(self.query);
29
30            // TODO: Return an error here instead
31            assert!(self.param_types.len() <= (u16::MAX as usize));
32
33            buf.extend(&(self.param_types.len() as i16).to_be_bytes());
34
35            for &oid in self.param_types {
36                buf.extend(&oid.0.to_be_bytes());
37            }
38        })
39    }
40}
41
42#[test]
43fn test_encode_parse() {
44    const EXPECTED: &[u8] = b"P\0\0\0\x1dsqlx_s_1\0SELECT $1\0\0\x01\0\0\0\x19";
45
46    let mut buf = Vec::new();
47    let m = Parse {
48        statement: Oid(1),
49        query: "SELECT $1",
50        param_types: &[Oid(25)],
51    };
52
53    m.encode(&mut buf);
54
55    assert_eq!(buf, EXPECTED);
56}