Class: CreateUsers

Inherits:
Debci::DB::LEGACY_MIGRATION
  • Object
show all
Defined in:
lib/debci/db/migrations/20200515000000_create_users.rb

Instance Method Summary collapse

Instance Method Details

#downObject



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/debci/db/migrations/20200515000000_create_users.rb', line 22

def down
  add_column :keys, :user, :string, limit: 256, null: true
  execute <<~SQL
    UPDATE keys
    SET "user" = users.username
    FROM users
    WHERE users.id = keys.user_id
  SQL
  remove_foreign_key :keys, :users
  change_column_null :keys, :user, false
  remove_column :keys, :user_id
  drop_table :users
end

#upObject



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/debci/db/migrations/20200515000000_create_users.rb', line 2

def up
  create_table :users do |t|
    t.string :username, limit: 256, null: false, unique: true
    t.boolean :admin, default: false
  end

  add_column :keys, :user_id, :integer, null: true
  add_foreign_key :keys, :users
  execute <<~SQL
    INSERT INTO users (username)
    SELECT DISTINCT("user") from keys;

    UPDATE keys SET user_id = users.id
    FROM users
    WHERE users.username = keys.user;
  SQL
  change_column_null :keys, :user_id, false
  remove_column :keys, :user
end