Class: AddRequestorIdToJobs

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

Instance Method Summary collapse

Instance Method Details

#downObject



14
15
16
17
18
# File 'lib/debci/db/migrations/20210612000000_add_requestor_id_to_jobs.rb', line 14

def down
  add_column :jobs, :requestor, :string
  execute "UPDATE jobs SET requestor = (SELECT users.username FROM users WHERE jobs.requestor_id = users.id)"
  remove_column :jobs, :requestor_id
end

#upObject



2
3
4
5
6
7
8
9
10
11
12
# File 'lib/debci/db/migrations/20210612000000_add_requestor_id_to_jobs.rb', line 2

def up
  add_column :jobs, :requestor_id, :integer
  add_foreign_key :jobs, :users, column: :requestor_id
  execute "INSERT INTO users (username) SELECT DISTINCT requestor FROM jobs WHERE requestor NOT IN (SELECT username FROM users)"
  cases = select_all("SELECT * FROM users").map do |u|
    "WHEN requestor = '#{u['username']}' THEN #{u['id']}"
  end.join(" ")
  execute "UPDATE jobs SET requestor_id = CASE #{cases} END" unless cases.empty?
  change_column_null :jobs, :requestor_id, false
  remove_column :jobs, :requestor
end