DEV: Add polymorphic bookmarkable columns (#15454)

We are planning on attaching bookmarks to more and
more other models, so it makes sense to make a polymorphic
relationship to handle this. This commit adds the new
columns and backfills them in the bookmark table, and
makes sure that any new bookmark changes fill in the columns
via DB triggers.

This way we can gradually change the frontend and backend
to use these new columns, and eventually delete the
old post_id and for_topic columns in `bookmarks`.
This commit is contained in:
Martin Brennan
2022-01-06 08:56:05 +10:00
committed by GitHub
parent e6ab8f5b71
commit e21c640a3c
6 changed files with 80 additions and 1 deletions

View File

@ -0,0 +1,10 @@
# frozen_string_literal: true
class AddBookmarkPolymorphicColumns < ActiveRecord::Migration[6.1]
def change
add_column :bookmarks, :bookmarkable_id, :integer
add_column :bookmarks, :bookmarkable_type, :string
add_index :bookmarks, [:user_id, :bookmarkable_type, :bookmarkable_id], name: "idx_bookmarks_user_polymorphic_unique", unique: true
end
end

View File

@ -0,0 +1,48 @@
# frozen_string_literal: true
class AddTriggerForPolymorphicBookmarkColumnsToSyncData < ActiveRecord::Migration[6.1]
def up
DB.exec <<~SQL
CREATE OR REPLACE FUNCTION sync_bookmarks_polymorphic_column_data()
RETURNS TRIGGER
LANGUAGE PLPGSQL AS $rcr$
BEGIN
IF NEW.for_topic
THEN
NEW.bookmarkable_id = (SELECT topic_id FROM posts WHERE posts.id = NEW.post_id);
NEW.bookmarkable_type = 'Topic';
ELSE
NEW.bookmarkable_id = NEW.post_id;
NEW.bookmarkable_type = 'Post';
END IF;
RETURN NEW;
END
$rcr$;
SQL
DB.exec <<~SQL
CREATE TRIGGER bookmarks_polymorphic_data_sync
BEFORE INSERT OR UPDATE OF post_id, for_topic ON bookmarks
FOR EACH ROW
EXECUTE FUNCTION sync_bookmarks_polymorphic_column_data();
SQL
# sync data that already exists in the table
DB.exec(<<~SQL)
UPDATE bookmarks
SET bookmarkable_id = post_id, bookmarkable_type = 'Post'
WHERE NOT bookmarks.for_topic
SQL
DB.exec(<<~SQL)
UPDATE bookmarks
SET bookmarkable_id = posts.topic_id, bookmarkable_type = 'Topic'
FROM posts
WHERE bookmarks.for_topic AND posts.id = bookmarks.post_id
SQL
end
def down
DB.exec("DROP TRIGGER IF EXISTS bookmarks_polymorphic_data_sync")
DB.exec("DROP FUNCTION IF EXISTS sync_bookmarks_polymorphic_column_data")
end
end