-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathimpls.rs
More file actions
612 lines (541 loc) · 19.3 KB
/
impls.rs
File metadata and controls
612 lines (541 loc) · 19.3 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use bytes::Buf;
use pyo3::{PyAny, Python};
use tokio_postgres::{CopyInSink, Portal as tp_Portal, Row, Statement, ToStatement};
use crate::{
exceptions::rust_errors::{PSQLPyResult, RustPSQLDriverError},
options::{IsolationLevel, ReadVariant},
query_result::{PSQLDriverPyQueryResult, PSQLDriverSinglePyQueryResult},
statement::{statement::PsqlpyStatement, statement_builder::StatementBuilder},
transaction::structs::PSQLPyTransaction,
value_converter::to_python::postgres_to_py,
};
use deadpool_postgres::Transaction as dp_Transaction;
use tokio_postgres::Transaction as tp_Transaction;
use super::{
structs::{PSQLPyConnection, PoolConnection, SingleConnection},
traits::{CloseTransaction, Connection, StartTransaction, Transaction},
};
impl<T> Transaction for T
where
T: Connection,
{
async fn _start_transaction(
&mut self,
isolation_level: Option<IsolationLevel>,
read_variant: Option<ReadVariant>,
deferrable: Option<bool>,
) -> PSQLPyResult<()> {
let start_qs = self.build_start_qs(isolation_level, read_variant, deferrable);
self.batch_execute(start_qs.as_str()).await.map_err(|err| {
RustPSQLDriverError::TransactionBeginError(format!(
"Cannot start transaction due to - {err}"
))
})?;
Ok(())
}
async fn _commit(&self) -> PSQLPyResult<()> {
self.batch_execute("COMMIT;").await.map_err(|err| {
RustPSQLDriverError::TransactionCommitError(format!(
"Cannot execute COMMIT statement, error - {err}"
))
})?;
Ok(())
}
async fn _rollback(&self) -> PSQLPyResult<()> {
self.batch_execute("ROLLBACK;").await.map_err(|err| {
RustPSQLDriverError::TransactionRollbackError(format!(
"Cannot execute ROLLBACK statement, error - {err}"
))
})?;
Ok(())
}
}
impl Connection for SingleConnection {
async fn prepare(&self, query: &str, prepared: bool) -> PSQLPyResult<Statement> {
let prepared_stmt = self.connection.prepare(query).await?;
if !prepared {
self.drop_prepared(&prepared_stmt).await?;
}
Ok(prepared_stmt)
}
async fn drop_prepared(&self, stmt: &Statement) -> PSQLPyResult<()> {
let deallocate_query = format!("DEALLOCATE PREPARE {}", stmt.name());
Ok(self.connection.batch_execute(&deallocate_query).await?)
}
async fn query<T>(
&self,
statement: &T,
params: &[&(dyn postgres_types::ToSql + Sync)],
) -> PSQLPyResult<Vec<Row>>
where
T: ?Sized + ToStatement,
{
Ok(self.connection.query(statement, params).await?)
}
async fn query_typed(
&self,
statement: &str,
params: &[(&(dyn postgres_types::ToSql + Sync), postgres_types::Type)],
) -> PSQLPyResult<Vec<Row>> {
Ok(self.connection.query_typed(statement, params).await?)
}
async fn batch_execute(&self, query: &str) -> PSQLPyResult<()> {
Ok(self.connection.batch_execute(query).await?)
}
async fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn postgres_types::ToSql + Sync)],
) -> PSQLPyResult<Row>
where
T: ?Sized + ToStatement,
{
Ok(self.connection.query_one(statement, params).await?)
}
}
impl StartTransaction for SingleConnection {
#[allow(clippy::used_underscore_items)]
async fn start_transaction(
&mut self,
isolation_level: Option<IsolationLevel>,
read_variant: Option<ReadVariant>,
deferrable: Option<bool>,
) -> PSQLPyResult<()> {
self._start_transaction(isolation_level, read_variant, deferrable)
.await?;
self.in_transaction = true;
Ok(())
}
}
impl CloseTransaction for SingleConnection {
#[allow(clippy::used_underscore_items)]
async fn commit(&mut self) -> PSQLPyResult<()> {
self._commit().await?;
self.in_transaction = false;
Ok(())
}
#[allow(clippy::used_underscore_items)]
async fn rollback(&mut self) -> PSQLPyResult<()> {
self._rollback().await?;
self.in_transaction = false;
Ok(())
}
}
impl Connection for PoolConnection {
async fn prepare(&self, query: &str, prepared: bool) -> PSQLPyResult<Statement> {
if prepared {
return Ok(self.connection.prepare_cached(query).await?);
}
let prepared = self.connection.prepare(query).await?;
self.drop_prepared(&prepared).await?;
Ok(prepared)
}
async fn drop_prepared(&self, stmt: &Statement) -> PSQLPyResult<()> {
let deallocate_query = format!("DEALLOCATE PREPARE {}", stmt.name());
Ok(self.connection.batch_execute(&deallocate_query).await?)
}
async fn query<T>(
&self,
statement: &T,
params: &[&(dyn postgres_types::ToSql + Sync)],
) -> PSQLPyResult<Vec<Row>>
where
T: ?Sized + ToStatement,
{
Ok(self.connection.query(statement, params).await?)
}
async fn query_typed(
&self,
statement: &str,
params: &[(&(dyn postgres_types::ToSql + Sync), postgres_types::Type)],
) -> PSQLPyResult<Vec<Row>> {
Ok(self.connection.query_typed(statement, params).await?)
}
async fn batch_execute(&self, query: &str) -> PSQLPyResult<()> {
Ok(self.connection.batch_execute(query).await?)
}
async fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn postgres_types::ToSql + Sync)],
) -> PSQLPyResult<Row>
where
T: ?Sized + ToStatement,
{
Ok(self.connection.query_one(statement, params).await?)
}
}
impl StartTransaction for PoolConnection {
#[allow(clippy::used_underscore_items)]
async fn start_transaction(
&mut self,
isolation_level: Option<IsolationLevel>,
read_variant: Option<ReadVariant>,
deferrable: Option<bool>,
) -> PSQLPyResult<()> {
self.in_transaction = true;
self._start_transaction(isolation_level, read_variant, deferrable)
.await
}
}
impl CloseTransaction for PoolConnection {
#[allow(clippy::used_underscore_items)]
async fn commit(&mut self) -> PSQLPyResult<()> {
self._commit().await?;
self.in_transaction = false;
Ok(())
}
#[allow(clippy::used_underscore_items)]
async fn rollback(&mut self) -> PSQLPyResult<()> {
self._rollback().await?;
self.in_transaction = false;
Ok(())
}
}
impl Connection for PSQLPyConnection {
async fn prepare(&self, query: &str, prepared: bool) -> PSQLPyResult<Statement> {
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.prepare(query, prepared).await,
PSQLPyConnection::SingleConnection(s_conn) => s_conn.prepare(query, prepared).await,
}
}
async fn drop_prepared(&self, stmt: &Statement) -> PSQLPyResult<()> {
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.drop_prepared(stmt).await,
PSQLPyConnection::SingleConnection(s_conn) => s_conn.drop_prepared(stmt).await,
}
}
async fn query<T>(
&self,
statement: &T,
params: &[&(dyn postgres_types::ToSql + Sync)],
) -> PSQLPyResult<Vec<Row>>
where
T: ?Sized + ToStatement,
{
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.query(statement, params).await,
PSQLPyConnection::SingleConnection(s_conn) => s_conn.query(statement, params).await,
}
}
async fn query_typed(
&self,
statement: &str,
params: &[(&(dyn postgres_types::ToSql + Sync), postgres_types::Type)],
) -> PSQLPyResult<Vec<Row>> {
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.query_typed(statement, params).await,
PSQLPyConnection::SingleConnection(s_conn) => {
s_conn.query_typed(statement, params).await
}
}
}
async fn batch_execute(&self, query: &str) -> PSQLPyResult<()> {
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.batch_execute(query).await,
PSQLPyConnection::SingleConnection(s_conn) => s_conn.batch_execute(query).await,
}
}
async fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn postgres_types::ToSql + Sync)],
) -> PSQLPyResult<Row>
where
T: ?Sized + ToStatement,
{
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.query_one(statement, params).await,
PSQLPyConnection::SingleConnection(s_conn) => s_conn.query_one(statement, params).await,
}
}
}
impl StartTransaction for PSQLPyConnection {
async fn start_transaction(
&mut self,
isolation_level: Option<IsolationLevel>,
read_variant: Option<ReadVariant>,
deferrable: Option<bool>,
) -> PSQLPyResult<()> {
match self {
PSQLPyConnection::PoolConn(p_conn) => {
p_conn
.start_transaction(isolation_level, read_variant, deferrable)
.await
}
PSQLPyConnection::SingleConnection(s_conn) => {
s_conn
.start_transaction(isolation_level, read_variant, deferrable)
.await
}
}
}
}
impl CloseTransaction for PSQLPyConnection {
async fn commit(&mut self) -> PSQLPyResult<()> {
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.commit().await,
PSQLPyConnection::SingleConnection(s_conn) => s_conn.commit().await,
}
}
async fn rollback(&mut self) -> PSQLPyResult<()> {
match self {
PSQLPyConnection::PoolConn(p_conn) => p_conn.rollback().await,
PSQLPyConnection::SingleConnection(s_conn) => s_conn.rollback().await,
}
}
}
impl PSQLPyConnection {
#[must_use]
pub fn in_transaction(&self) -> bool {
match self {
PSQLPyConnection::PoolConn(conn) => conn.in_transaction,
PSQLPyConnection::SingleConnection(conn) => conn.in_transaction,
}
}
/// Prepare internal `PSQLPy` statement
///
/// # Errors
/// May return error if there is some problem with DB communication.
pub async fn prepare_statement(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
) -> PSQLPyResult<PsqlpyStatement> {
StatementBuilder::new(&querystring, ¶meters, self, Some(true))
.build()
.await
}
/// Execute prepared `PSQLPy` statement.
///
/// # Errors
/// May return error if there is some problem with DB communication.
pub async fn execute_statement(
&self,
statement: &PsqlpyStatement,
) -> PSQLPyResult<PSQLDriverPyQueryResult> {
let result = self
.query(statement.statement_query()?, &statement.params())
.await?;
Ok(PSQLDriverPyQueryResult::new(result))
}
/// Execute raw query with parameters.
///
/// # Errors
/// May return error if there is some problem with DB communication.
pub async fn execute(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<PSQLDriverPyQueryResult> {
let statement = StatementBuilder::new(&querystring, ¶meters, self, prepared)
.build()
.await?;
let prepared = prepared.unwrap_or(true);
let result = if prepared {
self.query(statement.statement_query()?, &statement.params())
.await
} else {
self.query_typed(statement.raw_query(), &statement.params_typed())
.await
};
let return_result = result.map_err(|err| {
RustPSQLDriverError::ConnectionExecuteError(format!(
"Cannot execute query, error - {err}"
))
})?;
Ok(PSQLDriverPyQueryResult::new(return_result))
}
/// Execute many queries without return.
///
/// # Errors
/// May return error if there is some problem with DB communication.
pub async fn execute_many(
&self,
querystring: String,
parameters: Option<Vec<pyo3::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, &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}"
)));
}
}
Ok(())
}
/// Execute raw query with parameters. Return one raw row
///
/// # Errors
/// May return error if there is some problem with DB communication.
/// Or if cannot build statement.
pub async fn fetch_row_raw(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<Row> {
let statement = StatementBuilder::new(&querystring, ¶meters, 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}")))?
};
Ok(result)
}
/// Execute raw query with parameters. Return one row
///
/// # Errors
/// May return error if there is some problem with DB communication.
/// Or if cannot build statement.
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?;
Ok(PSQLDriverSinglePyQueryResult::new(result))
}
/// Execute raw query with parameters. Return single python object
///
/// # Errors
/// May return error if there is some problem with DB communication.
/// Or if cannot build statement.
pub async fn fetch_val(
&self,
querystring: String,
parameters: Option<pyo3::Py<PyAny>>,
prepared: Option<bool>,
) -> PSQLPyResult<pyo3::Py<PyAny>> {
let result = self
.fetch_row_raw(querystring, parameters, prepared)
.await?;
Python::with_gil(|gil| match result.columns().first() {
Some(first_column) => postgres_to_py(gil, &result, first_column, 0, &None),
None => Ok(gil.None()),
})
}
/// Create new sink for COPY operation.
///
/// # Errors
/// May return error if there is some problem with DB communication.
/// Or if cannot build statement.
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.connection.copy_in(statement).await?)
}
PSQLPyConnection::SingleConnection(sconn) => {
return Ok(sconn.connection.copy_in(statement).await?)
}
}
}
/// Create and open new transaction.
///
/// Unsafe here isn't a problem cuz it is stored within
/// the struct with the connection created this transaction.
///
/// # Errors
/// May return error if there is some problem with DB communication.
/// Or if cannot build statement.
pub async fn transaction(&mut self) -> PSQLPyResult<PSQLPyTransaction> {
match self {
PSQLPyConnection::PoolConn(conn) => {
let transaction = unsafe {
std::mem::transmute::<dp_Transaction<'_>, dp_Transaction<'static>>(
conn.connection.transaction().await?,
)
};
Ok(PSQLPyTransaction::PoolTransaction(transaction))
}
PSQLPyConnection::SingleConnection(conn) => {
let transaction = unsafe {
std::mem::transmute::<tp_Transaction<'_>, tp_Transaction<'static>>(
conn.connection.transaction().await?,
)
};
Ok(PSQLPyTransaction::SingleTransaction(transaction))
}
}
}
/// Create new Portal (server-side byte cursor).
///
/// # Errors
/// May return error if there is some problem with DB communication.
/// Or if cannot build statement.
pub async fn portal(
&mut self,
querystring: Option<&String>,
parameters: &Option<pyo3::Py<PyAny>>,
statement: Option<&PsqlpyStatement>,
) -> PSQLPyResult<(PSQLPyTransaction, tp_Portal)> {
let stmt = if let Some(stmt) = statement {
stmt
} else {
let Some(querystring) = querystring else {
return Err(RustPSQLDriverError::ConnectionExecuteError(
"Can't create cursor without querystring".into(),
));
};
&StatementBuilder::new(querystring, parameters, self, Some(false))
.build()
.await?
};
let transaction = self.transaction().await?;
let inner_portal = transaction.portal(stmt.raw_query(), &stmt.params()).await?;
Ok((transaction, inner_portal))
}
}