Permalink
Browse files

Add a helper function for mapping a row to a dict

  • Loading branch information...
1 parent 1fa86ae commit 94a29ff8d2f6f8ac1b0f8fe92c5a5c1a9b97ef9b @dstufft committed Feb 28, 2014
Showing with 29 additions and 19 deletions.
  1. +15 −0 warehouse/db.py
  2. +14 −19 warehouse/packaging/models.py
View
@@ -46,3 +46,18 @@ def inner(model, *args, **kwargs):
return [row_func(r) for r in conn.execute(query, *args, **kwargs)]
return inner
+
+
+def mapping(query, key_func, value_func):
+ """
+ A helper function that takes a query, a key_func, and a value_func and will
+ created a mapping that maps each row to a key: value pair.
+ """
+ def inner(model, *args, **kwargs):
+ with model.engine.connect() as conn:
+ return {
+ key_func(r): value_func(r)
+ for r in conn.execute(query, *args, **kwargs)
+ }
+
+ return inner
@@ -149,19 +149,15 @@ def get_top_projects(self, num=None):
"SELECT hosting_mode FROM packages WHERE name = %s"
)
- def get_release_urls(self, name):
- query = \
- """ SELECT version, home_page, download_url
- FROM releases
- WHERE name = %(project)s
- ORDER BY version DESC
- """
-
- with self.engine.connect() as conn:
- return {
- r["version"]: (r["home_page"], r["download_url"])
- for r in conn.execute(query, project=name)
- }
+ get_release_urls = db.mapping(
+ """ SELECT version, home_page, download_url
+ FROM releases
+ WHERE name = %s
+ ORDER BY version DESC
+ """,
+ key_func=lambda r: r["version"],
+ value_func=lambda r: (r["home_page"], r["download_url"]),
+ )
get_external_urls = db.rows(
""" SELECT DISTINCT ON (url) url
@@ -209,12 +205,11 @@ def get_last_serial(self, name=None):
return db.scalar(query)(self, name=name)
- def get_projects_with_serial(self):
- # return list of dict(name: max id)
- query = "SELECT name, max(id) FROM journals GROUP BY name"
-
- with self.engine.connect() as conn:
- return dict(r for r in conn.execute(query))
+ get_projects_with_serial = db.mapping(
+ "SELECT name, max(id) FROM journals GROUP BY name",
+ key_func=lambda r: r[0],
+ value_func=lambda r: r[1],
+ )
get_project_versions = db.rows(
""" SELECT version

0 comments on commit 94a29ff

Please sign in to comment.