use super::AnyDatabase;
use crate::datasource::DatasourceId;
use crate::error::BaseError;
use crate::table::TableDefinition;
use crate::tools::Tools;
use std::collections::BTreeMap;
pub async fn preflight_table_definitions_grouped_outcomes(
tools: &Tools,
definitions: &[&TableDefinition],
) -> BTreeMap<DatasourceId, Result<super::SchemaPreflightReport, BaseError>> {
let mut outcomes = BTreeMap::new();
for (source, group) in group_definitions(definitions) {
let outcome = match tools.database_named(&source) {
Ok(database) => {
DatabaseInitializer::from_any(database.clone())
.preflight_table_definitions(&group)
.await
}
Err(error) => Err(error),
};
outcomes.insert(source, outcome);
}
outcomes
}
pub async fn preflight_table_definitions_grouped(
tools: &Tools,
definitions: &[&TableDefinition],
) -> Result<BTreeMap<DatasourceId, super::SchemaPreflightReport>, BaseError> {
collect_outcomes(preflight_table_definitions_grouped_outcomes(tools, definitions).await)
}
pub async fn sync_table_definitions_grouped_outcomes(
tools: &Tools,
definitions: &[&TableDefinition],
) -> BTreeMap<DatasourceId, Result<super::SchemaSyncReport, BaseError>> {
let mut outcomes = BTreeMap::new();
for (source, group) in group_definitions(definitions) {
let outcome = match tools.database_named(&source) {
Ok(database) => {
DatabaseInitializer::from_any(database.clone())
.sync_table_definitions(&group)
.await
}
Err(error) => Err(error),
};
outcomes.insert(source, outcome);
}
outcomes
}
pub async fn sync_table_definitions_grouped(
tools: &Tools,
definitions: &[&TableDefinition],
) -> Result<BTreeMap<DatasourceId, super::SchemaSyncReport>, BaseError> {
collect_outcomes(sync_table_definitions_grouped_outcomes(tools, definitions).await)
}
fn collect_outcomes<T>(
outcomes: BTreeMap<DatasourceId, Result<T, BaseError>>,
) -> Result<BTreeMap<DatasourceId, T>, BaseError> {
let mut reports = BTreeMap::new();
for (source, outcome) in outcomes {
reports.insert(source, outcome?);
}
Ok(reports)
}
fn group_definitions<'a>(
definitions: &[&'a TableDefinition],
) -> BTreeMap<DatasourceId, Vec<&'a TableDefinition>> {
let mut groups: BTreeMap<DatasourceId, Vec<&'a TableDefinition>> = BTreeMap::new();
for definition in definitions {
groups
.entry(definition.datasource().clone())
.or_default()
.push(*definition);
}
groups
}
pub struct DatabaseInitializer {
db: AnyDatabase,
}
impl DatabaseInitializer {
#[cfg(feature = "mysql")]
pub fn new(db: yang_db::mysql::Database) -> Self {
Self::from_any(AnyDatabase::mysql(db))
}
#[cfg(feature = "postgres")]
pub fn new_postgres(db: yang_db::postgres::Database) -> Self {
Self::from_any(AnyDatabase::postgres(db))
}
pub fn from_any(db: AnyDatabase) -> Self {
Self { db }
}
pub(crate) fn db(&self) -> &AnyDatabase {
&self.db
}
}