rbdc_pg/message/
command_complete.rs

1use atoi::atoi;
2use bytes::Bytes;
3use memchr::memrchr;
4use rbdc::io::Decode;
5use rbdc::Error;
6
7#[derive(Debug)]
8pub struct CommandComplete {
9    /// The command tag. This is usually a single word that identifies which SQL command
10    /// was completed.
11    tag: Bytes,
12}
13
14impl Decode<'_> for CommandComplete {
15    #[inline]
16    fn decode_with(buf: Bytes, _: ()) -> Result<Self, Error> {
17        Ok(CommandComplete { tag: buf })
18    }
19}
20
21impl CommandComplete {
22    /// Returns the number of rows affected.
23    /// If the command does not return rows (e.g., "CREATE TABLE"), returns 0.
24    pub fn rows_affected(&self) -> u64 {
25        // Look backwards for the first SPACE
26        memrchr(b' ', &self.tag)
27            // This is either a word or the number of rows affected
28            .and_then(|i| atoi(&self.tag[(i + 1)..]))
29            .unwrap_or(0)
30    }
31}
32
33#[test]
34fn test_decode_command_complete_for_insert() {
35    const DATA: &[u8] = b"INSERT 0 1214\0";
36
37    let cc = CommandComplete::decode(Bytes::from_static(DATA)).unwrap();
38
39    assert_eq!(cc.rows_affected(), 1214);
40}
41
42#[test]
43fn test_decode_command_complete_for_begin() {
44    const DATA: &[u8] = b"BEGIN\0";
45
46    let cc = CommandComplete::decode(Bytes::from_static(DATA)).unwrap();
47
48    assert_eq!(cc.rows_affected(), 0);
49}
50
51#[test]
52fn test_decode_command_complete_for_update() {
53    const DATA: &[u8] = b"UPDATE 5\0";
54
55    let cc = CommandComplete::decode(Bytes::from_static(DATA)).unwrap();
56
57    assert_eq!(cc.rows_affected(), 5);
58}
59
60#[cfg(all(test, not(debug_assertions)))]
61#[bench]
62fn bench_decode_command_complete(b: &mut test::Bencher) {
63    const DATA: &[u8] = b"INSERT 0 1214\0";
64
65    b.iter(|| {
66        let _ = CommandComplete::decode(test::black_box(Bytes::from_static(DATA)));
67    });
68}
69
70#[cfg(all(test, not(debug_assertions)))]
71#[bench]
72fn bench_decode_command_complete_rows_affected(b: &mut test::Bencher) {
73    const DATA: &[u8] = b"INSERT 0 1214\0";
74
75    let data = CommandComplete::decode(Bytes::from_static(DATA)).unwrap();
76
77    b.iter(|| {
78        let _rows = test::black_box(&data).rows_affected();
79    });
80}