Skip to content

Instantly share code, notes, and snippets.

@TylerRick
Last active December 20, 2015 10:31
Show Gist options
  • Save TylerRick/6115936 to your computer and use it in GitHub Desktop.
Save TylerRick/6115936 to your computer and use it in GitHub Desktop.
Change all datetime columns to have a precision of 0, to match the default precision of these columns in MySQL. This is useful if you migrate a database from MySQL to PostgreSQL and don't need the extra microsecond precision (precision: 6) that is the default in PostgreSQL (see http://www.postgresql.org/docs/9.2/static/datatype-datetime.html).
# Change all datetime columns to have a precision of 0, to match the default precision of these
# columns in MySQL.
#
# This is useful if you migrate a database from MySQL to PostgreSQL and don't need the extra
# microsecond precision (precision: 6) that is the default in PostgreSQL
# (see http://www.postgresql.org/docs/9.2/static/datatype-datetime.html).
#
# Before:
# > some_record.created_at.strftime('%Y-%m-%d %H:%M:%S.%N')
# => "2013-07-25 11:49:33.270032000"
# After:
# > some_record.created_at.strftime('%Y-%m-%d %H:%M:%S.%N')
# => "2013-07-25 11:49:33.000000000"
#
class ReducePrecisionOfDatetimeColumns < ActiveRecord::Migration
def up
Rails.application.eager_load!
puts %(ActiveRecord::Base.descendants: #{(ActiveRecord::Base.descendants).map(&:name).inspect})
ActiveRecord::Base.descendants.each do |model|
model.columns.select {|_| _.type == :datetime }.map(&:name).each do |column_name|
execute "alter table #{model.table_name} alter column #{column_name} type timestamp (0)"
end
end
=begin If you're on Rails 4+, you can use this instead (see https://github.com/rails/rails/pull/6821):
ActiveRecord::Base.descendants.each do |model|
change_table model.table_name do |t|
model.columns.select {|_| _.type == :datetime }.map(&:name).each do |column_name|
t.change column_name, :datetime, precision: 0
end
end
end
=end
end
def down
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment