use crate::client::{InnerClient, Responses};
use crate::codec::FrontendMessage;
use crate::connection::RequestMessages;
use crate::prepare::get_type;
use crate::types::{BorrowToSql, IsNull};
use crate::{Column, Error, Portal, Row, Statement};
use bytes::{Bytes, BytesMut};
use fallible_iterator::FallibleIterator;
use futures_util::{ready, Stream};
use log::{debug, log_enabled, Level};
use pin_project_lite::pin_project;
use postgres_protocol::message::backend::{CommandCompleteBody, Message};
use postgres_protocol::message::frontend;
use postgres_types::Type;
use std::fmt;
use std::io;
use std::marker::PhantomPinned;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResultFormat {
Text,
Binary,
}
impl ResultFormat {
fn format_code(self) -> i16 {
match self {
ResultFormat::Text => 0,
ResultFormat::Binary => 1,
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum ResultFormats {
All(ResultFormat),
Columns(Arc<[ResultFormat]>),
}
impl ResultFormats {
pub(crate) fn get(&self, idx: usize) -> ResultFormat {
match self {
ResultFormats::All(format) => *format,
ResultFormats::Columns(formats) => formats[idx],
}
}
fn codes(&self) -> impl ExactSizeIterator<Item = i16> + '_ {
let formats: &[ResultFormat] = match self {
ResultFormats::All(format) => std::slice::from_ref(format),
ResultFormats::Columns(formats) => formats,
};
formats.iter().map(|format| format.format_code())
}
}
impl From<ResultFormat> for ResultFormats {
fn from(format: ResultFormat) -> Self {
ResultFormats::All(format)
}
}
struct BorrowToSqlParamsDebug<'a, T>(&'a [T]);
impl<T> fmt::Debug for BorrowToSqlParamsDebug<'_, T>
where
T: BorrowToSql,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.0.iter().map(|x| x.borrow_to_sql()))
.finish()
}
}
pub async fn query<P, I>(
client: &InnerClient,
statement: Statement,
params: I,
) -> Result<RowStream, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
query_with_format(client, statement, params, ResultFormat::Binary).await
}
pub async fn query_with_format<P, I>(
client: &InnerClient,
statement: Statement,
params: I,
result_format: ResultFormat,
) -> Result<RowStream, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
query_with_formats(client, statement, params, result_format.into()).await
}
pub async fn query_with_column_formats<P, I>(
client: &InnerClient,
statement: Statement,
params: I,
formats: &[ResultFormat],
) -> Result<RowStream, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
let result_formats = column_formats(&statement, formats)?;
query_with_formats(client, statement, params, result_formats).await
}
fn column_formats(statement: &Statement, formats: &[ResultFormat]) -> Result<ResultFormats, Error> {
let columns = statement.columns().len();
if formats.len() != columns {
return Err(Error::encode(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"{} result formats given for a statement of {columns} columns",
formats.len()
),
)));
}
Ok(ResultFormats::Columns(formats.into()))
}
async fn query_with_formats<P, I>(
client: &InnerClient,
statement: Statement,
params: I,
result_formats: ResultFormats,
) -> Result<RowStream, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
let buf = if log_enabled!(Level::Debug) {
let params = params.into_iter().collect::<Vec<_>>();
debug!(
"executing statement {} with parameters: {:?}",
statement.name(),
BorrowToSqlParamsDebug(params.as_slice()),
);
encode_with_formats(client, &statement, params, &result_formats)?
} else {
encode_with_formats(client, &statement, params, &result_formats)?
};
let responses = start(client, buf).await?;
Ok(RowStream {
statement,
responses,
result_formats,
rows_affected: None,
command_tag: None,
_p: PhantomPinned,
})
}
pub async fn query_typed<P, I>(
client: &Arc<InnerClient>,
query: &str,
params: I,
) -> Result<RowStream, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = (P, Type)>,
{
let buf = {
let params = params.into_iter().collect::<Vec<_>>();
let param_oids = params.iter().map(|(_, t)| t.oid()).collect::<Vec<_>>();
client.with_buf(|buf| {
frontend::parse("", query, param_oids, buf).map_err(Error::parse)?;
encode_bind_raw("", params, "", &ResultFormat::Binary.into(), buf)?;
frontend::describe(b'S', "", buf).map_err(Error::encode)?;
frontend::execute("", 0, buf).map_err(Error::encode)?;
frontend::sync(buf);
Ok(buf.split().freeze())
})?
};
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
loop {
match responses.next().await? {
Message::ParseComplete | Message::BindComplete | Message::ParameterDescription(_) => {}
Message::NoData => {
return Ok(RowStream {
statement: Statement::unnamed(vec![], vec![]),
responses,
result_formats: ResultFormat::Binary.into(),
rows_affected: None,
command_tag: None,
_p: PhantomPinned,
});
}
Message::RowDescription(row_description) => {
let mut columns: Vec<Column> = vec![];
let mut it = row_description.fields();
while let Some(field) = it.next().map_err(Error::parse)? {
let type_ = get_type(client, field.type_oid()).await?;
let column = Column {
name: field.name().to_string(),
table_oid: Some(field.table_oid()).filter(|n| *n != 0),
column_id: Some(field.column_id()).filter(|n| *n != 0),
r#type: type_,
};
columns.push(column);
}
return Ok(RowStream {
statement: Statement::unnamed(vec![], columns),
responses,
result_formats: ResultFormat::Binary.into(),
rows_affected: None,
command_tag: None,
_p: PhantomPinned,
});
}
_ => return Err(Error::unexpected_message()),
}
}
}
pub async fn query_portal(
client: &InnerClient,
portal: &Portal,
max_rows: i32,
) -> Result<RowStream, Error> {
let buf = client.with_buf(|buf| {
frontend::execute(portal.name(), max_rows, buf).map_err(Error::encode)?;
frontend::sync(buf);
Ok(buf.split().freeze())
})?;
let responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
Ok(RowStream {
statement: portal.statement().clone(),
responses,
result_formats: ResultFormat::Binary.into(),
rows_affected: None,
command_tag: None,
_p: PhantomPinned,
})
}
pub fn extract_row_affected(body: &CommandCompleteBody) -> Result<u64, Error> {
let rows = body
.tag()
.map_err(Error::parse)?
.rsplit(' ')
.next()
.unwrap()
.parse()
.unwrap_or(0);
Ok(rows)
}
pub async fn execute<P, I>(
client: &InnerClient,
statement: Statement,
params: I,
) -> Result<u64, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
let buf = if log_enabled!(Level::Debug) {
let params = params.into_iter().collect::<Vec<_>>();
debug!(
"executing statement {} with parameters: {:?}",
statement.name(),
BorrowToSqlParamsDebug(params.as_slice()),
);
encode(client, &statement, params, ResultFormat::Binary)?
} else {
encode(client, &statement, params, ResultFormat::Binary)?
};
let mut responses = start(client, buf).await?;
let mut rows = 0;
loop {
match responses.next().await? {
Message::DataRow(_) => {}
Message::CommandComplete(body) => {
rows = extract_row_affected(&body)?;
}
Message::EmptyQueryResponse => rows = 0,
Message::ReadyForQuery(_) => return Ok(rows),
_ => return Err(Error::unexpected_message()),
}
}
}
async fn start(client: &InnerClient, buf: Bytes) -> Result<Responses, Error> {
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
match responses.next().await? {
Message::BindComplete => {}
_ => return Err(Error::unexpected_message()),
}
Ok(responses)
}
pub fn encode<P, I>(
client: &InnerClient,
statement: &Statement,
params: I,
result_format: ResultFormat,
) -> Result<Bytes, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
encode_with_formats(client, statement, params, &result_format.into())
}
fn encode_with_formats<P, I>(
client: &InnerClient,
statement: &Statement,
params: I,
result_formats: &ResultFormats,
) -> Result<Bytes, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
client.with_buf(|buf| {
encode_bind_with_formats(statement, params, "", result_formats, buf)?;
frontend::execute("", 0, buf).map_err(Error::encode)?;
frontend::sync(buf);
Ok(buf.split().freeze())
})
}
pub fn encode_bind<P, I>(
statement: &Statement,
params: I,
portal: &str,
result_format: ResultFormat,
buf: &mut BytesMut,
) -> Result<(), Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
encode_bind_with_formats(statement, params, portal, &result_format.into(), buf)
}
fn encode_bind_with_formats<P, I>(
statement: &Statement,
params: I,
portal: &str,
result_formats: &ResultFormats,
buf: &mut BytesMut,
) -> Result<(), Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
let params = params.into_iter();
if params.len() != statement.params().len() {
return Err(Error::parameters(params.len(), statement.params().len()));
}
encode_bind_raw(
statement.name(),
params.zip(statement.params().iter().cloned()),
portal,
result_formats,
buf,
)
}
fn encode_bind_raw<P, I>(
statement_name: &str,
params: I,
portal: &str,
result_formats: &ResultFormats,
buf: &mut BytesMut,
) -> Result<(), Error>
where
P: BorrowToSql,
I: IntoIterator<Item = (P, Type)>,
I::IntoIter: ExactSizeIterator,
{
let (param_formats, params): (Vec<_>, Vec<_>) = params
.into_iter()
.map(|(p, ty)| (p.borrow_to_sql().encode_format(&ty) as i16, (p, ty)))
.unzip();
let mut error_idx = 0;
let r = frontend::bind(
portal,
statement_name,
param_formats,
params.into_iter().enumerate(),
|(idx, (param, ty)), buf| match param.borrow_to_sql().to_sql_checked(&ty, buf) {
Ok(IsNull::No) => Ok(postgres_protocol::IsNull::No),
Ok(IsNull::Yes) => Ok(postgres_protocol::IsNull::Yes),
Err(e) => {
error_idx = idx;
Err(e)
}
},
result_formats.codes(),
buf,
);
match r {
Ok(()) => Ok(()),
Err(frontend::BindError::Conversion(e)) => Err(Error::to_sql(e, error_idx)),
Err(frontend::BindError::Serialization(e)) => Err(Error::encode(e)),
}
}
pin_project! {
pub struct RowStream {
statement: Statement,
responses: Responses,
result_formats: ResultFormats,
rows_affected: Option<u64>,
command_tag: Option<String>,
#[pin]
_p: PhantomPinned,
}
}
impl Stream for RowStream {
type Item = Result<Row, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
loop {
match ready!(this.responses.poll_next(cx)?) {
Message::DataRow(body) => {
return Poll::Ready(Some(Ok(Row::new(
this.statement.clone(),
this.result_formats.clone(),
body,
)?)))
}
Message::CommandComplete(body) => {
*this.rows_affected = Some(extract_row_affected(&body)?);
*this.command_tag = extract_command_tag(&body).ok();
}
Message::EmptyQueryResponse | Message::PortalSuspended => {}
Message::ReadyForQuery(_) => return Poll::Ready(None),
_ => return Poll::Ready(Some(Err(Error::unexpected_message()))),
}
}
}
}
fn extract_command_tag(body: &CommandCompleteBody) -> Result<String, Error> {
let tag = body.tag().map_err(Error::parse)?;
Ok(tag
.split(' ')
.take_while(|part| part.parse::<u64>().is_err())
.collect::<Vec<_>>()
.join(" "))
}
impl RowStream {
pub fn columns(&self) -> &[Column] {
self.statement.columns()
}
pub fn rows_affected(&self) -> Option<u64> {
self.rows_affected
}
pub fn command_tag(&self) -> Option<&str> {
self.command_tag.as_deref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use postgres_protocol::message::backend::Message;
fn column(name: &str, ty: Type) -> Column {
Column {
name: name.to_string(),
table_oid: None,
column_id: None,
r#type: ty,
}
}
fn statement() -> Statement {
Statement::unnamed(
vec![Type::INT4],
vec![
column("a", Type::INT4),
column("b", Type::INTERVAL),
column("c", Type::TEXT),
],
)
}
fn result_codes(bind: &[u8]) -> Vec<i16> {
let mut bind = bind;
assert_eq!(bind[0], b'B');
bind = &bind[5..];
for _ in 0..2 {
let end = bind.iter().position(|b| *b == 0).unwrap();
bind = &bind[end + 1..];
}
let read_i16 = |b: &mut &[u8]| {
let v = i16::from_be_bytes([b[0], b[1]]);
*b = &b[2..];
v
};
let param_formats = read_i16(&mut bind);
bind = &bind[2 * param_formats as usize..];
let params = read_i16(&mut bind);
for _ in 0..params {
let len = i32::from_be_bytes([bind[0], bind[1], bind[2], bind[3]]);
bind = &bind[4 + len.max(0) as usize..];
}
let count = read_i16(&mut bind);
let codes = (0..count).map(|_| read_i16(&mut bind)).collect();
assert!(bind.is_empty(), "trailing bytes: {:?}", bind);
codes
}
fn bind(formats: &ResultFormats) -> BytesMut {
let mut buf = BytesMut::new();
encode_bind_with_formats(
&statement(),
[&7i32 as &dyn crate::types::ToSql],
"",
formats,
&mut buf,
)
.unwrap();
buf
}
#[test]
fn one_format_for_every_column_is_a_single_code() {
assert_eq!(result_codes(&bind(&ResultFormat::Binary.into())), [1]);
assert_eq!(result_codes(&bind(&ResultFormat::Text.into())), [0]);
}
#[test]
fn a_query_with_one_format_binds_as_it_did() {
let mut want = BytesMut::new();
encode_bind(
&statement(),
[&7i32 as &dyn crate::types::ToSql],
"",
ResultFormat::Binary,
&mut want,
)
.unwrap();
assert_eq!(bind(&ResultFormat::Binary.into()), want);
}
#[test]
fn per_column_formats_are_a_code_each() {
use ResultFormat::{Binary, Text};
let formats = column_formats(&statement(), &[Binary, Text, Binary]).unwrap();
assert_eq!(result_codes(&bind(&formats)), [1, 0, 1]);
assert_eq!(
(0..3).map(|i| formats.get(i)).collect::<Vec<_>>(),
[Binary, Text, Binary]
);
}
#[test]
fn per_column_formats_must_match_the_columns() {
use ResultFormat::{Binary, Text};
for formats in [
&[][..],
&[Binary, Text][..],
&[Binary, Text, Text, Binary][..],
] {
let err = column_formats(&statement(), formats).unwrap_err();
assert!(
err.to_string()
.contains("result formats given for a statement of 3 columns"),
"{}",
err
);
}
}
#[test]
fn a_row_tells_each_columns_format() {
use ResultFormat::{Binary, Text};
let mut msg = BytesMut::new();
let mut body = Vec::new();
body.extend_from_slice(&3i16.to_be_bytes());
body.extend_from_slice(&4i32.to_be_bytes());
body.extend_from_slice(&7i32.to_be_bytes());
body.extend_from_slice(&5i32.to_be_bytes());
body.extend_from_slice(b"1 day");
body.extend_from_slice(&(-1i32).to_be_bytes());
msg.extend_from_slice(b"D");
msg.extend_from_slice(&(4 + body.len() as i32).to_be_bytes());
msg.extend_from_slice(&body);
let Some(Message::DataRow(body)) = Message::parse(&mut msg).unwrap() else {
panic!("not a data row");
};
let formats = column_formats(&statement(), &[Binary, Text, Binary]).unwrap();
let row = Row::new(statement(), formats, body).unwrap();
assert_eq!(row.format(0), Binary);
assert_eq!(row.get::<_, i32>(0), 7);
assert_eq!(row.format(1), Text);
assert_eq!(row.col_buffer(1), Some(&b"1 day"[..]));
assert_eq!(row.col_buffer(2), None);
}
}