20170920024819_status_ids_to_timestamp_ids.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. class StatusIdsToTimestampIds < ActiveRecord::Migration[5.1]
  2. def up
  3. # Prepare the function we will use to generate IDs.
  4. Rake::Task['db:define_timestamp_id'].execute
  5. # Set up the statuses.id column to use our timestamp-based IDs.
  6. ActiveRecord::Base.connection.execute(<<~SQL)
  7. ALTER TABLE statuses
  8. ALTER COLUMN id
  9. SET DEFAULT timestamp_id('statuses')
  10. SQL
  11. # Make sure we have a sequence to use.
  12. Rake::Task['db:ensure_id_sequences_exist'].execute
  13. end
  14. def down
  15. # Revert the column to the old method of just using the sequence
  16. # value for new IDs. Set the current ID sequence to the maximum
  17. # existing ID, such that the next sequence will be one higher.
  18. # We lock the table during this so that the ID won't get clobbered,
  19. # but ID is indexed, so this should be a fast operation.
  20. ActiveRecord::Base.connection.execute(<<~SQL)
  21. LOCK statuses;
  22. SELECT setval('statuses_id_seq', (SELECT MAX(id) FROM statuses));
  23. ALTER TABLE statuses
  24. ALTER COLUMN id
  25. SET DEFAULT nextval('statuses_id_seq');
  26. SQL
  27. end
  28. end