From e45bca7298833cc0d131987ad41c25604b60f290 Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 23 Mar 2021 09:19:02 +1100 Subject: [PATCH] PERF: avoid regex on uploads table (#12485) In extreme circumstances when the uploads table is huge, the old version of this migration could take a very long time. The rewrite extracts the sha1 directly from the badges table and does an index based match on the uploads table --- ...20210311070755_add_image_upload_id_to_badges.rb | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/db/migrate/20210311070755_add_image_upload_id_to_badges.rb b/db/migrate/20210311070755_add_image_upload_id_to_badges.rb index ed0379bc67..c9d15ee030 100644 --- a/db/migrate/20210311070755_add_image_upload_id_to_badges.rb +++ b/db/migrate/20210311070755_add_image_upload_id_to_badges.rb @@ -8,10 +8,16 @@ class AddImageUploadIdToBadges < ActiveRecord::Migration[6.0] DB.exec <<~SQL UPDATE badges b1 SET image_upload_id = u.id - FROM badges b2 - INNER JOIN uploads u - ON b2.image ~ CONCAT('/', u.sha1, '\\.\\w') - WHERE b1.id = b2.id + FROM ( + SELECT id, (regexp_matches(b.image, '[a-f0-9]{40}'))[1] as sha1 + FROM badges b + WHERE + b.image IS NOT NULL AND + b.image ~ '[a-f0-9]{40}' + ) b2 + JOIN uploads u ON u.sha1 = b2.sha1 + WHERE + b1.id = b2.id SQL end end