From 122b046b92573f3e1db579b5ff73fa3bdfffc124 Mon Sep 17 00:00:00 2001
From: Lin Jen-Shin <godfat@godfat.org>
Date: Thu, 21 Jul 2016 01:10:08 +0800
Subject: [PATCH] Workaround MySQL with INNER JOIN:

This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME
subquery'

Oh well.
---
 app/models/commit_status.rb | 6 +++++-
 app/models/project.rb       | 9 +++++++--
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/app/models/commit_status.rb b/app/models/commit_status.rb
index 535db26240a..2d185c28809 100644
--- a/app/models/commit_status.rb
+++ b/app/models/commit_status.rb
@@ -16,7 +16,11 @@ class CommitStatus < ActiveRecord::Base
 
   alias_attribute :author, :user
 
-  scope :latest, -> { where(id: unscope(:select).select('max(id)').group(:name, :commit_id)) }
+  scope :latest, -> do
+    max_id = unscope(:select).select("max(#{quoted_table_name}.id)")
+
+    where(id: max_id.group(:name, :commit_id))
+  end
   scope :retried, -> { where.not(id: latest) }
   scope :ordered, -> { order(:name) }
   scope :ignored, -> { where(allow_failure: true, status: [:failed, :canceled]) }
diff --git a/app/models/project.rb b/app/models/project.rb
index 80860f142d4..9f0dcb9a212 100644
--- a/app/models/project.rb
+++ b/app/models/project.rb
@@ -431,8 +431,13 @@ class Project < ActiveRecord::Base
 
   # ref can't be HEAD, can only be branch/tag name or SHA
   def latest_successful_builds_for(ref = default_branch)
-    pipeline = pipelines.latest_successful_for(ref)
-    builds.where(pipeline: pipeline).latest.with_artifacts
+    pipeline = pipelines.latest_successful_for(ref).to_sql
+    join_sql = "INNER JOIN (#{pipeline}) pipelines" +
+               " ON pipelines.id = #{Ci::Build.quoted_table_name}.commit_id"
+    builds.joins(join_sql).latest.with_artifacts
+    # TODO: Whenever we dropped support for MySQL, we could change to:
+    # pipeline = pipelines.latest_successful_for(ref)
+    # builds.where(pipeline: pipeline).latest.with_artifacts
   end
 
   def merge_base_commit(first_commit_id, second_commit_id)
-- 
GitLab