Replies: 1 comment 2 replies
-
More specialised variant, less code but maybe harder codegen: pub fn authors<'a, 'b, C: GenericClient>(
client: &'a C,
city: &'a &str,
) -> AuthorQuery<'a, C, Author, 1> {
AuthorQuery {
client,
params: [city],
mapper: |it| Author::from(it),
}
}
pub struct AuthorQuery<'a, C: GenericClient, T, const N: usize> {
client: &'a C,
params: [&'a (dyn tokio_postgres::types::ToSql + Sync); N],
mapper: fn(AuthorBorrowed) -> T,
}
impl<'a, C: GenericClient, T, const N: usize> AuthorQuery<'a, C, T, N> {
pub fn map<R>(self, mapper: fn(AuthorBorrowed) -> R) -> AuthorQuery<'a, C, R, N> {
AuthorQuery {
client: self.client,
params: self.params,
mapper,
}
}
pub fn extractor(row: &Row) -> AuthorBorrowed {
AuthorBorrowed { name: row.get(0) }
}
pub async fn stmt(&self) -> Result<Statement, Error> {
self.client
.prepare("SELECT name WHERE city = $1 FROM Author;")
.await
}
pub async fn one(self) -> Result<T, Error> {
let stmt = self.stmt().await?;
let row = self.client.query_one(&stmt, &self.params).await?;
Ok((self.mapper)(Self::extractor(&row)))
}
pub async fn list(self) -> Result<Vec<T>, Error> {
self.raw().await?.try_collect().await
}
pub async fn opt(self) -> Result<Option<T>, Error> {
let stmt = self.stmt().await?;
Ok(self
.client
.query_opt(&stmt, &self.params)
.await?
.map(|r| (self.mapper)(Self::extractor(&r))))
}
pub async fn raw(self) -> Result<impl Stream<Item = Result<T, Error>>, Error> {
let stmt = self.stmt().await?;
let stream = self
.client
.query_raw(&stmt, slice_iter(&self.params))
.await?
.map(move |res| res.map(|r| (self.mapper)(Self::extractor(&r))));
Ok(stream.into_stream())
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have an idea for another query API that brings back the default inference and supports a custom mapper with a bit more verbosity:
Using a mapper is more verbose but is more flexible, it can be used with lambda,
From
or evenTryFrom
:Unfortunately, I still can't reuse the same query structure, declaring the lifetime of the borrowed type in a generic way seems impossible :/
Beta Was this translation helpful? Give feedback.
All reactions