datazen_driver_api/sync/adapter.rs
1//! Sync adapter traits — the bridge between native types and the IR.
2
3use super::ir::{IRColumn, IRDefault, IRTable, IRType};
4use crate::{ColumnSchema, TableSchema, Value};
5use std::collections::HashMap;
6use std::sync::Arc;
7
8/// Converts native column metadata into IR (used for the *source* side of a sync).
9pub trait SyncSourceAdapter: Send + Sync {
10 /// Convert a single column to its IR representation.
11 ///
12 /// `native_full_type` carries the fully-qualified type string with precision
13 /// (e.g. PostgreSQL's `format_type()` output). When `None`, the adapter
14 /// falls back to `column.data_type`.
15 fn column_to_ir(&self, column: &ColumnSchema, native_full_type: Option<&str>) -> IRColumn;
16
17 /// Convert an entire `TableSchema` to an `IRTable`.
18 ///
19 /// The default implementation iterates over columns and delegates to
20 /// [`column_to_ir`](Self::column_to_ir).
21 fn table_to_ir(
22 &self,
23 schema: &TableSchema,
24 full_types: Option<&HashMap<String, String>>,
25 ) -> IRTable {
26 let pk_set: std::collections::HashSet<&str> =
27 schema.primary_keys.iter().map(|s| s.as_str()).collect();
28
29 let columns = schema
30 .columns
31 .iter()
32 .map(|c| {
33 let ft = full_types.and_then(|m| m.get(&c.name)).map(|s| s.as_str());
34 let mut ir = self.column_to_ir(c, ft);
35 if pk_set.contains(c.name.as_str()) {
36 ir.is_primary_key = true;
37 }
38 ir
39 })
40 .collect();
41
42 IRTable {
43 name: schema.table_name.clone(),
44 columns,
45 primary_keys: schema.primary_keys.clone(),
46 table_options: None,
47 }
48 }
49
50 /// Optional SQL returning `(col_name, full_type)` rows for precision-preserving sync.
51 /// Default: none (host uses `column.data_type` only).
52 fn full_column_types_query(&self, _table: &str) -> Option<String> {
53 None
54 }
55
56 /// Optional SQL returning a single row whose first column is a CREATE TABLE suffix
57 /// (e.g. ClickHouse `ENGINE = MergeTree\nORDER BY (id)`).
58 /// Default: none.
59 fn table_options_query(&self, _table: &str) -> Option<String> {
60 None
61 }
62}
63
64/// Renders IR back into native DDL fragments (used for the *target* side of a sync).
65pub trait SyncTargetAdapter: Send + Sync {
66 /// Render an `IRType` as a native DDL type string.
67 fn ir_type_to_native(&self, ir_type: &IRType) -> String;
68
69 /// Render an `IRDefault` as the content of a `DEFAULT` clause.
70 /// Return `None` to omit the clause entirely (e.g. for auto-increment columns
71 /// whose default is handled by the database engine).
72 fn format_default(&self, default: &IRDefault) -> Option<String>;
73
74 /// Format a runtime `Value` as a SQL literal suitable for INSERT statements.
75 fn format_literal(&self, value: &Option<Value>, ir_type: &IRType) -> String;
76
77 fn quote_char(&self) -> char {
78 '"'
79 }
80
81 fn quote_ident(&self, name: &str) -> String {
82 let q = self.quote_char();
83 if q == '`' {
84 format!("`{}`", name.replace('`', "``"))
85 } else {
86 format!("\"{}\"", name.replace('"', "\"\""))
87 }
88 }
89
90 /// Whether the target database supports inline PRIMARY KEY constraints
91 /// in CREATE TABLE. OLAP engines typically do not.
92 fn supports_primary_key(&self) -> bool {
93 true
94 }
95
96 /// Keyword appended after the column type for auto-increment columns.
97 /// Return `None` if the engine uses a different mechanism (e.g. PG SERIAL/IDENTITY).
98 fn auto_increment_keyword(&self) -> Option<&str> {
99 None
100 }
101
102 /// Appended after `CREATE TABLE (...)` closing paren. Default: use `ir_table.table_options` if present.
103 fn create_table_suffix(&self, ir_table: &IRTable) -> Option<String> {
104 ir_table.table_options.clone()
105 }
106
107 /// Optional value transform before formatting literals (identity by default).
108 fn transform_value(&self, value: &Option<Value>, _ir_type: &IRType) -> Option<Value> {
109 value.clone()
110 }
111}
112
113/// Type-erased sync adapter pair produced by driver crates.
114pub struct BoxedSyncAdapter {
115 pub source: Arc<dyn SyncSourceAdapter>,
116 pub target: Arc<dyn SyncTargetAdapter>,
117}
118
119impl BoxedSyncAdapter {
120 pub fn both<T>(adapter: T) -> Self
121 where
122 T: SyncSourceAdapter + SyncTargetAdapter + 'static,
123 {
124 let arc = Arc::new(adapter);
125 Self {
126 source: arc.clone(),
127 target: arc,
128 }
129 }
130}
131
132/// Inventory factory discovered by the host sync registry.
133pub struct SyncAdapterFactory {
134 pub db_types: &'static [&'static str],
135 pub create: fn() -> BoxedSyncAdapter,
136}
137
138inventory::collect!(SyncAdapterFactory);
139
140/// Helper: submit a sync adapter factory at link time.
141///
142/// ```ignore
143/// datazen_driver_api::register_sync_adapter!(SyncAdapterFactory {
144/// db_types: &["postgresql"],
145/// create: || BoxedSyncAdapter::both(PgSyncAdapter),
146/// });
147/// ```
148#[macro_export]
149macro_rules! register_sync_adapter {
150 ($factory:expr) => {
151 $crate::inventory::submit! { $factory }
152 };
153}