Skip to content

Commit

Permalink
Merge pull request #16395 from opf/bug/rewrite-migration-for-release
Browse files Browse the repository at this point in the history
Update migration to use raw SQL rather than AR models
  • Loading branch information
machisuji authored Aug 12, 2024
2 parents 3518927 + fa15643 commit e8a297f
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions db/migrate/20240808125617_populate_remote_identities.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2024 the OpenProject GmbH
Expand Down Expand Up @@ -26,30 +28,31 @@
# See COPYRIGHT and LICENSE files for more details.
#++

class PopulateRemoteIdentities < ActiveRecord::Migration[7.1]
def up
fields = %i[user_id oauth_client_id origin_user_id]
require_relative "migration_utils/utils"

OAuthClientToken.where.not(origin_user_id: nil)
.select(:id, *fields)
.find_in_batches do |batch|
identities = batch.map { |record| record.slice(*fields) }
class PopulateRemoteIdentities < ActiveRecord::Migration[7.1]
include ::Migration::Utils

RemoteIdentity.insert_all(identities, unique_by: %i[user_id oauth_client_id])
end
def up
execute_sql <<~SQL.squish
INSERT INTO remote_identities(user_id, oauth_client_id, origin_user_id, created_at, updated_at)
SELECT DISTINCT ON (user_id, oauth_client_id) user_id, oauth_client_id, origin_user_id, created_at, updated_at
FROM oauth_client_tokens
WHERE oauth_client_tokens.origin_user_id IS NOT NULL
SQL

OAuthClientToken.update_all(origin_user_id: nil)
execute_sql "UPDATE oauth_client_tokens SET origin_user_id = NULL"
end

def down
RemoteIdentity.find_in_batches do |batch|
batch.each do |identity|
OAuthClientToken
.where(user: identity.user, oauth_client: identity.oauth_client)
.update_all(origin_user_id: identity.origin_user_id)
end
end
execute_sql <<~SQL.squish
UPDATE oauth_client_tokens
SET origin_user_id = remote_identities.origin_user_id
FROM remote_identities
WHERE oauth_client_tokens.user_id = remote_identities.user_id
AND oauth_client_tokens.oauth_client_id = remote_identities.oauth_client_id
SQL

RemoteIdentity.delete_all
execute_sql "DELETE FROM remote_identities"
end
end

0 comments on commit e8a297f

Please sign in to comment.