etl-unit 0.1.0

Semantic data model for ETL units — qualities and measurements over subjects and time. Built on Polars.
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Column expressions for deriving values from DataFrame columns.
//!
//! `ColumnExpr` is the fundamental building block for subjects, timestamps, and components.
//! It supports both simple single-column identity and complex multi-column compositions.
//!
//! Note: `ColumnExpr` only describes *how* to compute a value from source columns.
//! The output name (canonical name) is provided by the parent column type
//! (`SubjectColumn`, `TimeColumn`, etc.) when converting to a Polars expression.

use polars::prelude::*;
use serde::{Deserialize, Serialize};

use crate::column::SourceColumnName;

/// An expression that derives a value from one or more DataFrame columns.
///
/// This type describes the computation only - it does not include the output name.
/// The output name is provided when calling `to_polars_expr(output_name)`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ColumnExpr {
    /// Identity: single column, no transformation
    Single(SourceColumnName),

    /// Struct: combine columns into a Polars struct (preserves types, good for composite keys)
    Struct { columns: Vec<SourceColumnName> },

    /// Concat: join column string values with a separator
    Concat {
        columns: Vec<SourceColumnName>,
        separator: String,
    },

    /// Coalesce: first non-null value from columns (for fallback chains)
    Coalesce { columns: Vec<SourceColumnName> },

    /// DateTime: combine separate date and time columns
    DateTime {
        date: SourceColumnName,
        time: SourceColumnName,
    },

    /// DateTimeParts: build datetime from individual components
    DateTimeParts {
        year: SourceColumnName,
        month: SourceColumnName,
        day: SourceColumnName,
        hour: Option<SourceColumnName>,
        minute: Option<SourceColumnName>,
        second: Option<SourceColumnName>,
    },

    /// ParseDateTime: parse a string column with a format
    ParseDateTime {
        column: SourceColumnName,
        format: String,
    },

    /// EpochToDateTime: convert epoch seconds/millis/micros to datetime
    EpochToDateTime {
        column: SourceColumnName,
        unit: EpochUnit,
    },
}

/// Unit for epoch timestamp conversion
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum EpochUnit {
    Seconds,
    Milliseconds,
    Microseconds,
    Nanoseconds,
}

impl ColumnExpr {
    // =========================================================================
    // Constructors
    // =========================================================================

    /// Single column identity
    pub fn column(name: impl Into<String>) -> Self {
        Self::Single(SourceColumnName::new(name))
    }

    /// Composite struct key from multiple columns
    pub fn struct_key(columns: Vec<String>) -> Self {
        Self::Struct {
            columns: columns.into_iter().map(SourceColumnName::new).collect(),
        }
    }

    /// Concatenated string key with separator
    pub fn concat_key(columns: Vec<String>, separator: impl Into<String>) -> Self {
        Self::Concat {
            columns: columns.into_iter().map(SourceColumnName::new).collect(),
            separator: separator.into(),
        }
    }

    /// First non-null value from columns
    pub fn coalesce(columns: Vec<String>) -> Self {
        Self::Coalesce {
            columns: columns.into_iter().map(SourceColumnName::new).collect(),
        }
    }

    /// Date + time columns → datetime
    pub fn datetime_from_date_time(date: impl Into<String>, time: impl Into<String>) -> Self {
        Self::DateTime {
            date: SourceColumnName::new(date),
            time: SourceColumnName::new(time),
        }
    }

    /// Year/month/day → datetime (with optional time components)
    pub fn datetime_from_components(
        year: impl Into<String>,
        month: impl Into<String>,
        day: impl Into<String>,
    ) -> Self {
        Self::DateTimeParts {
            year: SourceColumnName::new(year),
            month: SourceColumnName::new(month),
            day: SourceColumnName::new(day),
            hour: None,
            minute: None,
            second: None,
        }
    }

    /// Parse string column as datetime
    pub fn parse_datetime(column: impl Into<String>, format: impl Into<String>) -> Self {
        Self::ParseDateTime {
            column: SourceColumnName::new(column),
            format: format.into(),
        }
    }

    /// Convert epoch column to datetime
    pub fn from_epoch(column: impl Into<String>, unit: EpochUnit) -> Self {
        Self::EpochToDateTime {
            column: SourceColumnName::new(column),
            unit,
        }
    }

    // =========================================================================
    // Builder methods (for DateTimeParts)
    // =========================================================================

