use tokio_postgres::Client;
use crate::adapters::postgres::models::PostgresDestination;
use crate::loader::errors::LoaderError;
use crate::postgres_source::errors::PostgresError;
use crate::postgres_source::main::connect_postgres::connect_postgres;
use crate::postgres_source::models::Encryption;
use crate::project::main::postgres_address::postgres_address;
async fn connect_session(
destination: &PostgresDestination,
) -> Result<(Client, Encryption), LoaderError> {
let mut address = postgres_address(&destination.project, &destination.connection)
.map_err(LoaderError::Invalid)?;
if let Some(database) = &destination.database {
address.database = database;
}
Ok(connect_postgres(address).await?)
}
pub(crate) async fn session(
destination: &PostgresDestination,
) -> Result<tokio::sync::OwnedMutexGuard<Option<(Client, Encryption)>>, LoaderError> {
let mut held = destination.session.clone().lock_owned().await;
let closed = held.as_ref().map(|(client, _)| client.is_closed());
match (closed, destination.reconnects) {
(None, _) | (Some(true), true) => *held = Some(connect_session(destination).await?),
(Some(true), false) => {
return Err(LoaderError::Transient(
"the table's Postgres session closed, and its staging table with it; nothing it had not committed was written".to_owned(),
));
}
(Some(false), _) => {}
}
Ok(held)
}
pub(crate) fn query_error(error: tokio_postgres::Error) -> LoaderError {
LoaderError::Postgres(PostgresError::Query(error))
}