From 2face963fcba5b3231e9cc26a38f1370b00eb7b0 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 20 May 2021 21:25:48 +0300 Subject: db: phenotypes: Add function for fetching a single result * gn3/db/phenotypes.py (fetchone): New function. --- gn3/db/phenotypes.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'gn3') diff --git a/gn3/db/phenotypes.py b/gn3/db/phenotypes.py index c3ad683..96cb275 100644 --- a/gn3/db/phenotypes.py +++ b/gn3/db/phenotypes.py @@ -142,3 +142,20 @@ def update(conn: Any, with conn.cursor() as cursor: cursor.execute(sql) return cursor.rowcount + + +def fetchone(conn: Any, + table: str, + where: Dataclass) -> Optional[Dataclass]: + """Run a SELECT on a table. Returns only one result!""" + if not any(astuple(where)): + return None + sql = f"SELECT * FROM {table} " + sql += "WHERE " + sql += "AND ".join(f"{TABLEMAP[table].get(k)} = " + f"'{escape_string(str(v)).decode('utf-8')}'" for + k, v in asdict(where).items() + if v is not None and k in TABLEMAP[table]) + with conn.cursor() as cursor: + cursor.execute(sql) + return DATACLASSMAP[table](*cursor.fetchone()) -- cgit v1.2.3