How do I get an Option<T> instead of an Option<Vec<T>> from a Diesel query which only returns 1 or 0 records?

£可爱£侵袭症+ 提交于 2019-12-10 16:21:27

问题


I'm querying for existing records in a table called messages; this query is then used as part of a 'find or create' function:

fn find_msg_by_uuid<'a>(conn: &PgConnection, msg_uuid: &Uuid) -> Option<Vec<Message>> {
    use schema::messages::dsl::*;
    use diesel::OptionalExtension;

    messages.filter(uuid.eq(msg_uuid))
        .limit(1)
        .load::<Message>(conn)
        .optional().unwrap()
}

I've made this optional as both finding a record and finding none are both valid outcomes in this scenario, so as a result this query might return a Vec with one Message or an empty Vec, so I always end up checking if the Vec is empty or not using code like this:

let extant_messages = find_msg_by_uuid(conn, message_uuid);

if !extant_messages.unwrap().is_empty() { ... }

and then if it isnt empty taking the first Message in the Vec as my found message using code like

let found_message = find_msg_by_uuid(conn, message_uuid).unwrap()[0];

I always take the first element in the Vec since the records are unique so the query will only ever return 1 or 0 records.

This feels kind of messy to me and seems to take too many steps, I feel as if there is a record for the query then it should return Option<Message> not Option<Vec<Message>> or None if there is no record matching the query.


回答1:


As mentioned in the comments, use first:

Attempts to load a single record. Returns Ok(record) if found, and Err(NotFound) if no results are returned. If the query truly is optional, you can call .optional() on the result of this to get a Result<Option<U>>.

fn find_msg_by_uuid<'a>(conn: &PgConnection, msg_uuid: &Uuid) -> Option<Message> {
    use schema::messages::dsl::*;
    use diesel::OptionalExtension;

    messages
        .filter(uuid.eq(msg_uuid))
        .first(conn)
        .optional()
        .unwrap()
}


来源:https://stackoverflow.com/questions/46297867/how-do-i-get-an-optiont-instead-of-an-optionvect-from-a-diesel-query-which

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!