From 7e617e2b3c637289584d9450e23fd793578e5f7b Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 3 Jun 2021 21:11:01 +0300 Subject: gn3: db: Add new function for doing sql INSERT --- gn3/db/__init__.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'gn3/db') 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: -- cgit v1.2.3