1#[cfg(feature = "runtime")]
2use crate::Socket;
3use crate::copy_out::CopyOutStream;
4use crate::query::RowStream;
5#[cfg(feature = "runtime")]
6use crate::tls::MakeTlsConnect;
7use crate::tls::TlsConnect;
8use crate::types::{BorrowToSql, ToSql, Type};
9use crate::{
10 CancelToken, Client, CopyInSink, Error, Portal, Row, SimpleQueryMessage, Statement,
11 ToStatement, bind, query, slice_iter,
12};
13use bytes::Buf;
14use futures_util::TryStreamExt;
15use tokio::io::{AsyncRead, AsyncWrite};
16
17pub struct Transaction<'a> {
22 client: &'a mut Client,
23 savepoint: Option<Savepoint>,
24 done: bool,
25}
26
27struct Savepoint {
29 name: String,
30 depth: u32,
31}
32
33impl Drop for Transaction<'_> {
34 fn drop(&mut self) {
35 if self.done {
36 return;
37 }
38
39 let name = self.savepoint.as_ref().map(|sp| sp.name.as_str());
40 self.client.__private_api_rollback(name);
41 }
42}
43
44impl<'a> Transaction<'a> {
45 pub(crate) fn new(client: &'a mut Client) -> Transaction<'a> {
46 Transaction {
47 client,
48 savepoint: None,
49 done: false,
50 }
51 }
52
53 pub async fn commit(mut self) -> Result<(), Error> {
55 self.done = true;
56 let query = if let Some(sp) = self.savepoint.as_ref() {
57 format!("RELEASE {}", sp.name)
58 } else {
59 "COMMIT".to_string()
60 };
61 self.client.batch_execute(&query).await
62 }
63
64 pub async fn rollback(mut self) -> Result<(), Error> {
68 self.done = true;
69 let query = if let Some(sp) = self.savepoint.as_ref() {
70 format!("ROLLBACK TO {}", sp.name)
71 } else {
72 "ROLLBACK".to_string()
73 };
74 self.client.batch_execute(&query).await
75 }
76
77 pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
79 self.client.prepare(query).await
80 }
81
82 pub async fn prepare_typed(
84 &self,
85 query: &str,
86 parameter_types: &[Type],
87 ) -> Result<Statement, Error> {
88 self.client.prepare_typed(query, parameter_types).await
89 }
90
91 pub async fn query<T>(
93 &self,
94 statement: &T,
95 params: &[&(dyn ToSql + Sync)],
96 ) -> Result<Vec<Row>, Error>
97 where
98 T: ?Sized + ToStatement,
99 {
100 self.client.query(statement, params).await
101 }
102
103 pub async fn query_one<T>(
105 &self,
106 statement: &T,
107 params: &[&(dyn ToSql + Sync)],
108 ) -> Result<Row, Error>
109 where
110 T: ?Sized + ToStatement,
111 {
112 self.client.query_one(statement, params).await
113 }
114
115 pub async fn query_opt<T>(
117 &self,
118 statement: &T,
119 params: &[&(dyn ToSql + Sync)],
120 ) -> Result<Option<Row>, Error>
121 where
122 T: ?Sized + ToStatement,
123 {
124 self.client.query_opt(statement, params).await
125 }
126
127 pub async fn query_raw<T, P, I>(&self, statement: &T, params: I) -> Result<RowStream, Error>
129 where
130 T: ?Sized + ToStatement,
131 P: BorrowToSql,
132 I: IntoIterator<Item = P>,
133 I::IntoIter: ExactSizeIterator,
134 {
135 self.client.query_raw(statement, params).await
136 }
137
138 pub async fn query_raw_with_format<T, P, I>(
140 &self,
141 statement: &T,
142 params: I,
143 result_format: crate::ResultFormat,
144 ) -> Result<RowStream, Error>
145 where
146 T: ?Sized + ToStatement,
147 P: BorrowToSql,
148 I: IntoIterator<Item = P>,
149 I::IntoIter: ExactSizeIterator,
150 {
151 self.client
152 .query_raw_with_format(statement, params, result_format)
153 .await
154 }
155
156 pub async fn query_raw_with_formats<P, I>(
158 &self,
159 statement: &Statement,
160 params: I,
161 formats: &[crate::ResultFormat],
162 ) -> Result<RowStream, Error>
163 where
164 P: BorrowToSql,
165 I: IntoIterator<Item = P>,
166 I::IntoIter: ExactSizeIterator,
167 {
168 self.client
169 .query_raw_with_formats(statement, params, formats)
170 .await
171 }
172
173 pub async fn query_typed(
175 &self,
176 statement: &str,
177 params: &[(&(dyn ToSql + Sync), Type)],
178 ) -> Result<Vec<Row>, Error> {
179 self.client.query_typed(statement, params).await
180 }
181
182 pub async fn query_typed_raw<P, I>(&self, query: &str, params: I) -> Result<RowStream, Error>
184 where
185 P: BorrowToSql,
186 I: IntoIterator<Item = (P, Type)>,
187 {
188 self.client.query_typed_raw(query, params).await
189 }
190
191 pub async fn execute<T>(
193 &self,
194 statement: &T,
195 params: &[&(dyn ToSql + Sync)],
196 ) -> Result<u64, Error>
197 where
198 T: ?Sized + ToStatement,
199 {
200 self.client.execute(statement, params).await
201 }
202
203 pub async fn execute_raw<P, I, T>(&self, statement: &T, params: I) -> Result<u64, Error>
205 where
206 T: ?Sized + ToStatement,
207 P: BorrowToSql,
208 I: IntoIterator<Item = P>,
209 I::IntoIter: ExactSizeIterator,
210 {
211 self.client.execute_raw(statement, params).await
212 }
213
214 pub async fn bind<T>(
223 &self,
224 statement: &T,
225 params: &[&(dyn ToSql + Sync)],
226 ) -> Result<Portal, Error>
227 where
228 T: ?Sized + ToStatement,
229 {
230 self.bind_raw(statement, slice_iter(params)).await
231 }
232
233 pub async fn bind_raw<P, T, I>(&self, statement: &T, params: I) -> Result<Portal, Error>
237 where
238 T: ?Sized + ToStatement,
239 P: BorrowToSql,
240 I: IntoIterator<Item = P>,
241 I::IntoIter: ExactSizeIterator,
242 {
243 let statement = statement.__convert().into_statement(self.client).await?;
244 bind::bind(self.client.inner(), statement, params).await
245 }
246
247 pub async fn query_portal(&self, portal: &Portal, max_rows: i32) -> Result<Vec<Row>, Error> {
252 self.query_portal_raw(portal, max_rows)
253 .await?
254 .try_collect()
255 .await
256 }
257
258 pub async fn query_portal_raw(
262 &self,
263 portal: &Portal,
264 max_rows: i32,
265 ) -> Result<RowStream, Error> {
266 query::query_portal(self.client.inner(), portal, max_rows).await
267 }
268
269 pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
271 where
272 T: ?Sized + ToStatement,
273 U: Buf + 'static + Send,
274 {
275 self.client.copy_in(statement).await
276 }
277
278 pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
280 where
281 T: ?Sized + ToStatement,
282 {
283 self.client.copy_out(statement).await
284 }
285
286 pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
288 self.client.simple_query(query).await
289 }
290
291 pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
293 self.client.batch_execute(query).await
294 }
295
296 pub fn cancel_token(&self) -> CancelToken {
298 self.client.cancel_token()
299 }
300
301 #[cfg(feature = "runtime")]
303 #[deprecated(since = "0.6.0", note = "use Transaction::cancel_token() instead")]
304 pub async fn cancel_query<T>(&self, tls: T) -> Result<(), Error>
305 where
306 T: MakeTlsConnect<Socket>,
307 {
308 #[allow(deprecated)]
309 self.client.cancel_query(tls).await
310 }
311
312 #[deprecated(since = "0.6.0", note = "use Transaction::cancel_token() instead")]
314 pub async fn cancel_query_raw<S, T>(&self, stream: S, tls: T) -> Result<(), Error>
315 where
316 S: AsyncRead + AsyncWrite + Unpin,
317 T: TlsConnect<S>,
318 {
319 #[allow(deprecated)]
320 self.client.cancel_query_raw(stream, tls).await
321 }
322
323 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
325 self._savepoint(None).await
326 }
327
328 pub async fn savepoint<I>(&mut self, name: I) -> Result<Transaction<'_>, Error>
330 where
331 I: Into<String>,
332 {
333 self._savepoint(Some(name.into())).await
334 }
335
336 async fn _savepoint(&mut self, name: Option<String>) -> Result<Transaction<'_>, Error> {
337 let depth = self.savepoint.as_ref().map_or(0, |sp| sp.depth) + 1;
338 let name = name.unwrap_or_else(|| format!("sp_{}", depth));
339 let query = format!("SAVEPOINT {}", name);
340 self.batch_execute(&query).await?;
341
342 Ok(Transaction {
343 client: self.client,
344 savepoint: Some(Savepoint { name, depth }),
345 done: false,
346 })
347 }
348
349 pub fn client(&self) -> &Client {
351 self.client
352 }
353}