trs_dataframe/dataframe/
join.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
use super::Key;
#[cfg(feature = "python")]
use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(feature = "utoipa")]
use utoipa::ToSchema;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "python", pyo3::pyclass)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct JoinById {
    pub keys: Vec<Key>,
}

impl JoinById {
    pub fn new(keys: Vec<Key>) -> Self {
        Self { keys }
    }
}

#[cfg(feature = "python")]
#[pymethods]
impl JoinById {
    #[new]
    pub fn init(keys: Vec<Key>) -> Self {
        Self { keys }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
/// Enum representing different strategies for combining or joining data structures.
pub enum JoinBy {
    /// Adds only non-existing columns to the existing structure.
    /// This is the default behavior.
    #[default]
    AddColumns,

    /// Replaces existing data with the new data.
    Replace,

    /// Extends the existing data by appending new elements.
    Extend,

    /// Performs a broadcast operation, replicating smaller data structures
    /// to match the size of larger ones.
    Broadcast,

    /// Computes the Cartesian product of the input structures,
    /// resulting in all possible combinations of elements.
    CartesianProduct,

    /// Joins two structures using a specific identifier or key.
    ///
    /// The behavior is determined by the provided `JoinById` variant.
    JoinById(JoinById),
}

#[cfg(feature = "python")]
pub mod python {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
    #[pyclass(eq, eq_int)]
    pub enum PythonJoinBy {
        /// Adds only non-existing columns to the existing structure.
        /// This is the default behavior.
        AddColumns,

        /// Replaces existing data with the new data.
        Replace,

        /// Extends the existing data by appending new elements.
        Extend,

        /// Performs a broadcast operation, replicating smaller data structures
        /// to match the size of larger ones.
        Broadcast,

        /// Computes the Cartesian product of the input structures,
        /// resulting in all possible combinations of elements.
        CartesianProduct,

        /// Joins two structures using a specific identifier or key.
        ///
        /// The behavior is determined by the provided `JoinById` variant.
        JoinById,
    }

    #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
    #[pyclass]
    pub struct PythonJoin {
        pub join_type: PythonJoinBy,
        pub join_by_id: Option<JoinById>,
    }

    impl TryFrom<PythonJoin> for JoinBy {
        type Error = crate::error::Error;
        fn try_from(py_join: PythonJoin) -> Result<Self, Self::Error> {
            Ok(match py_join.join_type {
                PythonJoinBy::AddColumns => JoinBy::AddColumns,
                PythonJoinBy::Replace => JoinBy::Replace,
                PythonJoinBy::Extend => JoinBy::Extend,
                PythonJoinBy::Broadcast => JoinBy::Broadcast,
                PythonJoinBy::CartesianProduct => JoinBy::CartesianProduct,
                PythonJoinBy::JoinById => {
                    let join_by_id = py_join
                        .join_by_id
                        .ok_or_else(|| crate::error::Error::MissingField("join_by_id".into()))?;
                    JoinBy::JoinById(join_by_id)
                }
            })
        }
    }

    impl TryFrom<JoinBy> for PythonJoin {
        type Error = crate::error::Error;
        fn try_from(py_join: JoinBy) -> Result<Self, Self::Error> {
            Ok(match py_join {
                JoinBy::AddColumns => PythonJoin {
                    join_type: PythonJoinBy::AddColumns,
                    join_by_id: None,
                },
                JoinBy::Replace => PythonJoin {
                    join_type: PythonJoinBy::Replace,
                    join_by_id: None,
                },
                JoinBy::Extend => PythonJoin {
                    join_type: PythonJoinBy::Extend,
                    join_by_id: None,
                },
                JoinBy::Broadcast => PythonJoin {
                    join_type: PythonJoinBy::Broadcast,
                    join_by_id: None,
                },
                JoinBy::CartesianProduct => PythonJoin {
                    join_type: PythonJoinBy::CartesianProduct,
                    join_by_id: None,
                },
                JoinBy::JoinById(join_by_id) => PythonJoin {
                    join_type: PythonJoinBy::JoinById,
                    join_by_id: Some(join_by_id),
                },
            })
        }
    }

    impl FromPyObject<'_> for JoinBy {
        fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> {
            let py_join: PythonJoin = ob.extract()?;
            Self::try_from(py_join).map_err(|e: crate::error::Error| {
                pyo3::exceptions::PyValueError::new_err(format!("{}", e))
            })
        }
    }

    impl<'py> IntoPyObject<'py> for JoinBy {
        type Error = PyErr;
        type Target = PythonJoin;
        type Output = Bound<'py, Self::Target>;
        fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
            let py_join: PythonJoin = self.try_into().map_err(|e: crate::error::Error| {
                pyo3::exceptions::PyValueError::new_err(format!("Error converting: {}", e))
            })?;
            py_join.into_pyobject(py)
        }
    }

    #[cfg(test)]
    mod test {
        use super::*;
        use rstest::*;

