about summary refs log tree commit diff
path: root/db/migrate/20170920024819_status_ids_to_timestamp_ids.rb
blob: 8679f8ece87ee4fed14bc8e2cb777654ba869938 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class StatusIdsToTimestampIds < ActiveRecord::Migration[5.1]
  def up
    # Prepare the function we will use to generate IDs.
    Mastodon::Snowflake.define_timestamp_id

    # Set up the statuses.id column to use our timestamp-based IDs.
    ActiveRecord::Base.connection.execute(<<~SQL)
      ALTER TABLE statuses
      ALTER COLUMN id
      SET DEFAULT timestamp_id('statuses')
    SQL

    # Make sure we have a sequence to use.
    Mastodon::Snowflake.ensure_id_sequences_exist
  end

  def down
    # Revert the column to the old method of just using the sequence
    # value for new IDs. Set the current ID sequence to the maximum
    # existing ID, such that the next sequence will be one higher.

    # We lock the table during this so that the ID won't get clobbered,
    # but ID is indexed, so this should be a fast operation.
    ActiveRecord::Base.connection.execute(<<~SQL)
      LOCK statuses;
      SELECT setval('statuses_id_seq', (SELECT MAX(id) FROM statuses));
      ALTER TABLE statuses
        ALTER COLUMN id
        SET DEFAULT nextval('statuses_id_seq');
    SQL
  end
end