Skip to content

Commit ddfd90f

Browse files
authored
Merge pull request #141 from psqlpy-python/new-pyo3
Support new pyo3 interfaces
2 parents d504d80 + 72f992a commit ddfd90f

22 files changed

+373
-368
lines changed

.pre-commit-config.yaml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ ci:
33

44
repos:
55
- repo: https://github.com/pre-commit/pre-commit-hooks
6-
rev: v2.1.0
6+
rev: v5.0.0
77
hooks:
88
- id: trailing-whitespace
99
- repo: https://github.com/pre-commit/mirrors-mypy
@@ -58,6 +58,8 @@ repos:
5858
- clippy::all
5959
- -W
6060
- clippy::pedantic
61+
# - -D
62+
# - warnings
6163

6264
- id: check
6365
types:

python/psqlpy/_internal/__init__.pyi

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -815,16 +815,6 @@ class Connection:
815815
816816
Return representation of prepared statement.
817817
"""
818-
async def commit(self: Self) -> None:
819-
"""Commit the transaction.
820-
821-
Do nothing if there is no active transaction.
822-
"""
823-
async def rollback(self: Self) -> None:
824-
"""Rollback the transaction.
825-
826-
Do nothing if there is no active transaction.
827-
"""
828818
async def execute(
829819
self: Self,
830820
querystring: str,

src/connection/impls.rs

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ where
3131
) -> PSQLPyResult<()> {
3232
let start_qs = self.build_start_qs(isolation_level, read_variant, deferrable);
3333
self.batch_execute(start_qs.as_str()).await.map_err(|err| {
34-
RustPSQLDriverError::TransactionBeginError(
35-
format!("Cannot start transaction due to - {err}").into(),
36-
)
34+
RustPSQLDriverError::TransactionBeginError(format!(
35+
"Cannot start transaction due to - {err}"
36+
))
3737
})?;
3838

3939
Ok(())
@@ -65,7 +65,7 @@ impl Connection for SingleConnection {
6565
if !prepared {
6666
self.drop_prepared(&prepared_stmt).await?;
6767
}
68-
return Ok(prepared_stmt);
68+
Ok(prepared_stmt)
6969
}
7070

7171
async fn drop_prepared(&self, stmt: &Statement) -> PSQLPyResult<()> {
@@ -116,28 +116,27 @@ impl StartTransaction for SingleConnection {
116116
read_variant: Option<ReadVariant>,
117117
deferrable: Option<bool>,
118118
) -> PSQLPyResult<()> {
119-
let res = self
120-
._start_transaction(isolation_level, read_variant, deferrable)
119+
self._start_transaction(isolation_level, read_variant, deferrable)
121120
.await?;
122121
self.in_transaction = true;
123122

124-
Ok(res)
123+
Ok(())
125124
}
126125
}
127126

128127
impl CloseTransaction for SingleConnection {
129128
async fn commit(&mut self) -> PSQLPyResult<()> {
130-
let res = self._commit().await?;
129+
self._commit().await?;
131130
self.in_transaction = false;
132131

133-
Ok(res)
132+
Ok(())
134133
}
135134

136135
async fn rollback(&mut self) -> PSQLPyResult<()> {
137-
let res = self._rollback().await?;
136+
self._rollback().await?;
138137
self.in_transaction = false;
139138

140-
Ok(res)
139+
Ok(())
141140
}
142141
}
143142

@@ -149,7 +148,7 @@ impl Connection for PoolConnection {
149148

150149
let prepared = self.connection.prepare(query).await?;
151150
self.drop_prepared(&prepared).await?;
152-
return Ok(prepared);
151+
Ok(prepared)
153152
}
154153

155154
async fn drop_prepared(&self, stmt: &Statement) -> PSQLPyResult<()> {
@@ -208,17 +207,17 @@ impl StartTransaction for PoolConnection {
208207

209208
impl CloseTransaction for PoolConnection {
210209
async fn commit(&mut self) -> PSQLPyResult<()> {
211-
let res = self._commit().await?;
210+
self._commit().await?;
212211
self.in_transaction = false;
213212

214-
Ok(res)
213+
Ok(())
215214
}
216215

217216
async fn rollback(&mut self) -> PSQLPyResult<()> {
218-
let res = self._rollback().await?;
217+
self._rollback().await?;
219218
self.in_transaction = false;
220219

221-
Ok(res)
220+
Ok(())
222221
}
223222
}
224223

@@ -407,14 +406,14 @@ impl PSQLPyConnection {
407406

408407
for statement in statements {
409408
let querystring_result = if prepared {
410-
let prepared_stmt = &self.prepare(&statement.raw_query(), true).await;
409+
let prepared_stmt = &self.prepare(statement.raw_query(), true).await;
411410
if let Err(error) = prepared_stmt {
412411
return Err(RustPSQLDriverError::ConnectionExecuteError(format!(
413412
"Cannot prepare statement in execute_many, operation rolled back {error}",
414413
)));
415414
}
416415
self.query(
417-
&self.prepare(&statement.raw_query(), true).await?,
416+
&self.prepare(statement.raw_query(), true).await?,
418417
&statement.params(),
419418
)
420419
.await
@@ -429,7 +428,7 @@ impl PSQLPyConnection {
429428
}
430429
}
431430

432-
return Ok(());
431+
Ok(())
433432
}
434433

435434
pub async fn fetch_row_raw(
@@ -447,7 +446,7 @@ impl PSQLPyConnection {
447446
let result = if prepared {
448447
self.query_one(
449448
&self
450-
.prepare(&statement.raw_query(), true)
449+
.prepare(statement.raw_query(), true)
451450
.await
452451
.map_err(|err| {
453452
RustPSQLDriverError::ConnectionExecuteError(format!(
@@ -464,7 +463,7 @@ impl PSQLPyConnection {
464463
.map_err(|err| RustPSQLDriverError::ConnectionExecuteError(format!("{err}")))?
465464
};
466465

467-
return Ok(result);
466+
Ok(result)
468467
}
469468

470469
pub async fn fetch_row(
@@ -477,7 +476,7 @@ impl PSQLPyConnection {
477476
.fetch_row_raw(querystring, parameters, prepared)
478477
.await?;
479478

480-
return Ok(PSQLDriverSinglePyQueryResult::new(result));
479+
Ok(PSQLDriverSinglePyQueryResult::new(result))
481480
}
482481

483482
pub async fn fetch_val(
@@ -490,10 +489,10 @@ impl PSQLPyConnection {
490489
.fetch_row_raw(querystring, parameters, prepared)
491490
.await?;
492491

493-
return Python::with_gil(|gil| match result.columns().first() {
492+
Python::with_gil(|gil| match result.columns().first() {
494493
Some(first_column) => postgres_to_py(gil, &result, first_column, 0, &None),
495494
None => Ok(gil.None()),
496-
});
495+
})
497496
}
498497

499498
pub async fn copy_in<T, U>(&self, statement: &T) -> PSQLPyResult<CopyInSink<U>>

src/connection/traits.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
use postgres_types::{ToSql, Type};
2-
use pyo3::PyAny;
32
use tokio_postgres::{Row, Statement, ToStatement};
43

54
use crate::exceptions::rust_errors::PSQLPyResult;

src/driver/connection_pool.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ impl ConnectionPool {
238238
prepare: Option<bool>,
239239
) -> Self {
240240
ConnectionPool {
241-
pool: pool,
241+
pool,
242242
pg_config: Arc::new(pg_config),
243243
pool_conf: ConnectionPoolConf::new(ca_file, ssl_mode, prepare.unwrap_or(true)),
244244
}

src/driver/cursor.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ impl Cursor {
5959
let Some(portal) = &self.inner else {
6060
return Err(RustPSQLDriverError::TransactionClosedError);
6161
};
62-
transaction.query_portal(&portal, size).await
62+
transaction.query_portal(portal, size).await
6363
}
6464
}
6565

@@ -157,7 +157,7 @@ impl Cursor {
157157
fn __anext__(&self) -> PSQLPyResult<Option<PyObject>> {
158158
let txid = self.transaction.clone();
159159
let portal = self.inner.clone();
160-
let size = self.array_size.clone();
160+
let size = self.array_size;
161161

162162
let py_future = Python::with_gil(move |gil| {
163163
rustdriver_future(gil, async move {
@@ -167,7 +167,7 @@ impl Cursor {
167167
let Some(portal) = &portal else {
168168
return Err(RustPSQLDriverError::TransactionClosedError);
169169
};
170-
let result = txid.query_portal(&portal, size).await?;
170+
let result = txid.query_portal(portal, size).await?;
171171

172172
if result.is_empty() {
173173
return Err(PyStopAsyncIteration::new_err(
@@ -192,7 +192,7 @@ impl Cursor {
192192
let (txid, inner_portal) = match &self.querystring {
193193
Some(querystring) => {
194194
write_conn_g
195-
.portal(Some(&querystring), &self.parameters, None)
195+
.portal(Some(querystring), &self.parameters, None)
196196
.await?
197197
}
198198
None => {
@@ -201,7 +201,7 @@ impl Cursor {
201201
"Cannot start cursor".into(),
202202
));
203203
};
204-
write_conn_g.portal(None, &None, Some(&statement)).await?
204+
write_conn_g.portal(None, &None, Some(statement)).await?
205205
}
206206
};
207207

src/driver/transaction.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ impl Transaction {
7878
.start_transaction(isolation_level, read_variant, deferrable)
7979
.await?;
8080

81-
return Ok(self_);
81+
Ok(self_)
8282
}
8383

8484
#[allow(clippy::needless_pass_by_value)]
@@ -114,7 +114,7 @@ impl Transaction {
114114
let mut self_ = self_.borrow_mut(gil);
115115
self_.conn = None;
116116
});
117-
return Err(RustPSQLDriverError::RustPyError(py_err));
117+
Err(RustPSQLDriverError::RustPyError(py_err))
118118
}
119119
}
120120

@@ -277,7 +277,7 @@ impl Transaction {
277277
let mut futures = vec![];
278278
if let Some(queries) = queries {
279279
let gil_result = pyo3::Python::with_gil(|gil| -> PyResult<()> {
280-
for single_query in queries.into_bound(gil).iter() {
280+
for single_query in queries.into_bound(gil).try_iter() {
281281
let query_tuple = single_query.downcast::<PyTuple>().map_err(|err| {
282282
RustPSQLDriverError::PyToRustValueConversionError(format!(
283283
"Cannot cast to tuple: {err}",

src/query_result.rs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
1-
use pyo3::{
2-
prelude::*,
3-
pyclass, pymethods,
4-
types::{PyDict, PyTuple},
5-
Py, PyAny, Python, ToPyObject,
6-
};
1+
use pyo3::{prelude::*, pyclass, pymethods, types::PyDict, IntoPyObjectExt, Py, PyAny, Python};
72
use tokio_postgres::Row;
83

94
use crate::{exceptions::rust_errors::PSQLPyResult, value_converter::to_python::postgres_to_py};
@@ -24,7 +19,7 @@ fn row_to_dict<'a>(
2419
let python_dict = PyDict::new(py);
2520
for (column_idx, column) in postgres_row.columns().iter().enumerate() {
2621
let python_type = postgres_to_py(py, postgres_row, column, column_idx, custom_decoders)?;
27-
python_dict.set_item(column.name().to_object(py), python_type)?;
22+
python_dict.set_item(column.name().into_py_any(py)?, python_type)?;
2823
}
2924
Ok(python_dict)
3025
}
@@ -72,7 +67,7 @@ impl PSQLDriverPyQueryResult {
7267
for row in &self.inner {
7368
result.push(row_to_dict(py, row, &custom_decoders)?);
7469
}
75-
Ok(result.to_object(py))
70+
Ok(result.into_py_any(py)?)
7671
}
7772

7873
/// Convert result from database to any class passed from Python.
@@ -83,14 +78,14 @@ impl PSQLDriverPyQueryResult {
8378
/// postgres type to python or create new Python class.
8479
#[allow(clippy::needless_pass_by_value)]
8580
pub fn as_class<'a>(&'a self, py: Python<'a>, as_class: Py<PyAny>) -> PSQLPyResult<Py<PyAny>> {
86-
let mut res: Vec<Py<PyAny>> = vec![];
81+
let mut result: Vec<Py<PyAny>> = vec![];
8782
for row in &self.inner {
8883
let pydict: pyo3::Bound<'_, PyDict> = row_to_dict(py, row, &None)?;
8984
let convert_class_inst = as_class.call(py, (), Some(&pydict))?;
90-
res.push(convert_class_inst);
85+
result.push(convert_class_inst);
9186
}
9287

93-
Ok(res.to_object(py))
88+
Ok(result.into_py_any(py)?)
9489
}
9590

9691
/// Convert result from database with function passed from Python.
@@ -107,13 +102,13 @@ impl PSQLDriverPyQueryResult {
107102
row_factory: Py<PyAny>,
108103
custom_decoders: Option<Py<PyDict>>,
109104
) -> PSQLPyResult<Py<PyAny>> {
110-
let mut res: Vec<Py<PyAny>> = vec![];
105+
let mut result: Vec<Py<PyAny>> = vec![];
111106
for row in &self.inner {
112107
let pydict: pyo3::Bound<'_, PyDict> = row_to_dict(py, row, &custom_decoders)?;
113108
let row_factory_class = row_factory.call(py, (pydict,), None)?;
114-
res.push(row_factory_class);
109+
result.push(row_factory_class);
115110
}
116-
Ok(res.to_object(py))
111+
Ok(result.into_py_any(py)?)
117112
}
118113
}
119114

@@ -154,7 +149,7 @@ impl PSQLDriverSinglePyQueryResult {
154149
py: Python<'_>,
155150
custom_decoders: Option<Py<PyDict>>,
156151
) -> PSQLPyResult<Py<PyAny>> {
157-
Ok(row_to_dict(py, &self.inner, &custom_decoders)?.to_object(py))
152+
Ok(row_to_dict(py, &self.inner, &custom_decoders)?.into_py_any(py)?)
158153
}
159154

160155
/// Convert result from database to any class passed from Python.
@@ -184,7 +179,7 @@ impl PSQLDriverSinglePyQueryResult {
184179
row_factory: Py<PyAny>,
185180
custom_decoders: Option<Py<PyDict>>,
186181
) -> PSQLPyResult<Py<PyAny>> {
187-
let pydict = row_to_dict(py, &self.inner, &custom_decoders)?.to_object(py);
182+
let pydict = row_to_dict(py, &self.inner, &custom_decoders)?.into_py_any(py)?;
188183
Ok(row_factory.call(py, (pydict,), None)?)
189184
}
190185
}

src/row_factories.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use pyo3::{
22
pyclass, pyfunction, pymethods,
33
types::{PyDict, PyDictMethods, PyModule, PyModuleMethods, PyTuple},
4-
wrap_pyfunction, Bound, Py, PyAny, PyResult, Python, ToPyObject,
4+
wrap_pyfunction, Bound, IntoPyObject, Py, PyAny, PyResult, Python,
55
};
66

77
use crate::exceptions::rust_errors::{PSQLPyResult, RustPSQLDriverError};
@@ -14,7 +14,10 @@ fn tuple_row(py: Python<'_>, dict_: Py<PyAny>) -> PSQLPyResult<Py<PyAny>> {
1414
"as_tuple accepts only dict as a parameter".into(),
1515
)
1616
})?;
17-
Ok(PyTuple::new_bound(py, dict_.items()).to_object(py))
17+
match PyTuple::new(py, dict_.items())?.into_pyobject(py) {
18+
Ok(x) => Ok(x.unbind().into_any()),
19+
_ => unreachable!(),
20+
}
1821
}
1922

2023
#[pyclass]
@@ -24,7 +27,7 @@ struct class_row(Py<PyAny>);
2427
#[pymethods]
2528
impl class_row {
2629
#[new]
27-
fn constract_class(class_: Py<PyAny>) -> Self {
30+
fn construct_class(class_: Py<PyAny>) -> Self {
2831
Self(class_)
2932
}
3033

@@ -35,7 +38,7 @@ impl class_row {
3538
"as_tuple accepts only dict as a parameter".into(),
3639
)
3740
})?;
38-
Ok(self.0.call_bound(py, (), Some(dict_))?)
41+
Ok(self.0.call(py, (), Some(dict_))?)
3942
}
4043
}
4144

0 commit comments

Comments
 (0)