Created
July 1, 2019 00:56
-
-
Save inopinatus/225ab1f33f3e13f132343ae2a4e90a83 to your computer and use it in GitHub Desktop.
example use of CTEs in object-rewriting migration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def remap_reviewer_ids(table) | |
connection.execute(<<~EOQ) | |
WITH reviewer_map AS ( | |
SELECT reviewers.base_id, to_jsonb(array_agg(DISTINCT profiles.account_id)) | |
FROM profiles | |
JOIN (SELECT jsonb_array_elements(options->'reviewer_ids')::text::int as reviewer_id, id AS base_id FROM #{table}) AS reviewers | |
ON reviewers.reviewer_id = profiles.id | |
GROUP BY base_id | |
) | |
UPDATE #{table} | |
SET options = jsonb_set(options, '{reviewer_ids}', reviewer_map.to_jsonb) | |
FROM reviewer_map | |
WHERE #{table}.id = reviewer_map.base_id | |
EOQ | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment