Debian Codegraph @

src/message/command_complete.rs

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