1
\$\begingroup\$

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 create_record(), delete_record() or 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
\$\endgroup\$
2
  • \$\begingroup\$ I've been trying to build an ORM - perhaps there's been a curse placed on you, or perhaps someone is secretly drugging you, but for a personal project this is biting off a lot more than most people could chew. Is there any reason you aren't using SQLAlchemy? \$\endgroup\$ – Reinderien Jun 19 '20 at 18:54
  • \$\begingroup\$ Actually it's a side project where I am trying to practice system design, applying best practices and writing clean code. Regarding the curse stuff, I started to doubt it :) . \$\endgroup\$ – dark knight Jun 20 '20 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.