fastasyncpg 0.1.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastasyncpg
3
- Version: 0.1.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
6
  License-Expression: Apache-2.0
@@ -4,4 +4,6 @@ Modules:
4
4
 
5
5
  - `fastasyncpg.skill`: Use fastasyncpg's async table helpers and SQL API."""
6
6
 
7
- __version__ = "0.1.1"
7
+ __version__ = "0.1.2"
8
+
9
+
@@ -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'),
@@ -218,6 +218,24 @@ async def q(self:Database, sql, *args, **kwargs):
218
218
  csql, kw_args = conv_placeholders(sql, **kwargs)
219
219
  return Results(await self.fetch(csql, *args, *kw_args))
220
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
+
221
239
  # %% ../nbs/00_core.ipynb #0fc7310b
222
240
  from datetime import datetime, date, time, timedelta
223
241
  from decimal import Decimal
@@ -363,7 +381,7 @@ async def rows_where(self:Table, where=None, where_args=None, order_by=None, sel
363
381
  # %% ../nbs/00_core.ipynb #b96b3f21
364
382
  @patch
365
383
  async def count_where(self:Table, where=None, where_args=None):
366
- # TODO: support `?` placeholders too
384
+ "Count rows matching `where` (plus any `xtra` constraints)"
367
385
  where, args = _add_xtra(self, where, where_args)
368
386
  sql = f'SELECT COUNT(*) FROM {self}'
369
387
  if where: sql += f' WHERE {where}'
@@ -373,6 +391,15 @@ async def count_where(self:Table, where=None, where_args=None):
373
391
  @patch(as_prop=True)
374
392
  async def count(self:Table): return await self.count_where()
375
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
+
376
403
  # %% ../nbs/00_core.ipynb #28682469
377
404
  from collections.abc import Mapping
378
405
 
@@ -399,35 +426,48 @@ async def __call__(self:Table, where=None, where_args=None, order_by=None, limit
399
426
 
400
427
  # %% ../nbs/00_core.ipynb #73e88814
401
428
  @patch
402
- async def selectone(
429
+ async def one_or_none(
403
430
  self:Table,
404
- where:str|None=None, # SQL where fragment to use, for example `id > ?`
405
- where_args: Iterable|dict|NoneType=None, # Parameters to use with `where`; iterable for `id>?`, or dict for `id>:id`
406
- select:str = "*", # Comma-separated list of columns to select
407
- as_cls:bool=True, # Convert returned dict to stored dataclass?
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?
408
435
  debug:bool=False
409
- )->list:
410
- "Shortcut for `__call__` that returns exactly one item"
436
+ ):
437
+ "Return the single matching row or None; raises ValueError if multiple match"
411
438
  res = await self(where=where, where_args=where_args, select=select, as_cls=as_cls, limit=2, debug=debug)
412
- if len(res)==0: raise NotFoundError
413
- elif len(res) > 1: raise ValueError(f"Not unique: {len(res)} results")
414
- return res[0]
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
415
449
 
416
450
  # %% ../nbs/00_core.ipynb #d994c66c
417
451
  @patch
418
- async def qone(self:Database, sql, *args, **kwargs):
419
- "Execute sql and return exactly one row"
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"
420
454
  res = await self.q(sql, *args, **kwargs)
421
- if len(res)==0: raise NotFoundError
422
- if len(res)>1: raise ValueError(f"Not unique: {len(res)} results")
423
- return res[0]
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
424
464
 
425
465
  # %% ../nbs/00_core.ipynb #e53a268a
426
466
  @patch
427
- async def item(self:Database, sql, *args, **kwargs):
428
- "Execute sql and return a single field from a single row"
429
- row = await self.qone(sql, *args, **kwargs)
430
- if len(row)>1: raise ValueError(f"Too many fields: {len(row)} fields")
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)}")
431
471
  return row[0]
432
472
 
433
473
  # %% ../nbs/00_core.ipynb #0261da8a
@@ -765,7 +805,7 @@ async def claim_one(self:Table, status_col='status', pending='pending', complete
765
805
  stmt = f'UPDATE {self} SET "{status_col}"=$1 WHERE "{pk}"=$2'
766
806
  if new:
767
807
  await txn.execute(stmt, new, get_field(p.evt, pk))
768
- p.evt = await self.selectone(f'"{pk}"=$1', [get_field(p.evt, pk)])
808
+ p.evt = await self.one(f'"{pk}"=$1', [get_field(p.evt, pk)])
769
809
 
770
810
 
771
811
  # %% ../nbs/00_core.ipynb #15582b9e
@@ -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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastasyncpg
3
- Version: 0.1.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
6
  License-Expression: Apache-2.0
@@ -1,18 +0,0 @@
1
- # NB: this file is designed for an LLM reader, not a human. Add it to your LLM's context and ask it to explain.
2
- r"""Use fastasyncpg's async table helpers and SQL API.
3
-
4
- Read `nbs/00_core.ipynb` for executable examples. Inspect `doc(fastasyncpg.core)` and bound table methods before use.
5
-
6
- - module-global `db = Database()`; `await db.connect(...)` at startup creates a pool per event loop. `await db.close()` closes that loop's pool.
7
- - `t = db.t.user`: cached Table; `t.cols`, `t.pks` are schema metadata. `await t(where, args)` returns a list, not a lazy query.
8
- - `await t[pk]`: row or `NotFoundError`; `await t.get(pk)`: row or `None`. These use the first primary-key column.
9
- - `await t.selectone(where, args)` / `await db.qone(sql, ...)`: exactly one row; zero -> `NotFoundError`, multiple -> `ValueError`. Prefer these over `first(await ...)`.
10
- - `await db.item(sql, ...)`: exactly one row and field. `await t.count`: async property.
11
- - `db.q`: `$1`, `?`, or `:name` placeholders; named values as kwargs. Delegated asyncpg methods (`fetch`, `execute`, etc.) and `count_where` require `$1`. Table `where_args` are positional values. `order_by` is SQL, e.g. `'name DESC'`, not `'-name'`.
12
- - interpolate `t` and `t.c.name` for quoted identifiers; parameterize values
13
- - `t.dataclass()` binds future reads to that class. Dataclass `UNSET` fields are omitted on writes; `None` writes NULL. Single-row writes return rows; `inserts`/`updates`/`upserts` return `None`. Missing bulk columns become NULL.
14
- - `async with db.transaction()`: all helpers join through task-local context; no connection/session passing. Nested transactions are savepoints. Spawn background tasks outside transaction/acquire blocks.
15
- - `t.xtra(...)` mutates the shared cached Table; `t.xtra()` clears it. Never use for request-local filters in concurrent code.
16
- - `upsert` updates supplied fields on primary-key conflict; it is not get-or-create
17
- - `claim` requires a transaction. `claim_one` manages status and catches processing exceptions; inspect its result's `failed` field.
18
- """
File without changes
File without changes
File without changes
File without changes