diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index eb98bc72a..e2d815115 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1269,7 +1269,8 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field: # casting the input to that storage type here merely relabels the raw JSON bytes as # JSONB. Lance must see arrow.json so it can perform the JSONB encoding. if _field_extension_name(target_field) == "lance.json": - if _field_extension_name(field) == "arrow.json": + input_extension = _field_extension_name(field) + if input_extension == "arrow.json": return field # Plain JSON text, which is what pyarrow infers for a column of `str`, only # needs the arrow.json label. @@ -1284,6 +1285,11 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field: metadata = dict(target_field.metadata or {}) metadata[b"ARROW:extension:name"] = b"arrow.json" return pa.field(field.name, json_storage, field.nullable, metadata) + if input_extension != "lance.json" and not pa.types.is_null(field.type): + raise ValueError( + f"Column '{field.name}' requires JSON text or an explicit JSON type, " + f"got {field.type}" + ) if pa.types.is_struct(target_field.type): if pa.types.is_struct(field.type): new_type = pa.struct( diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py index 7523cf034..ce98933b8 100644 --- a/python/python/tests/test_merge_insert_lsm.py +++ b/python/python/tests/test_merge_insert_lsm.py @@ -88,6 +88,109 @@ def test_lsm_merge_insert_unsharded(tmp_path): assert result.num_rows == 4 +@pytest.fixture +def json_rte_table(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) + schema = pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("j", pa.string(), metadata={"ARROW:extension:name": "arrow.json"}), + ] + ) + table = db.create_table( + "json_rte", pa.Table.from_pylist([{"id": 1, "j": '{"k": 1}'}], schema=schema) + ) + table.set_unenforced_primary_key("id") + table.enable_rte(RTEWriteSpec.unsharded()) + return table + + +@pytest.mark.parametrize( + "source_type", + [ + pytest.param(pa.string(), id="utf8"), + pytest.param(pa.large_string(), id="large-utf8"), + pytest.param( + pa.json_() if hasattr(pa, "json_") else None, + marks=pytest.mark.skipif( + not hasattr(pa, "json_"), reason="requires PyArrow JSON type" + ), + id="arrow-json", + ), + ], +) +def test_rte_merge_insert_encodes_json(tmp_path, json_rte_table, source_type): + values = ['{"k": 9}', '{"k": 2}', None] + if isinstance(source_type, pa.ExtensionType): + json_column = pa.ExtensionArray.from_storage( + source_type, pa.array(values, type=source_type.storage_type) + ) + else: + json_column = pa.array(values, type=source_type) + source = pa.table({"id": [1, 2, 3], "j": json_column}) + + result = ( + json_rte_table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(source) + ) + assert result.num_rows == 3 + assert result.version == 0 + + json_rte_table.close_rte_writers() + reopened = lancedb.connect(tmp_path).open_table("json_rte") + assert reopened.search().to_arrow().sort_by("id").to_pylist() == [ + {"id": 1, "j": '{"k":9}'}, + {"id": 2, "j": '{"k":2}'}, + {"id": 3, "j": None}, + ] + matched_ids = ( + reopened.search() + .where("json_extract(j, '$.k') IN ('9', '2')") + .select(["id"]) + .to_arrow() + ) + assert sorted(matched_ids["id"].to_pylist()) == [1, 2] + + +@pytest.mark.parametrize("binary_type", [pa.binary(), pa.large_binary()]) +def test_rte_merge_insert_rejects_unmarked_json_bytes( + tmp_path, json_rte_table, binary_type +): + source = pa.table( + {"id": [1, 2], "j": pa.array([b'{"k": 9}', b'{"k": 2}'], type=binary_type)} + ) + with pytest.raises( + ValueError, match="Column 'j' requires JSON text or an explicit JSON type" + ): + ( + json_rte_table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(source) + ) + + json_rte_table.close_rte_writers() + reopened = lancedb.connect(tmp_path).open_table("json_rte") + assert reopened.search().to_list() == [{"id": 1, "j": '{"k":1}'}] + + +def test_rte_merge_insert_rejects_invalid_json_before_writing(tmp_path, json_rte_table): + source = pa.table({"id": [1, 2], "j": ['{"k": 9}', "invalid JSON"]}) + with pytest.raises(RuntimeError, match="Failed to encode JSON in field 'j'"): + ( + json_rte_table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(source.to_reader(max_chunksize=1)) + ) + + json_rte_table.close_rte_writers() + reopened = lancedb.connect(tmp_path).open_table("json_rte") + assert reopened.search().to_list() == [{"id": 1, "j": '{"k":1}'}] + + def test_lsm_merge_insert_identity(tmp_path): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) table = db.create_table("t", _region_reader([(1, "us"), (2, "us")])) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index d8ffbc4b7..1eb519420 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5032,6 +5032,61 @@ def _json_arrow_table(schema, rows): ) +@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type") +def test_overwrite_json_column_uses_arrow_input_schema(tmp_db: DBConnection): + schema = pa.schema([pa.field("id", pa.string()), pa.field("j", pa.json_())]) + table = tmp_db.create_table("t", _json_arrow_table(schema, [("a", '{"k": 1}')])) + + plain = pa.table({"id": ["b", "c"], "j": ["plain text", '{"k": 2}']}) + table.add(plain, mode="overwrite") + table = tmp_db.open_table("t") + assert table.schema.field("j").equals(plain.schema.field("j"), check_metadata=True) + assert table.search().to_arrow().sort_by("id").to_pylist() == plain.to_pylist() + + table.add(_json_arrow_table(schema, [("d", '{"k": 3}')]), mode="overwrite") + table = tmp_db.open_table("t") + json_field = table.schema.field("j") + assert json_field.type == pa.large_binary() + assert (json_field.metadata or {}).get(b"ARROW:extension:name") == b"lance.json" + assert table.search().where("json_extract(j, '$.k') = '3'").to_list() == [ + {"id": "d", "j": '{"k":3}'} + ] + + +@pytest.mark.parametrize("operation", ["merge_insert", "sanitized_append"]) +def test_json_write_rejects_unmarked_binary(tmp_db: DBConnection, operation): + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("j", pa.string(), metadata={"ARROW:extension:name": "arrow.json"}), + ] + ) + table = tmp_db.create_table( + "t", pa.Table.from_pylist([{"id": 1, "j": '{"k": 1}'}], schema=schema) + ) + source = pa.table( + { + "id": [1, 2], + "j": pa.array([b'{"k": 9}', b'{"k": 2}'], type=pa.large_binary()), + } + ) + + with pytest.raises( + ValueError, match="Column 'j' requires JSON text or an explicit JSON type" + ): + if operation == "merge_insert": + ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(source) + ) + else: + table.add(source, on_bad_vectors="fill") + + assert tmp_db.open_table("t").search().to_list() == [{"id": 1, "j": '{"k":1}'}] + + @pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type") @pytest.mark.asyncio async def test_merge_insert_encodes_json(mem_db_async: AsyncConnection): diff --git a/rust/lancedb/src/table/datafusion/cast.rs b/rust/lancedb/src/table/datafusion/cast.rs index b6e815d5e..35994f870 100644 --- a/rust/lancedb/src/table/datafusion/cast.rs +++ b/rust/lancedb/src/table/datafusion/cast.rs @@ -88,11 +88,13 @@ pub(super) fn build_field_exprs( continue; } - // Anything else destined for a json column needs its JSON leaves labelled; see - // `json_write_target`. Structs are excluded because the recursion below rebuilds them - // field by field, which also handles reordered and partial input. - if !matches!(table_field.data_type(), DataType::Struct(_)) - && let Some(target) = json_write_target(input_field, table_field) + // Keep JSON text labelled until the writer encodes it. Structs use the + // field-by-field projection below, which also handles partial input. + let json_target = match (input_field.data_type(), table_field.data_type()) { + (DataType::Struct(_), DataType::Struct(_)) => None, + _ => json_write_target(input_field, table_field)?, + }; + if let Some(target) = json_target && can_cast_types(input_field.data_type(), target.data_type()) { // The label goes on the cast's target field rather than the field returned @@ -346,76 +348,135 @@ fn arrow_json_field(table_field: &Field, storage: &DataType) -> Field { .with_metadata(metadata) } -/// Rewrite `table_field` so that every lance.json leaf the input supplies as text becomes an -/// arrow.json leaf, leaving the rest of the shape untouched. +/// Choose the field to write for a JSON column or a container of JSON columns. /// -/// Lance-core encodes JSON text into JSONB on write, but only for leaves labelled arrow.json. -/// Casting to the lance.json storage type instead relabels raw text as JSONB, which appends -/// successfully but leaves the column unreadable, so the label has to reach every leaf however -/// deeply it is nested. Returns `None` when there is nothing to relabel. -fn json_write_target(input_field: &Field, table_field: &Field) -> Option { - if is_json_field(table_field) { - let storage = if is_arrow_json_field(input_field) { - input_field.data_type().clone() - } else { - arrow_json_storage_type(input_field.data_type())? - }; - return Some(arrow_json_field(table_field, &storage)); +/// Check the original fields before attaching the destination metadata. A cast to +/// LargeBinary can attach the `lance.json` marker without encoding the bytes. +fn json_write_target(input: &Field, target: &Field) -> Result> { + if input.data_type() == &DataType::Null || !has_json_fields(target) { + return Ok(None); + } + if is_json_field(target) { + if is_json_field(input) { + return Ok(None); + } + let storage = + arrow_json_storage_type(input.data_type()).ok_or_else(|| Error::InvalidInput { + message: format!( + "field '{}' requires JSON text or a JSONB column marked as lance.json, got {}", + input.name(), + input.data_type(), + ), + })?; + return Ok(Some(arrow_json_field(target, &storage))); } - if !has_json_fields(table_field) { - return None; - } - - let relabelled = match (input_field.data_type(), table_field.data_type()) { + let data_type = match (input.data_type(), target.data_type()) { ( DataType::List(input_item) | DataType::LargeList(input_item) - | DataType::FixedSizeList(input_item, _), - DataType::List(table_item) - | DataType::LargeList(table_item) - | DataType::FixedSizeList(table_item, _), + | DataType::FixedSizeList(input_item, _) + | DataType::ListView(input_item) + | DataType::LargeListView(input_item), + DataType::List(target_item) + | DataType::LargeList(target_item) + | DataType::FixedSizeList(target_item, _), ) => { - let item: FieldRef = Arc::new(json_write_target(input_item, table_item)?); - match table_field.data_type() { + let Some(item) = json_write_target(input_item, target_item)? else { + return Ok(None); + }; + let item = Arc::new(item); + match target.data_type() { DataType::List(_) => DataType::List(item), DataType::LargeList(_) => DataType::LargeList(item), DataType::FixedSizeList(_, len) => DataType::FixedSizeList(item, *len), _ => unreachable!("matched a list type above"), } } - (DataType::Map(input_entries, _), DataType::Map(table_entries, sorted)) => { - let entries = json_write_target(input_entries, table_entries)?; + (DataType::Map(input_entries, _), DataType::Map(target_entries, sorted)) + if let (DataType::Struct(input_fields), DataType::Struct(target_fields)) = + (input_entries.data_type(), target_entries.data_type()) => + { + // Arrow casts map keys and values by position. + let Some(fields) = json_struct_write_fields(input_fields, target_fields, false)? else { + return Ok(None); + }; + let entries = target_entries + .as_ref() + .clone() + .with_data_type(DataType::Struct(fields)); DataType::Map(Arc::new(entries), *sorted) } - (DataType::Struct(input_children), DataType::Struct(table_children)) => { - let mut children = Vec::with_capacity(table_children.len()); - let mut relabelled_any = false; - for table_child in table_children { - let relabelled_child = input_children + (DataType::Struct(input_fields), DataType::Struct(target_fields)) => { + // Arrow may fall back to position while DataFusion matches by name. + // Require unambiguous names before assigning JSON types to a struct. + if input_fields.len() == target_fields.len() + && !target_fields .iter() - .find(|f| f.name() == table_child.name()) - .and_then(|input_child| json_write_target(input_child, table_child)); - match relabelled_child { - Some(child) => { - relabelled_any = true; - children.push(Arc::new(child)); - } - None => children.push(table_child.clone()), - } + .all(|field| input_fields.find(field.name()).is_some()) + { + return Err(Error::InvalidInput { + message: format!( + "cannot match JSON struct fields by name in '{}'", + input.name() + ), + }); } - if !relabelled_any { - return None; - } - DataType::Struct(children.into()) + let Some(fields) = json_struct_write_fields(input_fields, target_fields, true)? else { + return Ok(None); + }; + DataType::Struct(fields) + } + (DataType::Dictionary(_, values), _) => { + return json_write_target( + &input.clone().with_data_type(values.as_ref().clone()), + target, + ); + } + (DataType::RunEndEncoded(_, values), _) => { + return json_write_target( + &input.clone().with_data_type(values.data_type().clone()), + target, + ); + } + _ => { + return Err(Error::InvalidInput { + message: format!( + "cannot cast field '{}' from {} to {} containing JSON", + input.name(), + input.data_type(), + target.data_type(), + ), + }); } - _ => return None, }; - Some( - Field::new(table_field.name(), relabelled, table_field.is_nullable()) - .with_metadata(table_field.metadata().clone()), - ) + Ok(Some(target.clone().with_data_type(data_type))) +} + +fn json_struct_write_fields( + input: &Fields, + target: &Fields, + match_by_name: bool, +) -> Result> { + let mut fields = Vec::with_capacity(target.len()); + let mut converted = false; + for (index, target_field) in target.iter().enumerate() { + let input_field = if match_by_name { + input.find(target_field.name()).map(|(_, field)| field) + } else { + input.get(index) + }; + if let Some(input_field) = input_field + && let Some(field) = json_write_target(input_field, target_field)? + { + converted = true; + fields.push(Arc::new(field)); + } else { + fields.push(target_field.clone()); + } + } + Ok(converted.then(|| fields.into())) } // The field's metadata is attached to the literal itself, because DataFusion derives the @@ -1081,6 +1142,80 @@ mod tests { assert_eq!(result.num_rows(), 2); } + #[rstest::rstest] + #[case::struct_field("struct", "field 'b' requires JSON text")] + #[case::large_list("large_list", "field 'b' requires JSON text")] + #[case::fixed_size_list("fixed_size_list", "field 'b' requires JSON text")] + #[case::list_view("list_view", "field 'b' requires JSON text")] + #[case::large_list_view("large_list_view", "field 'b' requires JSON text")] + #[case::map("map", "field 'b' requires JSON text")] + #[case::ambiguous_names("ambiguous", "cannot match JSON struct fields by name")] + fn test_nested_json_projection_rejects_unmarked_bytes( + #[case] container: &str, + #[case] diagnostic: &str, + ) { + use datafusion_physical_plan::empty::EmptyExec; + use lance_arrow::json::json_field; + + let wrap = |children: Vec, is_input: bool| { + let structure = DataType::Struct(children.into()); + let item = Arc::new(Field::new_list_field(structure.clone(), true)); + let data_type = match container { + "struct" => structure, + "large_list" => DataType::LargeList(item), + "fixed_size_list" => DataType::FixedSizeList(item, 1), + "list_view" if is_input => DataType::ListView(item), + "large_list_view" if is_input => DataType::LargeListView(item), + "list_view" | "large_list_view" | "ambiguous" => DataType::List(item), + "map" => DataType::Map( + Arc::new(Field::new( + "entries", + DataType::Struct( + vec![ + Field::new("key", DataType::Utf8, false), + Field::new("value", structure, true), + ] + .into(), + ), + false, + )), + false, + ), + _ => unreachable!(), + }; + Schema::new(vec![Field::new("docs", data_type, true)]) + }; + let input_fields = if container == "ambiguous" { + // A positional match would validate the marked first field as b. + // DataFusion's name-based cast would use the unmarked field instead. + vec![ + json_field("extra", true), + Field::new("b", DataType::LargeBinary, true), + ] + } else { + vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::LargeBinary, true), + ] + }; + let target_fields = if container == "ambiguous" { + vec![ + json_field("b", true), + Field::new("a", DataType::LargeBinary, true), + ] + } else { + vec![json_field("a", true), json_field("b", true)] + }; + let input = wrap(input_fields, true); + let target = wrap(target_fields, false); + let error = cast_to_table_schema(Arc::new(EmptyExec::new(Arc::new(input))), &target) + .expect_err("a cast must not mark raw bytes as JSONB"); + assert!( + matches!(&error, crate::Error::InvalidInput { message } if message.contains(diagnostic)), + "{error}" + ); + } + /// The same, for a json column nested inside a struct: the struct is rebuilt from its /// children, so the label has to travel on the child field. #[tokio::test] diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 5f9363dcd..8a72501b6 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -1196,6 +1196,141 @@ mod lsm_tests { assert_eq!(result.num_rows, 4); } + #[tokio::test] + async fn lsm_merge_insert_validates_nested_json_before_writing() { + use arrow_array::{Array, ArrayRef, LargeBinaryArray, ListArray, NullArray, StructArray}; + use arrow_buffer::OffsetBuffer; + use arrow_schema::FieldRef; + use lance_arrow::json::{JsonArray, json_field}; + + fn docs_batch(ids: Vec, fields: Vec<(FieldRef, ArrayRef)>) -> RecordBatch { + let docs = StructArray::from(fields); + let docs_item = Arc::new(Field::new_list_field(docs.data_type().clone(), true)); + let offsets = OffsetBuffer::from_lengths(std::iter::repeat_n(1, ids.len())); + let docs = ListArray::new(docs_item, offsets, Arc::new(docs), None); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("docs", docs.data_type().clone(), true), + ])); + RecordBatch::try_new( + schema, + vec![Arc::new(Int64Array::from(ids)), Arc::new(docs)], + ) + .unwrap() + } + + let jsonb = |values: &[Option<&str>]| -> ArrayRef { + Arc::new( + JsonArray::try_from_iter(values.iter().copied()) + .unwrap() + .into_inner(), + ) + }; + let a = Arc::new(json_field("a", true)); + let b = Arc::new(json_field("b", true)); + let seed = docs_batch( + vec![1], + vec![ + (a, jsonb(&[Some(r#"{"k":0}"#)])), + (b.clone(), jsonb(&[Some(r#"{"k":0}"#)])), + ], + ); + let dir = tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let db = connect(uri).execute().await.unwrap(); + let table = db.create_table("t", seed).execute().await.unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + + let a = Arc::new(Field::new("a", DataType::Utf8, true)); + let source = docs_batch( + vec![1, 2], + vec![ + ( + a.clone(), + Arc::new(StringArray::from(vec![r#"{"k":9}"#, r#"{"k":10}"#])), + ), + ( + Arc::new(Field::new("b", DataType::LargeBinary, true)), + Arc::new(LargeBinaryArray::from(vec![ + br#"{"k":9}"#.as_slice(), + br#"{"k":10}"#.as_slice(), + ])), + ), + ], + ); + let reader = |batch: RecordBatch| -> Box { + let schema = batch.schema(); + Box::new(RecordBatchIterator::new([Ok(batch)], schema)) + }; + let upsert = |table: &Table| { + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + merge + }; + let error = upsert(&table) + .execute(reader(source)) + .await + .expect_err("an unmarked binary JSON leaf must be refused"); + assert!( + matches!(&error, Error::InvalidInput { message } if message.contains("field 'b' requires JSON text")), + "{error}" + ); + + table.close_rte_writers().await.unwrap(); + let reopened = connect(uri) + .execute() + .await + .unwrap() + .open_table("t") + .execute() + .await + .unwrap(); + assert_eq!( + collect_ids(reopened.query().execute().await.unwrap()).await, + vec![1] + ); + let original = reopened.query() + .only_if("json_extract(get_field(docs[1], 'a'), '$.k') = '0' AND json_extract(get_field(docs[1], 'b'), '$.k') = '0'") + .execute().await.unwrap(); + assert_eq!(collect_ids(original).await, vec![1]); + + let valid = docs_batch( + vec![1], + vec![ + (a.clone(), Arc::new(StringArray::from(vec![r#"{"k":9}"#]))), + (b, jsonb(&[Some(r#"{"k":8}"#)])), + ], + ); + let null = docs_batch( + vec![2], + vec![ + (a, Arc::new(StringArray::from(vec![r#"{"k":10}"#]))), + ( + Arc::new(Field::new("b", DataType::Null, true)), + Arc::new(NullArray::new(1)), + ), + ], + ); + for batch in [valid, null] { + let result = upsert(&reopened).execute(reader(batch)).await.unwrap(); + assert_eq!(result.num_rows, 1); + assert_eq!(result.version, 0); + } + reopened.close_rte_writers().await.unwrap(); + let reopened = db.open_table("t").execute().await.unwrap(); + let mixed = reopened.query() + .only_if("json_extract(get_field(docs[1], 'a'), '$.k') = '9' AND json_extract(get_field(docs[1], 'b'), '$.k') = '8'") + .execute().await.unwrap(); + assert_eq!(collect_ids(mixed).await, vec![1]); + let with_null = reopened.query() + .only_if("get_field(docs[1], 'b') IS NULL AND json_extract(get_field(docs[1], 'a'), '$.k') = '10'") + .execute().await.unwrap(); + assert_eq!(collect_ids(with_null).await, vec![2]); + } + #[tokio::test] async fn lsm_merge_insert_identity() { let dir = tempdir().unwrap(); diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index e32b1a289..b4eef096e 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -34,6 +34,7 @@ use lance::dataset::mem_wal::{ evaluate_sharding_spec, validate_maintained_indexes_with, }; use lance::index::DatasetIndexExt; +use lance_arrow::json::{convert_json_columns, has_arrow_json_fields}; use lance_core::datatypes::Schema as LanceSchema; use lance_index::mem_wal::{MemWalIndexDetails, ShardingField, ShardingSpec}; use tokio::sync::RwLock; @@ -813,6 +814,11 @@ pub(crate) async fn execute_lsm_merge_insert( ) -> Result { let dataset = table.dataset.get().await?; let target_schema: SchemaRef = Arc::new(ArrowSchema::from(dataset.schema())); + let encode_json = new_data + .schema() + .fields() + .iter() + .any(|field| has_arrow_json_fields(field)); // Collect, align and shard-validate the whole input before writing // anything. `ShardWriter::put` is atomic over the batch vector, so any @@ -824,6 +830,12 @@ pub(crate) async fn execute_lsm_merge_insert( if batch.num_rows() == 0 { continue; } + // The shard writer expects physical storage types, including JSONB. + let batch = if encode_json { + convert_json_columns(&batch).map_err(|source| Error::Arrow { source })? + } else { + batch + }; let batch = align_batch_schema(batch, &target_schema)?; total_rows += batch.num_rows() as u64; batches.push(batch);