    /// Add hour component (for DateTimeParts)
    pub fn with_hour(mut self, hour: impl Into<String>) -> Self {
        if let Self::DateTimeParts { hour: h, .. } = &mut self {
            *h = Some(SourceColumnName::new(hour));
        }
        self
    }

    /// Add minute component (for DateTimeParts)
    pub fn with_minute(mut self, minute: impl Into<String>) -> Self {
        if let Self::DateTimeParts { minute: m, .. } = &mut self {
            *m = Some(SourceColumnName::new(minute));
        }
        self
    }

    /// Add second component (for DateTimeParts)
    pub fn with_second(mut self, second: impl Into<String>) -> Self {
        if let Self::DateTimeParts { second: s, .. } = &mut self {
            *s = Some(SourceColumnName::new(second));
        }
        self
    }

    // =========================================================================
    // Accessors
    // =========================================================================

    /// Get all source column names this expression depends on
    pub fn source_columns(&self) -> Vec<&SourceColumnName> {
        match self {
            Self::Single(c) => vec![c],
            Self::Struct { columns } => columns.iter().collect(),
            Self::Concat { columns, .. } => columns.iter().collect(),
            Self::Coalesce { columns } => columns.iter().collect(),
            Self::DateTime { date, time } => vec![date, time],
            Self::DateTimeParts {
                year,
                month,
                day,
                hour,
                minute,
                second,
            } => {
                let mut cols = vec![year, month, day];
                if let Some(h) = hour {
                    cols.push(h);
                }
                if let Some(m) = minute {
                    cols.push(m);
                }
                if let Some(s) = second {
                    cols.push(s);
                }
                cols
            }
            Self::ParseDateTime { column, .. } => vec![column],
            Self::EpochToDateTime { column, .. } => vec![column],
        }
    }

    /// Returns true if this is a single-column identity expression
    pub fn is_identity(&self) -> bool {
        matches!(self, Self::Single(_))
    }

    /// Returns true if this expression requires materialization (adds a new column)
    pub fn needs_materialization(&self) -> bool {
        !self.is_identity()
    }

    /// For identity expressions, get the source column name
    pub fn identity_column(&self) -> Option<&SourceColumnName> {
        match self {
            Self::Single(c) => Some(c),
            _ => None,
        }
    }

    // =========================================================================
    // Polars conversion
    // =========================================================================

