From c05706b9529b079423dccfbcaeaaf535b98e583b Mon Sep 17 00:00:00 2001 From: Vaclav Lunak Date: Wed, 7 Feb 2024 12:13:02 +0100 Subject: [PATCH] update SQL queries to improve performance, fix alembic automigrations --- alembic/env.py | 4 ++-- src/cr/service.py | 2 +- src/diffs/service.py | 4 ++-- src/models.py | 15 +++++++++++++++ src/mtr/service.py | 2 +- 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/alembic/env.py b/alembic/env.py index b3b9f37..6ea6d47 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -4,7 +4,7 @@ from sqlalchemy import engine_from_config, pool from alembic import context -from models import Base +from src.models import get_full_base # this is the Alembic Config object, which provides # access to the values within the .ini file in use. @@ -19,7 +19,7 @@ # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata -target_metadata = Base.metadata +target_metadata = get_full_base().metadata # other values from the config, defined by the needs of env.py, # can be acquired: diff --git a/src/cr/service.py b/src/cr/service.py index 7da9abe..b185d5c 100644 --- a/src/cr/service.py +++ b/src/cr/service.py @@ -9,7 +9,7 @@ def get_latest_cr(db: Session) -> Cr: - stmt = select(Cr).order_by(Cr.creation_day.desc()) + stmt = select(Cr).order_by(Cr.creation_day.desc()).limit(1) result = db.execute(stmt).scalars().first() return result diff --git a/src/diffs/service.py b/src/diffs/service.py index 226a311..707026d 100644 --- a/src/diffs/service.py +++ b/src/diffs/service.py @@ -18,9 +18,9 @@ def get_cr_diff(db: Session, old_code: str | None, new_code: str | None) -> CrDi stmt = stmt.order_by(CrDiff.creation_day.desc()).limit(1) else: if old_code: - stmt = stmt.where(src.set_code == old_code) + stmt = stmt.where(src.set_code == old_code).limit(1) if new_code: - stmt = stmt.where(dst.set_code == new_code) + stmt = stmt.where(dst.set_code == new_code).limit(1) return db.execute(stmt).scalars().first() diff --git a/src/models.py b/src/models.py index 59be703..812915e 100644 --- a/src/models.py +++ b/src/models.py @@ -1,3 +1,18 @@ from sqlalchemy.orm import declarative_base Base = declarative_base() + + +# noinspection PyUnresolvedReferences + + +def get_full_base(): + """Imports all database models before returning the Base object. Used for alembic migrations""" + + import src.cr.models # noqa: F401 + import src.diffs.models # noqa: F401 + import src.ipg.models # noqa: F401 + import src.link.models # noqa: F401 + import src.mtr.models # noqa: F401 + + return Base diff --git a/src/mtr/service.py b/src/mtr/service.py index a4b9a6c..3c9395b 100644 --- a/src/mtr/service.py +++ b/src/mtr/service.py @@ -7,7 +7,7 @@ def get_current_mtr(db: Session) -> Mtr: - stmt = select(Mtr).order_by(Mtr.creation_day.desc()) + stmt = select(Mtr).order_by(Mtr.creation_day.desc()).limit(1) result = db.execute(stmt).scalars().first() return result