feat(core): add fetch_optional and fetch_one

This commit is contained in:
Ryan Leckey 2021-02-10 17:18:09 -08:00
parent 06bad624de
commit b837a3ca25
No known key found for this signature in database
GPG Key ID: F8AA68C235AB08C9
4 changed files with 42 additions and 5 deletions

View File

@ -12,4 +12,20 @@ where
where
'e: 'x,
'q: 'x;
fn fetch_all<'x, 'e, 'q>(
&'e mut self,
sql: &'q str,
) -> crate::Result<Vec<<Self::Database as Database<Rt>>::Row>>
where
'e: 'x,
'q: 'x;
fn fetch_optional<'x, 'e, 'q>(
&'e mut self,
sql: &'q str,
) -> crate::Result<Option<<Self::Database as Database<Rt>>::Row>>
where
'e: 'x,
'q: 'x;
}

View File

@ -12,11 +12,20 @@ pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Configuration { message: Cow<'static, str>, source: Option<Box<dyn StdError + Send + Sync>> },
Configuration {
message: Cow<'static, str>,
source: Option<Box<dyn StdError + Send + Sync>>,
},
Connect(Box<dyn DatabaseError>),
Network(std::io::Error),
/// Returned by `fetch_one` when no row was returned from the query.
///
/// Use `fetch_optional` to return `None` instead of signaling an error.
///
RowNotFound,
}
impl Error {
@ -56,6 +65,10 @@ impl Display for Error {
Self::Configuration { message, source: Some(source) } => {
write!(f, "{}: {}", message, source)
}
Self::RowNotFound => {
f.write_str("no row returned by a query required to return at least one row")
}
}
}
}

View File

@ -1,7 +1,7 @@
#[cfg(feature = "async")]
use futures_core::future::BoxFuture;
use futures_util::future::{self, BoxFuture, FutureExt, TryFutureExt};
use crate::{Database, Result, Runtime};
use crate::{Database, Error, Result, Runtime};
/// Describes a type that can execute SQL queries on a self-provided database connection.
///
@ -55,5 +55,13 @@ pub trait Executor<Rt: Runtime> {
where
Rt: crate::Async,
'e: 'x,
'q: 'x;
'q: 'x,
{
self.fetch_optional(sql)
.and_then(|maybe_row| match maybe_row {
Some(row) => future::ok(row),
None => future::err(Error::RowNotFound),
})
.boxed()
}
}

View File

@ -1,6 +1,6 @@
use crate::{Column, Database, Runtime};
pub trait Row {
pub trait Row: 'static + Send + Sync {
type Column: Column;
/// Returns `true` if the row contains only `NULL` values.