Permalink
Browse files

Add the ability for a default value for scalars

  • Loading branch information...
1 parent ac27d8d commit f282f6681274ffca307f1953953fcb4b5af5eb7c @dstufft committed Feb 28, 2014
Showing with 11 additions and 7 deletions.
  1. +7 −2 warehouse/db.py
  2. +4 −5 warehouse/packaging/models.py
View
@@ -19,13 +19,18 @@
metadata = sqlalchemy.MetaData()
-def scalar(query):
+def scalar(query, default=None):
"""
A helper function that takes a query and returns a function that will query
the database and return a scalar.
"""
def scalar_inner(model, **kwargs):
with model.engine.connect() as conn:
- return conn.execute(query).scalar()
+ val = conn.execute(query).scalar()
+
+ if default is not None and val is None:
+ return default
+ else:
+ return val
return scalar_inner
@@ -32,11 +32,10 @@ class Model(models.Model):
"SELECT COUNT(*) FROM packages"
)
- def get_download_count(self):
- query = "SELECT SUM(downloads) FROM release_files"
-
- with self.engine.connect() as conn:
- return conn.execute(query).scalar() or 0
+ get_download_count = db.scalar(
+ "SELECT SUM(downloads) FROM release_files",
+ default=0,
+ )
def get_recently_updated(self, num=10):
# We only consider releases made in the last 7 days, otherwise we have

0 comments on commit f282f66

Please sign in to comment.