Commit 44fef4fe authored by Jasper Maes's avatar Jasper Maes

Remove rails 4 support in CI, Gemfiles, bin/ and config/

parent eafc8e2f
...@@ -77,18 +77,6 @@ stages: ...@@ -77,18 +77,6 @@ stages:
- mysql:5.7 - mysql:5.7
- redis:alpine - redis:alpine
.rails4: &rails4
allow_failure: false
except:
variables:
- $CI_COMMIT_REF_NAME =~ /(^docs[\/-].*|.*-docs$)/
- $CI_COMMIT_REF_NAME =~ /(^qa[\/-].*|.*-qa$)/
- $CI_COMMIT_REF_NAME =~ /norails4/
- $RAILS5_DISABLED
variables:
BUNDLE_GEMFILE: "Gemfile.rails4"
RAILS5: "false"
# Skip all jobs except the ones that begin with 'docs/'. # Skip all jobs except the ones that begin with 'docs/'.
# Used for commits including ONLY documentation changes. # Used for commits including ONLY documentation changes.
# https://docs.gitlab.com/ce/development/documentation/#testing # https://docs.gitlab.com/ce/development/documentation/#testing
...@@ -180,18 +168,10 @@ stages: ...@@ -180,18 +168,10 @@ stages:
<<: *rspec-metadata <<: *rspec-metadata
<<: *use-pg <<: *use-pg
.rspec-metadata-pg-rails4: &rspec-metadata-pg-rails4
<<: *rspec-metadata-pg
<<: *rails4
.rspec-metadata-mysql: &rspec-metadata-mysql .rspec-metadata-mysql: &rspec-metadata-mysql
<<: *rspec-metadata <<: *rspec-metadata
<<: *use-mysql <<: *use-mysql
.rspec-metadata-mysql-rails4: &rspec-metadata-mysql-rails4
<<: *rspec-metadata-mysql
<<: *rails4
.only-canonical-masters: &only-canonical-masters .only-canonical-masters: &only-canonical-masters
only: only:
- master@gitlab-org/gitlab-ce - master@gitlab-org/gitlab-ce
...@@ -432,7 +412,6 @@ setup-test-env: ...@@ -432,7 +412,6 @@ setup-test-env:
script: script:
- bundle exec ruby -Ispec -e 'require "spec_helper" ; TestEnv.init' - bundle exec ruby -Ispec -e 'require "spec_helper" ; TestEnv.init'
- scripts/gitaly-test-build # Do not use 'bundle exec' here - scripts/gitaly-test-build # Do not use 'bundle exec' here
- BUNDLE_GEMFILE=Gemfile.rails4 bundle install $BUNDLE_INSTALL_FLAGS
artifacts: artifacts:
expire_in: 7d expire_in: 7d
paths: paths:
...@@ -513,14 +492,6 @@ rspec-mysql: ...@@ -513,14 +492,6 @@ rspec-mysql:
<<: *rspec-metadata-mysql <<: *rspec-metadata-mysql
parallel: 50 parallel: 50
rspec-pg-rails4:
<<: *rspec-metadata-pg-rails4
parallel: 50
rspec-mysql-rails4:
<<: *rspec-metadata-mysql-rails4
parallel: 50
static-analysis: static-analysis:
<<: *dedicated-no-docs-no-db-pull-cache-job <<: *dedicated-no-docs-no-db-pull-cache-job
dependencies: dependencies:
...@@ -565,12 +536,6 @@ downtime_check: ...@@ -565,12 +536,6 @@ downtime_check:
- /(^docs[\/-].*|.*-docs$)/ - /(^docs[\/-].*|.*-docs$)/
- /(^qa[\/-].*|.*-qa$)/ - /(^qa[\/-].*|.*-qa$)/
rails4_gemfile_lock_check:
<<: *dedicated-no-docs-no-db-pull-cache-job
<<: *except-docs-and-qa
script:
- scripts/rails4-gemfile-lock-check
ee_compat_check: ee_compat_check:
<<: *rake-exec <<: *rake-exec
dependencies: [] dependencies: []
......
# --- Special code for migrating to Rails 5.0 ---
def rails5?
!%w[0 false].include?(ENV["RAILS5"])
end
gem_versions = {}
gem_versions['activerecord_sane_schema_dumper'] = rails5? ? '1.0' : '0.2'
gem_versions['rails'] = rails5? ? '5.0.7' : '4.2.11'
gem_versions['rails-i18n'] = rails5? ? '~> 5.1' : '~> 4.0.9'
# The 2.0.6 version of rack requires monkeypatch to be present in
# `config.ru`. This can be removed once a new update for Rack
# is available that contains https://github.com/rack/rack/pull/1201.
gem_versions['rack'] = rails5? ? '2.0.6' : '1.6.11'
# --- The end of special code for migrating to Rails 5.0 ---
source 'https://rubygems.org' source 'https://rubygems.org'
gem 'rails', gem_versions['rails'] gem 'rails', '5.0.7'
gem 'rails-deprecated_sanitizer', '~> 1.0.3' gem 'rails-deprecated_sanitizer', '~> 1.0.3'
# Improves copy-on-write performance for MRI # Improves copy-on-write performance for MRI
...@@ -28,11 +12,7 @@ gem 'responders', '~> 2.0' ...@@ -28,11 +12,7 @@ gem 'responders', '~> 2.0'
gem 'sprockets', '~> 3.7.0' gem 'sprockets', '~> 3.7.0'
# Default values for AR models # Default values for AR models
if rails5? gem 'gitlab-default_value_for', '~> 3.1.1', require: 'default_value_for'
gem 'gitlab-default_value_for', '~> 3.1.1', require: 'default_value_for'
else
gem 'default_value_for', '~> 3.0.0'
end
# Supported DBs # Supported DBs
gem 'mysql2', '~> 0.4.10', group: :mysql gem 'mysql2', '~> 0.4.10', group: :mysql
...@@ -159,7 +139,10 @@ gem 'icalendar' ...@@ -159,7 +139,10 @@ gem 'icalendar'
gem 'diffy', '~> 3.1.0' gem 'diffy', '~> 3.1.0'
# Application server # Application server
gem 'rack', gem_versions['rack'] # The 2.0.6 version of rack requires monkeypatch to be present in
# `config.ru`. This can be removed once a new update for Rack
# is available that contains https://github.com/rack/rack/pull/1201.
gem 'rack', '2.0.6'
group :unicorn do group :unicorn do
gem 'unicorn', '~> 5.1.0' gem 'unicorn', '~> 5.1.0'
...@@ -297,7 +280,7 @@ gem 'premailer-rails', '~> 1.9.7' ...@@ -297,7 +280,7 @@ gem 'premailer-rails', '~> 1.9.7'
# I18n # I18n
gem 'ruby_parser', '~> 3.8', require: false gem 'ruby_parser', '~> 3.8', require: false
gem 'rails-i18n', gem_versions['rails-i18n'] gem 'rails-i18n', '~> 5.1'
gem 'gettext_i18n_rails', '~> 1.8.0' gem 'gettext_i18n_rails', '~> 1.8.0'
gem 'gettext_i18n_rails_js', '~> 1.3' gem 'gettext_i18n_rails_js', '~> 1.3'
gem 'gettext', '~> 3.2.2', require: false, group: :development gem 'gettext', '~> 3.2.2', require: false, group: :development
...@@ -383,7 +366,7 @@ group :development, :test do ...@@ -383,7 +366,7 @@ group :development, :test do
gem 'license_finder', '~> 5.4', require: false gem 'license_finder', '~> 5.4', require: false
gem 'knapsack', '~> 1.17' gem 'knapsack', '~> 1.17'
gem 'activerecord_sane_schema_dumper', gem_versions['activerecord_sane_schema_dumper'] gem 'activerecord_sane_schema_dumper', '1.0'
gem 'stackprof', '~> 0.2.10', require: false gem 'stackprof', '~> 0.2.10', require: false
...@@ -397,8 +380,7 @@ group :test do ...@@ -397,8 +380,7 @@ group :test do
gem 'email_spec', '~> 2.2.0' gem 'email_spec', '~> 2.2.0'
gem 'json-schema', '~> 2.8.0' gem 'json-schema', '~> 2.8.0'
gem 'webmock', '~> 2.3.2' gem 'webmock', '~> 2.3.2'
gem 'rails-controller-testing' if rails5? # Rails5 only gem. gem 'rails-controller-testing'
gem 'test_after_commit', '~> 1.1' unless rails5? # Remove this gem when migrated to rails 5.0. It's been integrated to rails 5.0.
gem 'sham_rack', '~> 1.3.6' gem 'sham_rack', '~> 1.3.6'
gem 'concurrent-ruby', '~> 1.1' gem 'concurrent-ruby', '~> 1.1'
gem 'test-prof', '~> 0.2.5' gem 'test-prof', '~> 0.2.5'
......
# BUNDLE_GEMFILE=Gemfile.rails4 bundle install
ENV["RAILS5"] = "false"
gemfile = File.expand_path("../Gemfile", __FILE__)
eval(File.read(gemfile), nil, gemfile)
This diff is collapsed.
#!/usr/bin/env ruby #!/usr/bin/env ruby
# Remove this block when upgraded to rails 5.0.
if %w[0 false].include?(ENV["RAILS5"])
begin
load File.expand_path('../spring', __FILE__)
rescue LoadError => e
raise unless e.message.include?('spring')
end
end
APP_PATH = File.expand_path('../config/application', __dir__) APP_PATH = File.expand_path('../config/application', __dir__)
require_relative '../config/boot' require_relative '../config/boot'
require 'rails/commands' require 'rails/commands'
#!/usr/bin/env ruby #!/usr/bin/env ruby
# Remove this block when upgraded to rails 5.0.
if %w[0 false].include?(ENV["RAILS5"])
begin
load File.expand_path('../spring', __FILE__)
rescue LoadError => e
raise unless e.message.include?('spring')
end
end
require_relative '../config/boot' require_relative '../config/boot'
require 'rake' require 'rake'
Rake.application.run Rake.application.run
#!/usr/bin/env ruby #!/usr/bin/env ruby
# Remove these two lines below when upgraded to rails 5.0.
# Allow run `rspec` command as `RAILS5=1 rspec ...` instead of `BUNDLE_GEMFILE=Gemfile.rails5 rspec ...`
gemfile = %w[0 false].include?(ENV["RAILS5"]) ? "Gemfile.rails4" : "Gemfile"
ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../#{gemfile}", __dir__)
begin begin
load File.expand_path('../spring', __FILE__) load File.expand_path('../spring', __FILE__)
rescue LoadError => e rescue LoadError => e
......
#!/usr/bin/env ruby #!/usr/bin/env ruby
def rails5?
!%w[0 false].include?(ENV["RAILS5"])
end
require "pathname" require "pathname"
# path to your application root. # path to your application root.
APP_ROOT = Pathname.new File.expand_path("../../", __FILE__) APP_ROOT = Pathname.new File.expand_path("../../", __FILE__)
if rails5? def system!(*args)
def system!(*args) system(*args) || abort("\n== Command #{args} failed ==")
system(*args) || abort("\n== Command #{args} failed ==")
end
end end
Dir.chdir APP_ROOT do Dir.chdir APP_ROOT do
...@@ -20,14 +14,8 @@ Dir.chdir APP_ROOT do ...@@ -20,14 +14,8 @@ Dir.chdir APP_ROOT do
# Add necessary setup steps to this file: # Add necessary setup steps to this file:
puts "== Installing dependencies ==" puts "== Installing dependencies =="
system! "gem install bundler --conservative"
if rails5? system("bundle check") || system!("bundle install")
system! "gem install bundler --conservative"
system("bundle check") || system!("bundle install")
else
system "gem install bundler --conservative"
system "bundle check || bundle install"
end
# puts "\n== Copying sample files ==" # puts "\n== Copying sample files =="
# unless File.exist?("config/database.yml") # unless File.exist?("config/database.yml")
...@@ -35,27 +23,11 @@ Dir.chdir APP_ROOT do ...@@ -35,27 +23,11 @@ Dir.chdir APP_ROOT do
# end # end
puts "\n== Preparing database ==" puts "\n== Preparing database =="
system! "bin/rails db:setup"
if rails5?
system! "bin/rails db:setup"
else
system "bin/rake db:reset"
end
puts "\n== Removing old logs and tempfiles ==" puts "\n== Removing old logs and tempfiles =="
system! "bin/rails log:clear tmp:clear"
if rails5?
system! "bin/rails log:clear tmp:clear"
else
system "rm -f log/*"
system "rm -rf tmp/cache"
end
puts "\n== Restarting application server ==" puts "\n== Restarting application server =="
system! "bin/rails restart"
if rails5?
system! "bin/rails restart"
else
system "touch tmp/restart.txt"
end
end end
---
title: Remove rails 4 support in CI, Gemfiles, bin/ and config/
merge_request: 23717
author: Jasper Maes
type: other
...@@ -8,7 +8,7 @@ module Gitlab ...@@ -8,7 +8,7 @@ module Gitlab
# This method is used for smooth upgrading from the current Rails 4.x to Rails 5.0. # 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 # https://gitlab.com/gitlab-org/gitlab-ce/issues/14286
def self.rails5? def self.rails5?
!%w[0 false].include?(ENV["RAILS5"]) true
end end
class Application < Rails::Application class Application < Rails::Application
...@@ -26,9 +26,6 @@ module Gitlab ...@@ -26,9 +26,6 @@ module Gitlab
# setting disabled # setting disabled
require_dependency Rails.root.join('lib/mysql_zero_date') require_dependency Rails.root.join('lib/mysql_zero_date')
# This can be removed when we drop support for rails 4
require_dependency Rails.root.join('lib/rails4_migration_version')
# Settings in config/environments/* take precedence over those specified here. # Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers # Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded. # -- all .rb files in that directory are automatically loaded.
...@@ -86,7 +83,7 @@ module Gitlab ...@@ -86,7 +83,7 @@ module Gitlab
# namespaces/users. # namespaces/users.
# https://github.com/rails/rails/blob/5-0-stable/actioncable/lib/action_cable.rb#L38 # https://github.com/rails/rails/blob/5-0-stable/actioncable/lib/action_cable.rb#L38
# Please change this value when configuring ActionCable for real usage. # Please change this value when configuring ActionCable for real usage.
config.action_cable.mount_path = "/-/cable" if rails5? config.action_cable.mount_path = "/-/cable"
# Configure sensitive parameters which will be filtered from the log file. # Configure sensitive parameters which will be filtered from the log file.
# #
...@@ -213,8 +210,6 @@ module Gitlab ...@@ -213,8 +210,6 @@ module Gitlab
config.cache_store = :redis_store, caching_config_hash config.cache_store = :redis_store, caching_config_hash
config.active_record.raise_in_transactional_callbacks = true unless rails5?
config.active_job.queue_adapter = :sidekiq config.active_job.queue_adapter = :sidekiq
# This is needed for gitlab-shell # This is needed for gitlab-shell
......
def rails5? ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
!%w[0 false].include?(ENV["RAILS5"])
end
require 'rubygems' unless rails5?
gemfile = rails5? ? "Gemfile" : "Gemfile.rails4"
ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../#{gemfile}", __dir__)
# Set up gems listed in the Gemfile. # Set up gems listed in the Gemfile.
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
......
# Load the rails application # Load the rails application
# Remove this condition when upgraded to rails 5.0. require_relative 'application'
if %w[0 false].include?(ENV["RAILS5"])
require File.expand_path('application', __dir__)
else
require_relative 'application'
end
# Initialize the rails application # Initialize the rails application
Rails.application.initialize! Rails.application.initialize!
...@@ -9,11 +9,7 @@ Rails.application.configure do ...@@ -9,11 +9,7 @@ Rails.application.configure do
config.action_controller.perform_caching = true config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this) # Disable Rails's static asset server (Apache or nginx will already do this)
if Gitlab.rails5? config.public_file_server.enabled = false
config.public_file_server.enabled = false
else
config.serve_static_files = false
end
# Compress JavaScripts and CSS. # Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier config.assets.js_compressor = :uglifier
......
...@@ -19,13 +19,8 @@ Rails.application.configure do ...@@ -19,13 +19,8 @@ Rails.application.configure do
# Configure static asset server for tests with Cache-Control for performance # Configure static asset server for tests with Cache-Control for performance
config.assets.compile = false if ENV['CI'] config.assets.compile = false if ENV['CI']
if Gitlab.rails5? config.public_file_server.enabled = true
config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }
config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }
else
config.serve_static_files = true
config.static_cache_control = "public, max-age=3600"
end
# Show full error reports and disable caching # Show full error reports and disable caching
config.consider_all_requests_local = true config.consider_all_requests_local = true
......
# Remove this initializer when upgraded to Rails 5.0
unless Gitlab.rails5?
module ActiveRecord
class PredicateBuilder
class ArrayHandler
module TypeCasting
def call(attribute, value)
# This is necessary because by default ActiveRecord does not respect
# custom type definitions (like our `ShaAttribute`) when providing an
# array in `where`, like in `where(commit_sha: [sha1, sha2, sha3])`.
model = attribute.relation&.engine
type = model.user_provided_columns[attribute.name] if model
value = value.map { |value| type.type_cast_for_database(value) } if type
super(attribute, value)
end
end
prepend TypeCasting
end
end
end
end
...@@ -20,75 +20,73 @@ ...@@ -20,75 +20,73 @@
# #
# This bug was fixed in Rails 5.1 by https://github.com/rails/rails/pull/24745/commits/aa062318c451512035c10898a1af95943b1a3803 # This bug was fixed in Rails 5.1 by https://github.com/rails/rails/pull/24745/commits/aa062318c451512035c10898a1af95943b1a3803
if Gitlab.rails5? if Rails.version.start_with?("5.1")
if Rails.version.start_with?("5.1") raise "Remove this monkey patch: #{__FILE__}"
raise "Remove this monkey patch: #{__FILE__}" end
end
# Copy-paste from https://github.com/kamipo/rails/blob/aa062318c451512035c10898a1af95943b1a3803/activerecord/lib/active_record/validations/uniqueness.rb # Copy-paste from https://github.com/kamipo/rails/blob/aa062318c451512035c10898a1af95943b1a3803/activerecord/lib/active_record/validations/uniqueness.rb
# including local fixes to make Rubocop happy again. # including local fixes to make Rubocop happy again.
module ActiveRecord module ActiveRecord
module Validations module Validations
class UniquenessValidator < ActiveModel::EachValidator # :nodoc: class UniquenessValidator < ActiveModel::EachValidator # :nodoc:
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
finder_class = find_finder_class_for(record) finder_class = find_finder_class_for(record)
table = finder_class.arel_table table = finder_class.arel_table
value = map_enum_attribute(finder_class, attribute, value) value = map_enum_attribute(finder_class, attribute, value)
relation = build_relation(finder_class, table, attribute, value) relation = build_relation(finder_class, table, attribute, value)
if record.persisted? if record.persisted?
if finder_class.primary_key if finder_class.primary_key
relation = relation.where.not(finder_class.primary_key => record.id_was || record.id) relation = relation.where.not(finder_class.primary_key => record.id_was || record.id)
else else
raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.") raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.")
end
end end
end
relation = scope_relation(record, table, relation) relation = scope_relation(record, table, relation)
relation = relation.merge(options[:conditions]) if options[:conditions] relation = relation.merge(options[:conditions]) if options[:conditions]
if relation.exists? if relation.exists?
error_options = options.except(:case_sensitive, :scope, :conditions) error_options = options.except(:case_sensitive, :scope, :conditions)
error_options[:value] = value error_options[:value] = value
record.errors.add(attribute, :taken, error_options) record.errors.add(attribute, :taken, error_options)
end
rescue RangeError
end end
rescue RangeError
end
protected protected
def build_relation(klass, table, attribute, value) #:nodoc:
if reflection = klass._reflect_on_association(attribute)
attribute = reflection.foreign_key
value = value.attributes[reflection.klass.primary_key] unless value.nil?
end
# the attribute may be an aliased attribute def build_relation(klass, table, attribute, value) #:nodoc:
if klass.attribute_alias?(attribute) if reflection = klass._reflect_on_association(attribute)
attribute = klass.attribute_alias(attribute) attribute = reflection.foreign_key
end value = value.attributes[reflection.klass.primary_key] unless value.nil?
end
attribute_name = attribute.to_s # the attribute may be an aliased attribute
if klass.attribute_alias?(attribute)
attribute = klass.attribute_alias(attribute)
end
column = klass.columns_hash[attribute_name] attribute_name = attribute.to_s
cast_type = klass.type_for_attribute(attribute_name)
comparison = column = klass.columns_hash[attribute_name]
if !options[:case_sensitive] && !value.nil? cast_type = klass.type_for_attribute(attribute_name)
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
klass.connection.case_insensitive_comparison(table, attribute, column, value)
else
klass.connection.case_sensitive_comparison(table, attribute, column, value)
end
if value.nil? comparison =
klass.unscoped.where(comparison) if !options[:case_sensitive] && !value.nil?
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
klass.connection.case_insensitive_comparison(table, attribute, column, value)
else else
bind = Relation::QueryAttribute.new(attribute_name, value, cast_type) klass.connection.case_sensitive_comparison(table, attribute, column, value)
klass.unscoped.where(comparison, bind)
end end
if value.nil?
klass.unscoped.where(comparison)
else
bind = Relation::QueryAttribute.new(attribute_name, value, cast_type)
klass.unscoped.where(comparison, bind)
end end
end end
end end
......
...@@ -65,7 +65,7 @@ elsif Gitlab::Database.mysql? ...@@ -65,7 +65,7 @@ elsif Gitlab::Database.mysql?
prepend RegisterDateTimeWithTimeZone prepend RegisterDateTimeWithTimeZone
# Add the class `DateTimeWithTimeZone` so we can map `timestamp` to it. # Add the class `DateTimeWithTimeZone` so we can map `timestamp` to it.
class MysqlDateTimeWithTimeZone < (Gitlab.rails5? ? ActiveRecord::Type::DateTime : MysqlDateTime) class MysqlDateTimeWithTimeZone < ActiveRecord::Type::DateTime
def type def type
:datetime_with_timezone :datetime_with_timezone
end end
......
...@@ -64,21 +64,13 @@ module ActiveRecord ...@@ -64,21 +64,13 @@ module ActiveRecord
# This is patched because we want `lock_version` default to `NULL` # This is patched because we want `lock_version` default to `NULL`
# rather than `0` # rather than `0`
if Gitlab.rails5? class LockingType
class LockingType def deserialize(value)
def deserialize(value) super
super
end
def serialize(value)
super
end
end end
else
class LockingType < SimpleDelegator def serialize(value)
def type_cast_from_database(value) super
super
end
end end
end end
end end
......
# Remove this `if` condition when upgraded to rails 5.0.
# The body must be kept.
if Gitlab.rails5?
# Be sure to restart your server when you modify this file.
# ActiveSupport::Reloader.to_prepare do
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# end
end
# Remove this file when upgraded to rails 5.0.
unless Gitlab.rails5?
module ActiveRecord
module Batches
# Differences from upstream: enumerator support was removed, and custom
# order/limit clauses are ignored without a warning.
def in_batches(of: 1000, start: nil, finish: nil, load: false)
raise "Must provide a block" unless block_given?
relation = self.reorder(batch_order).limit(of)
relation = relation.where(arel_table[primary_key].gteq(start)) if start
relation = relation.where(arel_table[primary_key].lteq(finish)) if finish
batch_relation = relation
loop do
if load
records = batch_relation.records
ids = records.map(&:id)
yielded_relation = self.where(primary_key => ids)
yielded_relation.load_records(records)
else
ids = batch_relation.pluck(primary_key)
yielded_relation = self.where(primary_key => ids)
end
break if ids.empty?
primary_key_offset = ids.last
raise ArgumentError.new("Primary key not included in the custom select clause") unless primary_key_offset
yield yielded_relation
break if ids.length < of
batch_relation = relation.where(arel_table[primary_key].gt(primary_key_offset))
end
end
end
end
end
# Remove this file when upgraded to rails 5.0.
if !Gitlab.rails5? && Gitlab::Database.postgresql?
require 'active_record/connection_adapters/postgresql_adapter'
require 'active_record/connection_adapters/postgresql/schema_statements'
#
# Monkey-patch the refused Rails 4.2 patch at https://github.com/rails/rails/pull/31330
#
# Updates sequence logic to support PostgreSQL 10.
#
# rubocop:disable all
module ActiveRecord
module ConnectionAdapters
# We need #postgresql_version to be public as in ActiveRecord 5 for seed_fu
# to work. In ActiveRecord 4, it is protected.
# https://github.com/mbleigh/seed-fu/issues/123
class PostgreSQLAdapter
public :postgresql_version
end
module PostgreSQL
module SchemaStatements
# Resets the sequence of a table's primary key to the maximum value.
def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
unless pk and sequence
default_pk, default_sequence = pk_and_sequence_for(table)
pk ||= default_pk
sequence ||= default_sequence
end
if @logger && pk && !sequence
@logger.warn "#{table} has primary key #{pk} with no default sequence"
end
if pk && sequence
quoted_sequence = quote_table_name(sequence)
max_pk = select_value("SELECT MAX(#{quote_column_name pk}) FROM #{quote_table_name(table)}")
if max_pk.nil?
if postgresql_version >= 100000
minvalue = select_value("SELECT seqmin FROM pg_sequence WHERE seqrelid = #{quote(quoted_sequence)}::regclass")
else
minvalue = select_value("SELECT min_value FROM #{quoted_sequence}")
end
end
select_value <<-end_sql, 'SCHEMA'
SELECT setval(#{quote(quoted_sequence)}, #{max_pk ? max_pk : minvalue}, #{max_pk ? true : false})
end_sql
end
end
end
end
end
end
# rubocop:enable all
end
...@@ -2,28 +2,6 @@ ...@@ -2,28 +2,6 @@
# MySQL adapter apply a length of 20. Otherwise MySQL can't create an index on # MySQL adapter apply a length of 20. Otherwise MySQL can't create an index on
# binary columns. # binary columns.
# This module can be removed once a Rails 5 schema is used.
# It can't be wrapped in a check that checks Gitlab.rails5? because
# the old Rails 4 schema layout is still used
module MysqlSetLengthForBinaryIndex
def add_index(table_name, column_names, options = {})
options[:length] ||= {}
Array(column_names).each do |column_name|
column = ActiveRecord::Base.connection.columns(table_name).find { |c| c.name == column_name }
if column&.type == :binary
options[:length][column_name] = 20
end
end
super(table_name, column_names, options)
end
end
if defined?(ActiveRecord::ConnectionAdapters::Mysql2Adapter)
ActiveRecord::ConnectionAdapters::Mysql2Adapter.send(:prepend, MysqlSetLengthForBinaryIndex)
end
module MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema module MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema
# This method is used in Rails 5 schema loading as t.index # This method is used in Rails 5 schema loading as t.index
def index(column_names, options = {}) def index(column_names, options = {})
...@@ -34,15 +12,6 @@ module MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema ...@@ -34,15 +12,6 @@ module MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema
return return
end end
# when running rails 4 with rails 5 schema, rails 4 doesn't support multiple
# indexes on the same set of columns. Mysql doesn't support partial indexes, so if
# an index already exists and we add another index, skip it if it's partial:
# see https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/21492#note_102821326
if !Gitlab.rails5? && indexes[column_names] && options[:where]
warn "WARNING: index on columns #{column_names} already exists and partial index is not supported, skipping."
return
end
options[:length] ||= {} options[:length] ||= {}
Array(column_names).each do |column_name| Array(column_names).each do |column_name|
column = columns.find { |c| c.name == column_name } column = columns.find { |c| c.name == column_name }
...@@ -56,14 +25,6 @@ module MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema ...@@ -56,14 +25,6 @@ module MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema
end end
end end
def mysql_adapter? if defined?(ActiveRecord::ConnectionAdapters::MySQL::TableDefinition)
defined?(ActiveRecord::ConnectionAdapters::Mysql2Adapter) && ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters::Mysql2Adapter) ActiveRecord::ConnectionAdapters::MySQL::TableDefinition.send(:prepend, MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema)
end
if Gitlab.rails5?
if defined?(ActiveRecord::ConnectionAdapters::MySQL::TableDefinition)
ActiveRecord::ConnectionAdapters::MySQL::TableDefinition.send(:prepend, MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema)
end
elsif mysql_adapter? && defined?(ActiveRecord::ConnectionAdapters::TableDefinition)
ActiveRecord::ConnectionAdapters::TableDefinition.send(:prepend, MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema)
end end
# Remove this `if` condition when upgraded to rails 5.0. # Remove this `if` condition when upgraded to rails 5.0.
# The body must be kept. # The body must be kept.
if Gitlab.rails5? # Be sure to restart your server when you modify this file.
# Be sure to restart your server when you modify this file. #
# # This file contains migration options to ease your Rails 5.0 upgrade.
# This file contains migration options to ease your Rails 5.0 upgrade. #
# # Once upgraded flip defaults one by one to migrate to the new default.
# Once upgraded flip defaults one by one to migrate to the new default. #
# # Read the Guide for Upgrading Ruby on Rails for more info on each option.
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
Rails.application.config.action_controller.raise_on_unfiltered_parameters = true Rails.application.config.action_controller.raise_on_unfiltered_parameters = true
# Enable per-form CSRF tokens. Previous versions had false. # Enable per-form CSRF tokens. Previous versions had false.
Rails.application.config.action_controller.per_form_csrf_tokens = false Rails.application.config.action_controller.per_form_csrf_tokens = false
# Enable origin-checking CSRF mitigation. Previous versions had false. # Enable origin-checking CSRF mitigation. Previous versions had false.
Rails.application.config.action_controller.forgery_protection_origin_check = false Rails.application.config.action_controller.forgery_protection_origin_check = false
# Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`. # Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`.
# Previous versions had false. # Previous versions had false.
ActiveSupport.to_time_preserves_timezone = false ActiveSupport.to_time_preserves_timezone = false
# Require `belongs_to` associations by default. Previous versions had false. # Require `belongs_to` associations by default. Previous versions had false.
Rails.application.config.active_record.belongs_to_required_by_default = false Rails.application.config.active_record.belongs_to_required_by_default = false
# Do not halt callback chains when a callback returns false. Previous versions had true. # Do not halt callback chains when a callback returns false. Previous versions had true.
ActiveSupport.halt_callback_chains_on_return_false = true ActiveSupport.halt_callback_chains_on_return_false = true
end
...@@ -41,10 +41,7 @@ module ActiveRecord ...@@ -41,10 +41,7 @@ module ActiveRecord
# Abstract representation of an index definition on a table. Instances of # Abstract representation of an index definition on a table. Instances of
# this type are typically created and returned by methods in database # this type are typically created and returned by methods in database
# adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes # adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes
attrs = [:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using, :opclasses] attrs = [:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using, :comment, :opclasses]
# In Rails 5 the second last attribute is newly `:comment`
attrs.insert(-2, :comment) if Gitlab.rails5?
class IndexDefinition < Struct.new(*attrs) #:nodoc: class IndexDefinition < Struct.new(*attrs) #:nodoc:
end end
...@@ -112,15 +109,8 @@ module ActiveRecord ...@@ -112,15 +109,8 @@ module ActiveRecord
result.map do |row| result.map do |row|
index_name = row[0] index_name = row[0]
unique = if Gitlab.rails5? unique = row[1]
row[1] indkey = row[2].split(" ").map(&:to_i)
else
row[1] == 't'
end
indkey = row[2].split(" ")
if Gitlab.rails5?
indkey = indkey.map(&:to_i)
end
inddef = row[3] inddef = row[3]
oid = row[4] oid = row[4]
...@@ -144,8 +134,7 @@ module ActiveRecord ...@@ -144,8 +134,7 @@ module ActiveRecord
[column, opclass] if opclass [column, opclass] if opclass
end.compact] end.compact]
index_attrs = [table_name, index_name, unique, column_names, [], orders, where, nil, using, opclasses] index_attrs = [table_name, index_name, unique, column_names, [], orders, where, nil, using, nil, opclasses]
index_attrs.insert(-2, nil) if Gitlab.rails5? # include index comment for Rails 5
IndexDefinition.new(*index_attrs) IndexDefinition.new(*index_attrs)
end end
...@@ -205,7 +194,7 @@ module ActiveRecord ...@@ -205,7 +194,7 @@ module ActiveRecord
index_parts << "using: #{index.using.inspect}" if index.using index_parts << "using: #{index.using.inspect}" if index.using
index_parts << "type: #{index.type.inspect}" if index.type index_parts << "type: #{index.type.inspect}" if index.type
index_parts << "opclasses: #{index.opclasses.inspect}" if index.opclasses.present? index_parts << "opclasses: #{index.opclasses.inspect}" if index.opclasses.present?
index_parts << "comment: #{index.comment.inspect}" if Gitlab.rails5? && index.comment index_parts << "comment: #{index.comment.inspect}" if index.comment
index_parts index_parts
end end
......
app = Rails.application app = Rails.application
if (Gitlab.rails5? && app.config.public_file_server.enabled) || app.config.serve_static_files if app.config.public_file_server.enabled
# The `ActionDispatch::Static` middleware intercepts requests for static files # The `ActionDispatch::Static` middleware intercepts requests for static files
# by checking if they exist in the `/public` directory. # by checking if they exist in the `/public` directory.
# We're replacing it with our `Gitlab::Middleware::Static` that does the same, # We're replacing it with our `Gitlab::Middleware::Static` that does the same,
# except ignoring `/uploads`, letting those go through to the GitLab Rails app. # except ignoring `/uploads`, letting those go through to the GitLab Rails app.
if Gitlab.rails5? app.config.middleware.swap(
app.config.middleware.swap( ActionDispatch::Static,
ActionDispatch::Static, Gitlab::Middleware::Static,
Gitlab::Middleware::Static, app.paths["public"].first,
app.paths["public"].first, headers: app.config.public_file_server.headers
headers: app.config.public_file_server.headers )
)
else
app.config.middleware.swap(
ActionDispatch::Static,
Gitlab::Middleware::Static,
app.paths["public"].first,
app.config.static_cache_control
)
end
# If webpack-dev-server is configured, proxy webpack's public directory # If webpack-dev-server is configured, proxy webpack's public directory
# instead of looking for static assets # instead of looking for static assets
......
...@@ -26,12 +26,10 @@ Rails.application.config.action_dispatch.trusted_proxies = ( ...@@ -26,12 +26,10 @@ Rails.application.config.action_dispatch.trusted_proxies = (
# A monkey patch to make trusted proxies work with Rails 5.0. # A monkey patch to make trusted proxies work with Rails 5.0.
# Inspired by https://github.com/rails/rails/issues/5223#issuecomment-263778719 # Inspired by https://github.com/rails/rails/issues/5223#issuecomment-263778719
# Remove this monkey patch when upstream is fixed. # Remove this monkey patch when upstream is fixed.
if Gitlab.rails5? module TrustedProxyMonkeyPatch
module TrustedProxyMonkeyPatch def ip
def ip @ip ||= (get_header("action_dispatch.remote_ip") || super).to_s
@ip ||= (get_header("action_dispatch.remote_ip") || super).to_s
end
end end
ActionDispatch::Request.send(:include, TrustedProxyMonkeyPatch)
end end
ActionDispatch::Request.send(:include, TrustedProxyMonkeyPatch)
...@@ -4,7 +4,7 @@ GEMFILE_LOCK_NOT_UPDATED_MESSAGE = <<~MSG.freeze ...@@ -4,7 +4,7 @@ GEMFILE_LOCK_NOT_UPDATED_MESSAGE = <<~MSG.freeze
Usually, when %<gemfile>s is updated, you should run Usually, when %<gemfile>s is updated, you should run
``` ```
bundle install && \ bundle install && \
BUNDLE_GEMFILE=Gemfile.rails5 bundle install bundle install
``` ```
or or
......
# rubocop:disable Naming/FileName
# frozen_string_literal: true
# When switching to rails 5, we added migration version to all migration
# classes. This patch makes it possible to run versioned migrations
# also with rails 4
unless Gitlab.rails5?
module ActiveRecord
class Migration
def self.[](version)
Migration
end
end
end
end
#!/usr/bin/env bash
echo -e "=> Checking if Gemfile.rails4.lock is up-to-date...\\n"
cp Gemfile.rails4.lock Gemfile.rails4.lock.orig
BUNDLE_GEMFILE=Gemfile.rails4 bundle install "$BUNDLE_INSTALL_FLAGS"
diff -u Gemfile.rails4.lock.orig Gemfile.rails4.lock >/dev/null 2>&1
if [ $? == 1 ]
then
diff -u Gemfile.rails4.lock.orig Gemfile.rails4.lock
echo -e "\\n✖ ERROR: Gemfile.rails4.lock is not up-to-date!
Please run 'BUNDLE_GEMFILE=Gemfile.rails4 bundle install'\\n" >&2
exit 1
fi
echo "✔ Gemfile.rails4.lock is up-to-date"
exit 0
...@@ -1338,12 +1338,7 @@ describe Gitlab::Database::MigrationHelpers do ...@@ -1338,12 +1338,7 @@ describe Gitlab::Database::MigrationHelpers do
end end
describe '#index_exists_by_name?' do describe '#index_exists_by_name?' do
# TODO: remove rails5-only after removing rails4 tests it 'returns true if an index exists' do
# rails 4 can not handle multiple indexes on the same column set if
# index was added by 't.index' - t.index is used by default in schema.rb in
# rails 5. Let's run this test only in rails 5 env:
# see https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/21492#note_113602758
it 'returns true if an index exists', :rails5 do
expect(model.index_exists_by_name?(:projects, 'index_projects_on_path')) expect(model.index_exists_by_name?(:projects, 'index_projects_on_path'))
.to be_truthy .to be_truthy
end end
......
...@@ -462,8 +462,7 @@ describe Gitlab::Database do ...@@ -462,8 +462,7 @@ describe Gitlab::Database do
expect(described_class.db_read_only?).to be_truthy expect(described_class.db_read_only?).to be_truthy
end end
# TODO: remove rails5-only tag after removing rails4 tests it 'detects a read only database' do
it 'detects a read only database', :rails5 do
allow(ActiveRecord::Base.connection).to receive(:execute).with('SELECT pg_is_in_recovery()').and_return([{ "pg_is_in_recovery" => true }]) allow(ActiveRecord::Base.connection).to receive(:execute).with('SELECT pg_is_in_recovery()').and_return([{ "pg_is_in_recovery" => true }])
expect(described_class.db_read_only?).to be_truthy expect(described_class.db_read_only?).to be_truthy
...@@ -475,8 +474,7 @@ describe Gitlab::Database do ...@@ -475,8 +474,7 @@ describe Gitlab::Database do
expect(described_class.db_read_only?).to be_falsey expect(described_class.db_read_only?).to be_falsey
end end
# TODO: remove rails5-only tag after removing rails4 tests it 'detects a read write database' do
it 'detects a read write database', :rails5 do
allow(ActiveRecord::Base.connection).to receive(:execute).with('SELECT pg_is_in_recovery()').and_return([{ "pg_is_in_recovery" => false }]) allow(ActiveRecord::Base.connection).to receive(:execute).with('SELECT pg_is_in_recovery()').and_return([{ "pg_is_in_recovery" => false }])
expect(described_class.db_read_only?).to be_falsey expect(described_class.db_read_only?).to be_falsey
......
...@@ -240,12 +240,7 @@ describe Gitlab::GithubImport::Importer::PullRequestImporter, :clean_gitlab_redi ...@@ -240,12 +240,7 @@ describe Gitlab::GithubImport::Importer::PullRequestImporter, :clean_gitlab_redi
.and_return(user.id) .and_return(user.id)
end end
# TODO: remove rails5-only after removing rails4 tests it 'returns the existing merge request' do
# rails 4 can not handle multiple indexes on the same column set if
# index was added by 't.index' - t.index is used by default in schema.rb in
# rails 5. Let's run this test only in rails 5 env:
# see https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/21492#note_113602758
it 'returns the existing merge request', :rails5 do
mr1, exists1 = importer.create_merge_request mr1, exists1 = importer.create_merge_request
mr2, exists2 = importer.create_merge_request mr2, exists2 = importer.create_merge_request
......
...@@ -235,10 +235,6 @@ RSpec.configure do |config| ...@@ -235,10 +235,6 @@ RSpec.configure do |config|
example.run if Gitlab::Database.mysql? example.run if Gitlab::Database.mysql?
end end
config.around(:each, :rails5) do |example|
example.run if Gitlab.rails5?
end
# This makes sure the `ApplicationController#can?` method is stubbed with the # This makes sure the `ApplicationController#can?` method is stubbed with the
# original implementation for all view specs. # original implementation for all view specs.
config.before(:each, type: :view) do config.before(:each, type: :view) do
......
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