use super::ir::{IRColumn, IRDefault, IRTable, IRType};
use crate::{ColumnSchema, TableSchema, Value};
use std::collections::HashMap;
use std::sync::Arc;
pub trait SyncSourceAdapter: Send + Sync {
fn column_to_ir(&self, column: &ColumnSchema, native_full_type: Option<&str>) -> IRColumn;
fn table_to_ir(
&self,
schema: &TableSchema,
full_types: Option<&HashMap<String, String>>,
) -> IRTable {
let pk_set: std::collections::HashSet<&str> =
schema.primary_keys.iter().map(|s| s.as_str()).collect();
let columns = schema
.columns
.iter()
.map(|c| {
let ft = full_types.and_then(|m| m.get(&c.name)).map(|s| s.as_str());
let mut ir = self.column_to_ir(c, ft);
if pk_set.contains(c.name.as_str()) {
ir.is_primary_key = true;
}
ir
})
.collect();
IRTable {
name: schema.table_name.clone(),
columns,
primary_keys: schema.primary_keys.clone(),
table_options: None,
}
}
fn full_column_types_query(&self, _table: &str) -> Option<String> {
None
}
fn table_options_query(&self, _table: &str) -> Option<String> {
None
}
}
pub trait SyncTargetAdapter: Send + Sync {
fn ir_type_to_native(&self, ir_type: &IRType) -> String;
fn format_default(&self, default: &IRDefault) -> Option<String>;
fn format_literal(&self, value: &Option<Value>, ir_type: &IRType) -> String;
fn quote_char(&self) -> char {
'"'
}
fn quote_ident(&self, name: &str) -> String {
let q = self.quote_char();
if q == '`' {
format!("`{}`", name.replace('`', "``"))
} else {
format!("\"{}\"", name.replace('"', "\"\""))
}
}
fn supports_primary_key(&self) -> bool {
true
}
fn auto_increment_keyword(&self) -> Option<&str> {
None
}
fn create_table_suffix(&self, ir_table: &IRTable) -> Option<String> {
ir_table.table_options.clone()
}
fn transform_value(&self, value: &Option<Value>, _ir_type: &IRType) -> Option<Value> {
value.clone()
}
}
pub struct BoxedSyncAdapter {
pub source: Arc<dyn SyncSourceAdapter>,
pub target: Arc<dyn SyncTargetAdapter>,
}
impl BoxedSyncAdapter {
pub fn both<T>(adapter: T) -> Self
where
T: SyncSourceAdapter + SyncTargetAdapter + 'static,
{
let arc = Arc::new(adapter);
Self {
source: arc.clone(),
target: arc,
}
}
}
pub struct SyncAdapterFactory {
pub db_types: &'static [&'static str],
pub create: fn() -> BoxedSyncAdapter,
}
inventory::collect!(SyncAdapterFactory);
#[macro_export]
macro_rules! register_sync_adapter {
($factory:expr) => {
$crate::inventory::submit! { $factory }
};
}