databaserustsyntaxrust-dieselrust-diesel-mysql

Return type of row deletion function in Rust using Diesel


I have implemented helper functions for use with data querying in Rust as follows:

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))
    }
}

The return type for hard_delete() gives me a headache since the where_clause module is private.

What should be the correct return type here?


Solution

  • You can skip the Where stuff by using its Filter alias:

    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))
        }