From ed62339f899e30690f88a4d286a07c417796dbc1 Mon Sep 17 00:00:00 2001
From: Jake Moshenko <jake.moshenko@coreos.com>
Date: Tue, 4 Aug 2015 18:20:54 -0400
Subject: [PATCH] Improve the performance of queue candidate queries.

---
 data/queue.py | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/data/queue.py b/data/queue.py
index 60632f5b1..d40df3335 100644
--- a/data/queue.py
+++ b/data/queue.py
@@ -120,16 +120,21 @@ class WorkQueue(object):
     name_match_query = self._name_match_query()
 
     running = self._running_jobs(now, name_match_query)
-    avail = self._available_jobs_not_running(now, name_match_query, running)
+    avail = self._available_jobs_not_running(now, name_match_query, running).alias('avail')
 
     item = None
     try:
-      db_item_candidate = avail.order_by(QueueItem.id).get()
+      db_item_candidate_id = (QueueItem
+                              .select(avail.c.id)
+                              .from_(avail)
+                              .order_by(avail.c.id)
+                              .tuples()
+                              .get())[0]
 
       with self._transaction_factory(db):
         still_available_query = (db_for_update(self
                                                ._available_jobs(now, name_match_query)
-                                               .where(QueueItem.id == db_item_candidate.id)))
+                                               .where(QueueItem.id == db_item_candidate_id)))
 
         db_item = still_available_query.get()
         db_item.available = False