From f539db5933b7156effede2666fac7e4bbe29df5e Mon Sep 17 00:00:00 2001 From: Oscar Krause Date: Fri, 23 Dec 2022 13:17:19 +0100 Subject: [PATCH] implemented db_init --- app/main.py | 3 ++- app/orm.py | 12 +++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/app/main.py b/app/main.py index 15f0c35..5060361 100644 --- a/app/main.py +++ b/app/main.py @@ -22,7 +22,7 @@ from sqlalchemy.orm import sessionmaker from Crypto.PublicKey import RSA from Crypto.PublicKey.RSA import RsaKey -from orm import Origin, Lease +from orm import Origin, Lease, init as db_init logger = logging.getLogger() load_dotenv('../version.env') @@ -48,6 +48,7 @@ __details = dict( ) app, db = FastAPI(**__details), create_engine(url=str(getenv('DATABASE', 'sqlite:///db.sqlite'))) +db_init(db) TOKEN_EXPIRE_DELTA = relativedelta(hours=1) # days=1 LEASE_EXPIRE_DELTA = relativedelta(days=int(getenv('LEASE_EXPIRE_DAYS', 90))) diff --git a/app/orm.py b/app/orm.py index b7b05b7..bb806ae 100644 --- a/app/orm.py +++ b/app/orm.py @@ -1,6 +1,6 @@ import datetime -from sqlalchemy import Column, VARCHAR, CHAR, ForeignKey, DATETIME, UniqueConstraint, update, and_, delete +from sqlalchemy import Column, VARCHAR, CHAR, ForeignKey, DATETIME, UniqueConstraint, update, and_, delete, inspect from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.future import Engine from sqlalchemy.orm import sessionmaker @@ -102,3 +102,13 @@ class Lease(Base): deletions = session.query(Lease).delete(Lease.origin_ref == origin_ref) session.close() return deletions + + +def init(engine: Engine): + tables = [Origin, Lease] + db = inspect(engine) + session = sessionmaker(bind=engine)() + for table in tables: + if not db.dialect.has_table(engine.connect(), table.__tablename__): + session.execute(str(table.create_statement(engine))) + session.close()