2019-12-15 23:58:50 +00:00
|
|
|
use crate::Rt;
|
2019-11-30 16:04:59 +00:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2019-12-04 02:25:29 +00:00
|
|
|
use futures::SinkExt;
|
2019-11-30 16:04:59 +00:00
|
|
|
use std::io;
|
|
|
|
use std::io::Write;
|
|
|
|
use std::pin::Pin;
|
|
|
|
use tokio_postgres::{CopyInSink, Error};
|
|
|
|
|
|
|
|
/// The writer returned by the `copy_in` method.
|
|
|
|
///
|
|
|
|
/// The copy *must* be explicitly completed via the `finish` method. If it is not, the copy will be aborted.
|
|
|
|
pub struct CopyInWriter<'a> {
|
2019-12-15 23:58:50 +00:00
|
|
|
runtime: Rt<'a>,
|
2019-11-30 16:04:59 +00:00
|
|
|
sink: Pin<Box<CopyInSink<Bytes>>>,
|
|
|
|
buf: BytesMut,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> CopyInWriter<'a> {
|
2019-12-15 23:58:50 +00:00
|
|
|
pub(crate) fn new(runtime: Rt<'a>, sink: CopyInSink<Bytes>) -> CopyInWriter<'a> {
|
2019-11-30 16:04:59 +00:00
|
|
|
CopyInWriter {
|
2019-12-04 02:25:29 +00:00
|
|
|
runtime,
|
2019-11-30 16:04:59 +00:00
|
|
|
sink: Box::pin(sink),
|
|
|
|
buf: BytesMut::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Completes the copy, returning the number of rows written.
|
|
|
|
///
|
|
|
|
/// If this is not called, the copy will be aborted.
|
|
|
|
pub fn finish(mut self) -> Result<u64, Error> {
|
|
|
|
self.flush_inner()?;
|
2019-12-04 02:25:29 +00:00
|
|
|
self.runtime.block_on(self.sink.as_mut().finish())
|
2019-11-30 16:04:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn flush_inner(&mut self) -> Result<(), Error> {
|
|
|
|
if self.buf.is_empty() {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
2019-12-04 02:25:29 +00:00
|
|
|
self.runtime
|
|
|
|
.block_on(self.sink.as_mut().send(self.buf.split().freeze()))
|
2019-11-30 16:04:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Write for CopyInWriter<'_> {
|
|
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
|
|
if self.buf.len() > 4096 {
|
|
|
|
self.flush()?;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.buf.extend_from_slice(buf);
|
|
|
|
Ok(buf.len())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
|
|
self.flush_inner()
|
|
|
|
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
|
|
|
|
}
|
|
|
|
}
|