20170920024819_status_ids_to_timestamp_ids.rb 1.1 KB

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