fastasyncpg 0.1.0__tar.gz → 0.1.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {fastasyncpg-0.1.0/fastasyncpg.egg-info → fastasyncpg-0.1.2}/PKG-INFO +6 -14
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/README.md +3 -11
- fastasyncpg-0.1.2/fastasyncpg/__init__.py +9 -0
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/fastasyncpg/_modidx.py +11 -3
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/fastasyncpg/core.py +106 -25
- fastasyncpg-0.1.2/fastasyncpg/skill.py +19 -0
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2/fastasyncpg.egg-info}/PKG-INFO +6 -14
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/fastasyncpg.egg-info/SOURCES.txt +1 -1
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/fastasyncpg.egg-info/entry_points.txt +3 -0
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/fastasyncpg.egg-info/requires.txt +1 -1
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/pyproject.toml +6 -3
- fastasyncpg-0.1.0/MANIFEST.in +0 -5
- fastasyncpg-0.1.0/fastasyncpg/__init__.py +0 -1
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/LICENSE +0 -0
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/fastasyncpg.egg-info/dependency_links.txt +0 -0
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/fastasyncpg.egg-info/top_level.txt +0 -0
- {fastasyncpg-0.1.0 → fastasyncpg-0.1.2}/setup.cfg +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastasyncpg
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: A simple wrapper for asyncpg
|
|
5
5
|
Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
|
|
6
|
-
License: Apache-2.0
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
7
|
Project-URL: Repository, https://github.com/AnswerDotAI/fastasyncpg
|
|
8
8
|
Project-URL: Documentation, https://AnswerDotAI.github.io/fastasyncpg/
|
|
9
9
|
Keywords: nbdev
|
|
@@ -16,7 +16,7 @@ Requires-Dist: asyncpg
|
|
|
16
16
|
Requires-Dist: fastcore
|
|
17
17
|
Requires-Dist: sqlparse
|
|
18
18
|
Provides-Extra: dev
|
|
19
|
-
Requires-Dist:
|
|
19
|
+
Requires-Dist: fastcore>=2.2.34; extra == "dev"
|
|
20
20
|
Dynamic: license-file
|
|
21
21
|
|
|
22
22
|
# fastasyncpg
|
|
@@ -34,9 +34,7 @@ $ pip install fastasyncpg
|
|
|
34
34
|
|
|
35
35
|
## How to use
|
|
36
36
|
|
|
37
|
-
Create one
|
|
38
|
-
[`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database)
|
|
39
|
-
at import time, and connect it at app startup:
|
|
37
|
+
Create one [`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database) at import time, and connect it at app startup:
|
|
40
38
|
|
|
41
39
|
``` python
|
|
42
40
|
from fastasyncpg.core import Database
|
|
@@ -46,11 +44,7 @@ db = Database() # module-level singleton, importable everywhere
|
|
|
46
44
|
async def startup(): await db.connect(database='mydb')
|
|
47
45
|
```
|
|
48
46
|
|
|
49
|
-
Queries run through the pool by default. `transaction` (and `acquire`)
|
|
50
|
-
make a single connection *current for the running task* via a
|
|
51
|
-
`ContextVar`, so everything inside the block – including table helpers
|
|
52
|
-
and code called indirectly – joins the transaction, with no
|
|
53
|
-
handle-passing:
|
|
47
|
+
Queries run through the pool by default. `transaction` (and `acquire`) make a single connection *current for the running task* via a `ContextVar`, so everything inside the block – including table helpers and code called indirectly – joins the transaction, with no handle-passing:
|
|
54
48
|
|
|
55
49
|
``` python
|
|
56
50
|
async with db.transaction():
|
|
@@ -58,6 +52,4 @@ async with db.transaction():
|
|
|
58
52
|
await db.t.user.update(pk_values=[uid], credits=100)
|
|
59
53
|
```
|
|
60
54
|
|
|
61
|
-
See the [API docs](https://AnswerDotAI.github.io/fastasyncpg/core.html)
|
|
62
|
-
for table access (`db.t`), auto-generated dataclasses, queue helpers
|
|
63
|
-
(`claim_one`), and more.
|
|
55
|
+
See the [API docs](https://AnswerDotAI.github.io/fastasyncpg/core.html) for table access (`db.t`), auto-generated dataclasses, queue helpers (`claim_one`), and more.
|
|
@@ -13,9 +13,7 @@ $ pip install fastasyncpg
|
|
|
13
13
|
|
|
14
14
|
## How to use
|
|
15
15
|
|
|
16
|
-
Create one
|
|
17
|
-
[`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database)
|
|
18
|
-
at import time, and connect it at app startup:
|
|
16
|
+
Create one [`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database) at import time, and connect it at app startup:
|
|
19
17
|
|
|
20
18
|
``` python
|
|
21
19
|
from fastasyncpg.core import Database
|
|
@@ -25,11 +23,7 @@ db = Database() # module-level singleton, importable everywhere
|
|
|
25
23
|
async def startup(): await db.connect(database='mydb')
|
|
26
24
|
```
|
|
27
25
|
|
|
28
|
-
Queries run through the pool by default. `transaction` (and `acquire`)
|
|
29
|
-
make a single connection *current for the running task* via a
|
|
30
|
-
`ContextVar`, so everything inside the block – including table helpers
|
|
31
|
-
and code called indirectly – joins the transaction, with no
|
|
32
|
-
handle-passing:
|
|
26
|
+
Queries run through the pool by default. `transaction` (and `acquire`) make a single connection *current for the running task* via a `ContextVar`, so everything inside the block – including table helpers and code called indirectly – joins the transaction, with no handle-passing:
|
|
33
27
|
|
|
34
28
|
``` python
|
|
35
29
|
async with db.transaction():
|
|
@@ -37,6 +31,4 @@ async with db.transaction():
|
|
|
37
31
|
await db.t.user.update(pk_values=[uid], credits=100)
|
|
38
32
|
```
|
|
39
33
|
|
|
40
|
-
See the [API docs](https://AnswerDotAI.github.io/fastasyncpg/core.html)
|
|
41
|
-
for table access (`db.t`), auto-generated dataclasses, queue helpers
|
|
42
|
-
(`claim_one`), and more.
|
|
34
|
+
See the [API docs](https://AnswerDotAI.github.io/fastasyncpg/core.html) for table access (`db.t`), auto-generated dataclasses, queue helpers (`claim_one`), and more.
|
|
@@ -17,12 +17,16 @@ d = { 'settings': { 'branch': 'main',
|
|
|
17
17
|
'fastasyncpg.core.Database.create': ('core.html#database.create', 'fastasyncpg/core.py'),
|
|
18
18
|
'fastasyncpg.core.Database.create_from_schema': ( 'core.html#database.create_from_schema',
|
|
19
19
|
'fastasyncpg/core.py'),
|
|
20
|
+
'fastasyncpg.core.Database.exists': ('core.html#database.exists', 'fastasyncpg/core.py'),
|
|
21
|
+
'fastasyncpg.core.Database.fetchrow': ('core.html#database.fetchrow', 'fastasyncpg/core.py'),
|
|
22
|
+
'fastasyncpg.core.Database.fetchval': ('core.html#database.fetchval', 'fastasyncpg/core.py'),
|
|
20
23
|
'fastasyncpg.core.Database.get_tables': ('core.html#database.get_tables', 'fastasyncpg/core.py'),
|
|
21
|
-
'fastasyncpg.core.Database.item': ('core.html#database.item', 'fastasyncpg/core.py'),
|
|
22
24
|
'fastasyncpg.core.Database.link_dcs': ('core.html#database.link_dcs', 'fastasyncpg/core.py'),
|
|
25
|
+
'fastasyncpg.core.Database.one': ('core.html#database.one', 'fastasyncpg/core.py'),
|
|
26
|
+
'fastasyncpg.core.Database.one_or_none': ('core.html#database.one_or_none', 'fastasyncpg/core.py'),
|
|
23
27
|
'fastasyncpg.core.Database.q': ('core.html#database.q', 'fastasyncpg/core.py'),
|
|
24
|
-
'fastasyncpg.core.Database.qone': ('core.html#database.qone', 'fastasyncpg/core.py'),
|
|
25
28
|
'fastasyncpg.core.Database.refresh': ('core.html#database.refresh', 'fastasyncpg/core.py'),
|
|
29
|
+
'fastasyncpg.core.Database.scalar_one': ('core.html#database.scalar_one', 'fastasyncpg/core.py'),
|
|
26
30
|
'fastasyncpg.core.Database.set_classes': ('core.html#database.set_classes', 'fastasyncpg/core.py'),
|
|
27
31
|
'fastasyncpg.core.Database.t': ('core.html#database.t', 'fastasyncpg/core.py'),
|
|
28
32
|
'fastasyncpg.core.Database.table': ('core.html#database.table', 'fastasyncpg/core.py'),
|
|
@@ -51,15 +55,17 @@ d = { 'settings': { 'branch': 'main',
|
|
|
51
55
|
'fastasyncpg.core.Table.delete': ('core.html#table.delete', 'fastasyncpg/core.py'),
|
|
52
56
|
'fastasyncpg.core.Table.delete_where': ('core.html#table.delete_where', 'fastasyncpg/core.py'),
|
|
53
57
|
'fastasyncpg.core.Table.drop': ('core.html#table.drop', 'fastasyncpg/core.py'),
|
|
58
|
+
'fastasyncpg.core.Table.exists': ('core.html#table.exists', 'fastasyncpg/core.py'),
|
|
54
59
|
'fastasyncpg.core.Table.get': ('core.html#table.get', 'fastasyncpg/core.py'),
|
|
55
60
|
'fastasyncpg.core.Table.groupby': ('core.html#table.groupby', 'fastasyncpg/core.py'),
|
|
56
61
|
'fastasyncpg.core.Table.insert': ('core.html#table.insert', 'fastasyncpg/core.py'),
|
|
57
62
|
'fastasyncpg.core.Table.inserts': ('core.html#table.inserts', 'fastasyncpg/core.py'),
|
|
63
|
+
'fastasyncpg.core.Table.one': ('core.html#table.one', 'fastasyncpg/core.py'),
|
|
64
|
+
'fastasyncpg.core.Table.one_or_none': ('core.html#table.one_or_none', 'fastasyncpg/core.py'),
|
|
58
65
|
'fastasyncpg.core.Table.pks': ('core.html#table.pks', 'fastasyncpg/core.py'),
|
|
59
66
|
'fastasyncpg.core.Table.pks_and_rows_where': ( 'core.html#table.pks_and_rows_where',
|
|
60
67
|
'fastasyncpg/core.py'),
|
|
61
68
|
'fastasyncpg.core.Table.rows_where': ('core.html#table.rows_where', 'fastasyncpg/core.py'),
|
|
62
|
-
'fastasyncpg.core.Table.selectone': ('core.html#table.selectone', 'fastasyncpg/core.py'),
|
|
63
69
|
'fastasyncpg.core.Table.update': ('core.html#table.update', 'fastasyncpg/core.py'),
|
|
64
70
|
'fastasyncpg.core.Table.updates': ('core.html#table.updates', 'fastasyncpg/core.py'),
|
|
65
71
|
'fastasyncpg.core.Table.upsert': ('core.html#table.upsert', 'fastasyncpg/core.py'),
|
|
@@ -91,6 +97,7 @@ d = { 'settings': { 'branch': 'main',
|
|
|
91
97
|
'fastasyncpg.core._TablesGetter': ('core.html#_tablesgetter', 'fastasyncpg/core.py'),
|
|
92
98
|
'fastasyncpg.core._TablesGetter.__init__': ('core.html#_tablesgetter.__init__', 'fastasyncpg/core.py'),
|
|
93
99
|
'fastasyncpg.core._add_xtra': ('core.html#_add_xtra', 'fastasyncpg/core.py'),
|
|
100
|
+
'fastasyncpg.core._call': ('core.html#_call', 'fastasyncpg/core.py'),
|
|
94
101
|
'fastasyncpg.core._convq': ('core.html#_convq', 'fastasyncpg/core.py'),
|
|
95
102
|
'fastasyncpg.core._dataclass': ('core.html#_dataclass', 'fastasyncpg/core.py'),
|
|
96
103
|
'fastasyncpg.core._get_flds': ('core.html#_get_flds', 'fastasyncpg/core.py'),
|
|
@@ -113,6 +120,7 @@ d = { 'settings': { 'branch': 'main',
|
|
|
113
120
|
'fastasyncpg.core.create_pool': ('core.html#create_pool', 'fastasyncpg/core.py'),
|
|
114
121
|
'fastasyncpg.core.get_field': ('core.html#get_field', 'fastasyncpg/core.py'),
|
|
115
122
|
'fastasyncpg.core.get_typ': ('core.html#get_typ', 'fastasyncpg/core.py'),
|
|
123
|
+
'fastasyncpg.core.listen': ('core.html#listen', 'fastasyncpg/core.py'),
|
|
116
124
|
'fastasyncpg.core.pk_cols': ('core.html#pk_cols', 'fastasyncpg/core.py'),
|
|
117
125
|
'fastasyncpg.core.setup_json': ('core.html#setup_json', 'fastasyncpg/core.py'),
|
|
118
126
|
'fastasyncpg.core.table_names': ('core.html#table_names', 'fastasyncpg/core.py'),
|
|
@@ -5,12 +5,13 @@
|
|
|
5
5
|
# %% auto #0
|
|
6
6
|
__all__ = ['pg_to_py', 'py_to_pg', 'Results', 'FRecord', 'table_names', 'view_names', 'columns_info', 'pk_cols', 'Database',
|
|
7
7
|
'Table', 'conv_placeholders', 'get_typ', 'setup_json', 'connect', 'all_dcs', 'NotFoundError', 'get_field',
|
|
8
|
-
'create_mod', 'col_def', 'create_pool']
|
|
8
|
+
'create_mod', 'col_def', 'create_pool', 'listen']
|
|
9
9
|
|
|
10
10
|
# %% ../nbs/00_core.ipynb #222d751e
|
|
11
11
|
from fastcore.utils import *
|
|
12
|
-
from
|
|
13
|
-
import
|
|
12
|
+
from fastcore.meta import delegates
|
|
13
|
+
from contextlib import asynccontextmanager, suppress
|
|
14
|
+
import asyncio,asyncpg,logging,traceback,sys
|
|
14
15
|
from contextvars import ContextVar
|
|
15
16
|
from weakref import WeakKeyDictionary
|
|
16
17
|
from asyncpg import connection,protocol
|
|
@@ -217,6 +218,24 @@ async def q(self:Database, sql, *args, **kwargs):
|
|
|
217
218
|
csql, kw_args = conv_placeholders(sql, **kwargs)
|
|
218
219
|
return Results(await self.fetch(csql, *args, *kw_args))
|
|
219
220
|
|
|
221
|
+
# %% ../nbs/00_core.ipynb #e16bb20d
|
|
222
|
+
@patch
|
|
223
|
+
async def fetchrow(self:Database, sql, *args, timeout=None, record_class=None, **kwargs):
|
|
224
|
+
"Fetch the first row of `sql` (or None), supporting `?`, `:name`, and `$1` placeholders"
|
|
225
|
+
csql, kw_args = conv_placeholders(sql, **kwargs)
|
|
226
|
+
return await self.conn.fetchrow(csql, *args, *kw_args, timeout=timeout, record_class=record_class)
|
|
227
|
+
|
|
228
|
+
@patch
|
|
229
|
+
async def fetchval(self:Database, sql, *args, column=0, timeout=None, **kwargs):
|
|
230
|
+
"Fetch one value from the first row of `sql` (or None), supporting `?`, `:name`, and `$1` placeholders"
|
|
231
|
+
csql, kw_args = conv_placeholders(sql, **kwargs)
|
|
232
|
+
return await self.conn.fetchval(csql, *args, *kw_args, column=column, timeout=timeout)
|
|
233
|
+
|
|
234
|
+
@patch
|
|
235
|
+
async def exists(self:Database, sql, *args, **kwargs):
|
|
236
|
+
"Return True if `sql` produces at least one row"
|
|
237
|
+
return bool(await self.fetchval(f'SELECT EXISTS({sql.strip().rstrip(";")})', *args, **kwargs))
|
|
238
|
+
|
|
220
239
|
# %% ../nbs/00_core.ipynb #0fc7310b
|
|
221
240
|
from datetime import datetime, date, time, timedelta
|
|
222
241
|
from decimal import Decimal
|
|
@@ -362,7 +381,7 @@ async def rows_where(self:Table, where=None, where_args=None, order_by=None, sel
|
|
|
362
381
|
# %% ../nbs/00_core.ipynb #b96b3f21
|
|
363
382
|
@patch
|
|
364
383
|
async def count_where(self:Table, where=None, where_args=None):
|
|
365
|
-
|
|
384
|
+
"Count rows matching `where` (plus any `xtra` constraints)"
|
|
366
385
|
where, args = _add_xtra(self, where, where_args)
|
|
367
386
|
sql = f'SELECT COUNT(*) FROM {self}'
|
|
368
387
|
if where: sql += f' WHERE {where}'
|
|
@@ -372,6 +391,15 @@ async def count_where(self:Table, where=None, where_args=None):
|
|
|
372
391
|
@patch(as_prop=True)
|
|
373
392
|
async def count(self:Table): return await self.count_where()
|
|
374
393
|
|
|
394
|
+
# %% ../nbs/00_core.ipynb #dfb2a683
|
|
395
|
+
@patch
|
|
396
|
+
async def exists(self:Table, where=None, where_args=None):
|
|
397
|
+
"Return True if any row matches `where` (plus any `xtra` constraints)"
|
|
398
|
+
where, args = _add_xtra(self, where, where_args)
|
|
399
|
+
sql = f'SELECT 1 FROM {self}'
|
|
400
|
+
if where: sql += f' WHERE {where}'
|
|
401
|
+
return await self.db.exists(sql, *args)
|
|
402
|
+
|
|
375
403
|
# %% ../nbs/00_core.ipynb #28682469
|
|
376
404
|
from collections.abc import Mapping
|
|
377
405
|
|
|
@@ -398,35 +426,48 @@ async def __call__(self:Table, where=None, where_args=None, order_by=None, limit
|
|
|
398
426
|
|
|
399
427
|
# %% ../nbs/00_core.ipynb #73e88814
|
|
400
428
|
@patch
|
|
401
|
-
async def
|
|
429
|
+
async def one_or_none(
|
|
402
430
|
self:Table,
|
|
403
|
-
where:str|None=None,
|
|
404
|
-
where_args:
|
|
405
|
-
select:str
|
|
406
|
-
as_cls:bool=True, # Convert returned
|
|
431
|
+
where:str|None=None, # SQL where fragment, e.g. `id > ?`
|
|
432
|
+
where_args:Iterable|NoneType=None, # Positional parameters for `where`
|
|
433
|
+
select:str="*", # Comma-separated list of columns to select
|
|
434
|
+
as_cls:bool=True, # Convert returned row to stored dataclass?
|
|
407
435
|
debug:bool=False
|
|
408
|
-
)
|
|
409
|
-
"
|
|
436
|
+
):
|
|
437
|
+
"Return the single matching row or None; raises ValueError if multiple match"
|
|
410
438
|
res = await self(where=where, where_args=where_args, select=select, as_cls=as_cls, limit=2, debug=debug)
|
|
411
|
-
if len(res)
|
|
412
|
-
|
|
413
|
-
|
|
439
|
+
if len(res) > 1: raise ValueError(f"Not unique: {len(res)} results")
|
|
440
|
+
return res[0] if res else None
|
|
441
|
+
|
|
442
|
+
@patch
|
|
443
|
+
@delegates(Table.one_or_none)
|
|
444
|
+
async def one(self:Table, where:str|None=None, where_args:Iterable|NoneType=None, **kwargs):
|
|
445
|
+
"Return the single matching row; raises NotFoundError if none or ValueError if multiple match"
|
|
446
|
+
res = await self.one_or_none(where=where, where_args=where_args, **kwargs)
|
|
447
|
+
if res is None: raise NotFoundError
|
|
448
|
+
return res
|
|
414
449
|
|
|
415
450
|
# %% ../nbs/00_core.ipynb #d994c66c
|
|
416
451
|
@patch
|
|
417
|
-
async def
|
|
418
|
-
"Execute sql and return
|
|
452
|
+
async def one_or_none(self:Database, sql, *args, **kwargs):
|
|
453
|
+
"Execute `sql` and return the single row or None; raises ValueError if multiple rows"
|
|
419
454
|
res = await self.q(sql, *args, **kwargs)
|
|
420
|
-
if len(res)
|
|
421
|
-
|
|
422
|
-
|
|
455
|
+
if len(res) > 1: raise ValueError(f"Not unique: {len(res)} results")
|
|
456
|
+
return res[0] if res else None
|
|
457
|
+
|
|
458
|
+
@patch
|
|
459
|
+
async def one(self:Database, sql, *args, **kwargs):
|
|
460
|
+
"Execute `sql` and return exactly one row; raises NotFoundError if empty or ValueError if multiple rows"
|
|
461
|
+
res = await self.one_or_none(sql, *args, **kwargs)
|
|
462
|
+
if res is None: raise NotFoundError
|
|
463
|
+
return res
|
|
423
464
|
|
|
424
465
|
# %% ../nbs/00_core.ipynb #e53a268a
|
|
425
466
|
@patch
|
|
426
|
-
async def
|
|
427
|
-
"Execute sql and return
|
|
428
|
-
row = await self.
|
|
429
|
-
if len(row)
|
|
467
|
+
async def scalar_one(self:Database, sql, *args, **kwargs):
|
|
468
|
+
"Execute `sql` and return the single field from the single row"
|
|
469
|
+
row = await self.one(sql, *args, **kwargs)
|
|
470
|
+
if len(row) != 1: raise ValueError(f"Expected 1 field, got {len(row)}")
|
|
430
471
|
return row[0]
|
|
431
472
|
|
|
432
473
|
# %% ../nbs/00_core.ipynb #0261da8a
|
|
@@ -764,5 +805,45 @@ async def claim_one(self:Table, status_col='status', pending='pending', complete
|
|
|
764
805
|
stmt = f'UPDATE {self} SET "{status_col}"=$1 WHERE "{pk}"=$2'
|
|
765
806
|
if new:
|
|
766
807
|
await txn.execute(stmt, new, get_field(p.evt, pk))
|
|
767
|
-
p.evt = await self.
|
|
768
|
-
|
|
808
|
+
p.evt = await self.one(f'"{pk}"=$1', [get_field(p.evt, pk)])
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
# %% ../nbs/00_core.ipynb #15582b9e
|
|
812
|
+
_CLOSED = object()
|
|
813
|
+
_log = logging.getLogger(__name__)
|
|
814
|
+
|
|
815
|
+
async def _call(fn, *args):
|
|
816
|
+
res = fn(*args)
|
|
817
|
+
return (await res) if inspect.isawaitable(res) else res
|
|
818
|
+
|
|
819
|
+
@delegates(asyncpg.connect)
|
|
820
|
+
async def listen(
|
|
821
|
+
channel:str, # PostgreSQL NOTIFY channel name
|
|
822
|
+
on_notify, # Sync or async callback receiving each notification payload string
|
|
823
|
+
*, on_connect=None, # Optional sync or async callback receiving `reconnected: bool` after subscribing
|
|
824
|
+
on_disconnect=None, # Optional sync or async callback invoked when a connection drops
|
|
825
|
+
retry:float=1, # Seconds to wait before reconnecting after an error
|
|
826
|
+
**kwargs
|
|
827
|
+
):
|
|
828
|
+
"Listen on a PostgreSQL `NOTIFY` channel, reconnecting automatically on disconnect or error."
|
|
829
|
+
reconnected = False
|
|
830
|
+
while True:
|
|
831
|
+
conn, q = None, asyncio.Queue()
|
|
832
|
+
try:
|
|
833
|
+
conn = await asyncpg.connect(**kwargs)
|
|
834
|
+
conn.add_termination_listener(lambda *_: q.put_nowait(_CLOSED))
|
|
835
|
+
await conn.add_listener(channel, lambda *a: q.put_nowait(a[-1]))
|
|
836
|
+
if on_connect: await _call(on_connect, reconnected)
|
|
837
|
+
reconnected = True
|
|
838
|
+
while (payload := await q.get()) is not _CLOSED:
|
|
839
|
+
try: await _call(on_notify, payload)
|
|
840
|
+
except Exception as e: _log.warning('%s handler failed: %s', channel, e)
|
|
841
|
+
if on_disconnect: await _call(on_disconnect)
|
|
842
|
+
except asyncio.CancelledError: raise
|
|
843
|
+
except Exception as e:
|
|
844
|
+
_log.warning('%s listener error: %s', channel, e)
|
|
845
|
+
reconnected = True
|
|
846
|
+
await asyncio.sleep(retry)
|
|
847
|
+
finally:
|
|
848
|
+
if conn:
|
|
849
|
+
with suppress(Exception): await conn.close()
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
r"""Use fastasyncpg's API idiomatically. Always read before using the lib.
|
|
2
|
+
|
|
3
|
+
Examples: `nbs/00_core.ipynb`; `doc(fastasyncpg.core)` and table methods before use.
|
|
4
|
+
|
|
5
|
+
- lifecycle: module-global `db = Database()`; `await db.connect(...)` creates one pool per event loop; `await db.close()` closes that loop's pool
|
|
6
|
+
- tables: `t = db.t.user` (cached `Table`); schema metadata `t.cols`, `t.pks`; `await t(where, args)` returns list, not lazy query
|
|
7
|
+
- by pk (first pk col): `await t[pk]` returns row or raises `NotFoundError`; `await t.get(pk)` returns row or `None`
|
|
8
|
+
- single row: `await t.one(where, args)` and `await db.one(sql, ...)` return one row (0: `NotFoundError`, >1: `ValueError`); `one_or_none` returns row or `None` (>1: `ValueError`); prefer over `first(await ...)`
|
|
9
|
+
- scalars and predicates: `await db.scalar_one(sql, ...)` returns single field of single row; `await t.exists(where, args)` and `await db.exists(sql, ...)` return `bool` (`SELECT EXISTS`); `await t.count` (async prop) and `await t.count_where(where, args)` return counts
|
|
10
|
+
- permissive single: `await db.fetchrow(sql, ...)` returns first row or `None`; `await db.fetchval(sql, ...)` returns first value or `None` (`column=`, `timeout=`)
|
|
11
|
+
- placeholders: `?`, `:name` (kwargs), or `$1` on `db.{q,one,one_or_none,scalar_one,exists,fetchrow,fetchval}` and table helpers (`where_args` positional, incl. `count_where`, `exists`); other delegated `asyncpg` methods (`fetch`, `execute`, ...) require `$1`; `order_by` is SQL (`'name DESC'`, not `'-name'`)
|
|
12
|
+
- identifiers: interpolate `t` and `t.c.name` for quoted identifiers; parameterize values
|
|
13
|
+
- dataclasses: `t.dataclass()` binds future reads; `UNSET` omitted on writes, `None` writes NULL; single-row writes return rows, bulk `inserts`/`updates`/`upserts` return `None` with missing columns as NULL
|
|
14
|
+
- transactions: `async with db.transaction()` joins all helpers via task-local context (no handle passing); nested = savepoints; spawn background tasks outside transaction/acquire blocks
|
|
15
|
+
- xtra: `t.xtra(...)` mutates shared cached `Table`, `t.xtra()` clears; never use for request-local filters in concurrent code
|
|
16
|
+
- upsert: updates supplied fields on pk conflict, not get-or-create
|
|
17
|
+
- queues: `claim` requires transaction; `claim_one` manages status and catches handler exceptions (check `result.failed`)
|
|
18
|
+
- listen: `await listen(channel, on_notify, *, on_connect=None, on_disconnect=None, retry=1, **kwargs)` holds dedicated `asyncpg` conn with auto-reconnect, sync or async callbacks, handler errors logged, `on_connect(reconnected)` after `add_listener`
|
|
19
|
+
"""
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastasyncpg
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: A simple wrapper for asyncpg
|
|
5
5
|
Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
|
|
6
|
-
License: Apache-2.0
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
7
|
Project-URL: Repository, https://github.com/AnswerDotAI/fastasyncpg
|
|
8
8
|
Project-URL: Documentation, https://AnswerDotAI.github.io/fastasyncpg/
|
|
9
9
|
Keywords: nbdev
|
|
@@ -16,7 +16,7 @@ Requires-Dist: asyncpg
|
|
|
16
16
|
Requires-Dist: fastcore
|
|
17
17
|
Requires-Dist: sqlparse
|
|
18
18
|
Provides-Extra: dev
|
|
19
|
-
Requires-Dist:
|
|
19
|
+
Requires-Dist: fastcore>=2.2.34; extra == "dev"
|
|
20
20
|
Dynamic: license-file
|
|
21
21
|
|
|
22
22
|
# fastasyncpg
|
|
@@ -34,9 +34,7 @@ $ pip install fastasyncpg
|
|
|
34
34
|
|
|
35
35
|
## How to use
|
|
36
36
|
|
|
37
|
-
Create one
|
|
38
|
-
[`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database)
|
|
39
|
-
at import time, and connect it at app startup:
|
|
37
|
+
Create one [`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database) at import time, and connect it at app startup:
|
|
40
38
|
|
|
41
39
|
``` python
|
|
42
40
|
from fastasyncpg.core import Database
|
|
@@ -46,11 +44,7 @@ db = Database() # module-level singleton, importable everywhere
|
|
|
46
44
|
async def startup(): await db.connect(database='mydb')
|
|
47
45
|
```
|
|
48
46
|
|
|
49
|
-
Queries run through the pool by default. `transaction` (and `acquire`)
|
|
50
|
-
make a single connection *current for the running task* via a
|
|
51
|
-
`ContextVar`, so everything inside the block – including table helpers
|
|
52
|
-
and code called indirectly – joins the transaction, with no
|
|
53
|
-
handle-passing:
|
|
47
|
+
Queries run through the pool by default. `transaction` (and `acquire`) make a single connection *current for the running task* via a `ContextVar`, so everything inside the block – including table helpers and code called indirectly – joins the transaction, with no handle-passing:
|
|
54
48
|
|
|
55
49
|
``` python
|
|
56
50
|
async with db.transaction():
|
|
@@ -58,6 +52,4 @@ async with db.transaction():
|
|
|
58
52
|
await db.t.user.update(pk_values=[uid], credits=100)
|
|
59
53
|
```
|
|
60
54
|
|
|
61
|
-
See the [API docs](https://AnswerDotAI.github.io/fastasyncpg/core.html)
|
|
62
|
-
for table access (`db.t`), auto-generated dataclasses, queue helpers
|
|
63
|
-
(`claim_one`), and more.
|
|
55
|
+
See the [API docs](https://AnswerDotAI.github.io/fastasyncpg/core.html) for table access (`db.t`), auto-generated dataclasses, queue helpers (`claim_one`), and more.
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
LICENSE
|
|
2
|
-
MANIFEST.in
|
|
3
2
|
README.md
|
|
4
3
|
pyproject.toml
|
|
5
4
|
fastasyncpg/__init__.py
|
|
6
5
|
fastasyncpg/_modidx.py
|
|
7
6
|
fastasyncpg/core.py
|
|
7
|
+
fastasyncpg/skill.py
|
|
8
8
|
fastasyncpg.egg-info/PKG-INFO
|
|
9
9
|
fastasyncpg.egg-info/SOURCES.txt
|
|
10
10
|
fastasyncpg.egg-info/dependency_links.txt
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["setuptools>=
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
3
|
build-backend = "setuptools.build_meta"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
@@ -8,14 +8,14 @@ dynamic = ["version"]
|
|
|
8
8
|
description = "A simple wrapper for asyncpg"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
11
|
-
license =
|
|
11
|
+
license = "Apache-2.0"
|
|
12
12
|
authors = [{name = "Jeremy Howard", email = "github@jhoward.fastmail.fm"}]
|
|
13
13
|
keywords = ['nbdev']
|
|
14
14
|
classifiers = [ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only" ]
|
|
15
15
|
dependencies = [ "asyncpg", "fastcore","sqlparse" ]
|
|
16
16
|
|
|
17
17
|
[project.optional-dependencies]
|
|
18
|
-
dev = ['
|
|
18
|
+
dev = ['fastcore>=2.2.34']
|
|
19
19
|
|
|
20
20
|
[project.urls]
|
|
21
21
|
Repository = "https://github.com/AnswerDotAI/fastasyncpg"
|
|
@@ -24,6 +24,9 @@ Documentation = "https://AnswerDotAI.github.io/fastasyncpg/"
|
|
|
24
24
|
[project.entry-points.nbdev]
|
|
25
25
|
fastasyncpg = "fastasyncpg._modidx:d"
|
|
26
26
|
|
|
27
|
+
[project.entry-points.pyskills]
|
|
28
|
+
fastasyncpg = "fastasyncpg.skill"
|
|
29
|
+
|
|
27
30
|
[tool.setuptools.dynamic]
|
|
28
31
|
version = {attr = "fastasyncpg.__version__"}
|
|
29
32
|
|
fastasyncpg-0.1.0/MANIFEST.in
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.1.0"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|