From 8d697bbbd3de55df355705020382fc4a773286e7 Mon Sep 17 00:00:00 2001 From: Sam Saffron Date: Wed, 24 Apr 2019 17:21:29 +1000 Subject: [PATCH] FIX: ensure image tracking custom fields have no dupes All these columns must never include duplicates for a single post otherwise code breaks. All are defined in post.rb in the top in constants but we usually prefer not to ref constants in case they change and migration becomes inconsistent. --- .../20190424065841_add_post_image_indexes.rb | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 db/migrate/20190424065841_add_post_image_indexes.rb diff --git a/db/migrate/20190424065841_add_post_image_indexes.rb b/db/migrate/20190424065841_add_post_image_indexes.rb new file mode 100644 index 0000000000..eb1e4aa07a --- /dev/null +++ b/db/migrate/20190424065841_add_post_image_indexes.rb @@ -0,0 +1,24 @@ +class AddPostImageIndexes < ActiveRecord::Migration[5.2] + def change + + %w{ + large_images + broken_images + downloaded_images + }.each do |field| + + execute <<~SQL + DELETE FROM post_custom_fields f + WHERE name = '#{field}' AND id > ( + SELECT MIN(f2.id) FROM post_custom_fields f2 + WHERE f2.post_id = f.post_id AND f2.name = f.name + ) + SQL + + add_index :post_custom_fields, [:post_id], + name: "post_custom_field_#{field}_idx", + unique: true, + where: "name = '#{field}'" + end + end +end