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.
As mentioned in the comments, use first
:
Attempts to load a single record. Returns
Ok(record)
if found, andErr(NotFound)
if no results are returned. If the query truly is optional, you can call.optional()
on the result of this to get aResult<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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With