use std::marker::PhantomData;
use crate::conversion::FromRow;
use crate::error::Result;
use crate::handler::{CollectHandler, ExtendedHandler, ForEachHandler};
use super::Conn;
pub struct NamedPortal<'tx> {
pub(crate) name: String,
complete: bool,
_marker: PhantomData<&'tx ()>,
}
impl<'tx> NamedPortal<'tx> {
pub(crate) fn new(name: String) -> Self {
Self {
name,
complete: false,
_marker: PhantomData,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn is_complete(&self) -> bool {
self.complete
}
pub async fn exec<H: ExtendedHandler>(
&mut self,
conn: &mut Conn,
max_rows: u32,
handler: &mut H,
) -> Result<()> {
let has_more = conn.lowlevel_execute(&self.name, max_rows, handler).await?;
self.complete = !has_more;
Ok(())
}
pub async fn exec_collect<T: for<'a> FromRow<'a>>(
&mut self,
conn: &mut Conn,
max_rows: u32,
) -> Result<Vec<T>> {
let mut handler = CollectHandler::<T>::new();
self.exec(conn, max_rows, &mut handler).await?;
Ok(handler.into_rows())
}
pub async fn exec_foreach<T: for<'a> FromRow<'a>, F: FnMut(T) -> Result<()>>(
&mut self,
conn: &mut Conn,
max_rows: u32,
f: F,
) -> Result<()> {
let mut handler = ForEachHandler::<T, F>::new(f);
self.exec(conn, max_rows, &mut handler).await
}
pub async fn close(self, conn: &mut Conn) -> Result<()> {
conn.lowlevel_close_portal(&self.name).await?;
conn.lowlevel_sync().await
}
}