2018-04-20 10:44:20 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
# rubocop:disable Style/Documentation
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module BackgroundMigration
|
|
|
|
class MigrateStageIndex
|
2018-04-24 12:14:33 +00:00
|
|
|
def perform(start_id, stop_id)
|
|
|
|
migrate_stage_index_sql(start_id.to_i, stop_id.to_i).tap do |sql|
|
|
|
|
ActiveRecord::Base.connection.execute(sql)
|
2018-04-20 10:44:20 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-04-24 12:14:33 +00:00
|
|
|
private
|
|
|
|
|
|
|
|
def migrate_stage_index_sql(start_id, stop_id)
|
2018-04-24 09:50:57 +00:00
|
|
|
if Gitlab::Database.postgresql?
|
2018-04-24 12:14:33 +00:00
|
|
|
<<~SQL
|
2018-04-24 09:50:57 +00:00
|
|
|
WITH freqs AS (
|
|
|
|
SELECT stage_id, stage_idx, COUNT(*) AS freq FROM ci_builds
|
2018-04-24 12:14:33 +00:00
|
|
|
WHERE stage_id BETWEEN #{start_id} AND #{stop_id}
|
2018-04-24 09:50:57 +00:00
|
|
|
AND stage_idx IS NOT NULL
|
|
|
|
GROUP BY stage_id, stage_idx
|
|
|
|
), indexes AS (
|
2019-04-04 05:00:29 +00:00
|
|
|
SELECT DISTINCT stage_id, first_value(stage_idx)
|
|
|
|
OVER (PARTITION BY stage_id ORDER BY freq DESC) AS index
|
2018-04-24 09:50:57 +00:00
|
|
|
FROM freqs
|
|
|
|
)
|
|
|
|
|
2018-05-01 12:30:44 +00:00
|
|
|
UPDATE ci_stages SET position = indexes.index
|
2018-04-24 09:50:57 +00:00
|
|
|
FROM indexes WHERE indexes.stage_id = ci_stages.id
|
2018-05-01 12:30:44 +00:00
|
|
|
AND ci_stages.position IS NULL;
|
2018-04-24 09:50:57 +00:00
|
|
|
SQL
|
|
|
|
else
|
2018-04-24 12:14:33 +00:00
|
|
|
<<~SQL
|
2018-04-24 09:50:57 +00:00
|
|
|
UPDATE ci_stages
|
2018-05-01 12:30:44 +00:00
|
|
|
SET position =
|
2018-04-24 09:50:57 +00:00
|
|
|
(SELECT stage_idx FROM ci_builds
|
|
|
|
WHERE ci_builds.stage_id = ci_stages.id
|
|
|
|
GROUP BY ci_builds.stage_idx ORDER BY COUNT(*) DESC LIMIT 1)
|
2018-04-24 12:14:33 +00:00
|
|
|
WHERE ci_stages.id BETWEEN #{start_id} AND #{stop_id}
|
2018-05-01 12:30:44 +00:00
|
|
|
AND ci_stages.position IS NULL
|
2018-04-24 09:50:57 +00:00
|
|
|
SQL
|
|
|
|
end
|
2018-04-20 10:44:20 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|