Skip to content

Commit

Permalink
Bundle analysis: auto open and close DB session
Browse files Browse the repository at this point in the history
  • Loading branch information
JerrySentry committed Feb 21, 2024
1 parent 8e3e446 commit 9590e94
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions shared/bundle_analysis/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,27 @@

from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session as SQLAlchemySession
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func

from shared.bundle_analysis import models
from shared.bundle_analysis.parser import Parser


def db_query(f):
def wrapper(*args, **kw):
if not args[0].db_session:
raise Exception(f"No DB session found for {f}")

engine = args[0].db_session.get_bind()
Session = sessionmaker(engine)
with Session() as session:
args[0].db_session = session
return f(*args, **kw)

return wrapper


class AssetReport:
"""
Report wrapper around a single asset (many of which can exist in a single bundle).
Expand All @@ -33,6 +48,7 @@ def hashed_name(self):
def size(self):
return self.asset.size

@db_query
def modules(self):
return (
self.db_session.query(models.Module)
Expand All @@ -56,6 +72,7 @@ def __init__(self, bundle: models.Bundle):
def name(self):
return self.bundle.name

@db_query
def asset_reports(self) -> Iterator[AssetReport]:
assets = (
self.db_session.query(models.Asset)
Expand All @@ -66,6 +83,7 @@ def asset_reports(self) -> Iterator[AssetReport]:
)
return (AssetReport(asset) for asset in assets)

@db_query
def total_size(self) -> int:
return (
self.db_session.query(func.sum(models.Asset.size).label("asset_size"))
Expand All @@ -75,6 +93,7 @@ def total_size(self) -> int:
.scalar()
) or 0

@db_query
def info(self) -> dict:
session = (
self.db_session.query(models.Session)
Expand Down

0 comments on commit 9590e94

Please sign in to comment.