mirror of
https://github.com/launchbadge/sqlx.git
synced 2025-12-29 21:00:54 +00:00
feat(core): add fetch_optional and fetch_one
This commit is contained in:
parent
06bad624de
commit
b837a3ca25
@ -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;
|
||||
}
|
||||
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@ -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.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user