sqlx_core_guts/postgres/message/
command_complete.rs

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