Commit 56296f1e authored by Jasper Maes's avatar Jasper Maes

Remove rails4 specific code

parent 8b460204
......@@ -12,9 +12,6 @@ class ApplicationController < ActionController::Base
include EnforcesTwoFactorAuthentication
include WithPerformanceBar
include SessionlessAuthentication
# this can be removed after switching to rails 5
# https://gitlab.com/gitlab-org/gitlab-ce/issues/51908
include InvalidUTF8ErrorHandler unless Gitlab.rails5?
before_action :authenticate_user!
before_action :enforce_terms!, if: :should_enforce_terms?
......@@ -157,7 +154,7 @@ class ApplicationController < ActionController::Base
def log_exception(exception)
Gitlab::Sentry.track_acceptable_exception(exception)
backtrace_cleaner = Gitlab.rails5? ? request.env["action_dispatch.backtrace_cleaner"] : env
backtrace_cleaner = request.env["action_dispatch.backtrace_cleaner"]
application_trace = ActionDispatch::ExceptionWrapper.new(backtrace_cleaner, exception).application_trace
application_trace.map! { |t| " #{t}\n" }
logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
......
# frozen_string_literal: true
module InvalidUTF8ErrorHandler
extend ActiveSupport::Concern
included do
rescue_from ArgumentError, with: :handle_invalid_utf8
end
private
def handle_invalid_utf8(error)
if error.message == "invalid byte sequence in UTF-8"
render_412
else
raise(error)
end
end
def render_412
respond_to do |format|
format.html { render "errors/precondition_failed", layout: "errors", status: 412 }
format.js { render json: { error: 'Invalid UTF-8' }, status: :precondition_failed, content_type: 'application/json' }
format.any { head :precondition_failed }
end
end
end
......@@ -56,11 +56,7 @@ module Ci
validates :tag, inclusion: { in: [false], if: :merge_request? }
validates :status, presence: { unless: :importing? }
validate :valid_commit_sha, unless: :importing?
# Replace validator below with
# `validates :source, presence: { unless: :importing? }, on: :create`
# when removing Gitlab.rails5? code.
validate :valid_source, unless: :importing?, on: :create
validates :source, exclusion: { in: %w(unknown), unless: :importing? }, on: :create
after_create :keep_around_commits, unless: :importing?
......@@ -738,11 +734,5 @@ module Ci
project.repository.keep_around(self.sha, self.before_sha)
end
def valid_source
if source.nil? || source == "unknown"
errors.add(:source, "invalid source")
end
end
end
end
......@@ -58,8 +58,7 @@ module Ci
# BACKWARD COMPATIBILITY: There are needed to maintain compatibility with `AVAILABLE_SCOPES` used by `lib/api/runners.rb`
scope :deprecated_shared, -> { instance_type }
# this should get replaced with `project_type.or(group_type)` once using Rails5
scope :deprecated_specific, -> { where(runner_type: [runner_types[:project_type], runner_types[:group_type]]) }
scope :deprecated_specific, -> { project_type.or(group_type) }
scope :belonging_to_project, -> (project_id) {
joins(:runner_projects).where(ci_runner_projects: { project_id: project_id })
......
......@@ -16,7 +16,7 @@ module EnumWithNil
# E.g. for enum_with_nil failure_reason: { unknown_failure: nil }
# this overrides auto-generated method `unknown_failure?`
define_method("#{key_with_nil}?") do
Gitlab.rails5? ? self[name].nil? : super()
self[name].nil?
end
# E.g. for enum_with_nil failure_reason: { unknown_failure: nil }
......@@ -24,7 +24,6 @@ module EnumWithNil
define_method(name) do
orig = super()
return orig unless Gitlab.rails5?
return orig unless orig.nil?
self.class.public_send(name.to_s.pluralize).key(nil) # rubocop:disable GitlabSecurity/PublicSend
......
......@@ -49,10 +49,6 @@ module RedisCacheable
end
def cast_value_from_cache(attribute, value)
if Gitlab.rails5?
self.class.type_for_attribute(attribute.to_s).cast(value)
else
self.class.column_for_attribute(attribute).type_cast_from_database(value)
end
self.class.type_for_attribute(attribute.to_s).cast(value)
end
end
......@@ -114,19 +114,6 @@ class Event < ActiveRecord::Base
end
end
# Remove this method when removing Gitlab.rails5? code.
def subclass_from_attributes(attrs)
return super if Gitlab.rails5?
# Without this Rails will keep calling this method on the returned class,
# resulting in an infinite loop.
return unless self == Event
action = attrs.with_indifferent_access[inheritance_column].to_i
PushEvent if action == PUSHED
end
# Update Gitlab::ContributionsCalendar#activity_dates if this changes
def contributions
where("action = ? OR (target_type IN (?) AND action IN (?)) OR (target_type = ? AND action = ?)",
......
......@@ -210,11 +210,7 @@ class Service < ActiveRecord::Base
class_eval %{
def #{arg}?
# '!!' is used because nil or empty string is converted to nil
if Gitlab.rails5?
!!ActiveRecord::Type::Boolean.new.cast(#{arg})
else
!!ActiveRecord::Type::Boolean.new.type_cast_from_database(#{arg})
end
!!ActiveRecord::Type::Boolean.new.cast(#{arg})
end
}
end
......
---
title: Remove rails4 specific code
merge_request: 23847
author: Jasper Maes
type: other
......@@ -5,12 +5,6 @@ require 'rails/all'
Bundler.require(:default, Rails.env)
module Gitlab
# This method is used for smooth upgrading from the current Rails 4.x to Rails 5.0.
# https://gitlab.com/gitlab-org/gitlab-ce/issues/14286
def self.rails5?
true
end
class Application < Rails::Application
require_dependency Rails.root.join('lib/gitlab/redis/wrapper')
require_dependency Rails.root.join('lib/gitlab/redis/cache')
......
......@@ -37,12 +37,7 @@ class AddTrigramIndexesForSearching < ActiveRecord::Migration[4.2]
res = execute("SELECT true AS enabled FROM pg_available_extensions WHERE name = 'pg_trgm' AND installed_version IS NOT NULL;")
row = res.first
check = if Gitlab.rails5?
true
else
't'
end
row && row['enabled'] == check ? true : false
row && row['enabled'] == true
end
def create_trigrams_extension
......
class FixupEnvironmentNameUniqueness < ActiveRecord::Migration[4.2]
include Gitlab::Database::ArelMethods
include Gitlab::Database::MigrationHelpers
DOWNTIME = true
......@@ -42,7 +41,7 @@ class FixupEnvironmentNameUniqueness < ActiveRecord::Migration[4.2]
conflicts.each do |id, name|
update_sql =
arel_update_manager
Arel::UpdateManager.new
.table(environments)
.set(environments[:name] => name + "-" + id.to_s)
.where(environments[:id].eq(id))
......
......@@ -2,7 +2,6 @@
# for more information on how to write migrations for GitLab.
class AddEnvironmentSlug < ActiveRecord::Migration[4.2]
include Gitlab::Database::ArelMethods
include Gitlab::Database::MigrationHelpers
DOWNTIME = true
......@@ -20,7 +19,7 @@ class AddEnvironmentSlug < ActiveRecord::Migration[4.2]
finder = environments.project(:id, :name)
connection.exec_query(finder.to_sql).rows.each do |id, name|
updater = arel_update_manager
updater = Arel::UpdateManager.new
.table(environments)
.set(environments[:slug] => generate_slug(name))
.where(environments[:id].eq(id))
......
class FixProjectRecordsWithInvalidVisibility < ActiveRecord::Migration[4.2]
include Gitlab::Database::ArelMethods
include Gitlab::Database::MigrationHelpers
BATCH_SIZE = 500
......@@ -34,7 +33,7 @@ class FixProjectRecordsWithInvalidVisibility < ActiveRecord::Migration[4.2]
end
updates.each do |visibility_level, project_ids|
updater = arel_update_manager
updater = Arel::UpdateManager.new
.table(projects)
.set(projects[:visibility_level] => visibility_level)
.where(projects[:id].in(project_ids))
......
# rubocop:disable Migration/UpdateLargeTable
class MigrateUserActivitiesToUsersLastActivityOn < ActiveRecord::Migration[4.2]
include Gitlab::Database::ArelMethods
include Gitlab::Database::MigrationHelpers
disable_ddl_transaction!
......@@ -40,7 +39,7 @@ class MigrateUserActivitiesToUsersLastActivityOn < ActiveRecord::Migration[4.2]
activities = activities(day.at_beginning_of_day, day.at_end_of_day, page: page)
update_sql =
arel_update_manager
Arel::UpdateManager.new
.table(users_table)
.set(users_table[:last_activity_on] => day.to_date)
.where(users_table[:username].in(activities.map(&:first)))
......
......@@ -291,7 +291,7 @@ module API
end
end
permitted_attrs = ActionController::Parameters.new(attrs).permit!
Gitlab.rails5? ? permitted_attrs.to_h : permitted_attrs
permitted_attrs.to_h
end
# rubocop: disable CodeReuse/ActiveRecord
......
......@@ -22,14 +22,10 @@ module DeclarativePolicy
key = Cache.policy_key(user, subject)
cache[key] ||=
if Gitlab.rails5?
# to avoid deadlocks in multi-threaded environment when
# autoloading is enabled, we allow concurrent loads,
# https://gitlab.com/gitlab-org/gitlab-ce/issues/48263
ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
class_for(subject).new(user, subject, opts)
end
else
# to avoid deadlocks in multi-threaded environment when
# autoloading is enabled, we allow concurrent loads,
# https://gitlab.com/gitlab-org/gitlab-ce/issues/48263
ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
class_for(subject).new(user, subject, opts)
end
end
......
......@@ -232,11 +232,7 @@ module Gitlab
end
def self.cached_table_exists?(table_name)
if Gitlab.rails5?
connection.schema_cache.data_source_exists?(table_name)
else
connection.schema_cache.table_exists?(table_name)
end
connection.schema_cache.data_source_exists?(table_name)
end
private_class_method :connection
......
# frozen_string_literal: true
module Gitlab
module Database
module ArelMethods
private
# In Arel 7.0.0 (Arel 7.1.4 is used in Rails 5.0) the `engine` parameter of `Arel::UpdateManager#initializer`
# was removed.
# Remove this file and inline this method when removing rails5? code.
def arel_update_manager
if Gitlab.rails5?
Arel::UpdateManager.new
else
Arel::UpdateManager.new(ActiveRecord::Base)
end
end
end
end
end
......@@ -35,13 +35,7 @@ module Gitlab
end
def mysql_median_datetime_sql(arel_table, query_so_far, column_sym)
arel_from = if Gitlab.rails5?
arel_table.from
else
arel_table
end
query = arel_from
query = arel_table.from
.from(arel_table.project(Arel.sql('*')).order(arel_table[column_sym]).as(arel_table.table_name))
.project(average([arel_table[column_sym]], 'median'))
.where(
......@@ -151,13 +145,8 @@ module Gitlab
.order(arel_table[column_sym])
).as('row_id')
arel_from = if Gitlab.rails5?
arel_table.from.from(arel_table.alias)
else
arel_table.from(arel_table.alias)
end
count = arel_from.project('COUNT(*)')
count = arel_table.from.from(arel_table.alias)
.project('COUNT(*)')
.where(arel_table[partition_column].eq(arel_table.alias[partition_column]))
.as('ct')
......
......@@ -3,8 +3,6 @@
module Gitlab
module Database
module MigrationHelpers
include Gitlab::Database::ArelMethods
BACKGROUND_MIGRATION_BATCH_SIZE = 1000 # Number of rows to process per job
BACKGROUND_MIGRATION_JOB_BUFFER_SIZE = 1000 # Number of jobs to bulk queue at a time
......@@ -361,7 +359,7 @@ module Gitlab
stop_arel = yield table, stop_arel if block_given?
stop_row = exec_query(stop_arel.to_sql).to_hash.first
update_arel = arel_update_manager
update_arel = Arel::UpdateManager.new
.table(table)
.set([[table[column], value]])
.where(table[:id].gteq(start_id))
......
......@@ -5,8 +5,6 @@ module Gitlab
module RenameReservedPathsMigration
module V1
class RenameBase
include Gitlab::Database::ArelMethods
attr_reader :paths, :migration
delegate :update_column_in_batches,
......@@ -66,7 +64,7 @@ module Gitlab
old_full_path,
new_full_path)
update = arel_update_manager
update = Arel::UpdateManager.new
.table(routes)
.set([[routes[:path], replace_statement]])
.where(Arel::Nodes::SqlLiteral.new(filter))
......
......@@ -8,14 +8,7 @@ module Gitlab
# behaviour from the default Binary type.
ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea
else
# In Rails 5.0 `Type` has been moved from `ActiveRecord` to `ActiveModel`
# https://github.com/rails/rails/commit/9cc8c6f3730df3d94c81a55be9ee1b7b4ffd29f6#diff-f8ba7983a51d687976e115adcd95822b
# Remove this method and leave just `ActiveModel::Type::Binary` when removing Gitlab.rails5? code.
if Gitlab.rails5?
ActiveModel::Type::Binary
else
ActiveRecord::Type::Binary
end
ActiveModel::Type::Binary
end
# Class for casting binary data to hexadecimal SHA1 hashes (and vice-versa).
......@@ -26,31 +19,9 @@ module Gitlab
class ShaAttribute < BINARY_TYPE
PACK_FORMAT = 'H*'.freeze
# It is called from activerecord-4.2.10/lib/active_record internal methods.
# Remove this method when removing Gitlab.rails5? code.
def type_cast_from_database(value)
unpack_sha(super)
end
# It is called from activerecord-4.2.10/lib/active_record internal methods.
# Remove this method when removing Gitlab.rails5? code.
def type_cast_for_database(value)
serialize(value)
end
# It is called from activerecord-5.0.6/lib/active_record/attribute.rb
# Remove this method when removing Gitlab.rails5? code..
def deserialize(value)
value = Gitlab.rails5? ? super : method(:type_cast_from_database).super_method.call(value)
unpack_sha(value)
end
# Rename this method to `deserialize(value)` removing Gitlab.rails5? code.
# Casts binary data to a SHA1 in hexadecimal.
def unpack_sha(value)
# Uncomment this line when removing Gitlab.rails5? code.
# value = super
def deserialize(value)
value = super(value)
value ? value.unpack(PACK_FORMAT)[0] : nil
end
......@@ -58,7 +29,7 @@ module Gitlab
def serialize(value)
arg = value ? [value].pack(PACK_FORMAT) : nil
Gitlab.rails5? ? super(arg) : method(:type_cast_for_database).super_method.call(arg)
super(arg)
end
end
end
......
......@@ -6,15 +6,11 @@ module Gitlab
class << self
def self_join(relation)
t = relation.arel_table
t2 = if !Gitlab.rails5?
relation.arel.as('t2')
else
# Work around a bug in Rails 5, where LIMIT causes trouble
# See https://gitlab.com/gitlab-org/gitlab-ce/issues/51729
r = relation.limit(nil).arel
r.take(relation.limit_value) if relation.limit_value
r.as('t2')
end
# Work around a bug in Rails 5, where LIMIT causes trouble
# See https://gitlab.com/gitlab-org/gitlab-ce/issues/51729
r = relation.limit(nil).arel
r.take(relation.limit_value) if relation.limit_value
t2 = r.as('t2')
relation.unscoped.joins(t.join(t2).on(t[:id].eq(t2[:id])).join_sources.first)
end
......
......@@ -73,13 +73,7 @@ module Gitlab
if MUTEX.locked? && MUTEX.owned?
optimistic_using_tmp_keychain(&block)
else
if Gitlab.rails5?
ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
MUTEX.synchronize do
optimistic_using_tmp_keychain(&block)
end
end
else
ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
MUTEX.synchronize do
optimistic_using_tmp_keychain(&block)
end
......
......@@ -20,11 +20,7 @@ module Gitlab
private
def correlation_id(env)
if Gitlab.rails5?
request(env).request_id
else
request(env).uuid
end
request(env).request_id
end
def request(env)
......
......@@ -17,4 +17,4 @@ module MysqlZeroDate
end
end
ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.prepend(MysqlZeroDate) if Gitlab.rails5?
ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.prepend(MysqlZeroDate)
......@@ -551,14 +551,7 @@ describe ApplicationController do
subject { get :index, text: "hi \255" }
it 'renders 412' do
if Gitlab.rails5?
expect { subject }.to raise_error(ActionController::BadRequest)
else
subject
expect(response).to have_gitlab_http_status(412)
expect(response).to render_template :precondition_failed
end
expect { subject }.to raise_error(ActionController::BadRequest)
end
end
......@@ -566,16 +559,7 @@ describe ApplicationController do
subject { get :index, text: "hi \255", format: :js }
it 'renders 412' do
if Gitlab.rails5?
expect { subject }.to raise_error(ActionController::BadRequest)
else
subject
json_response = JSON.parse(response.body)
expect(response).to have_gitlab_http_status(412)
expect(json_response['error']).to eq('Invalid UTF-8')
end
expect { subject }.to raise_error(ActionController::BadRequest)
end
end
end
......
......@@ -163,11 +163,7 @@ describe Boards::ListsController do
list: { position: position },
format: :json }
if Gitlab.rails5?
patch :update, params: params, as: :json
else
patch :update, params
end
patch :update, params: params, as: :json
end
end
......
......@@ -357,11 +357,7 @@ describe Projects::MergeRequestsController do
context 'when the sha parameter matches the source SHA' do
def merge_with_sha(params = {})
post_params = base_params.merge(sha: merge_request.diff_head_sha).merge(params)
if Gitlab.rails5?
post :merge, params: post_params, as: :json
else
post :merge, post_params
end
post :merge, params: post_params, as: :json
end
it 'returns :success' do
......
......@@ -310,19 +310,11 @@ describe Projects::PipelineSchedulesController do
end
def go
if Gitlab.rails5?
put :update, params: { namespace_id: project.namespace.to_param,
project_id: project,
id: pipeline_schedule,
schedule: schedule },
as: :html
else
put :update, namespace_id: project.namespace.to_param,
project_id: project,
id: pipeline_schedule,
schedule: schedule
end
put :update, params: { namespace_id: project.namespace.to_param,
project_id: project,
id: pipeline_schedule,
schedule: schedule },
as: :html
end
end
......
......@@ -8,11 +8,7 @@ end
shared_examples 'content not cached without revalidation and no-store' do
it 'ensures content will not be cached without revalidation' do
# Fixed in newer versions of ActivePack, it will only output a single `private`.
if Gitlab.rails5?
expect(subject['Cache-Control']).to eq('max-age=0, private, must-revalidate, no-store')
else
expect(subject['Cache-Control']).to eq('max-age=0, private, must-revalidate, private, no-store')
end
expect(subject['Cache-Control']).to eq('max-age=0, private, must-revalidate, no-store')
end
end
......
......@@ -15,11 +15,7 @@ describe StorageHelper do
end
it "uses commas as thousands separator" do
if Gitlab.rails5?
expect(helper.storage_counter(100_000_000_000_000_000_000_000)).to eq("86,736.2 EB")
else
expect(helper.storage_counter(100_000_000_000_000_000)).to eq("90,949.5 TB")
end
expect(helper.storage_counter(100_000_000_000_000_000_000_000)).to eq("86,736.2 EB")
end
end
end
......@@ -400,13 +400,8 @@ describe Gitlab::Database do
describe '.cached_table_exists?' do
it 'only retrieves data once per table' do
if Gitlab.rails5?
expect(ActiveRecord::Base.connection).to receive(:data_source_exists?).with(:projects).once.and_call_original
expect(ActiveRecord::Base.connection).to receive(:data_source_exists?).with(:bogus_table_name).once.and_call_original
else
expect(ActiveRecord::Base.connection).to receive(:table_exists?).with(:projects).once.and_call_original
expect(ActiveRecord::Base.connection).to receive(:table_exists?).with(:bogus_table_name).once.and_call_original
end
expect(ActiveRecord::Base.connection).to receive(:data_source_exists?).with(:projects).once.and_call_original
expect(ActiveRecord::Base.connection).to receive(:data_source_exists?).with(:bogus_table_name).once.and_call_original
2.times do
expect(described_class.cached_table_exists?(:projects)).to be_truthy
......
......@@ -35,9 +35,8 @@ describe Gitlab::SQL::Glob do
value = query("SELECT #{quote(string)} LIKE #{pattern}")
.rows.flatten.first
check = Gitlab.rails5? ? true : 't'
case value
when check, 1
when true, 1
true
else
false
......
......@@ -42,12 +42,7 @@ RSpec.describe NotificationSetting do
expect(notification_setting.new_issue).to eq(true)
expect(notification_setting.close_issue).to eq(true)
expect(notification_setting.merge_merge_request).to eq(true)
# In Rails 5 assigning a value which is not explicitly `true` or `false` ("nil" in this case)
# to a boolean column transforms it to `true`.
# In Rails 4 it transforms the value to `false` with deprecation warning.
# Replace `eq(Gitlab.rails5?)` with `eq(true)` when removing rails5? code.
expect(notification_setting.close_merge_request).to eq(Gitlab.rails5?)
expect(notification_setting.close_merge_request).to eq(true)
expect(notification_setting.reopen_merge_request).to eq(false)
end
end
......
......@@ -969,17 +969,10 @@ describe API::Internal do
env: env
}
if Gitlab.rails5?
post(
api("/internal/allowed"),
params: params
)
else
post(
api("/internal/allowed"),
params
)
end
post(
api("/internal/allowed"),
params: params
)
end
def archive(key, project)
......
......@@ -2,10 +2,6 @@
module TestRequestHelpers
def test_request(remote_ip: '127.0.0.1')
if Gitlab.rails5?
ActionController::TestRequest.new({ remote_ip: remote_ip }, ActionController::TestSession.new)
else
ActionController::TestRequest.new(remote_ip: remote_ip)
end
ActionController::TestRequest.new({ remote_ip: remote_ip }, ActionController::TestSession.new)
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment