cdbc_mysql/connection/
mod.rs

1use cdbc::utils::statement_cache::StatementCache;
2use cdbc::connection::{Connection};
3use cdbc::error::Error;
4use crate::protocol::statement::StmtClose;
5use crate::protocol::text::{Ping, Quit};
6use crate::statement::MySqlStatementMetadata;
7use crate::{MySql, MySqlConnectOptions};
8use cdbc::transaction::Transaction;
9use std::fmt::{self, Debug, Formatter};
10
11mod auth;
12mod establish;
13mod executor;
14mod stream;
15mod tls;
16
17pub(crate) use stream::{MySqlStream, Waiting};
18
19
20const MAX_PACKET_SIZE: u32 = 1024;
21
22/// A connection to a MySQL database.
23pub struct MySqlConnection {
24    // underlying TCP stream,
25    // wrapped in a potentially TLS stream,
26    // wrapped in a buffered stream
27    pub(crate) stream: MySqlStream,
28
29    // transaction status
30    pub(crate) transaction_depth: usize,
31
32    // cache by query string to the statement id and metadata
33    cache_statement: StatementCache<(u32, MySqlStatementMetadata)>,
34}
35
36impl Debug for MySqlConnection {
37    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
38        f.debug_struct("MySqlConnection").finish()
39    }
40}
41
42impl Connection for MySqlConnection {
43
44    type Options = MySqlConnectOptions;
45
46    fn close(mut self) -> Result<(), Error> {
47        {
48            self.stream.send_packet(Quit)?;
49            self.stream.shutdown()?;
50
51            Ok(())
52        }
53    }
54
55    fn ping(&mut self) -> Result<(), Error> {
56        self.stream.wait_until_ready()?;
57        self.stream.send_packet(Ping)?;
58        self.stream.recv_ok()?;
59
60        Ok(())
61    }
62
63    #[doc(hidden)]
64    fn flush(&mut self) -> Result<(), Error> {
65        self.stream.wait_until_ready()
66    }
67
68    fn cached_statements_size(&self) -> usize {
69        self.cache_statement.len()
70    }
71
72    fn clear_cached_statements(&mut self) -> Result<(), Error> {
73        while let Some((statement_id, _)) = self.cache_statement.remove_lru() {
74            self.stream
75                .send_packet(StmtClose {
76                    statement: statement_id,
77                })
78                ?;
79        }
80        Ok(())
81    }
82
83    #[doc(hidden)]
84    fn should_flush(&self) -> bool {
85        !self.stream.wbuf.is_empty()
86    }
87
88    fn begin(&mut self) -> Result<Transaction<'_, Self::Database>, Error>
89        where
90            Self: Sized,
91    {
92
93        Transaction::begin(self)
94    }
95}