-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathmod.rs
More file actions
286 lines (231 loc) · 8.31 KB
/
mod.rs
File metadata and controls
286 lines (231 loc) · 8.31 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::sync::Arc;
use crate::HashMap;
use crate::common::StatementCache;
use crate::error::Error;
use crate::ext::ustr::UStr;
use crate::io::StatementId;
use crate::message::{
BackendMessageFormat, Close, Query, ReadyForQuery, ReceivedMessage, Terminate,
TransactionStatus,
};
use crate::statement::PgStatementMetadata;
use crate::transaction::Transaction;
use crate::types::Oid;
use crate::{PgConnectOptions, PgTypeInfo, Postgres};
pub(crate) use sqlx_core::connection::*;
use sqlx_core::sql_str::SqlSafeStr;
pub use self::stream::PgStream;
#[cfg(feature = "offline")]
mod describe;
mod establish;
mod executor;
mod resolve;
mod sasl;
mod stream;
mod tls;
/// A connection to a PostgreSQL database.
///
/// See [`PgConnectOptions`] for connection URL reference.
pub struct PgConnection {
pub(crate) inner: Box<PgConnectionInner>,
}
pub struct PgConnectionInner {
// underlying TCP or UDS stream,
// wrapped in a potentially TLS stream,
// wrapped in a buffered stream
pub(crate) stream: PgStream,
// process id of this backend
// used to send cancel requests
#[allow(dead_code)]
process_id: u32,
// secret key of this backend
// used to send cancel requests
#[allow(dead_code)]
secret_key: u32,
// sequence of statement IDs for use in preparing statements
// in PostgreSQL, the statement is prepared to a user-supplied identifier
next_statement_id: StatementId,
// cache statement by query string to the id and columns
cache_statement: StatementCache<(StatementId, Arc<PgStatementMetadata>)>,
// cache user-defined types by id <-> info
cache_type_info: HashMap<Oid, PgTypeInfo>,
cache_type_oid: HashMap<UStr, Oid>,
cache_elem_type_to_array: HashMap<Oid, Oid>,
cache_table_to_column_names: HashMap<Oid, TableColumns>,
// number of ReadyForQuery messages that we are currently expecting
pub(crate) pending_ready_for_query_count: usize,
// current transaction status
transaction_status: TransactionStatus,
pub(crate) transaction_depth: usize,
log_settings: LogSettings,
}
pub(crate) struct TableColumns {
table_name: Arc<str>,
/// Attribute number -> name.
columns: BTreeMap<i16, Arc<str>>,
}
impl PgConnection {
/// Connect to a PostgreSQL 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::postgres::{PgConnectOptions, PgConnection};
///
/// # async fn example() -> sqlx::Result<()> {
/// let socket: tokio::net::TcpStream = todo!();
/// let options = PgConnectOptions::new()
/// .username("postgres")
/// .database("mydb");
///
/// let _conn = PgConnection::connect_socket(socket, &options).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect_socket<S: sqlx_core::net::Socket>(
socket: S,
options: &PgConnectOptions,
) -> Result<Self, Error> {
Self::establish_with_socket(socket, options).await
}
/// the version number of the server in `libpq` format
pub fn server_version_num(&self) -> Option<u32> {
self.inner.stream.server_version_num
}
// will return when the connection is ready for another query
pub(crate) async fn wait_until_ready(&mut self) -> Result<(), Error> {
if !self.inner.stream.write_buffer_mut().is_empty() {
self.inner.stream.flush().await?;
}
while self.inner.pending_ready_for_query_count > 0 {
let message = self.inner.stream.recv().await?;
if let BackendMessageFormat::ReadyForQuery = message.format {
self.handle_ready_for_query(message)?;
}
}
Ok(())
}
async fn recv_ready_for_query(&mut self) -> Result<(), Error> {
let r: ReadyForQuery = self.inner.stream.recv_expect().await?;
self.inner.pending_ready_for_query_count -= 1;
self.inner.transaction_status = r.transaction_status;
Ok(())
}
#[inline(always)]
fn handle_ready_for_query(&mut self, message: ReceivedMessage) -> Result<(), Error> {
self.inner.pending_ready_for_query_count = self
.inner
.pending_ready_for_query_count
.checked_sub(1)
.ok_or_else(|| err_protocol!("received more ReadyForQuery messages than expected"))?;
self.inner.transaction_status = message.decode::<ReadyForQuery>()?.transaction_status;
Ok(())
}
/// Queue a simple query (not prepared) to execute the next time this connection is used.
///
/// Used for rolling back transactions and releasing advisory locks.
#[inline(always)]
pub(crate) fn queue_simple_query(&mut self, query: &str) -> Result<(), Error> {
self.inner.stream.write_msg(Query(query))?;
self.inner.pending_ready_for_query_count += 1;
Ok(())
}
pub(crate) fn in_transaction(&self) -> bool {
match self.inner.transaction_status {
TransactionStatus::Transaction => true,
TransactionStatus::Error | TransactionStatus::Idle => false,
}
}
}
impl Debug for PgConnection {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("PgConnection").finish()
}
}
impl Connection for PgConnection {
type Database = Postgres;
type Options = PgConnectOptions;
async fn close(mut self) -> Result<(), Error> {
// The normal, graceful termination procedure is that the frontend sends a Terminate
// message and immediately closes the connection.
// On receipt of this message, the backend closes the
// connection and terminates.
self.inner.stream.send(Terminate).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> {
// Users were complaining about this showing up in query statistics on the server.
// By sending a comment we avoid an error if the connection was in the middle of a rowset
// self.execute("/* SQLx ping */").map_ok(|_| ()).boxed()
// The simplest call-and-response that's possible.
self.write_sync();
self.wait_until_ready().await
}
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 cached_statements_size(&self) -> usize {
self.inner.cache_statement.len()
}
async fn clear_cached_statements(&mut self) -> Result<(), Error> {
self.inner.cache_type_oid.clear();
let mut cleared = 0_usize;
self.wait_until_ready().await?;
while let Some((id, _)) = self.inner.cache_statement.remove_lru() {
self.inner.stream.write_msg(Close::Statement(id))?;
cleared += 1;
}
if cleared > 0 {
self.write_sync();
self.inner.stream.flush().await?;
self.wait_for_close_complete(cleared).await?;
self.recv_ready_for_query().await?;
}
Ok(())
}
fn shrink_buffers(&mut self) {
self.inner.stream.shrink_buffers();
}
#[doc(hidden)]
fn flush(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_ {
self.wait_until_ready()
}
#[doc(hidden)]
fn should_flush(&self) -> bool {
!self.inner.stream.write_buffer().is_empty()
}
}
// Implement `AsMut<Self>` so that `PgConnection` can be wrapped in
// a `PgAdvisoryLockGuard`.
//
// See: https://github.com/launchbadge/sqlx/issues/2520
impl AsMut<PgConnection> for PgConnection {
fn as_mut(&mut self) -> &mut PgConnection {
self
}
}