Last active
December 19, 2015 09:39
-
-
Save clarkdave/5935158 to your computer and use it in GitHub Desktop.
basic support for PostgreSQL sequences in ActiveRecord migrations - place in an initializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PgSequence | |
module PostgreSQLAdapter | |
def create_sequence(name) | |
execute "CREATE SEQUENCE #{name}" | |
end | |
def drop_sequence(name) | |
execute "DROP SEQUENCE #{name}" | |
end | |
end | |
end | |
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do | |
include PgSequence::PostgreSQLAdapter | |
end | |
ActiveRecord::ConnectionAdapters.module_eval do | |
include PgSequence::PostgreSQLAdapter | |
end | |
module PgSequence | |
module SchemaDumper | |
extend ActiveSupport::Concern | |
included do | |
alias_method_chain :tables, :sequences | |
end | |
def tables_with_sequences(stream) | |
tables_without_sequences(stream) | |
sequences(stream) | |
end | |
private | |
def sequences(stream) | |
sequence_names = @connection.select_all("SELECT c.relname FROM pg_class c WHERE c.relkind = 'S' order by c.relname asc") | |
.map { |row| row['relname'] } | |
# ignore any sequences that end in 'id_seq', as these are generated by rails for primary keys | |
# and are added implicitly by the migrator | |
statements = sequence_names.reject {|seq| seq.end_with? 'id_seq'}.map do |seq| | |
" create_sequence(#{seq.inspect})" | |
end | |
stream.puts statements.sort.join("\n") | |
stream.puts | |
end | |
end | |
end | |
ActiveRecord::SchemaDumper.class_eval do | |
include PgSequence::SchemaDumper | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment