A platform for community discussion. Free, open, simple.
DEV: Make Bookmark#post_id column nullable (#16287)
Martin Brennan230e82e94874
diff --git a/app/models/bookmark.rb b/app/models/bookmark.rbindex 35363b60d7e..5af236ca2f4 100644--- a/app/models/bookmark.rb+++ b/app/models/bookmark.rb@@ -169,7 +169,7 @@ end## id :bigint not null, primary key# user_id :bigint not null-# post_id :bigint not null+# post_id :bigint# name :string(100)# reminder_at :datetime# created_at :datetime not nulldiff --git a/db/post_migrate/20220325064954_make_some_bookmark_columns_nullable.rb b/db/post_migrate/20220325064954_make_some_bookmark_columns_nullable.rbnew file mode 100644index 00000000000..90905d34af9--- /dev/null+++ b/db/post_migrate/20220325064954_make_some_bookmark_columns_nullable.rb@@ -0,0 +1,17 @@+# frozen_string_literal: true++class MakeSomeBookmarkColumnsNullable < ActiveRecord::Migration[6.1]+ def up+ change_column_null :bookmarks, :post_id, true+ execute "ALTER TABLE bookmarks ADD CONSTRAINT enforce_post_id_or_bookmarkable CHECK (+ (post_id IS NOT NULL) OR (bookmarkable_id IS NOT NULL AND bookmarkable_type IS NOT NULL)+ )"+ end++ def down+ DB.exec("UPDATE bookmarks SET post_id = bookmarkable_id WHERE bookmarkable_type = 'Post'")+ DB.exec("UPDATE bookmarks SET post_id = (SELECT id FROM posts WHERE topic_id = bookmarkable_id AND post_number = 1), for_topic = TRUE WHERE bookmarkable_type = 'Topic'")+ change_column_null :bookmarks, :post_id, false+ execute "ALTER TABLE bookmarks DROP CONSTRAINT enforce_post_id_or_bookmarkable"+ end+end