I've been trying to build an ORM. I started with the connector layer, which is responsible for the database server connections and executes raw SQL as the code below shows.
I have built the
_dbconnect decorator to separate database connection procedures from the CRUD functions. This will be responsible for SQL conversions only, maintaining the single responsibility principle.
Is the idea of this decorator good or not since it doesn't return any thing?
In the future the
read_record() functions will need some sort of values to be returned. The result is also going to be different for all of them because when creating a record you will need to return the id only which is supposed to be an
int, but selecting record will be a list of records in predefined data structure.
So is it OK for the decorator to be returning different types like mentioned above, and what are the better ways to handle it ?
from abstract_connector import AbstractConnector import psycopg2 class PsqlConnector(AbstractConnector): def __init__(self, username: str, password: str, dbname: str): self.username = username self.password = password self.dbname = dbname def _dbconnect(func): def wrapper(self, *args, **kwargs): query = func(self, *args, **kwargs) conn = psycopg2.connect("dbname=%s user=%s, password=%s" % (self.dbname, self.username, self.password)) cur = conn.cursor() cur.execute(query) conn.commit() cur.close() conn.close() return wrapper @_dbconnect def create_table(self, name: str): return "CREATE TABLE %s(id serial PRIMARY KEY, name VARCHAR(100));" % name @_dbconnect def drop_table(self, name: str): return "DROP TABLE IF EXISTS %s" % name