From fba2ec45b3bf493611f2d7e7e13a21c39bc654e0 Mon Sep 17 00:00:00 2001
From: Lin Jen-Shin <godfat@godfat.org>
Date: Tue, 19 Jul 2016 17:08:21 +0800
Subject: [PATCH] Just use order(id: :desc) for latest stuffs:

We don't need that subquery for group by ref and alike here.
---
 app/models/ci/build.rb    |  2 +-
 app/models/ci/pipeline.rb | 10 +---------
 app/models/project.rb     |  2 +-
 3 files changed, 3 insertions(+), 11 deletions(-)

diff --git a/app/models/ci/build.rb b/app/models/ci/build.rb
index 9af04964b85..c048eff0f80 100644
--- a/app/models/ci/build.rb
+++ b/app/models/ci/build.rb
@@ -16,7 +16,7 @@ module Ci
     scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
     scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
     scope :latest_success_with_artifacts, ->() do
-      with_artifacts.success.latest
+      with_artifacts.success.order(id: :desc)
     end
 
     mount_uploader :artifacts_file, ArtifactUploader
diff --git a/app/models/ci/pipeline.rb b/app/models/ci/pipeline.rb
index a8e6a23e1c4..148b056789a 100644
--- a/app/models/ci/pipeline.rb
+++ b/app/models/ci/pipeline.rb
@@ -20,14 +20,6 @@ module Ci
     after_touch :update_state
     after_save :keep_around_commits
 
-    scope :latest, -> do
-      max_id = unscope(:select).
-                 select("max(#{table_name}.id)").
-                 group(:ref)
-
-      where(id: max_id)
-    end
-
     def self.truncate_sha(sha)
       sha[0...8]
     end
@@ -226,7 +218,7 @@ module Ci
 
     def keep_around_commits
       return unless project
-      
+
       project.repository.keep_around(self.sha)
       project.repository.keep_around(self.before_sha)
     end
diff --git a/app/models/project.rb b/app/models/project.rb
index 77431c3f538..30e8ade99ff 100644
--- a/app/models/project.rb
+++ b/app/models/project.rb
@@ -431,7 +431,7 @@ class Project < ActiveRecord::Base
 
   # ref can't be HEAD or SHA, can only be branch/tag name
   def latest_success_pipeline_for(ref = 'master')
-    pipelines.where(ref: ref).success.latest
+    pipelines.where(ref: ref).success.order(id: :desc)
   end
 
   # ref can't be HEAD or SHA, can only be branch/tag name
-- 
GitLab