From 9de02a89cf4d134a4b289e5a799e0880c0e5840f 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/db') 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