From 9039ee66f091fbdba6ab0f15a27dcf76f90503b8 Mon Sep 17 00:00:00 2001
From: Awiteb
Date: Wed, 17 Jul 2024 22:28:36 +0300
Subject: [PATCH] feat: Create unique index for `RecipientId` and `Sender`
Signed-off-by: Awiteb
---
.../src/database/in_chat_requests.rs | 34 +++++++++----------
.../create_incoming_chat_requests_table.rs | 12 +++++++
2 files changed, 29 insertions(+), 17 deletions(-)
diff --git a/crates/oxidetalis/src/database/in_chat_requests.rs b/crates/oxidetalis/src/database/in_chat_requests.rs
index 537b3fe..0e36c74 100644
--- a/crates/oxidetalis/src/database/in_chat_requests.rs
+++ b/crates/oxidetalis/src/database/in_chat_requests.rs
@@ -19,7 +19,7 @@
use chrono::Utc;
use oxidetalis_core::types::PublicKey;
use oxidetalis_entities::prelude::*;
-use sea_orm::DatabaseConnection;
+use sea_orm::{sea_query::OnConflict, DatabaseConnection};
use crate::errors::ServerResult;
@@ -40,22 +40,22 @@ impl InChatRequestsExt for DatabaseConnection {
sender: &PublicKey,
recipient: &UserModel,
) -> ServerResult<()> {
- if recipient
- .find_related(InChatRequestsEntity)
- .filter(InChatRequestsColumn::Sender.eq(sender.to_string()))
- .one(self)
- .await?
- .is_none()
- {
- InChatRequestsActiveModel {
- recipient_id: Set(recipient.id),
- sender: Set(sender.to_string()),
- in_on: Set(Utc::now()),
- ..Default::default()
- }
- .save(self)
- .await?;
- }
+ InChatRequestsEntity::insert(InChatRequestsActiveModel {
+ recipient_id: Set(recipient.id),
+ sender: Set(sender.to_string()),
+ in_on: Set(Utc::now()),
+ ..Default::default()
+ })
+ .on_conflict(
+ OnConflict::columns([
+ InChatRequestsColumn::RecipientId,
+ InChatRequestsColumn::Sender,
+ ])
+ .do_nothing()
+ .to_owned(),
+ )
+ .exec(self)
+ .await?;
Ok(())
}
}
diff --git a/crates/oxidetalis_migrations/src/create_incoming_chat_requests_table.rs b/crates/oxidetalis_migrations/src/create_incoming_chat_requests_table.rs
index fee1dec..d33a5b3 100644
--- a/crates/oxidetalis_migrations/src/create_incoming_chat_requests_table.rs
+++ b/crates/oxidetalis_migrations/src/create_incoming_chat_requests_table.rs
@@ -29,6 +29,18 @@ pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
+ manager
+ .create_index(
+ Index::create()
+ .if_not_exists()
+ .name("sep_request")
+ .table(InChatRequests::Table)
+ .col(InChatRequests::RecipientId)
+ .col(InChatRequests::Sender)
+ .unique()
+ .to_owned(),
+ )
+ .await?;
manager
.create_table(
Table::create()