Skip to main content

connectorx/
typesystem.rs

1//! This module defines traits that required to define a typesystem.
2//!
3//! A typesystem is an enum that describes what types can be produced by a source and accepted by a destination.
4//! A typesystem also needs to implement [`TypeAssoc`] to associate the enum variants to the physical representation
5//! of the types in the typesystem.
6
7use crate::destinations::{Consume, Destination, DestinationPartition};
8use crate::errors::{ConnectorXError, Result as CXResult};
9use crate::sources::{PartitionParser, Produce, Source, SourcePartition};
10
11#[doc(hidden)]
12/// `TypeSystem` describes all the types a source or destination support
13/// using enum variants.
14/// The variant can be used to type check with a static type `T` through the `check` method.
15pub trait TypeSystem: Copy + Clone + Send + Sync {
16    /// Check whether T is the same type as defined by self.
17    fn check<T: TypeAssoc<Self>>(self) -> CXResult<()> {
18        T::check(self)
19    }
20}
21
22#[doc(hidden)]
23/// Associate a static type to a TypeSystem
24pub trait TypeAssoc<TS: TypeSystem> {
25    fn check(ts: TS) -> CXResult<()>;
26}
27
28#[doc(hidden)]
29/// Realize means that a TypeSystem can realize a parameterized func F, based on its current variants.
30pub trait Realize<F>
31where
32    F: ParameterizedFunc,
33{
34    /// realize a parameterized function with the type that self currently is.
35    fn realize(self) -> CXResult<F::Function>;
36}
37
38#[doc(hidden)]
39/// A ParameterizedFunc refers to a function that is parameterized on a type T,
40/// where type T will be dynaically determined by the variant of a TypeSystem.
41/// An example is the `transmit<S,W,T>` function. When piping values from a source
42/// to the destination, its type `T` is determined by the schema at the runtime.
43pub trait ParameterizedFunc {
44    type Function;
45    fn realize<T>() -> Self::Function
46    where
47        Self: ParameterizedOn<T>,
48    {
49        Self::parameterize()
50    }
51}
52
53#[doc(hidden)]
54/// `ParameterizedOn` indicates a parameterized function `Self`
55/// is parameterized on type `T`
56pub trait ParameterizedOn<T>: ParameterizedFunc {
57    fn parameterize() -> Self::Function;
58}
59
60/// Defines a rule to convert a type `T` to a type `U`.
61pub trait TypeConversion<T, U> {
62    /// Convert `val` from `T` to `U`.
63    fn convert(val: T) -> U;
64}
65
66/// Transport asks the source to produce a value, do type conversion and then write
67/// the value to a destination. Do not manually implement this trait for types.
68/// Use [`impl_transport!`](crate::impl_transport) to create a struct that implements this trait instead.
69pub trait Transport {
70    /// Type system of the source.
71    type TSS: TypeSystem;
72    /// Type system of the destination.
73    type TSD: TypeSystem;
74    /// Source this transport reads from.
75    type S: Source;
76    /// Destination this transport writes to.
77    type D: Destination;
78    /// Error type, convertible from the source, destination and ConnectorX errors.
79    type Error: From<ConnectorXError>
80        + From<<Self::S as Source>::Error>
81        + From<<Self::D as Destination>::Error>
82        + Send
83        + std::fmt::Debug;
84
85    /// convert_typesystem convert the source type system TSS to the destination
86    /// type system TSD.
87    fn convert_typesystem(ts: Self::TSS) -> CXResult<Self::TSD>;
88
89    /// convert_type convert the type T1 associated with the source type system
90    /// TSS to a type T2 which is associated with the destination type system TSD.
91    fn convert_type<T1, T2>(val: T1) -> T2
92    where
93        Self: TypeConversion<T1, T2>,
94    {
95        <Self as TypeConversion<T1, T2>>::convert(val)
96    }
97
98    /// `process` will ask source to produce a value with type T1, based on TSS, and then do
99    /// type conversion using `convert_type` to get value with type T2, which is associated to
100    /// TSD. Finally, it will write the value with type T2 to the destination.
101    fn process<'s, 'd, 'r>(
102        ts1: Self::TSS,
103        ts2: Self::TSD,
104        src: &'r mut <<Self::S as Source>::Partition as SourcePartition>::Parser<'s>,
105        dst: &'r mut <Self::D as Destination>::Partition<'d>,
106    ) -> Result<(), Self::Error>
107    where
108        Self: 'd;
109
110    /// Return a function pointer that moves one value of source type `ts1` into the
111    /// destination as type `ts2`, or an error if no conversion rule exists.
112    #[allow(clippy::type_complexity)]
113    fn processor<'s, 'd>(
114        ts1: Self::TSS,
115        ts2: Self::TSD,
116    ) -> CXResult<
117        fn(
118            src: &mut <<Self::S as Source>::Partition as SourcePartition>::Parser<'s>,
119            dst: &mut <Self::D as Destination>::Partition<'d>,
120        ) -> Result<(), Self::Error>,
121    >
122    where
123        Self: 'd;
124}
125
126#[doc(hidden)]
127pub fn process<'s, 'd, 'r, T1, T2, TP, S, D, ES, ED, ET>(
128    src: &'r mut <<S as Source>::Partition as SourcePartition>::Parser<'s>,
129    dst: &'r mut <D as Destination>::Partition<'d>,
130) -> Result<(), ET>
131where
132    T1: TypeAssoc<<S as Source>::TypeSystem>,
133    S: Source<Error = ES>,
134    <S as Source>::Partition: SourcePartition<Error = ES>,
135
136    <<S as Source>::Partition as SourcePartition>::Parser<'s>: Produce<'r, T1, Error = ES>,
137    ES: From<ConnectorXError> + Send,
138
139    T2: TypeAssoc<<D as Destination>::TypeSystem>,
140    D: Destination<Error = ED>,
141    <D as Destination>::Partition<'d>: Consume<T2, Error = ED>,
142    ED: From<ConnectorXError> + Send,
143
144    TP: TypeConversion<T1, T2>,
145    ET: From<ES> + From<ED>,
146{
147    let val: T1 = PartitionParser::parse(src)?;
148    let val: T2 = <TP as TypeConversion<T1, _>>::convert(val);
149    DestinationPartition::write(dst, val)?;
150    Ok(())
151}
152
153/// Test helpers for the mappings that `impl_typesystem!` generates.
154// Only the MySQL and Postgres type-system tests use these.
155#[cfg(all(test, any(feature = "src_mysql", feature = "src_postgres")))]
156pub(crate) mod testing {
157    use super::*;
158    use std::marker::PhantomData;
159
160    /// Realizes to the realized type's `TypeAssoc::check`.
161    pub(crate) struct Check<TS>(PhantomData<TS>);
162
163    impl<TS> ParameterizedFunc for Check<TS> {
164        type Function = fn(TS) -> CXResult<()>;
165    }
166
167    impl<TS: TypeSystem, T: TypeAssoc<TS>> ParameterizedOn<T> for Check<TS> {
168        fn parameterize() -> Self::Function {
169            T::check
170        }
171    }
172
173    /// Realizes to the realized type's name.
174    pub(crate) struct Name;
175
176    impl ParameterizedFunc for Name {
177        type Function = fn() -> &'static str;
178    }
179
180    impl<T> ParameterizedOn<T> for Name {
181        fn parameterize() -> Self::Function {
182            std::any::type_name::<T>
183        }
184    }
185
186    /// Asserts that the variant `ts(false)` realizes to the Rust type whose
187    /// name ends in `rust_type`, `ts(true)` to `Option` of it, and that each
188    /// realized type type-checks against its own variant and not the other.
189    pub(crate) fn assert_maps<TS>(ts: fn(bool) -> TS, rust_type: &str)
190    where
191        TS: TypeSystem + Realize<Check<TS>> + Realize<Name> + std::fmt::Debug,
192    {
193        let (non_null, nullable) = (ts(false), ts(true));
194
195        let name = Realize::<Name>::realize(non_null).unwrap()();
196        assert!(
197            name.ends_with(rust_type) && !name.starts_with("core::option::Option"),
198            "{non_null:?} realizes to {name}, expected {rust_type}"
199        );
200        let name = Realize::<Name>::realize(nullable).unwrap()();
201        assert!(
202            name.starts_with("core::option::Option<") && name.ends_with(&format!("{rust_type}>")),
203            "{nullable:?} realizes to {name}, expected Option<{rust_type}>"
204        );
205
206        for (ts, other) in [(non_null, nullable), (nullable, non_null)] {
207            let check = Realize::<Check<TS>>::realize(ts).unwrap();
208            assert!(check(ts).is_ok(), "{ts:?} does not check against itself");
209            let err = check(other).unwrap_err();
210            assert!(
211                matches!(err, crate::errors::ConnectorXError::TypeCheckFailed(..)),
212                "{err}"
213            );
214        }
215    }
216}