        #[rstest]
        #[case(JoinBy::AddColumns)]
        #[case(JoinBy::Replace)]
        #[case(JoinBy::Extend)]
        #[case(JoinBy::Broadcast)]
        #[case(JoinBy::CartesianProduct)]
        #[case(JoinBy::JoinById(JoinById::new(vec!["a".into()])))]
        fn test_join_by(#[case] join_by: JoinBy) {
            let py_join = PythonJoin::try_from(join_by.clone()).unwrap();
            let join_by2 = JoinBy::try_from(py_join).unwrap();
            assert_eq!(join_by, join_by2);
        }

        #[rstest]
        #[case(JoinBy::AddColumns)]
        #[case(JoinBy::Replace)]
        #[case(JoinBy::Extend)]
        #[case(JoinBy::Broadcast)]
        #[case(JoinBy::CartesianProduct)]
        #[case(JoinBy::JoinById(JoinById::new(vec!["a".into()])))]
        fn test_into_py(#[case] join_by: JoinBy) {
            pyo3::Python::with_gil(|py| {
                let py_join = join_by.clone().into_pyobject(py);
                assert!(py_join.is_ok());
                let py_join = py_join.unwrap();
                let from_py = JoinBy::extract_bound(&py_join);
                assert!(from_py.is_ok());
                let join_by2 = from_py.unwrap();
                assert_eq!(join_by, join_by2);
            });
        }
    }
}

#[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "python", pyclass)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct JoinRelation {
    pub join_type: JoinBy,
}

#[cfg(feature = "python")]
#[pymethods]
impl JoinRelation {
    #[new]
    pub fn init(join_type: JoinBy) -> Self {
        Self::new(join_type)
    }
}

impl JoinRelation {
    pub fn new(join_type: JoinBy) -> Self {
        Self { join_type }
    }

    pub fn broadcast() -> Self {
        Self {
            join_type: JoinBy::Broadcast,
        }
    }

    pub fn add_columns() -> Self {
        Self {
            join_type: JoinBy::AddColumns,
        }
    }

    pub fn replace() -> Self {
        Self {
            join_type: JoinBy::Replace,
        }
    }

    pub fn extend() -> Self {
        Self {
            join_type: JoinBy::Extend,
        }
    }

    pub fn cartesian_product() -> Self {
        Self {
            join_type: JoinBy::CartesianProduct,
        }
    }

    pub fn join_by_id(keys: Vec<Key>) -> Self {
        Self {
            join_type: JoinBy::JoinById(JoinById::new(keys)),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use rstest::*;

    #[cfg(feature = "utoipa")]
    #[rstest]
    fn test_join_relation_to_schema() {
        let _name = JoinRelation::name();
        let mut schemas = vec![];

        JoinRelation::schemas(&mut schemas);

        assert!(!schemas.is_empty());
    }

    #[rstest]
    #[case(JoinBy::AddColumns)]
    #[case(JoinBy::Replace)]
    #[case(JoinBy::Extend)]
    #[case(JoinBy::Broadcast)]
    #[case(JoinBy::CartesianProduct)]
    fn test_join_relation_new(#[case] join_type: JoinBy) {
        let join_relation = JoinRelation::new(join_type.clone());
        assert_eq!(join_relation.join_type, join_type);
        let serde = serde_json::to_string(&join_relation).expect("BUG: Cannot serialize");
        let deserialized: JoinRelation =
            serde_json::from_str(&serde).expect("BUG: cannot deserialize");
        assert_eq!(deserialized, join_relation);
    }

    #[rstest]
    #[case(JoinBy::AddColumns, JoinRelation::add_columns())]
    #[case(JoinBy::Replace, JoinRelation::replace())]
    #[case(JoinBy::Extend, JoinRelation::extend())]
    #[case(JoinBy::Broadcast, JoinRelation::broadcast())]
    #[case(JoinBy::CartesianProduct, JoinRelation::cartesian_product())]
    #[case(JoinBy::JoinById(JoinById::new(vec!["a".into()])), JoinRelation::join_by_id(vec!["a".into()]))]
    fn test_join_releation(#[case] join_type: JoinBy, #[case] jt: JoinRelation) {
        let join_relation = JoinRelation::new(join_type.clone());
        assert_eq!(join_relation.join_type, join_type);
        assert_eq!(join_relation, jt);
        let serde = serde_json::to_string(&join_relation).expect("BUG: Cannot serialize");
        let deserialized: JoinRelation =
            serde_json::from_str(&serde).expect("BUG: cannot deserialize");
        assert_eq!(deserialized, join_relation);
    }

    #[cfg(feature = "python")]
    #[rstest]
    #[case(JoinBy::AddColumns)]
    #[case(JoinBy::Replace)]
    #[case(JoinBy::Extend)]
    #[case(JoinBy::Broadcast)]
    #[case(JoinBy::CartesianProduct)]
    #[case(JoinBy::JoinById(JoinById::new(vec!["a".into()])))]
    fn test_join_relation_py(#[case] join_type: JoinBy) {
        pyo3::Python::with_gil(|_py| {
            let join_relation = JoinRelation::new(join_type.clone());
            let py_join_relation = JoinRelation::init(join_type.clone());
            assert_eq!(join_relation.join_type, join_type);
            assert_eq!(join_relation, py_join_relation);
        });
    }
}