use crate::connection::ConnectionRef;
use crate::types::{BorrowToSql, ToSql, Type};
use crate::{CopyInWriter, CopyOutReader, Error};
use fallible_iterator::FallibleIterator;
use futures_util::StreamExt;
use std::pin::Pin;
#[doc(inline)]
pub use tokio_postgres::binary_copy::BinaryCopyOutRow;
use tokio_postgres::binary_copy::{self, BinaryCopyOutStream};
pub struct BinaryCopyInWriter<'a> {
connection: ConnectionRef<'a>,
sink: Pin<Box<binary_copy::BinaryCopyInWriter>>,
}
impl<'a> BinaryCopyInWriter<'a> {
pub fn new(writer: CopyInWriter<'a>, types: &[Type]) -> BinaryCopyInWriter<'a> {
let stream = writer
.sink
.into_unpinned()
.expect("writer has already been written to");
BinaryCopyInWriter {
connection: writer.connection,
sink: Box::pin(binary_copy::BinaryCopyInWriter::new(stream, types)),
}
}
pub fn write(&mut self, values: &[&(dyn ToSql + Sync)]) -> Result<(), Error> {
self.connection.block_on(self.sink.as_mut().write(values))
}
pub fn write_raw<P, I>(&mut self, values: I) -> Result<(), Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
self.connection
.block_on(self.sink.as_mut().write_raw(values))
}
pub fn finish(mut self) -> Result<u64, Error> {
self.connection.block_on(self.sink.as_mut().finish())
}
}
pub struct BinaryCopyOutIter<'a> {
connection: ConnectionRef<'a>,
stream: Pin<Box<BinaryCopyOutStream>>,
}
impl<'a> BinaryCopyOutIter<'a> {
pub fn new(reader: CopyOutReader<'a>, types: &[Type]) -> BinaryCopyOutIter<'a> {
let stream = reader
.stream
.into_unpinned()
.expect("reader has already been read from");
BinaryCopyOutIter {
connection: reader.connection,
stream: Box::pin(BinaryCopyOutStream::new(stream, types)),
}
}
}
impl FallibleIterator for BinaryCopyOutIter<'_> {
type Item = BinaryCopyOutRow;
type Error = Error;
fn next(&mut self) -> Result<Option<BinaryCopyOutRow>, Error> {
let stream = &mut self.stream;
self.connection
.block_on(async { stream.next().await.transpose() })
}
}