alamb commented on code in PR #9494:
URL: https://github.com/apache/arrow-rs/pull/9494#discussion_r2966369371
##########
arrow-json/src/reader/schema.rs:
##########
@@ -600,33 +366,12 @@ mod tests {
assert_eq!(small_field.data_type(), &DataType::Float64);
}
- #[test]
- fn test_coercion_scalar_and_list() {
- assert_eq!(
- list_type_of(DataType::Float64),
- coerce_data_type(vec![&DataType::Float64,
&list_type_of(DataType::Float64)])
- );
- assert_eq!(
- list_type_of(DataType::Float64),
- coerce_data_type(vec![&DataType::Float64,
&list_type_of(DataType::Int64)])
- );
- assert_eq!(
- list_type_of(DataType::Int64),
- coerce_data_type(vec![&DataType::Int64,
&list_type_of(DataType::Int64)])
- );
- // boolean and number are incompatible, return utf8
- assert_eq!(
- list_type_of(DataType::Utf8),
- coerce_data_type(vec![&DataType::Boolean,
&list_type_of(DataType::Float64)])
- );
- }
-
#[test]
fn test_invalid_json_infer_schema() {
let re = infer_json_schema_from_seekable(Cursor::new(b"}"), None);
assert_eq!(
re.err().unwrap().to_string(),
- "Json error: Not valid JSON: expected value at line 1 column 1",
+ "Json error: Encountered unexpected '}' whilst parsing value"
);
}
Review Comment:
I think this PR changes inference rules
For example these two tests pass on main but not on this branch
```rust
#[test]
fn test_empty_input_infers_empty_schema() {
let (inferred_schema, n_rows) =
infer_json_schema_from_seekable(Cursor::new(b""),
None).expect("infer");
assert_eq!(inferred_schema, Schema::empty());
assert_eq!(n_rows, 0);
}
#[test]
fn test_scalar_and_list_are_coerced_to_list() {
let inferred_schema = infer_json_schema_from_iterator(
vec![
Ok(serde_json::json!({"value": [1]})),
Ok(serde_json::json!({"value": 2})),
]
.into_iter(),
)
.expect("infer");
let schema = Schema::new(vec![Field::new(
"value",
list_type_of(DataType::Int64),
true,
)]);
assert_eq!(inferred_schema, schema);
}
```
They fail like
```rust
failures:
---- reader::schema::tests::test_empty_input_infers_empty_schema stdout ----
thread 'reader::schema::tests::test_empty_input_infers_empty_schema'
(12716924) panicked at arrow-json/src/reader/schema.rs:381:69:
infer: JsonError("Expected JSON object, found InferTy(Any)")
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
---- reader::schema::tests::test_scalar_and_list_are_coerced_to_list stdout
----
thread 'reader::schema::tests::test_scalar_and_list_are_coerced_to_list'
(12716934) panicked at arrow-json/src/reader/schema.rs:395:10:
infer: JsonError("Expected an array, found a number")
failures:
reader::schema::tests::test_empty_input_infers_empty_schema
reader::schema::tests::test_scalar_and_list_are_coerced_to_list
test result: FAILED. 116 passed; 2 failed; 0 ignored; 0 measured; 0 filtered
out; finished in 0.01s
```
##########
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);
Review Comment:
I was a little confused about these LazyLocks -- maybe you could add some
background about why they are needed (e.g. why not ust use
`InferTy::new_scalar(ScalarTy::Bool))` directly?
I still don't fully understand the need for this design (why not just use
plain enums). Could you also help document the design and its rationale in
these structures?
##########
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>);
Review Comment:
since this is in a non pub crate I don't think this structure is part of the
public API
Any chance you would be willing to mark them as `pub(crate)` so it is
explicit?
##########
arrow-json/test/data/mixed_arrays.json:
##########
@@ -1,4 +0,0 @@
-{"a":1, "b":[2.0, 1.3, -6.1], "c":[false, true], "d":4.1}
Review Comment:
What is the purpose of removing this file?
##########
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:
I found it strange that the Json type and tape value are now in the `infer`
module -- they seem more widely applicable than just for schema inference
##########
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() {
Review Comment:
if you implemented `impl Display for TyKind` you could just use it directly
in the msg
```rust
ArrowError::JsonError(format!("Expected {expected}, found {got}"))
```
##########
arrow-json/test/data/arrays.json.gz:
##########
Review Comment:
Given this file is so small (133 bytes), can you please unzip it to make the
contents more explicit and easier to review and track changes
##########
arrow-json/src/reader/schema.rs:
##########
@@ -600,33 +366,12 @@ mod tests {
assert_eq!(small_field.data_type(), &DataType::Float64);
}
- #[test]
Review Comment:
why is this test removed?
--
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]