DEV: Add messages_count to ChatChannel table (#19295)

This commit adds the messages_count column for ChatChannel messages,
which is the number of not-deleted messages in the channel.

This is not updated every time a message is created or deleted in a
channel, so it should not be displayed in the UI.
It is updated eventually via Jobs::ChatPeriodicalUpdates, which
will have additional functions in future after being introduced
here.

Also update these counts for existing channels in a post migration.
This commit is contained in:
Martin Brennan
2022-12-06 08:40:46 +10:00
committed by GitHub
parent ea542d632a
commit 22a55ef0ce
8 changed files with 140 additions and 9 deletions

View File

@ -0,0 +1,8 @@
# frozen_string_literal: true
class AddChatMessageCountToChatChannels < ActiveRecord::Migration[7.0]
def change
add_column :chat_channels, :messages_count, :integer, null: false, default: 0
add_index :chat_channels, :messages_count
end
end

View File

@ -0,0 +1,23 @@
# frozen_string_literal: true
class UpdateChatChannelMessageCounts < ActiveRecord::Migration[7.0]
def up
DB.exec <<~SQL
UPDATE chat_channels channels
SET messages_count = subquery.messages_count
FROM (
SELECT COUNT(*) AS messages_count, chat_channel_id
FROM chat_messages
WHERE chat_messages.deleted_at IS NULL
GROUP BY chat_channel_id
) subquery
WHERE channels.id = subquery.chat_channel_id
AND channels.deleted_at IS NULL
AND subquery.messages_count != channels.messages_count
SQL
end
def down
raise ActiveRecord::IrreversibleMigration
end
end