]> review.fuel-infra Code Review - openstack-build/heat-build.git/commitdiff
Optimise DB lookups by ID
authorZane Bitter <zbitter@redhat.com>
Thu, 5 Jul 2012 12:12:46 +0000 (14:12 +0200)
committerZane Bitter <zbitter@redhat.com>
Wed, 11 Jul 2012 15:54:36 +0000 (11:54 -0400)
SQLAlchemy caches objects in the database per-session, but cannot cache
queries. A query just generates a list of object primary keys, which is
then used to fetch the corresponding objects from the cache (if possible)
or database. Therefore a query which filters by primary key is a waste of
time, since it just returns (surprise!) the key we started off with. If we
have the primary key (in this case the id field), just look up the object.

Change-Id: I7123c12372b26c0e1b91b2496921c54d9d992cd8
Signed-off-by: Zane Bitter <zbitter@redhat.com>
heat/db/sqlalchemy/api.py

index dd800fe5be5831f51de167812ffb4d76b17b6c17..3d5b4bbd0692ace602140343ce9bf14afc121cb8 100644 (file)
@@ -33,8 +33,7 @@ def model_query(context, *args, **kwargs):
 
 
 def raw_template_get(context, template_id):
-    result = model_query(context, models.RawTemplate).\
-                        filter_by(id=template_id).first()
+    result = model_query(context, models.RawTemplate).get(template_id)
 
     if not result:
         raise NotFound("raw template with id %s not found" % template_id)
@@ -59,8 +58,7 @@ def raw_template_create(context, values):
 
 
 def resource_get(context, resource_id):
-    result = model_query(context, models.Resource).\
-                        filter_by(id=resource_id).first()
+    result = model_query(context, models.Resource).get(resource_id)
 
     if not result:
         raise NotFound("resource with id %s not found" % resource_id)
@@ -123,11 +121,12 @@ def stack_get_by_name(context, stack_name, owner_id=None):
 
 
 def stack_get(context, stack_id):
-    result = model_query(context, models.Stack).\
-                        filter_by(id=stack_id).first()
+    result = model_query(context, models.Stack).get(stack_id)
+
     if (result is not None and context is not None and
         result.username != context.username):
         return None
+
     return result
 
 
@@ -183,15 +182,13 @@ def user_creds_create(values):
 
 
 def user_creds_get(user_creds_id):
-    result = model_query(None, models.UserCreds).\
-                        filter_by(id=user_creds_id).first()
+    result = model_query(None, models.UserCreds).get(user_creds_id)
 
     return result
 
 
 def event_get(context, event_id):
-    result = model_query(context, models.Event).\
-                        filter_by(id=event_id).first()
+    result = model_query(context, models.Event).get(event_id)
 
     return result