Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Created July 1, 2019 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inopinatus/225ab1f33f3e13f132343ae2a4e90a83 to your computer and use it in GitHub Desktop.
Save inopinatus/225ab1f33f3e13f132343ae2a4e90a83 to your computer and use it in GitHub Desktop.
example use of CTEs in object-rewriting migration
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