Rust中使用Diesel的行删除函数的返回类型

uinbv5nw  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(90)

我已经实现了用于Rust中数据查询的helper函数,如下所示:

pub type All<Table, T> = Select<Table, AsSelect<T, Mysql>>;
pub type FilterExisting<Target, DeletedAtColumn> =
    Filter<Target, Eq<DeletedAtColumn, NaiveDateTime>>;
pub type ById<Id, R> = Filter<R, Eq<Id, Uuid>>;
pub type ByName<Name, R> = Filter<R, Eq<Name, String>>;
pub type SelectById<Table, Id, DeletedAtColumn, T> =
    ById<Id, FilterExisting<All<Table, T>, DeletedAtColumn>>;
pub type SelectByName<Table, Name, DeletedAtColumn, T> =
    ByName<Name, FilterExisting<All<Table, T>, DeletedAtColumn>>;

#[derive(Queryable, Selectable, Identifiable, Insertable, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[diesel(table_name = dataitems)]
pub struct DataItem {
    #[serde(default = "Uuid::random")]
    pub id: Uuid,
    pub name: String,
    pub content: String,
    pub created_at: NaiveDateTime,
    pub updated_at: NaiveDateTime,
    pub deleted_at: NaiveDateTime,
}

impl DataItem {
    fn all_with_deleted() -> All<dataitems::table, Self> {
        dataitems::table.select(Self::as_select())
    }

    pub fn all() -> FilterExisting<All<dataitems::table, Self>, dataitems::deleted_at> {
        Self::all_with_deleted().filter(dataitems::deleted_at.eq(*NAIVEDATETIME_DEFAULT_VALUE))
    }

    pub fn by_id(id: Uuid) -> SelectById<dataitems::table, dataitems::id, dataitems::deleted_at, Self> {
        Self::all().filter(dataitems::id.eq(id))
    }

    pub fn by_name(
        name: String,
    ) -> SelectByName<dataitems::table, dataitems::name, dataitems::deleted_at, Self> {
        Self::all().filter(dataitems::name.eq(name))
    }

    pub fn hard_delete(&self) -> DeleteStatement<dataitems::table, query_builder::where_clause::WhereClause<diesel::dsl::Eq<dataitems::id, Uuid>>> {
        diesel::delete(dataitems::table).filter(dataitems::id.eq(self.id))
    }
}

hard_delete()的返回类型让我头疼,因为where_clause模块是私有的。
这里正确的返回类型应该是什么?

vd2z7a6w

vd2z7a6w1#

您可以通过使用Filter别名跳过Where内容:

use diesel::helper_types::{Eq, Filter};
use diesel::query_builder::{DeleteStatement, IntoUpdateTarget};

    pub fn hard_delete(
        &self,
    ) -> Filter<
        DeleteStatement<dataitems::table, <dataitems::table as IntoUpdateTarget>::WhereClause>,
        Eq<dataitems::id, Uuid>,
    > {
        diesel::delete(dataitems::table).filter(dataitems::id.eq(self.id))
    }

相关问题