-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathmod.rs
More file actions
171 lines (143 loc) · 4.76 KB
/
mod.rs
File metadata and controls
171 lines (143 loc) · 4.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::fmt::{self, Debug, Formatter};
use std::future::Future;
pub(crate) use sqlx_core::connection::*;
use sqlx_core::sql_str::SqlSafeStr;
pub(crate) use stream::{MySqlStream, Waiting};
use crate::collation::Collation;
use crate::common::StatementCache;
use crate::error::Error;
use crate::protocol::response::Status;
use crate::protocol::statement::StmtClose;
use crate::protocol::text::{Ping, Quit};
use crate::statement::MySqlStatementMetadata;
use crate::transaction::Transaction;
use crate::{MySql, MySqlConnectOptions};
mod auth;
mod establish;
mod executor;
mod stream;
mod tls;
const MAX_PACKET_SIZE: u32 = 1024;
/// The charset parameter sent in the `Protocol::HandshakeResponse41` packet.
///
/// This becomes the default if `set_names = false`,
/// and also ensures that any error messages returned before `SET NAMES` are encoded correctly.
#[allow(clippy::cast_possible_truncation)]
const INITIAL_CHARSET: u8 = Collation::UTF8MB4_GENERAL_CI.0 as u8;
/// A connection to a MySQL database.
pub struct MySqlConnection {
pub(crate) inner: Box<MySqlConnectionInner>,
}
pub(crate) struct MySqlConnectionInner {
// underlying TCP stream,
// wrapped in a potentially TLS stream,
// wrapped in a buffered stream
pub(crate) stream: MySqlStream,
// transaction status
pub(crate) transaction_depth: usize,
status_flags: Status,
// cache by query string to the statement id and metadata
cache_statement: StatementCache<(u32, MySqlStatementMetadata)>,
log_settings: LogSettings,
}
impl MySqlConnection {
/// Connect to a MySQL database using a pre-connected socket.
///
/// This allows using custom transport layers such as vsock, QUIC,
/// or any type that implements [`sqlx_core::net::Socket`].
///
/// The provided socket will go through TLS upgrade negotiation based on the
/// SSL mode configured in `options`.
///
/// # Example
///
/// ```rust,ignore
/// use sqlx::mysql::{MySqlConnectOptions, MySqlConnection};
///
/// # async fn example() -> sqlx::Result<()> {
/// let socket: tokio::net::TcpStream = todo!();
/// let options = MySqlConnectOptions::new()
/// .username("root")
/// .database("mydb");
///
/// let _conn = MySqlConnection::connect_socket(socket, &options).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect_socket<S: sqlx_core::net::Socket>(
socket: S,
options: &MySqlConnectOptions,
) -> Result<Self, Error> {
let mut conn = Self::establish_with_socket(socket, options).await?;
options.configure_session(&mut conn).await?;
Ok(conn)
}
pub(crate) fn in_transaction(&self) -> bool {
self.inner
.status_flags
.intersects(Status::SERVER_STATUS_IN_TRANS)
}
}
impl Debug for MySqlConnection {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("MySqlConnection").finish()
}
}
impl Connection for MySqlConnection {
type Database = MySql;
type Options = MySqlConnectOptions;
async fn close(mut self) -> Result<(), Error> {
self.inner.stream.send_packet(Quit).await?;
self.inner.stream.shutdown().await?;
Ok(())
}
async fn close_hard(mut self) -> Result<(), Error> {
self.inner.stream.shutdown().await?;
Ok(())
}
async fn ping(&mut self) -> Result<(), Error> {
self.inner.stream.wait_until_ready().await?;
self.inner.stream.send_packet(Ping).await?;
self.inner.stream.recv_ok().await?;
Ok(())
}
#[doc(hidden)]
fn flush(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_ {
self.inner.stream.wait_until_ready()
}
fn cached_statements_size(&self) -> usize {
self.inner.cache_statement.len()
}
async fn clear_cached_statements(&mut self) -> Result<(), Error> {
while let Some((statement_id, _)) = self.inner.cache_statement.remove_lru() {
self.inner
.stream
.send_packet(StmtClose {
statement: statement_id,
})
.await?;
}
Ok(())
}
#[doc(hidden)]
fn should_flush(&self) -> bool {
!self.inner.stream.write_buffer().is_empty()
}
fn begin(
&mut self,
) -> impl Future<Output = Result<Transaction<'_, Self::Database>, Error>> + Send + '_ {
Transaction::begin(self, None)
}
fn begin_with(
&mut self,
statement: impl SqlSafeStr,
) -> impl Future<Output = Result<Transaction<'_, Self::Database>, Error>> + Send + '_
where
Self: Sized,
{
Transaction::begin(self, Some(statement.into_sql_str()))
}
fn shrink_buffers(&mut self) {
self.inner.stream.shrink_buffers();
}
}