-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path__init__.pyi
985 lines (792 loc) · 29.2 KB
/
__init__.pyi
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
import types
from enum import Enum
from typing import Any, Callable, Optional, TypeVar
from typing_extensions import Self
_CustomClass = TypeVar(
"_CustomClass",
)
class QueryResult:
"""Result."""
def result(
self: Self,
custom_decoders: dict[str, Callable[[bytes], Any]] | None = None,
) -> list[dict[Any, Any]]:
"""Return result from database as a list of dicts."""
def as_class(
self: Self,
as_class: Callable[..., _CustomClass],
) -> list[_CustomClass]:
"""Convert results to passed class.
The main goal of this method is pydantic,
msgspec and dataclasses support.
### Parameters:
- `as_class`: Any callable python class for the results.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
class ExampleOfAsClass:
def __init__(self, username: str) -> None:
self.username = username
async def main() -> None:
db_pool = PSQLPool()
query_result: QueryResult = await db_pool.execute(
"SELECT username FROM users WHERE id = $1",
[100],
)
class_results: List[ExampleOfAsClass] = query_result.as_class(
as_class=ExampleOfAsClass,
)
```
"""
class SingleQueryResult:
"""Single result."""
def result(self: Self) -> dict[Any, Any]:
"""Return result from database as a dict."""
def as_class(
self: Self,
as_class: Callable[..., _CustomClass],
) -> list[_CustomClass]:
"""Convert results to passed class.
The main goal of this method is pydantic,
msgspec and dataclasses support.
### Parameters:
- `as_class`: Any callable python class for the results.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
class ExampleOfAsClass:
def __init__(self, username: str) -> None:
self.username = username
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
async with connection.transaction() as trans:
query_result: SingleQueryResult = await trans.fetch_row(
"SELECT username FROM users WHERE id = $1",
[100],
)
class_result: ExampleOfAsClass = query_result.as_class(
as_class=ExampleOfAsClass,
)
```
"""
class IsolationLevel(Enum):
"""Class for Isolation Level for transactions."""
ReadUncommitted = 1
ReadCommitted = 2
RepeatableRead = 3
Serializable = 4
class ReadVariant(Enum):
"""Class for Read Variant for transaction."""
ReadOnly = 1
ReadWrite = 2
class ConnRecyclingMethod(Enum):
"""Possible methods of how a connection is recycled.
The default is [`Fast`] which does not check the connection health or
perform any clean-up queries.
# Description:
## Fast:
Only run [`is_closed()`] when recycling existing connections.
Unless you have special needs this is a safe choice.
## Verified:
Run [`is_closed()`] and execute a test query.
This is slower, but guarantees that the database connection is ready to
be used. Normally, [`is_closed()`] should be enough to filter
out bad connections, but under some circumstances (i.e. hard-closed
network connections) it's possible that [`is_closed()`]
returns `false` while the connection is dead. You will receive an error
on your first query then.
## Clean:
Like [`Verified`] query method, but instead use the following sequence
of statements which guarantees a pristine connection:
```sql
CLOSE ALL;
SET SESSION AUTHORIZATION DEFAULT;
RESET ALL;
UNLISTEN *;
SELECT pg_advisory_unlock_all();
DISCARD TEMP;
DISCARD SEQUENCES;
```
This is similar to calling `DISCARD ALL`. but doesn't call
`DEALLOCATE ALL` and `DISCARD PLAN`, so that the statement cache is not
rendered ineffective.
"""
Fast = 1
Verified = 2
Clean = 3
class Cursor:
"""Represent opened cursor in a transaction.
It can be used as an asynchronous iterator.
"""
def __aiter__(self: Self) -> Self: ...
async def __anext__(self: Self) -> QueryResult: ...
async def __aenter__(self: Self) -> Self: ...
async def __aexit__(
self: Self,
exception_type: type[BaseException] | None,
exception: BaseException | None,
traceback: types.TracebackType | None,
) -> None: ...
async def start(self: Self) -> None:
"""Start the cursor.
Execute DECLARE command for the cursor.
"""
async def close(self: Self) -> None:
"""Close the cursor.
Execute CLOSE command for the cursor.
"""
async def fetch(
self: Self,
fetch_number: int | None = None,
) -> QueryResult:
"""Fetch next <fetch_number> rows.
By default fetches 10 next rows.
### Parameters:
- `fetch_number`: how many rows need to fetch.
### Returns:
result as `QueryResult`.
"""
async def fetch_next(
self: Self,
) -> QueryResult:
"""Fetch next row.
Execute FETCH NEXT
### Returns:
result as `QueryResult`.
"""
async def fetch_prior(
self: Self,
) -> QueryResult:
"""Fetch previous row.
Execute FETCH PRIOR
### Returns:
result as `QueryResult`.
"""
async def fetch_first(
self: Self,
) -> QueryResult:
"""Fetch first row.
Execute FETCH FIRST
### Returns:
result as `QueryResult`.
"""
async def fetch_last(
self: Self,
) -> QueryResult:
"""Fetch last row.
Execute FETCH LAST
### Returns:
result as `QueryResult`.
"""
async def fetch_absolute(
self: Self,
absolute_number: int,
) -> QueryResult:
"""Fetch absolute rows.
Execute FETCH ABSOLUTE <absolute_number>.
### Returns:
result as `QueryResult`.
"""
async def fetch_relative(
self: Self,
relative_number: int,
) -> QueryResult:
"""Fetch absolute rows.
Execute FETCH RELATIVE <relative_number>.
### Returns:
result as `QueryResult`.
"""
async def fetch_forward_all(
self: Self,
) -> QueryResult:
"""Fetch forward all rows.
Execute FETCH FORWARD ALL.
### Returns:
result as `QueryResult`.
"""
async def fetch_backward(
self: Self,
backward_count: int,
) -> QueryResult:
"""Fetch backward rows.
Execute FETCH BACKWARD <backward_count>.
### Returns:
result as `QueryResult`.
"""
async def fetch_backward_all(
self: Self,
) -> QueryResult:
"""Fetch backward all rows.
Execute FETCH BACKWARD ALL.
### Returns:
result as `QueryResult`.
"""
class Transaction:
"""Single connection for executing queries.
It represents transaction in database.
You can create it only from `PSQLPool` with method
`.transaction()`.
"""
async def __aenter__(self: Self) -> Self: ...
async def __aexit__(
self: Self,
exception_type: type[BaseException] | None,
exception: BaseException | None,
traceback: types.TracebackType | None,
) -> None: ...
async def begin(self: Self) -> None:
"""Start the transaction.
Execute `BEGIN`.
`begin()` can be called only once per transaction.
"""
async def commit(self: Self) -> None:
"""Commit the transaction.
Execute `COMMIT`.
`commit()` can be called only once per transaction.
"""
async def execute(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
prepared: bool = True,
) -> QueryResult:
"""Execute the query.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.begin()
query_result: QueryResult = await transaction.execute(
"SELECT username FROM users WHERE id = $1",
[100],
)
dict_result: List[Dict[Any, Any]] = query_result.result()
# You must call commit manually
await transaction.commit()
```
"""
async def execute_many(
self: Self,
querystring: str,
parameters: list[list[Any]] | None = None,
prepared: bool = True,
) -> None: ...
"""Execute query multiple times with different parameters.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.begin()
query_result: QueryResult = await transaction.execute_many(
"INSERT INTO users (name, age) VALUES ($1, $2)",
[["boba", 10], ["boba", 20]],
)
dict_result: List[Dict[Any, Any]] = query_result.result()
# You must call commit manually
await transaction.commit()
```
"""
async def fetch_row(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
prepared: bool = True,
) -> SingleQueryResult:
"""Fetch exaclty single row from query.
Query must return exactly one row, otherwise error will be raised.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.begin()
query_result: SingleQueryResult = await transaction.fetch_row(
"SELECT username FROM users WHERE id = $1",
[100],
)
dict_result: Dict[Any, Any] = query_result.result()
# You must call commit manually
await transaction.commit()
```
"""
async def fetch_val(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
prepared: bool = True,
) -> Any | None:
"""Execute the query and return first value of the first row.
Returns an error if the query does not return exactly one row.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Raises
- `RustPSQLDriverPyBaseError`: if the query does not
return exactly one row
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.begin()
value: Any = await transaction.fetch_val(
"SELECT username FROM users WHERE id = $1",
[100],
)
```
"""
async def pipeline(
self,
queries: list[tuple[str, list[Any] | None]],
prepared: bool = True,
) -> list[QueryResult]:
"""Execute queries in pipeline.
Pipelining can improve performance in use cases in which multiple,
independent queries need to be executed.
In a traditional workflow,
each query is sent to the server after the previous query completes.
In contrast, pipelining allows the client to send all of the
queries to the server up front, minimizing time spent
by one side waiting for the other to finish sending data:
```
Sequential Pipelined
| Client | Server | | Client | Server |
|----------------|-----------------| |----------------|-----------------|
| send query 1 | | | send query 1 | |
| | process query 1 | | send query 2 | process query 1 |
| receive rows 1 | | | send query 3 | process query 2 |
| send query 2 | | | receive rows 1 | process query 3 |
| | process query 2 | | receive rows 2 | |
| receive rows 2 | | | receive rows 3 | |
| send query 3 | |
| | process query 3 |
| receive rows 3 | |
```
Read more: https://docs.rs/tokio-postgres/latest/tokio_postgres/#pipelining
### Parameters:
- `queries`: queries with parameters to execute.
- `prepared`: should the querystring/querystrings be prepared before the request.
By default any querystrings will be prepared.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
results: list[QueryResult] = await transaction.pipeline(
queries=[
(
"SELECT username FROM users WHERE id = $1",
[100],
),
(
"SELECT some_data FROM profiles",
None,
),
(
"INSERT INTO users (username, id) VALUES ($1, $2)",
["PSQLPy", 1],
),
]
)
```
"""
async def create_savepoint(self: Self, savepoint_name: str) -> None:
"""Create new savepoint.
One `savepoint_name` can be used once.
If you specify the same savepoint name more than once
exception will be raised.
### Parameters:
- `savepoint_name`: name of the savepoint.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.create_savepoint("my_savepoint")
await transaction.execute(...)
await transaction.rollback_savepoint("my_savepoint")
```
"""
async def rollback(self: Self) -> None:
"""Rollback all queries in the transaction.
It can be done only one, after execution transaction marked
as `done`.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.execute(...)
await transaction.rollback()
```
"""
async def rollback_savepoint(self: Self, savepoint_name: str) -> None:
"""ROLLBACK to the specified `savepoint_name`.
If you specified wrong savepoint name
then exception will be raised.
### Parameters:
- `savepoint_name`: name of the SAVEPOINT.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.savepoint("my_savepoint")
await transaction.execute(...)
await transaction.rollback_savepoint("my_savepoint")
```
"""
async def release_savepoint(self: Self, savepoint_name: str) -> None:
"""Execute ROLLBACK TO SAVEPOINT.
If you specified wrong savepoint name
then exception will be raised.
### Parameters:
- `savepoint_name`: name of the SAVEPOINT.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = connection.transaction()
await transaction.savepoint("my_savepoint")
await transaction.release_savepoint
```
"""
def cursor(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
fetch_number: int | None = None,
scroll: bool | None = None,
prepared: bool = True,
) -> Cursor:
"""Create new cursor object.
Cursor can be used as an asynchronous iterator.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `fetch_number`: how many rows need to fetch.
- `scroll`: SCROLL or NO SCROLL cursor.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Returns:
new initialized cursor.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
transaction = await connection.transaction()
cursor = transaction.cursor(
querystring="SELECT * FROM users WHERE username = $1",
parameters=["Some_Username"],
fetch_number=5,
)
await cursor.start()
async for fetched_result in cursor:
dict_result: List[Dict[Any, Any]] = fetched_result.result()
... # do something with this result.
await cursor.close()
```
"""
class Connection:
"""Connection from Database Connection Pool.
It can be created only from connection pool.
"""
async def execute(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
prepared: bool = True,
) -> QueryResult:
"""Execute the query.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Returns:
query result as `QueryResult`
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
query_result: QueryResult = await connection.execute(
"SELECT username FROM users WHERE id = $1",
[100],
)
dict_result: List[Dict[Any, Any]] = query_result.result()
```
"""
async def execute_many(
self: Self,
querystring: str,
parameters: list[list[Any]] | None = None,
prepared: bool = True,
) -> None: ...
"""Execute query multiple times with different parameters.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
await connection.execute_many(
"INSERT INTO users (name, age) VALUES ($1, $2)",
[["boba", 10], ["boba", 20]],
)
```
"""
async def fetch_row(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
prepared: bool = True,
) -> SingleQueryResult:
"""Fetch exaclty single row from query.
Query must return exactly one row, otherwise error will be raised.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
query_result: SingleQueryResult = await transaction.fetch_row(
"SELECT username FROM users WHERE id = $1",
[100],
)
dict_result: Dict[Any, Any] = query_result.result()
```
"""
async def fetch_val(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
prepared: bool = True,
) -> Any:
"""Execute the query and return first value of the first row.
Returns an error if the query does not return exactly one row.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Raises
- `RustPSQLDriverPyBaseError`: if the query does not
return exactly one row
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
connection = await db_pool.connection()
# this will be an int value
query_result_value = await connection.fetch_row(
"SELECT COUNT(*) FROM users WHERE id > $1",
[100],
)
```
"""
def transaction(
self,
isolation_level: IsolationLevel | None = None,
read_variant: ReadVariant | None = None,
deferrable: bool | None = None,
) -> Transaction:
"""Create new transaction.
### Parameters:
- `isolation_level`: configure isolation level of the transaction.
- `read_variant`: configure read variant of the transaction.
- `deferrable`: configure deferrable of the transaction.
"""
class ConnectionPool:
"""Connection pool for executing queries.
This is the main entrypoint in the library.
"""
def __init__(
self: Self,
dsn: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
host: Optional[str] = None,
port: Optional[int] = None,
db_name: Optional[str] = None,
max_db_pool_size: int = 2,
conn_recycling_method: Optional[ConnRecyclingMethod] = None,
) -> None:
"""Create new PostgreSQL connection pool.
It connects to the database and create pool.
You cannot set the minimum size for the connection
pool, by default it is 1.
This connection pool can:
- Startup itself with `startup` method
- Execute queries and return `QueryResult` class as a result
- Create new instance of `Transaction`
### Parameters:
- `dsn`: full dsn connection string.
`postgres://postgres:postgres@localhost:5432/postgres?target_session_attrs=read-write`
- `username`: username of the user in postgres
- `password`: password of the user in postgres
- `host`: host of postgres
- `port`: port of postgres
- `db_name`: name of the database in postgres
- `max_db_pool_size`: maximum size of the connection pool
- `conn_recycling_method`: how a connection is recycled.
"""
async def execute(
self: Self,
querystring: str,
parameters: list[Any] | None = None,
prepared: bool = True,
) -> QueryResult:
"""Execute the query.
Querystring can contain `$<number>` parameters
for converting them in the driver side.
### Parameters:
- `querystring`: querystring to execute.
- `parameters`: list of parameters to pass in the query.
- `prepared`: should the querystring be prepared before the request.
By default any querystring will be prepared.
### Example:
```python
import asyncio
from psqlpy import PSQLPool, QueryResult
async def main() -> None:
db_pool = PSQLPool()
query_result: QueryResult = await psqlpy.execute(
"SELECT username FROM users WHERE id = $1",
[100],
)
dict_result: List[Dict[Any, Any]] = query_result.result()
# you don't need to close the pool,
# it will be dropped on Rust side.
```
"""
async def connection(self: Self) -> Connection:
"""Create new connection.
It acquires new connection from the database pool.
"""
def close(self: Self) -> None:
"""Close the connection pool."""
def create_pool(
dsn: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
host: Optional[str] = None,
port: Optional[int] = None,
db_name: Optional[str] = None,
max_db_pool_size: int = 2,
conn_recycling_method: Optional[ConnRecyclingMethod] = None,
) -> ConnectionPool:
"""Create new connection pool.
### Parameters:
- `dsn`: full dsn connection string.
`postgres://postgres:postgres@localhost:5432/postgres?target_session_attrs=read-write`
- `username`: username of the user in postgres
- `password`: password of the user in postgres
- `host`: host of postgres
- `port`: port of postgres
- `db_name`: name of the database in postgres
- `max_db_pool_size`: maximum size of the connection pool
- `conn_recycling_method`: how a connection is recycled.
"""
async def connect(
dsn: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
host: Optional[str] = None,
port: Optional[int] = None,
db_name: Optional[str] = None,
) -> Connection:
"""Create new single connection.
### Parameters:
- `dsn`: full dsn connection string.
`postgres://postgres:postgres@localhost:5432/postgres?target_session_attrs=read-write`
- `username`: username of the user in the PostgreSQL
- `password`: password of the user in PostgreSQL
- `host`: host of the PostgreSQL
- `port`: port of the PostgreSQL
- `db_name`: name of the database in PostgreSQL
"""