kriti-sc commented on code in PR #2889:
URL: https://github.com/apache/iggy/pull/2889#discussion_r3035585287


##########
core/connectors/sinks/delta_sink/src/coercions.rs:
##########
@@ -0,0 +1,600 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use deltalake::kernel::Schema as DeltaSchema;
+use deltalake::kernel::{DataType, PrimitiveType};
+
+use chrono::prelude::*;
+use serde_json::Value;
+use std::collections::HashMap;
+use std::str::FromStr;
+
+#[derive(Debug, Clone, PartialEq)]
+#[allow(unused)]
+enum CoercionNode {
+    Coercion(Coercion),
+    Tree(CoercionTree),
+    ArrayTree(CoercionTree),
+    ArrayPrimitive(Coercion),
+}
+
+#[derive(Debug, Clone, PartialEq)]
+enum Coercion {
+    ToString,
+    ToTimestamp,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct CoercionTree {
+    root: HashMap<String, CoercionNode>,
+}
+
+/// Returns a [`CoercionTree`] so the schema can be walked efficiently level 
by level when performing conversions.
+pub(crate) fn create_coercion_tree(schema: &DeltaSchema) -> CoercionTree {
+    let mut root = HashMap::new();
+
+    for field in schema.fields() {
+        if let Some(node) = build_coercion_node(field.data_type()) {
+            root.insert(field.name().to_string(), node);
+        }
+    }
+
+    CoercionTree { root }
+}
+
+fn build_coercion_node(data_type: &DataType) -> Option<CoercionNode> {
+    match data_type {
+        DataType::Primitive(primitive) => match primitive {
+            PrimitiveType::String => 
Some(CoercionNode::Coercion(Coercion::ToString)),
+            PrimitiveType::Timestamp => 
Some(CoercionNode::Coercion(Coercion::ToTimestamp)),
+            _ => None,
+        },
+        DataType::Struct(st) => {
+            let nested_context = create_coercion_tree(st);
+            if !nested_context.root.is_empty() {
+                Some(CoercionNode::Tree(nested_context))
+            } else {
+                None
+            }
+        }
+        DataType::Array(array) => {
+            build_coercion_node(array.element_type()).and_then(|node| match 
node {
+                CoercionNode::Coercion(c) => 
Some(CoercionNode::ArrayPrimitive(c)),
+                CoercionNode::Tree(t) => Some(CoercionNode::ArrayTree(t)),
+                _ => None,
+            })
+        }
+        _ => None,
+    }
+}
+
+/// Applies all data coercions specified by the [`CoercionTree`] to the 
[`Value`].
+pub(crate) fn coerce(value: &mut Value, coercion_tree: &CoercionTree) {
+    if let Some(context) = value.as_object_mut() {
+        for (field_name, coercion) in coercion_tree.root.iter() {
+            if let Some(value) = context.get_mut(field_name) {
+                apply_coercion(value, coercion);
+            }
+        }
+    }
+}
+
+fn apply_coercion(value: &mut Value, node: &CoercionNode) {
+    match node {
+        CoercionNode::Coercion(Coercion::ToString) => {
+            if !value.is_string() {
+                *value = Value::String(value.to_string());
+            }
+        }
+        CoercionNode::Coercion(Coercion::ToTimestamp) => {

Review Comment:
   Fair point. 
   
   TLDR: The logic gives the desired behaviour, but there are paths in the code 
that are incorrect. I have made the change to fix these incorrect paths.
   
   Desired behaviour: If timestamp can be correctly parsed, parse it and 
ingest. If not, do not convert to null and do not ingest the record with 
malformed timestamp. The latter would lead to entire batch failing, but this 
will be solved as part of DQ implementation. 
   
   Fix: 
   
   1. Ultimately, the timestamp with ' ' separator does get ingeted into Delta. 
Incorrect paths: we get a warning that coercion has failed but the write 
succeeds, which is incorrect. This is fixed. Now, coercion explicitly handles 
such timestamps. 
   
   2. A record that contains an invalid timestamp will be rejected, causing the 
entire batch to fail. This is correct semantics. Incorrect path: coercion emits 
a warning but does not error out. The error happens downstream. This is 
incorrect. Now, for invalid timestamps error out at the coercion layer. 
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to