2016-12-08 01:09:18 +00:00
|
|
|
# See http://doc.gitlab.com/ce/development/migration_style_guide.html
|
|
|
|
# for more information on how to write migrations for GitLab.
|
|
|
|
|
2018-11-13 07:27:31 +00:00
|
|
|
class AddEnvironmentSlug < ActiveRecord::Migration[4.2]
|
2018-06-06 09:15:46 +00:00
|
|
|
include Gitlab::Database::ArelMethods
|
2016-12-08 01:09:18 +00:00
|
|
|
include Gitlab::Database::MigrationHelpers
|
|
|
|
|
|
|
|
DOWNTIME = true
|
|
|
|
DOWNTIME_REASON = 'Adding NOT NULL column environments.slug with dependent data'
|
|
|
|
|
|
|
|
# Used to generate random suffixes for the slug
|
2017-01-19 14:42:03 +00:00
|
|
|
LETTERS = 'a'..'z'
|
2016-12-08 01:09:18 +00:00
|
|
|
NUMBERS = '0'..'9'
|
2017-01-19 14:42:03 +00:00
|
|
|
SUFFIX_CHARS = LETTERS.to_a + NUMBERS.to_a
|
2016-12-08 01:09:18 +00:00
|
|
|
|
|
|
|
def up
|
|
|
|
environments = Arel::Table.new(:environments)
|
|
|
|
|
|
|
|
add_column :environments, :slug, :string
|
|
|
|
finder = environments.project(:id, :name)
|
|
|
|
|
|
|
|
connection.exec_query(finder.to_sql).rows.each do |id, name|
|
2018-06-06 09:15:46 +00:00
|
|
|
updater = arel_update_manager
|
2017-06-21 13:48:12 +00:00
|
|
|
.table(environments)
|
|
|
|
.set(environments[:slug] => generate_slug(name))
|
|
|
|
.where(environments[:id].eq(id))
|
2016-12-08 01:09:18 +00:00
|
|
|
|
|
|
|
connection.exec_update(updater.to_sql, self.class.name, [])
|
|
|
|
end
|
|
|
|
|
|
|
|
change_column_null :environments, :slug, false
|
|
|
|
end
|
|
|
|
|
|
|
|
def down
|
|
|
|
remove_column :environments, :slug
|
|
|
|
end
|
|
|
|
|
|
|
|
# Copy of the Environment#generate_slug implementation
|
|
|
|
def generate_slug(name)
|
|
|
|
# Lowercase letters and numbers only
|
|
|
|
slugified = name.to_s.downcase.gsub(/[^a-z0-9]/, '-')
|
|
|
|
|
|
|
|
# Must start with a letter
|
2017-01-19 14:42:03 +00:00
|
|
|
slugified = 'env-' + slugified unless LETTERS.cover?(slugified[0])
|
|
|
|
|
|
|
|
# Repeated dashes are invalid (OpenShift limitation)
|
|
|
|
slugified.gsub!(/\-+/, '-')
|
2016-12-08 01:09:18 +00:00
|
|
|
|
|
|
|
# Maximum length: 24 characters (OpenShift limitation)
|
|
|
|
slugified = slugified[0..23]
|
|
|
|
|
2017-01-19 14:42:03 +00:00
|
|
|
# Cannot end with a dash (Kubernetes label limitation)
|
|
|
|
slugified.chop! if slugified.end_with?('-')
|
2016-12-08 01:09:18 +00:00
|
|
|
|
|
|
|
# Add a random suffix, shortening the current string if necessary, if it
|
|
|
|
# has been slugified. This ensures uniqueness.
|
2017-01-19 14:42:03 +00:00
|
|
|
if slugified != name
|
|
|
|
slugified = slugified[0..16]
|
|
|
|
slugified << '-' unless slugified.end_with?('-')
|
|
|
|
slugified << random_suffix
|
|
|
|
end
|
2016-12-08 01:09:18 +00:00
|
|
|
|
|
|
|
slugified
|
|
|
|
end
|
|
|
|
|
|
|
|
def random_suffix
|
|
|
|
(0..5).map { SUFFIX_CHARS.sample }.join
|
|
|
|
end
|
|
|
|
end
|