Skip to content

Commit a38415c

Browse files
committed
Added support for any custom python class in QueryResult
1 parent 431d68c commit a38415c

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

README.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,14 +119,48 @@ As connection can be closed in different situations on various sides you can sel
119119
`DEALLOCATE ALL` and `DISCARD PLAN`, so that the statement cache is not
120120
rendered ineffective.
121121

122+
## Results from querying
123+
You have some options to get results from the query.
124+
`execute()` method, for example, returns `QueryResult` and this class can be converted into `list` of `dict`s - `list[dict[Any, Any]]` or into any Python class (`pydantic` model, as an example).
125+
126+
Let's see some code:
127+
```python
128+
from typing import Any
129+
130+
from pydantic import BaseModel
131+
from psqlpy import PSQLPool, QueryResult
132+
133+
134+
class ExampleModel(BaseModel):
135+
id: int
136+
username: str
137+
138+
139+
db_pool = PSQLPool(
140+
dsn="postgres://postgres:postgres@localhost:5432/postgres",
141+
max_db_pool_size=2,
142+
)
143+
144+
async def main() -> None:
145+
await db_pool.startup()
146+
147+
res: QueryResult = await db_pool.execute(
148+
"SELECT * FROM users",
149+
)
150+
151+
pydantic_res: list[ExampleModel] = res.as_class(
152+
as_class=ExampleModel,
153+
)
154+
```
155+
122156
## Query parameters
123157

124158
You can pass parameters into queries.
125159
Parameters can be passed in any `execute` method as the second parameter, it must be a list.
126160
Any placeholder must be marked with `$< num>`.
127161

128162
```python
129-
res: list[dict[str, Any]] = await db_pool.execute(
163+
res: QueryResult = await db_pool.execute(
130164
"SELECT * FROM users WHERE user_id = $1 AND first_name = $2",
131165
[100, "RustDriver"],
132166
)

0 commit comments

Comments
 (0)