use std::collections::BTreeMap;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LineageStep {
pub source: String,
pub operation: String,
pub parameters: BTreeMap<String, String>,
}
impl LineageStep {
pub fn new(source: impl Into<String>, operation: impl Into<String>) -> Self {
Self {
source: source.into(),
operation: operation.into(),
parameters: BTreeMap::new(),
}
}
pub fn parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.parameters.insert(key.into(), value.into());
self
}
}
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Lineage {
pub steps: Vec<LineageStep>,
}
impl Lineage {
pub fn new() -> Self {
Self::default()
}
pub fn record(&mut self, step: LineageStep) {
self.steps.push(step);
}
pub fn sources(&self) -> Vec<&str> {
let mut sources: Vec<&str> = self.steps.iter().map(|step| step.source.as_str()).collect();
sources.sort_unstable();
sources.dedup();
sources
}
pub fn operations(&self) -> Vec<&str> {
let mut operations: Vec<&str> = self.steps.iter().map(|step| step.operation.as_str()).collect();
operations.sort_unstable();
operations.dedup();
operations
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lineage_records_sources_and_operations() {
let mut lineage = Lineage::new();
lineage.record(LineageStep::new("input.csv", "csv").parameter("delimiter", ","));
lineage.record(LineageStep::new("input.csv", "filter").parameter("where", "v > 0"));
assert_eq!(lineage.sources(), ["input.csv"]);
assert_eq!(lineage.operations(), ["csv", "filter"]);
assert_eq!(lineage.steps[1].parameters["where"], "v > 0");
}
}