impl GetCollection via async_trait

This commit is contained in:
Akulij 2025-06-07 02:08:00 +05:00
parent 5a7bb0e0f6
commit bd8b1e8843
2 changed files with 17 additions and 8 deletions

View File

@ -43,19 +43,23 @@ impl BotInstance {
Ok(self)
});
pub async fn get_all<D: CallDB>(db: &mut D) -> DbResult<Vec<Self>> {
pub async fn get_all<D: GetCollection>(db: &mut D) -> DbResult<Vec<Self>> {
let bi = db.get_collection::<Self>().await;
Ok(bi.find(doc! {}).await?.try_collect().await?)
}
pub async fn get_by_name<D: CallDB>(db: &mut D, name: &str) -> DbResult<Option<Self>> {
pub async fn get_by_name<D: GetCollection>(db: &mut D, name: &str) -> DbResult<Option<Self>> {
let bi = db.get_collection::<Self>().await;
Ok(bi.find_one(doc! {"name": name}).await?)
}
pub async fn restart_one<D: CallDB>(db: &mut D, name: &str, restart: bool) -> DbResult<()> {
pub async fn restart_one<D: GetCollection>(
db: &mut D,
name: &str,
restart: bool,
) -> DbResult<()> {
let bi = db.get_collection::<Self>().await;
bi.update_one(
@ -66,7 +70,7 @@ impl BotInstance {
Ok(())
}
pub async fn restart_all<D: CallDB>(db: &mut D, restart: bool) -> DbResult<()> {
pub async fn restart_all<D: GetCollection>(db: &mut D, restart: bool) -> DbResult<()> {
let bi = db.get_collection::<Self>().await;
bi.update_many(doc! {}, doc! { "$set": { "restart_flag": restart } })
@ -74,7 +78,11 @@ impl BotInstance {
Ok(())
}
pub async fn update_script<D: CallDB>(db: &mut D, name: &str, script: &str) -> DbResult<()> {
pub async fn update_script<D: GetCollection>(
db: &mut D,
name: &str,
script: &str,
) -> DbResult<()> {
let bi = db.get_collection::<Self>().await;
bi.update_one(

View File

@ -11,7 +11,6 @@ use chrono::{DateTime, Local, Utc};
use enum_stringify::EnumStringify;
use futures::stream::TryStreamExt;
use futures::StreamExt;
use mongodb::bson::serde_helpers::chrono_datetime_as_bson_datetime;
use mongodb::options::IndexOptions;
use mongodb::{bson::doc, options::ClientOptions, Client};
@ -57,7 +56,7 @@ macro_rules! query_call {
#[macro_export]
macro_rules! query_call_consume {
($func_name:ident, $self:ident, $db:ident, $return_type:ty, $body:block) => {
pub async fn $func_name<D: CallDB>($self, $db: &mut D)
pub async fn $func_name<D: crate::db::GetCollection + CallDB>($self, $db: &mut D)
-> DbResult<$return_type> $body
};
}
@ -207,6 +206,7 @@ pub trait DbCollection {
const COLLECTION: &str;
}
#[async_trait]
pub trait GetCollection {
async fn get_collection<C: DbCollection + Send + Sync>(&mut self) -> Collection<C>;
}
@ -222,7 +222,8 @@ impl CallDB for DB {
}
}
impl<T: CallDB> GetCollection for T {
#[async_trait]
impl<T: CallDB + Send> GetCollection for T {
async fn get_collection<C: DbCollection + Send + Sync>(&mut self) -> Collection<C> {
self.get_database()
.await