aboutsummaryrefslogtreecommitdiff
path: root/gn3
diff options
context:
space:
mode:
authorBonfaceKilz2021-06-03 21:11:01 +0300
committerBonfaceKilz2021-06-03 21:58:31 +0300
commit7e617e2b3c637289584d9450e23fd793578e5f7b (patch)
tree6661e4f8d7d5b96cdd8d6b83146b5dafdfd5f5fd /gn3
parent2bab870e5ef47b32a3356de74159e641138146c7 (diff)
downloadgenenetwork3-7e617e2b3c637289584d9450e23fd793578e5f7b.tar.gz
gn3: db: Add new function for doing sql INSERT
Diffstat (limited to 'gn3')
-rw-r--r--gn3/db/__init__.py18
1 files changed, 17 insertions, 1 deletions
diff --git a/gn3/db/__init__.py b/gn3/db/__init__.py
index 175a640..8b6bf73 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 typing import Optional, Dict, Any
-from dataclasses import dataclass, asdict, astuple
+from dataclasses import asdict, astuple
from typing_extensions import Protocol
from MySQLdb import escape_string
@@ -75,6 +75,22 @@ def fetchone(conn: Any,
return DATACLASSMAP[table](*cursor.fetchone())
+def insert(conn: Any,
+ table: str,
+ data: Dataclass) -> Optional[int]:
+ """Run an INSERT into a table"""
+ dict_ = {k: v for k, v in asdict(data).items()
+ if v is not None and k in TABLEMAP[table]}
+ sql = f"INSERT INTO {table} ("
+ sql += ", ".join(f"{k}" for k in dict_.keys())
+ sql += ") VALUES ("
+ sql += ", ".join("%s" for _ in dict_.keys())
+ sql += ")"
+ with conn.cursor() as cursor:
+ cursor.execute(sql, tuple(dict_.values()))
+ conn.commit()
+ return cursor.rowcount
+
def diff_from_dict(old: Dict, new: Dict) -> Dict:
"""Construct a new dict with a specific structure that contains the difference
between the 2 dicts in the structure: