Rafferty97 commented on code in PR #9494:
URL: https://github.com/apache/arrow-rs/pull/9494#discussion_r2968606176


##########
arrow-json/src/reader/schema/infer.rs:
##########
@@ -0,0 +1,358 @@
+// 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 std::collections::HashMap;
+use std::sync::{Arc, LazyLock};
+
+use arrow_schema::{ArrowError, DataType, Field, Fields, Schema};
+
+use crate::reader::tape::{Tape, TapeElement};
+
+#[derive(Clone, Debug)]
+pub struct InferTy(Arc<TyKind>);
+
+#[derive(Clone, Debug)]
+enum TyKind {
+    Any,
+    Scalar(ScalarTy),
+    Array(InferTy),
+    Object(Arc<[InferField]>),
+}
+
+pub type InferField = (Arc<str>, InferTy);
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum ScalarTy {
+    Bool,
+    Int64,
+    Float64,
+    String,
+    // NOTE: Null isn't needed because it's absorbed into Any
+}
+
+pub static ANY_TY: LazyLock<InferTy> = LazyLock::new(InferTy::new_any);
+pub static BOOL_TY: LazyLock<InferTy> = LazyLock::new(|| 
InferTy::new_scalar(ScalarTy::Bool));
+pub static INT64_TY: LazyLock<InferTy> = LazyLock::new(|| 
InferTy::new_scalar(ScalarTy::Int64));
+pub static FLOAT64_TY: LazyLock<InferTy> = LazyLock::new(|| 
InferTy::new_scalar(ScalarTy::Float64));
+pub static STRING_TY: LazyLock<InferTy> = LazyLock::new(|| 
InferTy::new_scalar(ScalarTy::String));
+pub static ARRAY_OF_ANY_TY: LazyLock<InferTy> = LazyLock::new(|| 
InferTy::new_array(&*ANY_TY));
+pub static EMPTY_FIELDS: LazyLock<Arc<[InferField]>> = LazyLock::new(|| 
Arc::new([]));
+pub static EMPTY_OBJECT_TY: LazyLock<InferTy> =
+    LazyLock::new(|| InferTy::new_object(EMPTY_FIELDS.clone()));
+
+/// Infers the type of the provided JSON value, given an expected type.
+pub fn infer_json_type<'a>(
+    value: impl JsonValue<'a>,
+    expected: InferTy,
+) -> Result<InferTy, ArrowError> {
+    let make_err = |got| {
+        let expected = match expected.kind() {
+            TyKind::Any => unreachable!(),
+            TyKind::Scalar(_) => "a scalar value",
+            TyKind::Array(_) => "an array",
+            TyKind::Object(_) => "an object",
+        };
+        let msg = format!("Expected {expected}, found {got}");
+        ArrowError::JsonError(msg)
+    };
+
+    let infer_scalar = |scalar: ScalarTy, got: &'static str| {
+        Ok(match expected.kind() {
+            TyKind::Any => match scalar {
+                ScalarTy::Bool => BOOL_TY.clone(),
+                ScalarTy::Int64 => INT64_TY.clone(),
+                ScalarTy::Float64 => FLOAT64_TY.clone(),
+                ScalarTy::String => STRING_TY.clone(),
+            },
+            TyKind::Scalar(expect) => match (expect, &scalar) {
+                (ScalarTy::Bool, ScalarTy::Bool) => BOOL_TY.clone(),
+                (ScalarTy::Int64, ScalarTy::Int64) => INT64_TY.clone(),
+                // Mixed numbers coerce to f64
+                (ScalarTy::Int64 | ScalarTy::Float64, ScalarTy::Int64 | 
ScalarTy::Float64) => {
+                    FLOAT64_TY.clone()
+                }
+                // Any other combination coerces to string
+                _ => STRING_TY.clone(),
+            },
+            _ => Err(make_err(got))?,
+        })
+    };
+
+    match value.get() {
+        JsonType::Null => Ok(expected),
+        JsonType::Bool => infer_scalar(ScalarTy::Bool, "a boolean"),
+        JsonType::Int64 => infer_scalar(ScalarTy::Int64, "a number"),
+        JsonType::Float64 => infer_scalar(ScalarTy::Float64, "a number"),
+        JsonType::String => infer_scalar(ScalarTy::String, "a string"),
+        JsonType::Array => {
+            let (expected_elem, expected) = match expected.kind() {
+                TyKind::Any => (ANY_TY.clone(), ARRAY_OF_ANY_TY.clone()),
+                TyKind::Array(inner) => (inner.clone(), expected),
+                _ => Err(make_err("an array"))?,
+            };
+
+            let elem = value
+                .elements()
+                .try_fold(expected_elem.clone(), |expected, value| {
+                    infer_json_type(value, expected)
+                })?;
+
+            if elem.ptr_eq(&expected_elem) {
+                return Ok(expected);
+            }
+
+            Ok(InferTy::new_array(elem))
+        }
+        JsonType::Object => {
+            let (expected_fields, expected) = match expected.kind() {
+                TyKind::Any => (EMPTY_FIELDS.clone(), EMPTY_OBJECT_TY.clone()),
+                TyKind::Object(fields) => (fields.clone(), expected),
+                _ => Err(make_err("an object"))?,
+            };
+
+            let mut num_fields = expected_fields.len();
+            let mut substs = HashMap::<usize, (Arc<str>, InferTy)>::new();
+
+            for (key, value) in value.fields() {
+                let existing_field = expected_fields
+                    .iter()
+                    .enumerate()
+                    .find(|(_, (existing_key, _))| &**existing_key == key);
+
+                match existing_field {
+                    Some((field_idx, (key, expect_ty))) => {
+                        let ty = infer_json_type(value, expect_ty.clone())?;
+                        if !ty.ptr_eq(expect_ty) {
+                            substs.insert(field_idx, (key.clone(), ty));
+                        }
+                    }
+                    None => {
+                        let field_idx = num_fields;
+                        num_fields += 1;
+                        let ty = infer_json_type(value, ANY_TY.clone())?;
+                        substs.insert(field_idx, (key.into(), ty));
+                    }
+                };
+            }
+
+            if substs.is_empty() {
+                return Ok(expected);
+            }
+
+            let fields = (0..num_fields)
+                .map(|idx| match substs.remove(&idx) {
+                    Some(subst) => subst,
+                    None => expected_fields[idx].clone(),
+                })
+                .collect();
+
+            Ok(InferTy::new_object(fields))
+        }
+    }
+}
+
+impl InferTy {
+    fn new_any() -> Self {
+        Self(TyKind::Any.into())
+    }
+
+    fn new_scalar(scalar: ScalarTy) -> Self {
+        Self(TyKind::Scalar(scalar).into())
+    }
+
+    fn new_array(inner: impl Into<Self>) -> Self {
+        Self(TyKind::Array(inner.into()).into())
+    }
+
+    fn new_object(fields: Arc<[(Arc<str>, InferTy)]>) -> Self {
+        Self(TyKind::Object(fields).into())
+    }
+
+    fn kind(&self) -> &TyKind {
+        &self.0
+    }
+
+    fn ptr_eq(&self, other: &Self) -> bool {
+        Arc::ptr_eq(&self.0, &other.0)
+    }
+
+    pub fn to_datatype(&self) -> DataType {
+        match self.kind() {
+            TyKind::Any => DataType::Null,
+            TyKind::Scalar(s) => s.into_datatype(),
+            TyKind::Array(elem) => DataType::List(elem.to_list_field().into()),
+            TyKind::Object(fields) => {
+                DataType::Struct(fields.iter().map(|(key, ty)| 
ty.to_field(&**key)).collect())
+            }
+        }
+    }
+
+    pub fn to_field(&self, name: impl Into<String>) -> Field {
+        Field::new(name, self.to_datatype(), true)
+    }
+
+    pub fn to_list_field(&self) -> Field {
+        Field::new_list_field(self.to_datatype(), true)
+    }
+
+    pub fn into_schema(self) -> Result<Schema, ArrowError> {
+        let TyKind::Object(fields) = self.kind() else {
+            Err(ArrowError::JsonError(format!(
+                "Expected JSON object, found {self:?}",
+            )))?
+        };
+
+        let fields = fields
+            .iter()
+            .map(|(key, ty)| ty.to_field(&**key))
+            .collect::<Fields>();
+
+        Ok(Schema::new(fields))
+    }
+}
+
+impl From<&InferTy> for InferTy {
+    fn from(value: &InferTy) -> Self {
+        Self(value.0.clone())
+    }
+}
+
+impl ScalarTy {
+    fn into_datatype(self) -> DataType {
+        match self {
+            Self::Bool => DataType::Boolean,
+            Self::Int64 => DataType::Int64,
+            Self::Float64 => DataType::Float64,
+            Self::String => DataType::Utf8,
+        }
+    }
+}
+
+/// Abstraction of a JSON value that is only concerned with the
+/// type of the value rather than the value itself.
+pub trait JsonValue<'a> {
+    /// Gets the type of this JSON value.
+    fn get(&self) -> JsonType;
+
+    /// Returns an iterator over the elements of this JSON array.
+    ///
+    /// Panics if the JSON value is not an array.
+    fn elements(&self) -> impl Iterator<Item = Self>;
+
+    /// Returns an iterator over the fields of this JSON object.
+    ///
+    /// Panics if the JSON value is not an object.
+    fn fields(&self) -> impl Iterator<Item = (&'a str, Self)>;
+}
+
+/// The type of a JSON value
+pub enum JsonType {

Review Comment:
   That's fair. I've moved them to a separate module within `schema` for better 
code organisation.



-- 
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