2018-11-13 07:27:31 +00:00
|
|
|
class FixupEnvironmentNameUniqueness < ActiveRecord::Migration[4.2]
|
2018-06-06 09:15:46 +00:00
|
|
|
include Gitlab::Database::ArelMethods
|
2016-12-14 22:58:44 +00:00
|
|
|
include Gitlab::Database::MigrationHelpers
|
|
|
|
|
|
|
|
DOWNTIME = true
|
2017-02-22 22:34:45 +00:00
|
|
|
DOWNTIME_REASON = 'Renaming non-unique environments'
|
2016-12-14 22:58:44 +00:00
|
|
|
|
|
|
|
def up
|
|
|
|
environments = Arel::Table.new(:environments)
|
|
|
|
|
|
|
|
# Get all [project_id, name] pairs that occur more than once
|
2017-06-21 13:48:12 +00:00
|
|
|
finder_sql = environments
|
|
|
|
.group(environments[:project_id], environments[:name])
|
|
|
|
.having(Arel.sql("COUNT(1)").gt(1))
|
|
|
|
.project(environments[:project_id], environments[:name])
|
|
|
|
.to_sql
|
2016-12-14 22:58:44 +00:00
|
|
|
|
|
|
|
conflicting = connection.exec_query(finder_sql)
|
|
|
|
|
|
|
|
conflicting.rows.each do |project_id, name|
|
|
|
|
fix_duplicates(project_id, name)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def down
|
|
|
|
# Nothing to do
|
|
|
|
end
|
|
|
|
|
|
|
|
# Rename conflicting environments by appending "-#{id}" to all but the first
|
|
|
|
def fix_duplicates(project_id, name)
|
|
|
|
environments = Arel::Table.new(:environments)
|
2017-06-21 13:48:12 +00:00
|
|
|
finder_sql = environments
|
|
|
|
.where(environments[:project_id].eq(project_id))
|
|
|
|
.where(environments[:name].eq(name))
|
|
|
|
.order(environments[:id].asc)
|
|
|
|
.project(environments[:id], environments[:name])
|
|
|
|
.to_sql
|
2016-12-14 22:58:44 +00:00
|
|
|
|
|
|
|
# Now we have the data for all the conflicting rows
|
|
|
|
conflicts = connection.exec_query(finder_sql).rows
|
|
|
|
conflicts.shift # Leave the first row alone
|
|
|
|
|
|
|
|
conflicts.each do |id, name|
|
|
|
|
update_sql =
|
2018-06-06 09:15:46 +00:00
|
|
|
arel_update_manager
|
2017-06-21 13:48:12 +00:00
|
|
|
.table(environments)
|
|
|
|
.set(environments[:name] => name + "-" + id.to_s)
|
|
|
|
.where(environments[:id].eq(id))
|
|
|
|
.to_sql
|
2016-12-14 22:58:44 +00:00
|
|
|
|
|
|
|
connection.exec_update(update_sql, self.class.name, [])
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|