Merge pull request #568 from runfalk/master

Added information on how to use Vec<T> with Client::query_raw
This commit is contained in:
Steven Fackler 2020-02-09 17:13:42 +00:00 committed by GitHub
commit 14252af4c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 0 deletions

View File

@ -255,6 +255,33 @@ impl Client {
/// # Ok(())
/// # }
/// ```
///
/// If you have a type like `Vec<T>` where `T: ToSql` Rust will not know how to use it as params. To get around
/// this the type must explicitly be converted to `&dyn ToSql`.
///
/// ```no_run
/// # use postgres::{Client, NoTls};
/// use postgres::types::ToSql;
/// use fallible_iterator::FallibleIterator;
/// # fn main() -> Result<(), postgres::Error> {
/// # let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
///
/// let params: Vec<String> = vec![
/// "first param".into(),
/// "second param".into(),
/// ];
/// let mut it = client.query_raw(
/// "SELECT foo FROM bar WHERE biz = $1 AND baz = $2",
/// params.iter().map(|p| p as &dyn ToSql),
/// )?;
///
/// while let Some(row) = it.next()? {
/// let foo: i32 = row.get("foo");
/// println!("foo: {}", foo);
/// }
/// # Ok(())
/// # }
/// ```
pub fn query_raw<'a, T, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error>
where
T: ?Sized + ToStatement,

View File

@ -313,6 +313,34 @@ impl Client {
/// Panics if the number of parameters provided does not match the number expected.
///
/// [`query`]: #method.query
///
/// # Examples
///
/// If you have a type like `Vec<T>` where `T: ToSql` Rust will not know how to use it as params. To get around
/// this the type must explicitly be converted to `&dyn ToSql`.
///
/// ```no_run
/// # async fn async_main(client: &tokio_postgres::Client) -> Result<(), tokio_postgres::Error> {
/// use tokio_postgres::types::ToSql;
/// use futures::{pin_mut, StreamExt};
///
/// let params: Vec<String> = vec![
/// "first param".into(),
/// "second param".into(),
/// ];
/// let mut it = client.query_raw(
/// "SELECT foo FROM bar WHERE biz = $1 AND baz = $2",
/// params.iter().map(|p| p as &dyn ToSql),
/// ).await?;
///
/// pin_mut!(it);
/// while let Some(row) = it.next().await.transpose()? {
/// let foo: i32 = row.get("foo");
/// println!("foo: {}", foo);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn query_raw<'a, T, I>(&self, statement: &T, params: I) -> Result<RowStream, Error>
where
T: ?Sized + ToStatement,