From 571f381c7502135d29f89612a91bf77a4b5568a5 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 29 Mar 2019 15:48:13 +0100 Subject: [PATCH] Generalize alchemy --- royalnet/database/alchemy.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/royalnet/database/alchemy.py b/royalnet/database/alchemy.py index e0f4464a..f1187e45 100644 --- a/royalnet/database/alchemy.py +++ b/royalnet/database/alchemy.py @@ -1,17 +1,19 @@ +import typing from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker -from .tables import Royal from ..utils import classdictjanitor class Alchemy: - def __init__(self, database_uri: str = "sqlite://"): + def __init__(self, database_uri: str = "sqlite://", tables: typing.Optional[typing.List] = None): self.engine = create_engine(database_uri) self.Base = declarative_base(bind=self.engine) self.Session = sessionmaker(bind=self.engine) - self._create_tables() + self._create_tables(tables) - def _create_tables(self): - self.Royal = type("Royal", (self.Base,), classdictjanitor(Royal)) + def _create_tables(self, tables: typing.Optional[typing.List]): + for table in tables: + name = table.__name__ + self.__setattr__(name, type(name, (self.Base,), classdictjanitor(table))) self.Base.metadata.create_all()