fastasyncpg 0.0.4__tar.gz → 0.0.6__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.0.4
3
+ Version: 0.0.6
4
4
  Summary: A simple wrapper for asyncpg
5
5
  Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
6
  License: Apache-2.0
@@ -0,0 +1 @@
1
+ __version__ = "0.0.6"
@@ -19,6 +19,7 @@ d = { 'settings': { 'branch': 'main',
19
19
  'fastasyncpg.core.Database.item': ('core.html#database.item', 'fastasyncpg/core.py'),
20
20
  'fastasyncpg.core.Database.link_dcs': ('core.html#database.link_dcs', 'fastasyncpg/core.py'),
21
21
  'fastasyncpg.core.Database.q': ('core.html#database.q', 'fastasyncpg/core.py'),
22
+ 'fastasyncpg.core.Database.qone': ('core.html#database.qone', 'fastasyncpg/core.py'),
22
23
  'fastasyncpg.core.Database.refresh': ('core.html#database.refresh', 'fastasyncpg/core.py'),
23
24
  'fastasyncpg.core.Database.set_classes': ('core.html#database.set_classes', 'fastasyncpg/core.py'),
24
25
  'fastasyncpg.core.Database.t': ('core.html#database.t', 'fastasyncpg/core.py'),
@@ -47,6 +48,7 @@ d = { 'settings': { 'branch': 'main',
47
48
  'fastasyncpg.core.Table.delete_where': ('core.html#table.delete_where', 'fastasyncpg/core.py'),
48
49
  'fastasyncpg.core.Table.drop': ('core.html#table.drop', 'fastasyncpg/core.py'),
49
50
  'fastasyncpg.core.Table.get': ('core.html#table.get', 'fastasyncpg/core.py'),
51
+ 'fastasyncpg.core.Table.groupby': ('core.html#table.groupby', 'fastasyncpg/core.py'),
50
52
  'fastasyncpg.core.Table.insert': ('core.html#table.insert', 'fastasyncpg/core.py'),
51
53
  'fastasyncpg.core.Table.inserts': ('core.html#table.inserts', 'fastasyncpg/core.py'),
52
54
  'fastasyncpg.core.Table.pks': ('core.html#table.pks', 'fastasyncpg/core.py'),
@@ -57,6 +59,7 @@ d = { 'settings': { 'branch': 'main',
57
59
  'fastasyncpg.core.Table.update': ('core.html#table.update', 'fastasyncpg/core.py'),
58
60
  'fastasyncpg.core.Table.updates': ('core.html#table.updates', 'fastasyncpg/core.py'),
59
61
  'fastasyncpg.core.Table.upsert': ('core.html#table.upsert', 'fastasyncpg/core.py'),
62
+ 'fastasyncpg.core.Table.upserts': ('core.html#table.upserts', 'fastasyncpg/core.py'),
60
63
  'fastasyncpg.core.Table.xtra': ('core.html#table.xtra', 'fastasyncpg/core.py'),
61
64
  'fastasyncpg.core._Col': ('core.html#_col', 'fastasyncpg/core.py'),
62
65
  'fastasyncpg.core._Col.__init__': ('core.html#_col.__init__', 'fastasyncpg/core.py'),
@@ -85,11 +88,10 @@ d = { 'settings': { 'branch': 'main',
85
88
  'fastasyncpg.core._convq': ('core.html#_convq', 'fastasyncpg/core.py'),
86
89
  'fastasyncpg.core._dataclass': ('core.html#_dataclass', 'fastasyncpg/core.py'),
87
90
  'fastasyncpg.core._get_flds': ('core.html#_get_flds', 'fastasyncpg/core.py'),
88
- 'fastasyncpg.core._join_where': ('core.html#_join_where', 'fastasyncpg/core.py'),
91
+ 'fastasyncpg.core._norm_rows': ('core.html#_norm_rows', 'fastasyncpg/core.py'),
89
92
  'fastasyncpg.core._pk_where': ('core.html#_pk_where', 'fastasyncpg/core.py'),
90
93
  'fastasyncpg.core._prep_row': ('core.html#_prep_row', 'fastasyncpg/core.py'),
91
94
  'fastasyncpg.core._process_row': ('core.html#_process_row', 'fastasyncpg/core.py'),
92
- 'fastasyncpg.core._vals_sql': ('core.html#_vals_sql', 'fastasyncpg/core.py'),
93
95
  'fastasyncpg.core.all_dcs': ('core.html#all_dcs', 'fastasyncpg/core.py'),
94
96
  'fastasyncpg.core.col_def': ('core.html#col_def', 'fastasyncpg/core.py'),
95
97
  'fastasyncpg.core.columns_info': ('core.html#columns_info', 'fastasyncpg/core.py'),
@@ -392,15 +392,21 @@ async def selectone(
392
392
  elif len(res) > 1: raise ValueError(f"Not unique: {len(res)} results")
393
393
  return res[0]
394
394
 
395
- # %% ../nbs/00_core.ipynb #215c7630
395
+ # %% ../nbs/00_core.ipynb #d994c66c
396
396
  @patch
397
- async def item(self:Database, sql, args=None):
398
- "Execute sql and return a single field from a single row"
399
- res = await self.fetch(sql, *(args or []))
397
+ async def qone(self:Database, sql, *args, **kwargs):
398
+ "Execute sql and return exactly one row"
399
+ res = await self.q(sql, *args, **kwargs)
400
400
  if len(res)==0: raise NotFoundError
401
- elif len(res) > 1: raise ValueError(f"Not unique: {len(res)} results")
402
- row = res[0]
403
- if len(row) > 1: raise ValueError(f"Too many fields: {len(row)} fields")
401
+ if len(res)>1: raise ValueError(f"Not unique: {len(res)} results")
402
+ return res[0]
403
+
404
+ # %% ../nbs/00_core.ipynb #e53a268a
405
+ @patch
406
+ async def item(self:Database, sql, *args, **kwargs):
407
+ "Execute sql and return a single field from a single row"
408
+ row = await self.qone(sql, *args, **kwargs)
409
+ if len(row)>1: raise ValueError(f"Too many fields: {len(row)} fields")
404
410
  return row[0]
405
411
 
406
412
  # %% ../nbs/00_core.ipynb #0261da8a
@@ -499,51 +505,37 @@ async def update(self:Table, record=None, pk_values=None, **kwargs):
499
505
  return await self._rec(sql, *row.values(), *args, err=f"{self.name}[{pk_values}]")
500
506
 
501
507
  # %% ../nbs/00_core.ipynb #4e7c77dc
502
- def _vals_sql(rows, types):
503
- "Build the VALUES clause and list of arguments"
504
- n, args, parts = len(types), [], []
505
- ct = [t.split('(')[0].strip() for t in types]
506
- for i,row in enumerate(rows):
507
- parts.append('(' + ', '.join(f'${i*n+j+1}::{ct[j]}' for j in range(n)) + ')')
508
- args.extend(row.values())
509
- return args, ', '.join(parts)
510
-
511
- # %% ../nbs/00_core.ipynb #1a1e9bfe
512
- def _join_where(pks, xtra_id, n_args):
513
- "Get the join WHERE clause for `updates` and the xtra args needed for it (if any)"
514
- pw = ' AND '.join(f't."{pk}"=v."{pk}"' for pk in pks)
515
- args = []
516
- if xtra_id:
517
- pw += ' AND ' + ' AND '.join(f't."{k}"=${n_args+i+1}' for i,k in enumerate(xtra_id))
518
- args = list(xtra_id.values())
519
- return pw, args
508
+ def _norm_rows(rows):
509
+ "Normalize rows to same columns, return (cols, list of arg tuples)"
510
+ cols = list(dict.fromkeys(k for r in rows for k in r))
511
+ return cols, [tuple(r.get(c) for c in cols) for r in rows]
520
512
 
521
513
  # %% ../nbs/00_core.ipynb #51c5ace8
522
514
  @patch
523
515
  async def updates(self:Table, records):
524
- "Update multiple rows in one query and return them"
525
- if not records: return []
516
+ "Update multiple rows"
517
+ if not records: return
526
518
  rows = [_process_row(r, {}) for r in records]
527
- cols = list(rows[0].keys())
528
- args, vals = _vals_sql(rows, [self.cols[c] for c in cols])
519
+ cols, norm = _norm_rows(rows)
529
520
  non_pk = [c for c in cols if c not in self.pks]
530
- sets = ', '.join(f'"{c}"=v."{c}"' for c in non_pk)
531
- pw, xa = _join_where(self.pks, self.xtra_id, len(args))
532
- qcols = ', '.join(f'"{c}"' for c in cols)
533
- sql = f'UPDATE {self} AS t SET {sets} FROM (VALUES {vals}) AS v({qcols}) WHERE {pw} RETURNING t.*'
534
- return await self._recs(sql, *args, *xa)
521
+ sets = ', '.join(f'"{c}"=${i+1}' for i,c in enumerate(non_pk))
522
+ pw = _pk_where(self.pks, len(non_pk))
523
+ xa = tuple(self.xtra_id.values())
524
+ if xa: pw += ' AND ' + ' AND '.join(f'"{k}"=${len(non_pk)+len(self.pks)+i+1}' for i,k in enumerate(self.xtra_id))
525
+ ci = {c:i for i,c in enumerate(cols)}
526
+ args = [tuple(row[ci[c]] for c in non_pk) + tuple(row[ci[pk]] for pk in self.pks) + xa for row in norm]
527
+ await self.db.executemany(f'UPDATE {self} SET {sets} WHERE {pw}', args)
535
528
 
536
529
  # %% ../nbs/00_core.ipynb #27ebb35c
537
530
  @patch
538
531
  async def inserts(self:Table, records):
539
- "Insert multiple rows in one query and return them"
540
- if not records: return []
532
+ "Insert multiple rows"
533
+ if not records: return
541
534
  rows = [_process_row(r, self.xtra_id) for r in records]
542
- cols = list(rows[0].keys())
543
- args, vals = _vals_sql(rows, [self.cols[c] for c in cols])
535
+ cols, args = _norm_rows(rows)
544
536
  qcols = ', '.join(f'"{c}"' for c in cols)
545
- sql = f'INSERT INTO {self} ({qcols}) VALUES {vals} RETURNING *'
546
- return await self._recs(sql, *args)
537
+ vals = ', '.join(f'${i+1}' for i in range(len(cols)))
538
+ await self.db.executemany(f'INSERT INTO {self} ({qcols}) VALUES ({vals})', args)
547
539
 
548
540
  # %% ../nbs/00_core.ipynb #f9968e6f
549
541
  @patch
@@ -626,6 +618,38 @@ async def upsert(self:Table, record=None, **kwargs):
626
618
  updates = ', '.join(f'"{k}"=EXCLUDED."{k}"' for k in row if k != pk)
627
619
  return await self._rec(f'INSERT INTO {self} ({cols}) VALUES ({vals}) ON CONFLICT ("{pk}") DO UPDATE SET {updates} RETURNING *', *row.values())
628
620
 
621
+ # %% ../nbs/00_core.ipynb #9abd1d88
622
+ @patch
623
+ async def upserts(self:Table, records):
624
+ "Insert or update multiple rows"
625
+ if not records: return
626
+ pk = self.pks[0]
627
+ proc = [_process_row(r, self.xtra_id) for r in records]
628
+ has_pk = [r for r in proc if r.get(pk) is not None]
629
+ no_pk = [{k:v for k,v in r.items() if k != pk} for r in proc if r.get(pk) is None]
630
+ if has_pk:
631
+ cols, args = _norm_rows(has_pk)
632
+ qcols = ', '.join(f'"{c}"' for c in cols)
633
+ vals = ', '.join(f'${i+1}' for i in range(len(cols)))
634
+ upd = ', '.join(f'"{c}"=EXCLUDED."{c}"' for c in cols if c != pk)
635
+ await self.db.executemany(f'INSERT INTO {self} ({qcols}) VALUES ({vals}) ON CONFLICT ("{pk}") DO UPDATE SET {upd}', args)
636
+ if no_pk: await self.inserts(no_pk)
637
+
638
+ # %% ../nbs/00_core.ipynb #4962e324
639
+ @patch
640
+ async def groupby(self:Table, groupflds:list[str], aggs:list[str]):
641
+ "Dict of `groupflds` to `aggs` results via GROUP BY"
642
+ gcols,acols = ','.join(f'"{g}"' for g in groupflds), ','.join(aggs)
643
+ where, args = _add_xtra(self, None, [])
644
+ sql = f"SELECT {gcols},{acols} FROM {self}"
645
+ if where: sql += f" WHERE {where}"
646
+ sql += f" GROUP BY {gcols}"
647
+ rows = await self.db.q(sql, *args)
648
+ ng = len(groupflds)
649
+ def _key(r): return r[0] if ng==1 else tuple(r[i] for i in range(ng))
650
+ def _val(r): return r[ng] if len(aggs)==1 else tuple(r[ng+i] for i in range(len(aggs)))
651
+ return {_key(r): _val(r) for r in rows}
652
+
629
653
  # %% ../nbs/00_core.ipynb #6be00990
630
654
  async def create_pool(*args, **kwargs):
631
655
  kwargs.setdefault('record_class', FRecord)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastasyncpg
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Summary: A simple wrapper for asyncpg
5
5
  Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
6
  License: Apache-2.0
@@ -1 +0,0 @@
1
- __version__ = "0.0.4"
File without changes
File without changes
File without changes
File without changes
File without changes