Skip to content

Instantly share code, notes, and snippets.

@clarkdave
Last active December 19, 2015 09:39
Show Gist options
  • Save clarkdave/5935158 to your computer and use it in GitHub Desktop.
Save clarkdave/5935158 to your computer and use it in GitHub Desktop.
basic support for PostgreSQL sequences in ActiveRecord migrations - place in an initializer
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