    /// Convert to a Polars expression with the given output name.
    ///
    /// The `output_name` is typically the canonical name from the parent column type
    /// (e.g., `SubjectColumn::canonical_name`).
    pub fn to_polars_expr(&self, output_name: &str) -> Expr {
        match self {
            Self::Single(c) => col(c.as_str()).alias(output_name),

            Self::Struct { columns } => {
                as_struct(columns.iter().map(|c| col(c.as_str())).collect::<Vec<_>>())
                    .alias(output_name)
            }

            Self::Concat { columns, separator } => concat_str(
                columns
                    .iter()
                    .map(|c| col(c.as_str()).cast(DataType::String))
                    .collect::<Vec<_>>(),
                separator,
                false,
            )
            .alias(output_name),

            Self::Coalesce { columns } => coalesce(
                columns
                    .iter()
                    .map(|c| col(c.as_str()))
                    .collect::<Vec<_>>()
                    .as_slice(),
            )
            .alias(output_name),

            Self::DateTime { date, time } => {
                // Combine date and time columns
                col(date.as_str())
                    .dt()
                    .combine(col(time.as_str()), TimeUnit::Microseconds)
                    .alias(output_name)
            }

            Self::DateTimeParts {
                year,
                month,
                day,
                hour,
                minute,
                second,
            } => {
                let hour_expr = hour.as_ref().map(|h| col(h.as_str())).unwrap_or(lit(0i64));
                let minute_expr = minute
                    .as_ref()
                    .map(|m| col(m.as_str()))
                    .unwrap_or(lit(0i64));
                let second_expr = second
                    .as_ref()
                    .map(|s| col(s.as_str()))
                    .unwrap_or(lit(0i64));

                // Build a date first, then add time
                let year_str = col(year.as_str()).cast(DataType::String);
                let month_str = when(col(month.as_str()).lt(lit(10)))
                    .then(lit("0") + col(month.as_str()).cast(DataType::String))
                    .otherwise(col(month.as_str()).cast(DataType::String));
                let day_str = when(col(day.as_str()).lt(lit(10)))
                    .then(lit("0") + col(day.as_str()).cast(DataType::String))
                    .otherwise(col(day.as_str()).cast(DataType::String));

                let date_str = year_str + lit("-") + month_str + lit("-") + day_str;

                let date_expr = date_str.str().to_date(StrptimeOptions {
                    format: Some("%Y-%m-%d".to_string().into()),
                    ..Default::default()
                });

                // Convert date to datetime and add time components
                let datetime_base =
                    date_expr.cast(DataType::Datetime(TimeUnit::Microseconds, None));

                // Add time as duration (hours + minutes + seconds in microseconds)
                let time_offset_us = (hour_expr.cast(DataType::Int64)
                    * lit(3600i64 * 1_000_000i64))
                    + (minute_expr.cast(DataType::Int64) * lit(60i64 * 1_000_000i64))
                    + (second_expr.cast(DataType::Int64) * lit(1_000_000i64));

                let time_duration = time_offset_us.cast(DataType::Duration(TimeUnit::Microseconds));

                (datetime_base + time_duration).alias(output_name)
            }

            Self::ParseDateTime { column, format } => col(column.as_str())
                .str()
                .to_datetime(
                    Some(TimeUnit::Microseconds),
                    None,
                    StrptimeOptions {
                        format: Some(format.clone().into()),
                        ..Default::default()
                    },
                    lit("raise"),
                )
                .alias(output_name),

            Self::EpochToDateTime { column, unit } => {
                let (time_unit, multiplier) = match unit {
                    EpochUnit::Seconds => (TimeUnit::Milliseconds, Some(1000i64)),
                    EpochUnit::Milliseconds => (TimeUnit::Milliseconds, None),
                    EpochUnit::Microseconds => (TimeUnit::Microseconds, None),
                    EpochUnit::Nanoseconds => (TimeUnit::Nanoseconds, None),
                };

                let expr = if let Some(mult) = multiplier {
                    col(column.as_str()) * lit(mult)
                } else {
                    col(column.as_str())
                };

                expr.cast(DataType::Datetime(time_unit, None))
                    .alias(output_name)
            }
        }
    }
}

impl Default for ColumnExpr {
    fn default() -> Self {
        Self::Single(SourceColumnName::new("id"))
    }
}

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

    #[test]
    fn test_single_column() {
        let expr = ColumnExpr::column("pump_id");
        assert!(expr.is_identity());
        assert_eq!(expr.identity_column().unwrap().as_str(), "pump_id");
        assert_eq!(expr.source_columns().len(), 1);
        assert_eq!(expr.source_columns()[0].as_str(), "pump_id");
    }

    #[test]
    fn test_struct_key() {
        let expr = ColumnExpr::struct_key(vec!["region".into(), "station".into()]);
        assert!(!expr.is_identity());
        assert!(expr.identity_column().is_none());
        let sources: Vec<&str> = expr.source_columns().iter().map(|s| s.as_str()).collect();
        assert_eq!(sources, vec!["region", "station"]);
    }

    #[test]
    fn test_concat_key() {
        let expr = ColumnExpr::concat_key(vec!["a".into(), "b".into(), "c".into()], "-");
        let sources: Vec<&str> = expr.source_columns().iter().map(|s| s.as_str()).collect();
        assert_eq!(sources, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_datetime_components() {
        let expr = ColumnExpr::datetime_from_components("year", "month", "day")
            .with_hour("hour")
            .with_minute("minute");

        let sources: Vec<&str> = expr.source_columns().iter().map(|s| s.as_str()).collect();
        assert_eq!(sources, vec!["year", "month", "day", "hour", "minute"]);
    }

    #[test]
    fn test_epoch_conversion() {
        let expr = ColumnExpr::from_epoch("unix_ts", EpochUnit::Seconds);
        assert_eq!(expr.source_columns()[0].as_str(), "unix_ts");
    }

    #[test]
    fn test_to_polars_expr_uses_output_name() {
        let expr = ColumnExpr::column("source_col");
        let _polars_expr = expr.to_polars_expr("canonical_name");
        // The expression should use the provided output name as alias
        assert!(expr.is_identity());
    }

    #[test]
    fn test_struct_to_polars_expr() {
        let expr = ColumnExpr::struct_key(vec!["a".into(), "b".into()]);
        let _polars_expr = expr.to_polars_expr("my_struct");
        assert!(!expr.is_identity());
    }
}