Exemple #1
0
class dbConector:

    __instance = None  # singleton reference
    dbAgent = None

    @staticmethod
    def getInstance():  # Method to get the unique reference for the class
        if dbConector.__instance == None:
            dbConector()
        return dbConector.__instance

    def __init__(self):
        if dbConector.__instance != None:
            raise Exception("glitch in the matrix, talk to nio")
        else:
            dbConector.__instance = self

    def doConection(
            self):  # Do the connection with DB users in the same directory

        if not isfile(
                'Users.db'):  # If is the first time, it will create the DB
            self.dbAgent = Database("Users.db")
            self.dbAgent.query(Person, Groups).create().execute()
        else:
            self.dbAgent = Database("Users.db")

    def closeConection(self) -> None:
        self.dbAgent.close()
Exemple #2
0
class DB:
    "The main database object"
    tables = (User, Settings,)

    def __init__(self):
        is_db_exists = os.path.isfile(settings.DB_NAME)
        self._db = Database(settings.DB_NAME)
        if not is_db_exists:
            self._create_db_for_first_use()

    @property
    def database(self):
        "Returns the database"
        return self._db

    def _create_db_for_first_use(self, skip_error=False):
        logger.debug("Creating tables")
        # Create the tables
        for table in self.tables:
            try:
                self.database.query(table).create().execute()
            except sqlite3.OperationalError:
                if not skip_error:
                    logger.error(
                        "Could not created table %s",
                        table.__table_name__
                    )
                    raise
                logger.warning(
                    "Could not created table %s",
                    table.__table_name__
                )
        self.insert(Settings())

    def select(self, select_from, *condition_expressions, logical_operator='AND'):
        "Returns the values from database based on conditions"
        query = self._db.query(select_from).select()

        if condition_expressions:
            query = query.filter(
                *condition_expressions,
                logical_operator_inner=logical_operator
            )

        result = query.execute()
        result_list = []
        for res in result:
            result_list.append(select_from(*res))
        return result_list

    def insert(self, obj):
        "Inserts the record"
        self.database.query().insert(obj).execute()

    def delete(self, obj):
        "Deletes record from database based on id"
        self.database.query(obj.__class__).delete().filter(
            obj.__class__.id == obj.id
        ).execute()

    def update(self, obj, *parts):
        "Updates the database"
        if not parts:
            # Update all fields
            parts = tuple(obj.fields())

        kwargs = {}
        for part in parts:
            kwargs[part] = getattr(obj, part)

        self.database.query(obj.__class__).update(
            **kwargs
        ).filter(obj.__class__.id == obj.id).execute()

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        self.database.close()

    def __del__(self):
        # pylint:disable=bare-except
        try:
            self._db.close()
        except:
            pass