Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 624
dch Avatar asked Sep 19 '17 10:09

dch


1 Answers

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()
}
like image 108
Shepmaster Avatar answered Oct 26 '22 15:10

Shepmaster