I had to connect to PostgreSQL 10 and test it with Rails 3.0.1, so I decided to add an initializer.
config/initializers/backport_pg_10_support_to_rails_3.rb
if Rails.env.test?
module ActiveRecord
class Base
class << self
def establish_connection(*arg)
end
end
end
end
require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
# Resets the sequence of a table's primary key to the maximum value.
def reset_pk_sequence!(table, pk = nil, sequence = nil)
unless pk and sequence
default_pk, default_sequence = pk_and_sequence_for(table)
pk ||= default_pk
sequence ||= default_sequence
end
if pk
if sequence
quoted_sequence = quote_column_name(sequence)
if ActiveRecord::Base.connection.select_value('SELECT version()').include?('PostgreSQL 10')
# language=sql
sql =<<-EOS
SELECT setval('#{quoted_sequence}', (SELECT GREATEST(MAX(#{quote_column_name pk})+(SELECT seqincrement FROM pg_sequence WHERE seqrelid = '#{quoted_sequence}'::regclass), (SELECT seqmin FROM pg_sequence WHERE seqrelid = '#{quoted_sequence}'::regclass)) FROM #{quote_table_name(table)}), false)
EOS
else
# language=sql
sql =<<-EOS
SELECT setval('#{quoted_sequence}', (SELECT GREATEST(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
EOS
end
else
@logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger
end
end
end
end
end
end
end
I put require'active_record / connection_adapters / postgresql_adapter'
and overwrotedef reset_pk_sequence! (Table, pk = nil, sequence = nil)
, but that alone gives an error that ʻestablish_connection does not exist. , I wrote ʻestablish_connection
before require
.
reset_pk_sequence!
is basically a copy from https://github.com/rails/rails/blob/3-0-stable/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb, and the change is the SQL creation part is.