Skip to content

Commit e58b899

Browse files
committed
use CTE for message mention query
1 parent add2a64 commit e58b899

3 files changed

Lines changed: 17 additions & 10 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
DROP INDEX IF EXISTS idx_messages_channel_message;
2+
DROP INDEX IF EXISTS idx_role_data_user_guild;
3+
DROP INDEX IF EXISTS idx_messages_mentions;
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
CREATE INDEX IF NOT EXISTS idx_messages_channel_message ON messages (channel_id, id);
2+
CREATE INDEX IF NOT EXISTS idx_role_data_user_guild ON role_data (user_id, guild_id);
3+
CREATE INDEX IF NOT EXISTS idx_messages_mentions ON messages USING GIN (mentions);

src/db/message.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -666,7 +666,7 @@ pub trait MessageDbExt<'t>: DbExt<'t> {
666666
/// Edits a message in the given channel. This turns the current message into a revision of the
667667
/// message, and creates a new message with the new data.
668668
///
669-
/// If provided, ``user_id``` will be checked against the author of the message and throw a
669+
/// If provided, ``user_id`` will be checked against the author of the message and throw a
670670
/// forbidden error if they do not match.
671671
///
672672
/// # Note
@@ -832,22 +832,23 @@ pub trait MessageDbExt<'t>: DbExt<'t> {
832832
.collect_vec();
833833

834834
let res = sqlx::query!(
835-
r"SELECT m.id, m.channel_id FROM messages m
835+
r"WITH user_roles AS (
836+
SELECT guild_id, array_agg(role_id) AS role_ids
837+
FROM role_data
838+
WHERE user_id = $1
839+
GROUP BY guild_id
840+
)
841+
SELECT m.id, m.channel_id FROM messages m
836842
INNER JOIN channels c ON m.channel_id = c.id
837843
LEFT JOIN channel_acks a ON m.channel_id = a.channel_id AND a.user_id = $1
844+
LEFT JOIN user_roles r ON r.guild_id = c.guild_id
838845
WHERE
839846
m.channel_id = ANY($2::BIGINT[])
840-
AND (
841-
a.last_message_id IS NULL
842-
OR m.id > a.last_message_id
843-
)
847+
AND m.id > COALESCE(a.last_message_id, 0)
844848
AND (
845849
$1 = ANY(m.mentions)
846850
OR c.guild_id = ANY(m.mentions)
847-
OR m.mentions && (
848-
SELECT array_agg(role_id) FROM role_data
849-
WHERE guild_id = c.guild_id AND user_id = $1
850-
)
851+
OR m.mentions && r.role_ids
851852
)",
852853
user_id as i64,
853854
&channel_ids,

0 commit comments

Comments
 (0)