aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBonfaceKilz2021-06-03 21:11:01 +0300
committerzsloan2021-06-18 22:08:04 +0000
commit511cde13c8f18c2e2be3a29eee3fa7366fce81a3 (patch)
tree1abb7ad3bd400eefc9a4586139e0d4d8c8437f88
parent1c7709af72e1826da830e2897d937a0706753b89 (diff)
downloadgenenetwork3-511cde13c8f18c2e2be3a29eee3fa7366fce81a3.tar.gz
gn3: db: Add new function for doing sql INSERT
-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: