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
/*!
 * A Struct for the materialized view metadata   
*/

use itertools::Itertools;
use serde::{Deserialize, Serialize};

use crate::error::Error;

use super::view_metadata::{GeneralViewMetadata, GeneralViewMetadataBuilder};

/// Property for the metadata location
pub static STORAGE_TABLE: &str = "storage_table";

/// Fields for the version 1 of the view metadata.
pub type MaterializedViewMetadata = GeneralViewMetadata<String>;
/// Builder for materialized view metadata
pub type MaterializedViewMetadataBuilder = GeneralViewMetadataBuilder<String>;

pub fn depends_on_tables_to_string(source_tables: &[SourceTable]) -> Result<String, Error> {
    Ok(source_tables
        .iter()
        .map(|x| x.identifier.to_string() + "=" + &x.snapshot_id.to_string())
        .join(","))
}

pub fn depends_on_tables_from_string(value: &str) -> Result<Vec<SourceTable>, Error> {
    value
        .split(',')
        .map(|x| {
            x.split('=')
                .next_tuple()
                .ok_or(Error::InvalidFormat("Lineage information".to_owned()))
                .and_then(|(identifier, snapshot_id)| {
                    Ok(SourceTable {
                        identifier: identifier.to_owned(),
                        snapshot_id: snapshot_id.parse()?,
                    })
                })
        })
        .collect::<Result<_, Error>>()
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "kebab-case")]
/// Freshness information of the materialized view
pub struct SourceTable {
    /// Table reference in the SQL expression.
    pub identifier: String,
    /// Snapshot id of the base table when the refresh operation was performed.
    pub snapshot_id: i64,
}

#[cfg(test)]
mod tests {

    use crate::{
        error::Error,
        spec::materialized_view_metadata::{
            depends_on_tables_from_string, depends_on_tables_to_string, MaterializedViewMetadata,
            SourceTable,
        },
    };

    #[test]
    fn test_deserialize_materialized_view_metadata_v1() -> Result<(), Error> {
        let data = r#"
        {
        "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385",
        "format-version" : 1,
        "location" : "s3://bucket/warehouse/default.db/event_agg",
        "current-version-id" : 1,
        "properties" : {
            "comment" : "Daily event counts",
            "storage_table": "iceberg.default.event_agg"
        },
        "versions" : [ {
            "version-id" : 1,
            "timestamp-ms" : 1573518431292,
            "schema-id" : 1,
            "default-catalog" : "prod",
            "default-namespace" : [ "default" ],
            "summary" : {
            "operation" : "create",
            "engine-name" : "Spark",
            "engineVersion" : "3.3.2"
            },
            "representations" : [ {
            "type" : "sql",
            "sql" : "SELECT\n    COUNT(1), CAST(event_ts AS DATE)\nFROM events\nGROUP BY 2",
            "dialect" : "spark"
            } ]
        } ],
        "schemas": [ {
            "schema-id": 1,
            "type" : "struct",
            "fields" : [ {
            "id" : 1,
            "name" : "event_count",
            "required" : false,
            "type" : "int",
            "doc" : "Count of events"
            }, {
            "id" : 2,
            "name" : "event_date",
            "required" : false,
            "type" : "date"
            } ]
        } ],
        "version-log" : [ {
            "timestamp-ms" : 1573518431292,
            "version-id" : 1
        } ]
        }
        "#;
        let metadata = serde_json::from_str::<MaterializedViewMetadata>(data)
            .expect("Failed to deserialize json");
        //test serialise deserialise works.
        let metadata_two: MaterializedViewMetadata = serde_json::from_str(
            &serde_json::to_string(&metadata).expect("Failed to serialize metadata"),
        )
        .expect("Failed to serialize json");
        assert_eq!(metadata, metadata_two);

        Ok(())
    }

    #[test]
    fn test_depends_on_tables_try_from_str() {
        let input = "table1=1,table2=2";

        let result = depends_on_tables_from_string(input).unwrap();

        assert_eq!(
            result,
            vec![
                SourceTable {
                    identifier: "table1".to_string(),
                    snapshot_id: 1
                },
                SourceTable {
                    identifier: "table2".to_string(),
                    snapshot_id: 2
                }
            ]
        );
    }

    #[test]
    fn test_try_from_depends_on_tables_to_string() {
        let depends_on_tables = vec![
            SourceTable {
                identifier: "table1".to_string(),
                snapshot_id: 1,
            },
            SourceTable {
                identifier: "table2".to_string(),
                snapshot_id: 2,
            },
        ];

        let result = depends_on_tables_to_string(&depends_on_tables);

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "table1=1,table2=2");
    }
}