diff --git a/sqlx-core/src/from_row.rs b/sqlx-core/src/from_row.rs index 9c647d370a..a3bf6bd2a1 100644 --- a/sqlx-core/src/from_row.rs +++ b/sqlx-core/src/from_row.rs @@ -1,4 +1,7 @@ -use crate::{error::Error, row::Row}; +use crate::{ + error::{Error, UnexpectedNullError}, + row::Row, +}; /// A record that can be built from a row returned by the database. /// @@ -285,6 +288,22 @@ where } } +impl<'r, R, T> FromRow<'r, R> for Option +where + R: Row, + T: FromRow<'r, R>, +{ + fn from_row(row: &'r R) -> Result { + let value = T::from_row(row).map(Some); + if let Err(Error::ColumnDecode { source, .. }) = value.as_ref() { + if let Some(UnexpectedNullError) = source.downcast_ref() { + return Ok(None); + } + } + value + } +} + // implement FromRow for tuples of types that implement Decode // up to tuples of 9 values