-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathinner_connection.rs
More file actions
347 lines (314 loc) · 11.4 KB
/
inner_connection.rs
File metadata and controls
347 lines (314 loc) · 11.4 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use bytes::Buf;
use deadpool_postgres::{Object, Transaction};
use postgres_types::{ToSql, Type};
use pyo3::{pyclass, Py, PyAny, Python};
use std::vec;
use tokio_postgres::{Client, CopyInSink, Row, Statement, ToStatement};
use crate::{
exceptions::rust_errors::{PSQLPyResult, RustPSQLDriverError},
query_result::{PSQLDriverPyQueryResult, PSQLDriverSinglePyQueryResult},
statement::{statement::PsqlpyStatement, statement_builder::StatementBuilder},
value_converter::to_python::postgres_to_py,
};
#[allow(clippy::module_name_repetitions)]
pub enum PsqlpyConnection {
PoolConn(Object, bool),
SingleConn(Client),
}
// #[pyclass]
// struct Portal {
// trans: Transaction<'static>,
// }
impl PsqlpyConnection {
/// Prepare cached statement.
///
/// # Errors
/// May return Err if cannot prepare statement.
pub async fn prepare(&self, query: &str, prepared: bool) -> PSQLPyResult<Statement> {
match self {
PsqlpyConnection::PoolConn(pconn, _) => {
if prepared {
return Ok(pconn.prepare_cached(query).await?);
} else {
let prepared = pconn.prepare(query).await?;
self.drop_prepared(&prepared).await?;
return Ok(prepared);
}
}
PsqlpyConnection::SingleConn(sconn) => return Ok(sconn.prepare(query).await?),
}
}
// pub async fn transaction(&mut self) -> Portal {
// match self {
// PsqlpyConnection::PoolConn(pconn, _) => {
// let b = unsafe {
// std::mem::transmute::<Transaction<'_>, Transaction<'static>>(pconn.transaction().await.unwrap())
// };
// Portal {trans: b}
// // let c = b.bind("SELECT 1", &[]).await.unwrap();
// // b.query_portal(&c, 1).await;
// }
// PsqlpyConnection::SingleConn(sconn) => {
// let b = unsafe {
// std::mem::transmute::<Transaction<'_>, Transaction<'static>>(sconn.transaction().await.unwrap())
// };
// Portal {trans: b}
// },
// }
// }
/// Delete prepared statement.
///
/// # Errors
/// May return Err if cannot prepare statement.
pub async fn drop_prepared(&self, stmt: &Statement) -> PSQLPyResult<()> {
let deallocate_query = format!("DEALLOCATE PREPARE {}", stmt.name());
match self {
PsqlpyConnection::PoolConn(pconn, _) => {
let res = Ok(pconn.batch_execute(&deallocate_query).await?);
res
}
PsqlpyConnection::SingleConn(sconn) => {
return Ok(sconn.batch_execute(&deallocate_query).await?)
}
}
}
/// Execute statement with parameters.
///
/// # Errors
/// May return Err if cannot execute statement.
pub async fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> PSQLPyResult<Vec<Row>>
where
T: ?Sized + ToStatement,
{
match self {
PsqlpyConnection::PoolConn(pconn, _) => {
return Ok(pconn.query(statement, params).await?)
}
PsqlpyConnection::SingleConn(sconn) => {
return Ok(sconn.query(statement, params).await?)
}
}
}
/// Execute statement with parameters.
///
/// # Errors
/// May return Err if cannot execute statement.
pub async fn query_typed(
&self,
statement: &str,
params: &[(&(dyn ToSql + Sync), Type)],
) -> PSQLPyResult<Vec<Row>> {
match self {
PsqlpyConnection::PoolConn(pconn, _) => {
return Ok(pconn.query_typed(statement, params).await?)
}
PsqlpyConnection::SingleConn(sconn) => {
return Ok(sconn.query_typed(statement, params).await?)
}
}
}
/// Batch execute statement.
///
/// # Errors
/// May return Err if cannot execute statement.
pub async fn batch_execute(&self, query: &str) -> PSQLPyResult<()> {
match self {
PsqlpyConnection::PoolConn(pconn, _) => return Ok(pconn.batch_execute(query).await?),
PsqlpyConnection::SingleConn(sconn) => return Ok(sconn.batch_execute(query).await?),
}
}
/// Prepare cached statement.
///
/// # Errors
/// May return Err if cannot execute copy data.
pub async fn copy_in<T, U>(&self, statement: &T) -> PSQLPyResult<CopyInSink<U>>
where
T: ?Sized + ToStatement,
U: Buf + 'static + Send,
{
match self {
PsqlpyConnection::PoolConn(pconn, _) => return Ok(pconn.copy_in(statement).await?),
PsqlpyConnection::SingleConn(sconn) => return Ok(sconn.copy_in(statement).await?),
}
}
/// Executes a statement which returns a single row, returning it.
///
/// # Errors
/// May return Err if cannot execute statement.
pub async fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> PSQLPyResult<Row>
where
T: ?Sized + ToStatement,
{
match self {
PsqlpyConnection::PoolConn(pconn, _) => {
return Ok(pconn.query_one(statement, params).await?)
}
PsqlpyConnection::SingleConn(sconn) => {
return Ok(sconn.query_one(statement, params).await?)
}
}
}
pub async fn cursor_execute(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<PSQLDriverPyQueryResult> {
let statement = StatementBuilder::new(querystring, parameters, self, prepared)
.build()
.await?;
let prepared = prepared.unwrap_or(true);
let result = if prepared {
self.query(
&self
.prepare(&statement.raw_query(), true)
.await
.map_err(|err| {
RustPSQLDriverError::ConnectionExecuteError(format!(
"Cannot prepare statement, error - {err}"
))
})?,
&statement.params(),
)
.await
.map_err(|err| RustPSQLDriverError::ConnectionExecuteError(format!("{err}")))?
} else {
self.query(statement.raw_query(), &statement.params())
.await
.map_err(|err| RustPSQLDriverError::ConnectionExecuteError(format!("{err}")))?
};
Ok(PSQLDriverPyQueryResult::new(result))
}
pub async fn execute(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<PSQLDriverPyQueryResult> {
let statement = StatementBuilder::new(querystring, parameters, self, prepared)
.build()
.await?;
let prepared = prepared.unwrap_or(true);
let result = match prepared {
true => self
.query(statement.statement_query()?, &statement.params())
.await
.map_err(|err| {
RustPSQLDriverError::ConnectionExecuteError(format!(
"Cannot prepare statement, error - {err}"
))
})?,
false => self
.query_typed(statement.raw_query(), &statement.params_typed())
.await
.map_err(|err| RustPSQLDriverError::ConnectionExecuteError(format!("{err}")))?,
};
Ok(PSQLDriverPyQueryResult::new(result))
}
pub async fn execute_many(
&self,
querystring: String,
parameters: Option<Vec<Py<PyAny>>>,
prepared: Option<bool>,
) -> PSQLPyResult<()> {
let mut statements: Vec<PsqlpyStatement> = vec![];
if let Some(parameters) = parameters {
for vec_of_py_any in parameters {
// TODO: Fix multiple qs creation
let statement =
StatementBuilder::new(querystring.clone(), Some(vec_of_py_any), self, prepared)
.build()
.await?;
statements.push(statement);
}
}
let prepared = prepared.unwrap_or(true);
for statement in statements {
let querystring_result = if prepared {
let prepared_stmt = &self.prepare(&statement.raw_query(), true).await;
if let Err(error) = prepared_stmt {
return Err(RustPSQLDriverError::ConnectionExecuteError(format!(
"Cannot prepare statement in execute_many, operation rolled back {error}",
)));
}
self.query(
&self.prepare(&statement.raw_query(), true).await?,
&statement.params(),
)
.await
} else {
self.query(statement.raw_query(), &statement.params()).await
};
if let Err(error) = querystring_result {
return Err(RustPSQLDriverError::ConnectionExecuteError(format!(
"Error occured in `execute_many` statement: {error}"
)));
}
}
return Ok(());
}
pub async fn fetch_row_raw(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<Row> {
let statement = StatementBuilder::new(querystring, parameters, self, prepared)
.build()
.await?;
let prepared = prepared.unwrap_or(true);
let result = if prepared {
self.query_one(
&self
.prepare(&statement.raw_query(), true)
.await
.map_err(|err| {
RustPSQLDriverError::ConnectionExecuteError(format!(
"Cannot prepare statement, error - {err}"
))
})?,
&statement.params(),
)
.await
.map_err(|err| RustPSQLDriverError::ConnectionExecuteError(format!("{err}")))?
} else {
self.query_one(statement.raw_query(), &statement.params())
.await
.map_err(|err| RustPSQLDriverError::ConnectionExecuteError(format!("{err}")))?
};
return Ok(result);
}
pub async fn fetch_row(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<PSQLDriverSinglePyQueryResult> {
let result = self
.fetch_row_raw(querystring, parameters, prepared)
.await?;
return Ok(PSQLDriverSinglePyQueryResult::new(result));
}
pub async fn fetch_val(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<Py<PyAny>> {
let result = self
.fetch_row_raw(querystring, parameters, prepared)
.await?;
return Python::with_gil(|gil| match result.columns().first() {
Some(first_column) => postgres_to_py(gil, &result, first_column, 0, &None),
None => Ok(gil.None()),
});
}
}