Skip to content

Commit

Permalink
Improve performance
Browse files Browse the repository at this point in the history
  • Loading branch information
hackenbergstefan committed Jul 29, 2024
1 parent 3d68bb9 commit 08d4f96
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
2 changes: 1 addition & 1 deletion coffeebuddy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import OperationalError

__version__ = "1.1.0"
__version__ = "1.1.1"

db = SQLAlchemy()
login_manager = flask_login.LoginManager()
Expand Down
23 changes: 20 additions & 3 deletions coffeebuddy/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,18 @@ def drinks_today(self):

@property
def unpayed(self):
# TODO: Fast enough?
return sum(c.price for c in self.drinks) - sum(p.amount for p in self.pays)
db = flask.current_app.db
return (
db.session.scalar(
db.select(db.func.sum(Drink.price)).where(Drink.userid == self.id),
)
or 0.0
) - (
db.session.scalar(
db.select(db.func.sum(Pay.amount)).where(Pay.userid == self.id),
)
or 0.0
)

def nth_drink(self, date, n):
return (
Expand Down Expand Up @@ -129,7 +139,14 @@ def update_bill(self, newbill):
def count_selected_manually(self, host: Optional[str] = None) -> int:
"""Return how often this user logged in using 'Select manually'."""
host = host or socket.gethostname()
return sum(d.selected_manually for d in self.drinks if d.host == host)
db = flask.current_app.db
return db.session.scalar(
db.select(db.func.count("*")).where(
(Drink.userid == self.id)
& (Drink.host == host)
& Drink.selected_manually
)
)


class Drink(flask.current_app.db.Model):
Expand Down

0 comments on commit 08d4f96

Please sign in to comment.