Skip to main content

datazen_driver_api/sync/
ir.rs

1//! Intermediate Representation for cross-database type mapping.
2//!
3//! Each database adapter converts native types to/from this IR,
4//! reducing N×N direct mappings to N adapters (O(N) instead of O(N²)).
5
6/// Database-agnostic column type.
7#[derive(Debug, Clone, PartialEq)]
8pub enum IRType {
9    Bool,
10
11    Int8,
12    Int16,
13    Int32,
14    Int64,
15
16    Float32,
17    Float64,
18
19    /// Exact numeric with optional precision/scale. `precision == 0` means unbounded.
20    Decimal {
21        precision: u8,
22        scale: u8,
23    },
24
25    Char {
26        length: u32,
27    },
28    /// `None` length means unbounded (equivalent to TEXT in most databases).
29    Varchar {
30        length: Option<u32>,
31    },
32    Text,
33
34    Binary {
35        length: Option<u32>,
36    },
37    Blob,
38
39    Date,
40    Time {
41        with_timezone: bool,
42    },
43    Timestamp {
44        with_timezone: bool,
45    },
46
47    Json,
48    Uuid,
49
50    Bit {
51        length: u32,
52    },
53
54    /// Fallback for types that have no standard IR mapping.
55    /// Target adapters should degrade this to TEXT.
56    Other(String),
57}
58
59/// Standardised default-value expression.
60#[derive(Debug, Clone, PartialEq)]
61pub enum IRDefault {
62    CurrentTimestamp,
63    /// A literal value stripped of any database-specific cast syntax.
64    Literal(String),
65    /// An expression that could not be normalised (e.g. sequence calls).
66    RawExpression(String),
67}
68
69/// One column in the intermediate schema.
70#[derive(Debug, Clone)]
71pub struct IRColumn {
72    pub name: String,
73    pub ir_type: IRType,
74    pub nullable: bool,
75    pub default_expr: Option<IRDefault>,
76    pub is_primary_key: bool,
77    pub is_auto_increment: bool,
78    pub comment: Option<String>,
79}
80
81/// A full table definition in intermediate form.
82#[derive(Debug, Clone)]
83pub struct IRTable {
84    pub name: String,
85    pub columns: Vec<IRColumn>,
86    pub primary_keys: Vec<String>,
87    /// Dialect-specific CREATE TABLE suffix (e.g. ClickHouse `ENGINE = MergeTree ORDER BY (...)`).
88    /// None means target adapter may apply its own default suffix.
89    pub table_options: Option<String>,
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    #[test]
97    fn ir_type_equality() {
98        assert_eq!(
99            IRType::Varchar { length: Some(255) },
100            IRType::Varchar { length: Some(255) },
101        );
102        assert_ne!(
103            IRType::Varchar { length: Some(255) },
104            IRType::Varchar { length: None },
105        );
106    }
107
108    #[test]
109    fn ir_default_equality() {
110        assert_eq!(IRDefault::CurrentTimestamp, IRDefault::CurrentTimestamp);
111        assert_ne!(
112            IRDefault::Literal("42".into()),
113            IRDefault::RawExpression("42".into()),
114        );
115    }
116}