13

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
dch
  • 133
  • 1
  • 4
  • 3
    you probably want to use [first](http://docs.diesel.rs/diesel/prelude/trait.FirstDsl.html#method.first) – user25064 Sep 19 '17 at 11:33

1 Answers1

18

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()
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366