use super::ops;
use super::types::{to_sql_checked, BoxError, BytesMut, FromSql, IsNull, ToSql, Type};
use super::{Row, RowStream};
async fn connect() -> tokio_postgres::Client {
let uri = std::env::var("ENCORE_TEST_PG")
.unwrap_or_else(|_| "postgresql://postgres@127.0.0.1:5432/postgres".to_string());
let (client, connection) = tokio_postgres::connect(&uri, tokio_postgres::NoTls)
.await
.expect("connect to ENCORE_TEST_PG");
tokio::spawn(connection);
client
}
async fn row(
client: &tokio_postgres::Client,
query: &str,
params: &[&(dyn ToSql + Sync)],
) -> Result<Row, tokio_postgres::Error> {
let stream = client.query_raw(query, ops::params(params)).await?;
let mut rows = RowStream::new(stream);
let row = rows.next().await.expect("a row").expect("a readable row");
assert!(rows.next().await.is_none());
assert_eq!(rows.rows_affected(), Some(1));
Ok(row)
}
#[derive(Debug, PartialEq)]
struct Celsius(f64);
impl ToSql for Celsius {
fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result<IsNull, BoxError> {
self.0.to_sql(ty, out)
}
fn accepts(ty: &Type) -> bool {
<f64 as ToSql>::accepts(ty)
}
to_sql_checked!();
}
impl<'a> FromSql<'a> for Celsius {
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, BoxError> {
f64::from_sql(ty, raw).map(Celsius)
}
fn accepts(ty: &Type) -> bool {
<f64 as FromSql>::accepts(ty)
}
}
#[tokio::test]
#[ignore = "needs a PostgreSQL server; see the module docs"]
async fn parameters_and_columns_round_trip() {
let client = connect().await;
let row = row(
&client,
"SELECT $1::int4 AS n, $2::text AS name, $3::int8 AS missing, $4::int8[] AS ids, \
$5::float8 AS temp",
&[&7i32, &"ada", &None::<i64>, &vec![1i64, 2], &Celsius(21.5)],
)
.await
.expect("query");
assert_eq!(row.len(), 5);
assert!(!row.is_empty());
assert_eq!(row.columns()[0].name(), "n");
assert_eq!(row.get::<_, i32>(0), 7);
assert_eq!(row.get::<_, String>("name"), "ada");
assert_eq!(row.get::<_, &str>("name"), "ada");
assert_eq!(row.get::<_, Option<i64>>("missing"), None);
assert_eq!(row.get::<_, Vec<i64>>("ids"), vec![1, 2]);
assert_eq!(row.get::<_, Celsius>("temp"), Celsius(21.5));
assert!(row.try_get::<_, i32>("name").is_err());
assert!(row.try_get::<_, i64>("missing").is_err());
assert!(row.try_get::<_, i32>("nope").is_err());
assert!(row.try_get::<_, i32>(9).is_err());
assert!(row.try_get::<_, Celsius>("name").is_err());
}
#[tokio::test]
#[ignore = "needs a PostgreSQL server; see the module docs"]
async fn a_parameter_of_the_wrong_type_is_rejected() {
let client = connect().await;
assert!(row(&client, "SELECT $1::int4", &[&"seven"]).await.is_err());
assert!(row(&client, "SELECT $1::text", &[&Celsius(21.5)])
.await
.is_err());
assert!(row(&client, "SELECT $1::int4", &[&7i32]).await.is_ok());
}