0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails 3 から PostgreSQL 10 に接続するときに使ったコード

Last updated at Posted at 2020-10-24

Rails 3.0.1 で PostgreSQL 10 に繋いでテストする必要があり、 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

require 'active_record/connection_adapters/postgresql_adapter' を入れて、 def reset_pk_sequence!(table, pk = nil, sequence = nil) を上書きしましたが、 それだけだと establish_connection が存在しないというエラーが出るので、 require の前に establish_connection を記述しました。

reset_pk_sequence!https://github.com/rails/rails/blob/3-0-stable/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb から基本的にコピーで、 変更したのは SQL 作成部分です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?