aboutsummaryrefslogtreecommitdiff
path: root/gn3
diff options
context:
space:
mode:
authorBonfaceKilz2021-06-07 11:16:25 +0300
committerBonfaceKilz2021-06-07 19:58:44 +0300
commitae77ad6f35999dd416590f2a9d9d6451880a4a70 (patch)
tree851e2210b2154def61b884239f45d597c7bb7b79 /gn3
parent3d4ed55b9e163938b11a5c62d2c5bbe938727f03 (diff)
downloadgenenetwork3-ae77ad6f35999dd416590f2a9d9d6451880a4a70.tar.gz
gn3: db: Add "fetchall" method.
Diffstat (limited to 'gn3')
-rw-r--r--gn3/db/__init__.py20
1 files changed, 19 insertions, 1 deletions
diff --git a/gn3/db/__init__.py b/gn3/db/__init__.py
index d311dea..25ecfd6 100644
--- a/gn3/db/__init__.py
+++ b/gn3/db/__init__.py
@@ -1,7 +1,7 @@
# pylint: disable=[R0902, R0903]
"""Module that exposes common db operations"""
from dataclasses import asdict, astuple
-from typing import Optional, Dict, Any
+from typing import Any, Dict, Optional, Generator
from typing_extensions import Protocol
from gn3.db.metadata_audit import MetadataAudit
@@ -77,6 +77,24 @@ def fetchone(conn: Any,
return DATACLASSMAP[table](*cursor.fetchone())
+def fetchall(conn: Any,
+ table: str,
+ where: Optional[Dataclass]) -> Optional[Generator]:
+ """Run a SELECT on a table. Returns all the results as a tuple!"""
+ if not any(astuple(where)):
+ return None
+ where_ = {k: v for k, v in asdict(where).items()
+ if v is not None and k in TABLEMAP[table]}
+ sql = f"SELECT * FROM {table} "
+ if where:
+ sql += "WHERE "
+ sql += " AND ".join(f"{TABLEMAP[table].get(k)} = "
+ "%s" for k in where_.keys())
+ with conn.cursor() as cursor:
+ cursor.execute(sql, tuple(where_.values()))
+ return (DATACLASSMAP[table](*record) for record in cursor.fetchall())
+
+
def insert(conn: Any,
table: str,
data: Dataclass) -> Optional[int]: