fastasyncpg 0.0.9__tar.gz → 0.1.0__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.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastasyncpg
3
+ Version: 0.1.0
4
+ Summary: A simple wrapper for asyncpg
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/fastasyncpg
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/fastasyncpg/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: asyncpg
16
+ Requires-Dist: fastcore
17
+ Requires-Dist: sqlparse
18
+ Provides-Extra: dev
19
+ Requires-Dist: ipykernel_helper>=0.0.58; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # fastasyncpg
23
+
24
+
25
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
26
+
27
+ ## Installation
28
+
29
+ Install latest from [pypi](https://pypi.org/project/fastasyncpg/)
30
+
31
+ ``` sh
32
+ $ pip install fastasyncpg
33
+ ```
34
+
35
+ ## How to use
36
+
37
+ Create one
38
+ [`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database)
39
+ at import time, and connect it at app startup:
40
+
41
+ ``` python
42
+ from fastasyncpg.core import Database
43
+
44
+ db = Database() # module-level singleton, importable everywhere
45
+
46
+ async def startup(): await db.connect(database='mydb')
47
+ ```
48
+
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:
54
+
55
+ ``` python
56
+ async with db.transaction():
57
+ await db.execute('SELECT 1 FROM "user" WHERE id=$1 FOR UPDATE', uid)
58
+ await db.t.user.update(pk_values=[uid], credits=100)
59
+ ```
60
+
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.
@@ -0,0 +1,42 @@
1
+ # fastasyncpg
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ ## Installation
7
+
8
+ Install latest from [pypi](https://pypi.org/project/fastasyncpg/)
9
+
10
+ ``` sh
11
+ $ pip install fastasyncpg
12
+ ```
13
+
14
+ ## How to use
15
+
16
+ Create one
17
+ [`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database)
18
+ at import time, and connect it at app startup:
19
+
20
+ ``` python
21
+ from fastasyncpg.core import Database
22
+
23
+ db = Database() # module-level singleton, importable everywhere
24
+
25
+ async def startup(): await db.connect(database='mydb')
26
+ ```
27
+
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:
33
+
34
+ ``` python
35
+ async with db.transaction():
36
+ await db.execute('SELECT 1 FROM "user" WHERE id=$1 FOR UPDATE', uid)
37
+ await db.t.user.update(pk_values=[uid], credits=100)
38
+ ```
39
+
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.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -9,12 +9,14 @@ d = { 'settings': { 'branch': 'main',
9
9
  'fastasyncpg.core.Database.__getattr__': ('core.html#database.__getattr__', 'fastasyncpg/core.py'),
10
10
  'fastasyncpg.core.Database.__init__': ('core.html#database.__init__', 'fastasyncpg/core.py'),
11
11
  'fastasyncpg.core.Database.__str__': ('core.html#database.__str__', 'fastasyncpg/core.py'),
12
+ 'fastasyncpg.core.Database._conn': ('core.html#database._conn', 'fastasyncpg/core.py'),
12
13
  'fastasyncpg.core.Database._retr_tbl': ('core.html#database._retr_tbl', 'fastasyncpg/core.py'),
13
14
  'fastasyncpg.core.Database.acquire': ('core.html#database.acquire', 'fastasyncpg/core.py'),
15
+ 'fastasyncpg.core.Database.conn': ('core.html#database.conn', 'fastasyncpg/core.py'),
16
+ 'fastasyncpg.core.Database.connect': ('core.html#database.connect', 'fastasyncpg/core.py'),
14
17
  'fastasyncpg.core.Database.create': ('core.html#database.create', 'fastasyncpg/core.py'),
15
18
  'fastasyncpg.core.Database.create_from_schema': ( 'core.html#database.create_from_schema',
16
19
  'fastasyncpg/core.py'),
17
- 'fastasyncpg.core.Database.from_meta': ('core.html#database.from_meta', 'fastasyncpg/core.py'),
18
20
  'fastasyncpg.core.Database.get_tables': ('core.html#database.get_tables', 'fastasyncpg/core.py'),
19
21
  'fastasyncpg.core.Database.item': ('core.html#database.item', 'fastasyncpg/core.py'),
20
22
  'fastasyncpg.core.Database.link_dcs': ('core.html#database.link_dcs', 'fastasyncpg/core.py'),
@@ -1,4 +1,4 @@
1
- """Docs: https://AnswerDotAI.github.io/fastasyncpgcore.html.md"""
1
+ """Docs: https://AnswerDotAI.github.io/fastasyncpg/core.html.md"""
2
2
 
3
3
  # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
4
4
 
@@ -10,7 +10,9 @@ __all__ = ['pg_to_py', 'py_to_pg', 'Results', 'FRecord', 'table_names', 'view_na
10
10
  # %% ../nbs/00_core.ipynb #222d751e
11
11
  from fastcore.utils import *
12
12
  from contextlib import asynccontextmanager
13
- import asyncpg,traceback,sys
13
+ import asyncio,asyncpg,traceback,sys
14
+ from contextvars import ContextVar
15
+ from weakref import WeakKeyDictionary
14
16
  from asyncpg import connection,protocol
15
17
 
16
18
  # %% ../nbs/00_core.ipynb #cdb9cd9e
@@ -75,18 +77,31 @@ async def pk_cols(conn, table):
75
77
 
76
78
  # %% ../nbs/00_core.ipynb #350e6168
77
79
  class Database:
78
- def __init__(self, conn, refresh=True):
79
- self.conn = conn
80
+ def __init__(self, conn=None, refresh=True):
81
+ self._conns = WeakKeyDictionary()
82
+ self._cur = ContextVar('cur', default=None)
80
83
  self._tnames,self._vnames = [],[]
81
84
  self._tables = {}
82
- if refresh: asyncio.create_task(self.refresh())
85
+ if conn is not None:
86
+ self._conns[asyncio.get_running_loop()] = conn
87
+ if refresh: asyncio.create_task(self.refresh())
88
+
89
+ @property
90
+ def _conn(self):
91
+ try: return self._conns.get(asyncio.get_running_loop())
92
+ except RuntimeError: return None
93
+
94
+ @property
95
+ def conn(self): return self._cur.get() or self._conn
83
96
 
84
97
  @property
85
98
  def t(self):
86
99
  if not hasattr(self, '_t'): self._t = _TablesGetter(self)
87
100
  return self._t
88
101
 
89
- def __getattr__(self, k): return getattr(self.conn, k)
102
+ def __getattr__(self, k):
103
+ if k.startswith('_'): raise AttributeError(k)
104
+ return getattr(self.conn, k)
90
105
 
91
106
  def table(self, name):
92
107
  if name not in self._tables: self._tables[name] = Table(self, name)
@@ -97,13 +112,15 @@ class Database:
97
112
  self._tnames,self._vnames = await table_names(self),await view_names(self)
98
113
  self._cols = {o: (await columns_info(self, o)) for o in self._tnames+self._vnames}
99
114
  self._pks = {o: (await pk_cols(self, o)) for o in self._tnames}
100
-
115
+
101
116
  def __str__(self):
102
- if isinstance(self.conn, asyncpg.pool.Pool):
103
- kw = self.conn._connect_kwargs
117
+ conn = self._conn or next(iter(self._conns.values()), None)
118
+ if conn is None: return 'Database (not connected)'
119
+ if isinstance(conn, asyncpg.pool.Pool):
120
+ kw = conn._connect_kwargs
104
121
  u,h,d,p = kw.get('user','postgres'), kw.get('host','localhost'), kw.get('database','postgres'), kw.get('port',5432)
105
122
  else:
106
- pr,a = self.conn._params, self.conn._addr
123
+ pr,a = conn._params, conn._addr
107
124
  u,h,d,p = pr.user, a[0], pr.database, a[1]
108
125
  return f"postgresql://{u}@{h}:{p}/{d}"
109
126
 
@@ -296,12 +313,7 @@ def _add_xtra(tbl, where, args, offset=0):
296
313
  async def _recs(self:Table, sql, *args):
297
314
  "Fetch rows and convert to cls"
298
315
  cls = getattr(self, 'cls', None)
299
- def f(r):
300
- if not cls: return r
301
- res = cls(**r)
302
- res._db = self.db
303
- return res
304
- return [f(r) for r in await self.db.q(sql, *args)]
316
+ return [cls(**r) if cls else r for r in await self.db.q(sql, *args)]
305
317
 
306
318
  @patch
307
319
  async def _rec(self:Table, sql, *args, err=None):
@@ -350,6 +362,7 @@ async def rows_where(self:Table, where=None, where_args=None, order_by=None, sel
350
362
  # %% ../nbs/00_core.ipynb #b96b3f21
351
363
  @patch
352
364
  async def count_where(self:Table, where=None, where_args=None):
365
+ # TODO: support `?` placeholders too
353
366
  where, args = _add_xtra(self, where, where_args)
354
367
  sql = f'SELECT COUNT(*) FROM {self}'
355
368
  if where: sql += f' WHERE {where}'
@@ -658,40 +671,42 @@ async def groupby(self:Table, groupflds:list[str], aggs:list[str]):
658
671
  return {_key(r): _val(r) for r in rows}
659
672
 
660
673
  # %% ../nbs/00_core.ipynb #6be00990
661
- async def create_pool(*args, **kwargs):
674
+ @patch
675
+ async def connect(self:Database, *args, **kwargs):
676
+ "Create (or replace) the running event loop's connection pool, and refresh metadata"
662
677
  kwargs.setdefault('record_class', FRecord)
663
678
  kwargs.setdefault('init', setup_json)
664
- pool = await asyncpg.create_pool(*args, **kwargs)
665
- res = Database(pool, refresh=False)
666
- await res.refresh()
667
- return res
679
+ loop = asyncio.get_running_loop()
680
+ if (old := self._conns.get(loop)) is not None: await old.close()
681
+ self._conns[loop] = await asyncpg.create_pool(*args, **kwargs)
682
+ await self.refresh()
683
+ return self
668
684
 
669
- # %% ../nbs/00_core.ipynb #7072a71f
670
- @patch(cls_method=True)
671
- def from_meta(cls:Database, conn, db):
672
- "Create a Database sharing metadata from `db` but using `conn`"
673
- res = cls(conn, refresh=False)
674
- res._tnames,res._vnames,res._cols,res._pks = db._tnames,db._vnames,db._cols,db._pks
675
- for name,tbl in db._tables.items():
676
- if hasattr(tbl, 'cls'): res.table(name).cls = tbl.cls
677
- return res
685
+
686
+ # %% ../nbs/00_core.ipynb #eb7b122d
687
+ async def create_pool(*args, **kwargs): return await Database().connect(*args, **kwargs)
678
688
 
679
689
  # %% ../nbs/00_core.ipynb #c6be6cb0
680
690
  @patch
681
691
  @asynccontextmanager
682
692
  async def acquire(self:Database):
683
- "Context manager yielding a Database on a single connection"
684
- if isinstance(self.conn, asyncpg.pool.Pool):
685
- async with self.conn.acquire() as conn: yield Database.from_meta(conn, self)
686
- else: yield self
693
+ "Make a single pool connection the current executor for this task"
694
+ if self._cur.get() or not isinstance(self._conn, asyncpg.pool.Pool): yield self
695
+ else:
696
+ async with self._conn.acquire() as conn:
697
+ token = self._cur.set(conn)
698
+ try: yield self
699
+ finally: self._cur.reset(token)
700
+
687
701
 
688
702
  # %% ../nbs/00_core.ipynb #f0b7826a
689
703
  @patch
690
704
  @asynccontextmanager
691
705
  async def transaction(self:Database):
692
- "Context manager yielding a transactional Database on a single connection"
693
- async with self.acquire() as db:
694
- async with db.conn.transaction(): yield db
706
+ "Run the block in a transaction on a single connection, current for this task"
707
+ async with self.acquire():
708
+ async with self.conn.transaction(): yield self
709
+
695
710
 
696
711
  # %% ../nbs/00_core.ipynb #0f3e2764
697
712
  def _sql_kinds(sql):
@@ -733,13 +748,21 @@ async def claim_one(self:Table, status_col='status', pending='pending', complete
733
748
  "Claim a row and manage its status transitions"
734
749
  p = _ClaimCtx()
735
750
  async with self.db.transaction() as txn:
736
- tbl = txn.t[self.name]
751
+ p.evt = await self.claim(where=f'"{status_col}"=$1', where_args=[pending], order_by=order_by)
737
752
  p.db = txn
738
- p.evt = await tbl.claim(where=f'"{status_col}"=$1', where_args=[pending], order_by=order_by)
739
- try: yield p
740
- except Exception as e: p.failed, p.exc, p.tb = True, e, traceback.format_exc()
753
+ entered = False
754
+ try:
755
+ async with txn.conn.transaction():
756
+ entered = True
757
+ yield p
758
+ except Exception as e:
759
+ if not entered: raise
760
+ p.failed,p.exc,p.tb = True,e,traceback.format_exc()
741
761
  if p.evt is None: return
742
762
  pk = self.pks[0]
743
763
  new = failed if p.failed else (None if p.retry else completed)
744
764
  stmt = f'UPDATE {self} SET "{status_col}"=$1 WHERE "{pk}"=$2'
745
- if new: await txn.execute(stmt, new, get_field(p.evt, pk))
765
+ if new:
766
+ await txn.execute(stmt, new, get_field(p.evt, pk))
767
+ p.evt = await self.selectone(f'"{pk}"=$1', [get_field(p.evt, pk)])
768
+
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastasyncpg
3
+ Version: 0.1.0
4
+ Summary: A simple wrapper for asyncpg
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/fastasyncpg
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/fastasyncpg/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: asyncpg
16
+ Requires-Dist: fastcore
17
+ Requires-Dist: sqlparse
18
+ Provides-Extra: dev
19
+ Requires-Dist: ipykernel_helper>=0.0.58; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # fastasyncpg
23
+
24
+
25
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
26
+
27
+ ## Installation
28
+
29
+ Install latest from [pypi](https://pypi.org/project/fastasyncpg/)
30
+
31
+ ``` sh
32
+ $ pip install fastasyncpg
33
+ ```
34
+
35
+ ## How to use
36
+
37
+ Create one
38
+ [`Database`](https://AnswerDotAI.github.io/fastasyncpg/core.html#database)
39
+ at import time, and connect it at app startup:
40
+
41
+ ``` python
42
+ from fastasyncpg.core import Database
43
+
44
+ db = Database() # module-level singleton, importable everywhere
45
+
46
+ async def startup(): await db.connect(database='mydb')
47
+ ```
48
+
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:
54
+
55
+ ``` python
56
+ async with db.transaction():
57
+ await db.execute('SELECT 1 FROM "user" WHERE id=$1 FOR UPDATE', uid)
58
+ await db.t.user.update(pk_values=[uid], credits=100)
59
+ ```
60
+
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.
@@ -0,0 +1,6 @@
1
+ asyncpg
2
+ fastcore
3
+ sqlparse
4
+
5
+ [dev]
6
+ ipykernel_helper>=0.0.58
@@ -7,13 +7,16 @@ name = "fastasyncpg"
7
7
  dynamic = ["version"]
8
8
  description = "A simple wrapper for asyncpg"
9
9
  readme = "README.md"
10
- requires-python = ">=3.10"
10
+ requires-python = ">=3.11"
11
11
  license = {text = "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
+ [project.optional-dependencies]
18
+ dev = ['ipykernel_helper>=0.0.58']
19
+
17
20
  [project.urls]
18
21
  Repository = "https://github.com/AnswerDotAI/fastasyncpg"
19
22
  Documentation = "https://AnswerDotAI.github.io/fastasyncpg/"
@@ -31,3 +34,6 @@ include = ["fastasyncpg"]
31
34
  allowed_metadata_keys = ['solveit']
32
35
  allowed_cell_metadata_keys = ['solveit_ai']
33
36
  custom_sidebar = false
37
+
38
+ [tool.chkstyle]
39
+ skip_paths = ["_modidx.py"]
@@ -1,35 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: fastasyncpg
3
- Version: 0.0.9
4
- Summary: A simple wrapper for asyncpg
5
- Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
- License: Apache-2.0
7
- Project-URL: Repository, https://github.com/AnswerDotAI/fastasyncpg
8
- Project-URL: Documentation, https://AnswerDotAI.github.io/fastasyncpg/
9
- Keywords: nbdev
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3 :: Only
12
- Requires-Python: >=3.10
13
- Description-Content-Type: text/markdown
14
- License-File: LICENSE
15
- Requires-Dist: asyncpg
16
- Requires-Dist: fastcore
17
- Requires-Dist: sqlparse
18
- Dynamic: license-file
19
-
20
- # fastasyncpg
21
-
22
-
23
- <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
24
-
25
- ## Installation
26
-
27
- Install latest from [pypi](https://pypi.org/project/fastasyncpg/)
28
-
29
- ``` sh
30
- $ pip install fastasyncpg
31
- ```
32
-
33
- ## How to use
34
-
35
- See API docs for now.
@@ -1,16 +0,0 @@
1
- # fastasyncpg
2
-
3
-
4
- <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
-
6
- ## Installation
7
-
8
- Install latest from [pypi](https://pypi.org/project/fastasyncpg/)
9
-
10
- ``` sh
11
- $ pip install fastasyncpg
12
- ```
13
-
14
- ## How to use
15
-
16
- See API docs for now.
@@ -1 +0,0 @@
1
- __version__ = "0.0.9"
@@ -1,35 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: fastasyncpg
3
- Version: 0.0.9
4
- Summary: A simple wrapper for asyncpg
5
- Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
- License: Apache-2.0
7
- Project-URL: Repository, https://github.com/AnswerDotAI/fastasyncpg
8
- Project-URL: Documentation, https://AnswerDotAI.github.io/fastasyncpg/
9
- Keywords: nbdev
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3 :: Only
12
- Requires-Python: >=3.10
13
- Description-Content-Type: text/markdown
14
- License-File: LICENSE
15
- Requires-Dist: asyncpg
16
- Requires-Dist: fastcore
17
- Requires-Dist: sqlparse
18
- Dynamic: license-file
19
-
20
- # fastasyncpg
21
-
22
-
23
- <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
24
-
25
- ## Installation
26
-
27
- Install latest from [pypi](https://pypi.org/project/fastasyncpg/)
28
-
29
- ``` sh
30
- $ pip install fastasyncpg
31
- ```
32
-
33
- ## How to use
34
-
35
- See API docs for now.
@@ -1,3 +0,0 @@
1
- asyncpg
2
- fastcore
3
- sqlparse
File without changes
File without changes
File without changes