This is an automated email from the ASF dual-hosted git repository.

CurtHagenlocher pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-dotnet.git


The following commit(s) were added to refs/heads/main by this push:
     new aad9dc1  fix: Allow a StructType with no fields (#514)
aad9dc1 is described below

commit aad9dc1eeae3b99693ef94c740adf54af2d38714
Author: Curt Hagenlocher <[email protected]>
AuthorDate: Fri Nov 27 05:31:37 2026 -0800

    fix: Allow a StructType with no fields (#514)
    
    ## What's Changed
    
    The Arrow format allows a struct, or a union, with no children.
    pyarrow's `struct<>` is an example. Apache.Arrow refused these in three
    places, and this PR fixes all three:
    
    - **`NestedType`:** the list constructor treated an empty field list
    like `null` and threw `ArgumentNullException("fields")`. It now throws
    only for `null`. `StructType` and `UnionType` are the only types that
    use this constructor.
    - **IPC reader (`MessageSerializer`):** a field with no children has
    `childFields == null`. The `Struct_` and `Union` cases now build the
    type with no children instead of asserting that `childFields` is
    non-null.
    - **C data interface (`CArrowSchemaExporter`):** a nested type with zero
    children is now exported as `n_children = 0` with a null `children`
    pointer, which the C data interface allows. It used to throw
    `NotSupportedException`.
    
    Because the type change also allows a union with no children, two union
    paths needed fixing as well (from review):
    
    - **C data import (`CArrowSchemaImporter`):** the empty type-id list
    that the exporter writes (`+us:` / `+ud:`) failed to import, because the
    parser always read at least one code.
    - **IPC reader:** a union's `typeIds` is optional in `Schema.fbs`, and
    without it the ids are the children's offsets. Reading a union without
    the vector threw `ArgumentNullException`, with or without children. It
    now defaults to `0..n-1`.
    
    The new `EmptyStructTests` cover:
    - the type and the array, including slicing and validity
    - round-trips through the IPC stream format, the IPC file format and the
    C data interface, both as a top-level column and as the item type of a
    list
    - concatenation
    - an empty union through the C data interface and the IPC stream format,
    in both modes
    - a schema flatbuffer whose union omits `typeIds`, with zero and with
    two children
    
    `EmptyStructPythonTests` (in the `PythonNet` collection, which CI runs
    against pyarrow) checks interop with pyarrow in both directions:
    - a batch with `struct<>`, `list<struct<>>` and an int column through
    the C data interface, pyarrow to C# and C# to pyarrow (pyarrow validates
    with `full=True` and compares schema and values)
    - the same batch through the IPC stream format, written by each side and
    read by the other
    - `sparse_union<>` and `dense_union<>` through the C data interface,
    both directions
    
    All eight fail against main's source and pass with this change (locally
    with pyarrow 24, on net8.0, net462 and net472).
    
    Closes #513.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 src/Apache.Arrow/C/CArrowSchemaExporter.cs        |   4 +-
 src/Apache.Arrow/C/CArrowSchemaImporter.cs        |   5 +-
 src/Apache.Arrow/Ipc/MessageSerializer.cs         |  21 +-
 src/Apache.Arrow/Types/NestedType.cs              |   5 +-
 test/Apache.Arrow.Tests/EmptyStructPythonTests.cs | 261 ++++++++++++++++++++++
 test/Apache.Arrow.Tests/EmptyStructTests.cs       | 251 +++++++++++++++++++++
 6 files changed, 538 insertions(+), 9 deletions(-)

diff --git a/src/Apache.Arrow/C/CArrowSchemaExporter.cs 
b/src/Apache.Arrow/C/CArrowSchemaExporter.cs
index da875c0..10d8b35 100644
--- a/src/Apache.Arrow/C/CArrowSchemaExporter.cs
+++ b/src/Apache.Arrow/C/CArrowSchemaExporter.cs
@@ -280,7 +280,9 @@ namespace Apache.Arrow.C
                 numChildren = numFields;
                 if (numFields == 0)
                 {
-                    throw new NotSupportedException("Exporting nested data 
types with zero children.");
+                    // A struct or a union may have no children; the C data 
interface allows a null children
+                    // pointer when n_children is 0.
+                    return null;
                 }
 
                 var pointerList = 
(CArrowSchema**)Marshal.AllocHGlobal(numFields * IntPtr.Size);
diff --git a/src/Apache.Arrow/C/CArrowSchemaImporter.cs 
b/src/Apache.Arrow/C/CArrowSchemaImporter.cs
index dfa5c08..2d8c826 100644
--- a/src/Apache.Arrow/C/CArrowSchemaImporter.cs
+++ b/src/Apache.Arrow/C/CArrowSchemaImporter.cs
@@ -316,7 +316,8 @@ namespace Apache.Arrow.C
                     UnionMode unionMode = format[2] == 'd' ? UnionMode.Dense : 
UnionMode.Sparse;
                     List<int> typeIds = new List<int>();
                     int pos = 4;
-                    do
+                    // A union with no children has an empty type-id list 
("+us:" or "+ud:").
+                    while (pos < format.Length)
                     {
                         int next = format.IndexOf(',', pos);
                         if (next < 0) { next = format.Length; }
@@ -329,7 +330,7 @@ namespace Apache.Arrow.C
                         typeIds.Add(code);
 
                         pos = next + 1;
-                    } while (pos < format.Length);
+                    }
 
                     return new UnionType(ParseChildren("union", 
extensionRegistry), typeIds, unionMode);
                 }
diff --git a/src/Apache.Arrow/Ipc/MessageSerializer.cs 
b/src/Apache.Arrow/Ipc/MessageSerializer.cs
index 675f946..b987ecf 100644
--- a/src/Apache.Arrow/Ipc/MessageSerializer.cs
+++ b/src/Apache.Arrow/Ipc/MessageSerializer.cs
@@ -15,7 +15,6 @@
 
 using System;
 using System.Collections.Generic;
-using System.Diagnostics;
 using System.IO;
 using Apache.Arrow.Types;
 
@@ -132,6 +131,16 @@ namespace Apache.Arrow.Ipc
             return arrowField;
         }
 
+        private static int[] DefaultUnionTypeIds(int childCount)
+        {
+            var typeIds = new int[childCount];
+            for (int i = 0; i < childCount; i++)
+            {
+                typeIds[i] = i;
+            }
+            return typeIds;
+        }
+
         private static Types.IArrowType GetFieldArrowType(Flatbuf.Field field, 
Field[] childFields = null)
         {
             switch (field.TypeType)
@@ -251,12 +260,14 @@ namespace Apache.Arrow.Ipc
                     Flatbuf.FixedSizeList fixedSizeListMetadata = 
field.Type<Flatbuf.FixedSizeList>().Value;
                     return new Types.FixedSizeListType(childFields[0], 
fixedSizeListMetadata.ListSize);
                 case Flatbuf.Type.Struct_:
-                    Debug.Assert(childFields != null);
-                    return new Types.StructType(childFields);
+                    // A struct or a union may have no children.
+                    return new Types.StructType(childFields ?? 
System.Array.Empty<Field>());
                 case Flatbuf.Type.Union:
-                    Debug.Assert(childFields != null);
                     Flatbuf.Union unionMetadata = 
field.Type<Flatbuf.Union>().Value;
-                    return new Types.UnionType(childFields, 
unionMetadata.GetTypeIdsArray(), unionMetadata.Mode.ToArrow());
+                    Field[] unionFields = childFields ?? 
System.Array.Empty<Field>();
+                    // typeIds is optional; without it, the ids in the type 
vector are the children's offsets.
+                    int[] typeIds = unionMetadata.GetTypeIdsArray() ?? 
DefaultUnionTypeIds(unionFields.Length);
+                    return new Types.UnionType(unionFields, typeIds, 
unionMetadata.Mode.ToArrow());
                 case Flatbuf.Type.Map:
                     if (childFields == null || childFields.Length != 1)
                     {
diff --git a/src/Apache.Arrow/Types/NestedType.cs 
b/src/Apache.Arrow/Types/NestedType.cs
index 1e60e95..ab57b03 100644
--- a/src/Apache.Arrow/Types/NestedType.cs
+++ b/src/Apache.Arrow/Types/NestedType.cs
@@ -25,9 +25,12 @@ namespace Apache.Arrow.Types
 
         public IReadOnlyList<Field> Fields { get; }
 
+        /// <remarks>
+        /// <paramref name="fields"/> may be empty: the Arrow format allows a 
struct or a union with no children.
+        /// </remarks>
         protected NestedType(IReadOnlyList<Field> fields)
         {
-            if (fields == null || fields.Count == 0)
+            if (fields == null)
             {
                 throw new ArgumentNullException(nameof(fields));
             }
diff --git a/test/Apache.Arrow.Tests/EmptyStructPythonTests.cs 
b/test/Apache.Arrow.Tests/EmptyStructPythonTests.cs
new file mode 100644
index 0000000..3c1d6c0
--- /dev/null
+++ b/test/Apache.Arrow.Tests/EmptyStructPythonTests.cs
@@ -0,0 +1,261 @@
+// 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.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Apache.Arrow.C;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Types;
+using Python.Runtime;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// Structs and unions with no children, exchanged with pyarrow through 
the C data interface and the IPC
+    /// stream format, in both directions.
+    /// </summary>
+    [Collection("PythonNet")]
+    public class EmptyStructPythonTests
+    {
+        public EmptyStructPythonTests(PythonNetFixture pythonNet)
+        {
+            pythonNet.EnsureInitialized();
+        }
+
+        /// <summary>
+        /// What <see cref="EmptyStructTests.Batch"/> holds, built by pyarrow. 
<c>check(batch)</c> validates a
+        /// batch fully and returns an empty string when it matches, or a 
description of the difference.
+        /// </summary>
+        private const string ExpectedBatch = @"
+import pyarrow as pa
+
+expected = pa.record_batch(
+    [
+        pa.array([{}, None, {}], type=pa.struct([])),
+        pa.array([[{}, None], [], [{}]], type=pa.list_(pa.field('item', 
pa.struct([]), nullable=True))),
+        pa.array([1, 2, 3], type=pa.int32()),
+    ],
+    schema=pa.schema([
+        pa.field('empty', pa.struct([]), nullable=True),
+        pa.field('list_of_empty', pa.list_(pa.field('item', pa.struct([]), 
nullable=True)), nullable=True),
+        pa.field('ints', pa.int32(), nullable=False),
+    ]))
+
+def check(batch):
+    batch.validate(full=True)
+    if not batch.schema.equals(expected.schema):
+        return 'schema: ' + str(batch.schema)
+    if batch.to_pylist() != expected.to_pylist():
+        return 'values: ' + str(batch.to_pylist())
+    return ''
+";
+
+        private static void AssertIsExpectedBatch(RecordBatch batch)
+        {
+            Assert.Equal(3, batch.Length);
+            var empty = (StructArray)batch.Column("empty");
+            Assert.Empty(((StructType)empty.Data.DataType).Fields);
+            Assert.True(empty.IsValid(0));
+            Assert.True(empty.IsNull(1));
+            Assert.True(empty.IsValid(2));
+
+            var list = (ListArray)batch.Column("list_of_empty");
+            Assert.Equal(new[] { 0, 2, 2, 3 }, list.ValueOffsets.ToArray());
+            var items = (StructArray)list.Values;
+            Assert.Empty(((StructType)items.Data.DataType).Fields);
+            Assert.True(items.IsValid(0));
+            Assert.True(items.IsNull(1));
+            Assert.True(items.IsValid(2));
+
+            Assert.Equal(new[] { 1, 2, 3 }, 
((Int32Array)batch.Column("ints")).Values.ToArray());
+        }
+
+        [SkippableFact]
+        public unsafe void ABatchFromPyarrow_ImportsThroughTheCDataInterface()
+        {
+            CArrowArray* cArray = CArrowArray.Create();
+            CArrowSchema* cSchema = CArrowSchema.Create();
+            try
+            {
+                using (Py.GIL())
+                using (PyModule scope = Py.CreateScope())
+                {
+                    scope.Exec(ExpectedBatch);
+                    scope.Get("expected").InvokeMethod(
+                        "_export_to_c",
+                        new PyInt(((IntPtr)cArray).ToInt64()),
+                        new PyInt(((IntPtr)cSchema).ToInt64()));
+                }
+
+                Schema schema = CArrowSchemaImporter.ImportSchema(cSchema);
+                using RecordBatch batch = 
CArrowArrayImporter.ImportRecordBatch(cArray, schema);
+                AssertIsExpectedBatch(batch);
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+                CArrowSchema.Free(cSchema);
+            }
+        }
+
+        [SkippableFact]
+        public unsafe void 
ABatchExportedThroughTheCDataInterface_ReadsInPyarrow()
+        {
+            RecordBatch batch = EmptyStructTests.Batch();
+            CArrowArray* cArray = CArrowArray.Create();
+            CArrowSchema* cSchema = CArrowSchema.Create();
+            try
+            {
+                CArrowSchemaExporter.ExportSchema(batch.Schema, cSchema);
+                CArrowArrayExporter.ExportRecordBatch(batch, cArray);
+
+                using (Py.GIL())
+                using (PyModule scope = Py.CreateScope())
+                {
+                    scope.Exec(ExpectedBatch);
+                    scope.Set("array_ptr", ((IntPtr)cArray).ToInt64());
+                    scope.Set("schema_ptr", ((IntPtr)cSchema).ToInt64());
+                    scope.Exec("result = 
check(pa.RecordBatch._import_from_c(array_ptr, schema_ptr))");
+                    Assert.Equal("", scope.Get<string>("result"));
+                }
+            }
+            finally
+            {
+                // pyarrow took ownership by calling release; Free only 
releases what is still unreleased.
+                CArrowArray.Free(cArray);
+                CArrowSchema.Free(cSchema);
+            }
+        }
+
+        [SkippableFact]
+        public void AStreamWrittenByPyarrow_Reads()
+        {
+            string path = Path.Combine(Path.GetTempPath(), 
$"arrow_empty_struct_{Guid.NewGuid():N}.arrows");
+            try
+            {
+                using (Py.GIL())
+                using (PyModule scope = Py.CreateScope())
+                {
+                    scope.Exec(ExpectedBatch);
+                    scope.Set("path", path);
+                    scope.Exec(@"
+with pa.OSFile(path, 'wb') as sink:
+    with pa.ipc.new_stream(sink, expected.schema) as writer:
+        writer.write_batch(expected)
+");
+                }
+
+                using var stream = File.OpenRead(path);
+                using var reader = new ArrowStreamReader(stream);
+                AssertIsExpectedBatch(reader.ReadNextRecordBatch());
+            }
+            finally
+            {
+                File.Delete(path);
+            }
+        }
+
+        [SkippableFact]
+        public void AStreamWrittenHere_ReadsInPyarrow()
+        {
+            RecordBatch batch = EmptyStructTests.Batch();
+            string path = Path.Combine(Path.GetTempPath(), 
$"arrow_empty_struct_{Guid.NewGuid():N}.arrows");
+            try
+            {
+                using (var stream = File.Create(path))
+                using (var writer = new ArrowStreamWriter(stream, 
batch.Schema))
+                {
+                    writer.WriteRecordBatch(batch);
+                    writer.WriteEnd();
+                }
+
+                using (Py.GIL())
+                using (PyModule scope = Py.CreateScope())
+                {
+                    scope.Exec(ExpectedBatch);
+                    scope.Set("path", path);
+                    scope.Exec(@"
+with pa.OSFile(path, 'rb') as source:
+    batches = pa.ipc.open_stream(source).read_all().to_batches()
+result = check(batches[0]) if len(batches) == 1 else 'batches: ' + 
str(len(batches))
+");
+                    Assert.Equal("", scope.Get<string>("result"));
+                }
+            }
+            finally
+            {
+                File.Delete(path);
+            }
+        }
+
+        [SkippableTheory]
+        [InlineData("sparse")]
+        [InlineData("dense")]
+        public unsafe void AnEmptyUnionTypeFromPyarrow_Imports(string mode)
+        {
+            CArrowSchema* cSchema = CArrowSchema.Create();
+            try
+            {
+                using (Py.GIL())
+                using (PyModule scope = Py.CreateScope())
+                {
+                    scope.Set("schema_ptr", ((IntPtr)cSchema).ToInt64());
+                    scope.Exec($"import pyarrow as 
pa\npa.{mode}_union([])._export_to_c(schema_ptr)");
+                }
+
+                var type = (UnionType)CArrowSchemaImporter.ImportType(cSchema);
+                Assert.Equal(mode == "sparse" ? UnionMode.Sparse : 
UnionMode.Dense, type.Mode);
+                Assert.Empty(type.Fields);
+                Assert.Empty(type.TypeIds);
+            }
+            finally
+            {
+                CArrowSchema.Free(cSchema);
+            }
+        }
+
+        [SkippableTheory]
+        [InlineData(UnionMode.Sparse)]
+        [InlineData(UnionMode.Dense)]
+        public unsafe void 
AnEmptyUnionTypeExportedHere_ImportsInPyarrow(UnionMode mode)
+        {
+            CArrowSchema* cSchema = CArrowSchema.Create();
+            try
+            {
+                CArrowSchemaExporter.ExportType(new UnionType(new 
List<Field>(), new int[0], mode), cSchema);
+
+                using (Py.GIL())
+                using (PyModule scope = Py.CreateScope())
+                {
+                    scope.Set("schema_ptr", ((IntPtr)cSchema).ToInt64());
+                    scope.Set("mode", mode == UnionMode.Sparse ? "sparse" : 
"dense");
+                    scope.Exec(@"
+import pyarrow as pa
+imported = pa.DataType._import_from_c(schema_ptr)
+expected = pa.sparse_union([]) if mode == 'sparse' else pa.dense_union([])
+result = '' if imported.equals(expected) else str(imported)
+");
+                    Assert.Equal("", scope.Get<string>("result"));
+                }
+            }
+            finally
+            {
+                CArrowSchema.Free(cSchema);
+            }
+        }
+    }
+}
diff --git a/test/Apache.Arrow.Tests/EmptyStructTests.cs 
b/test/Apache.Arrow.Tests/EmptyStructTests.cs
new file mode 100644
index 0000000..826ac1b
--- /dev/null
+++ b/test/Apache.Arrow.Tests/EmptyStructTests.cs
@@ -0,0 +1,251 @@
+// 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.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Apache.Arrow.C;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// The Arrow format allows a struct with no fields; other implementations 
(C++, Rust, Java) create and
+    /// exchange them.
+    /// </summary>
+    public class EmptyStructTests
+    {
+        internal static readonly StructType EmptyStruct = new StructType(new 
List<Field>());
+
+        /// <summary>Three rows, the second null.</summary>
+        internal static StructArray EmptyStructArray()
+        {
+            ArrowBuffer validity = new 
ArrowBuffer.BitmapBuilder().Append(true).Append(false).Append(true).Build();
+            return new StructArray(EmptyStruct, 3, new List<IArrowArray>(), 
validity, nullCount: 1);
+        }
+
+        /// <summary>An empty struct column, a list of empty structs, and an 
int column; three rows.</summary>
+        internal static RecordBatch Batch()
+        {
+            var listType = new ListType(new Field("item", EmptyStruct, true));
+            var offsets = new 
ArrowBuffer.Builder<int>().Append(0).Append(2).Append(2).Append(3).Build();
+            var list = new ListArray(listType, 3, offsets, EmptyStructArray(), 
ArrowBuffer.Empty, 0);
+
+            var schema = new Schema.Builder()
+                .Field(f => 
f.Name("empty").DataType(EmptyStruct).Nullable(true))
+                .Field(f => 
f.Name("list_of_empty").DataType(listType).Nullable(true))
+                .Field(f => 
f.Name("ints").DataType(Int32Type.Default).Nullable(false))
+                .Build();
+            var ints = new 
Int32Array.Builder().Append(1).Append(2).Append(3).Build();
+            return new RecordBatch(schema, new IArrowArray[] { 
EmptyStructArray(), list, ints }, 3);
+        }
+
+        [Fact]
+        public void AStructTypeMayHaveNoFields()
+        {
+            Assert.Empty(EmptyStruct.Fields);
+            Assert.Equal(-1, EmptyStruct.GetFieldIndex("a"));
+            Assert.Null(EmptyStruct.GetFieldByName("a"));
+        }
+
+        [Fact]
+        public void NullFieldsAreStillRefused()
+        {
+            Assert.Throws<ArgumentNullException>(() => new StructType(null));
+        }
+
+        [Fact]
+        public void AStructArrayMayHaveNoChildren()
+        {
+            StructArray array = EmptyStructArray();
+            Assert.Equal(3, array.Length);
+            Assert.Empty(array.Fields);
+            Assert.True(array.IsValid(0));
+            Assert.True(array.IsNull(1));
+
+            var slice = (StructArray)array.Slice(1, 2);
+            Assert.Equal(2, slice.Length);
+            Assert.True(slice.IsNull(0));
+            Assert.True(slice.IsValid(1));
+        }
+
+        [Fact]
+        public void RoundTripsThroughTheStreamFormat()
+        {
+            RecordBatch original = Batch();
+            using var stream = new MemoryStream();
+            using (var writer = new ArrowStreamWriter(stream, original.Schema, 
leaveOpen: true))
+            {
+                writer.WriteRecordBatch(original);
+                writer.WriteEnd();
+            }
+
+            stream.Position = 0;
+            using var reader = new ArrowStreamReader(stream);
+            RecordBatch read = reader.ReadNextRecordBatch();
+            ArrowReaderVerifier.CompareBatches(original, read);
+            
Assert.Empty(((StructType)read.Schema.GetFieldByName("empty").DataType).Fields);
+        }
+
+        [Fact]
+        public void RoundTripsThroughTheFileFormat()
+        {
+            RecordBatch original = Batch();
+            using var stream = new MemoryStream();
+            using (var writer = new ArrowFileWriter(stream, original.Schema, 
leaveOpen: true))
+            {
+                writer.WriteRecordBatch(original);
+                writer.WriteEnd();
+            }
+
+            stream.Position = 0;
+            using var reader = new ArrowFileReader(stream);
+            ArrowReaderVerifier.CompareBatches(original, 
reader.ReadNextRecordBatch());
+        }
+
+        [Fact]
+        public unsafe void RoundTripsThroughTheCDataInterface()
+        {
+            RecordBatch original = Batch();
+
+            CArrowSchema* cSchema = CArrowSchema.Create();
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowSchemaExporter.ExportSchema(original.Schema, cSchema);
+                CArrowArrayExporter.ExportRecordBatch(original, cArray);
+
+                Schema schema = CArrowSchemaImporter.ImportSchema(cSchema);
+                using RecordBatch imported = 
CArrowArrayImporter.ImportRecordBatch(cArray, schema);
+                // Not strict: an imported buffer is only as long as the data, 
not padded as a built one is.
+                ArrowReaderVerifier.CompareBatches(original, imported, 
strictCompare: false);
+                
Assert.Empty(((StructType)schema.GetFieldByName("empty").DataType).Fields);
+            }
+            finally
+            {
+                CArrowSchema.Free(cSchema);
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Fact]
+        public void Concatenates()
+        {
+            var result = (StructArray)ArrowArrayConcatenator.Concatenate(
+                new List<IArrowArray> { EmptyStructArray(), EmptyStructArray() 
});
+            Assert.Equal(6, result.Length);
+            Assert.Equal(2, result.NullCount);
+            Assert.True(result.IsNull(4));
+            Assert.Empty(result.Fields);
+        }
+
+        [Fact]
+        public void AUnionTypeMayHaveNoFields()
+        {
+            var union = new UnionType(new List<Field>(), new int[0], 
UnionMode.Sparse);
+            Assert.Empty(union.Fields);
+        }
+
+        /// <summary>The exporter writes "+us:" or "+ud:"; the importer 
required at least one type id.</summary>
+        [Theory]
+        [InlineData(UnionMode.Sparse)]
+        [InlineData(UnionMode.Dense)]
+        public unsafe void 
AnEmptyUnionTypeRoundTripsThroughTheCDataInterface(UnionMode mode)
+        {
+            var union = new UnionType(new List<Field>(), new int[0], mode);
+            CArrowSchema* cSchema = CArrowSchema.Create();
+            try
+            {
+                CArrowSchemaExporter.ExportType(union, cSchema);
+                var imported = 
(UnionType)CArrowSchemaImporter.ImportType(cSchema);
+                Assert.Equal(mode, imported.Mode);
+                Assert.Empty(imported.Fields);
+                Assert.Empty(imported.TypeIds);
+            }
+            finally
+            {
+                CArrowSchema.Free(cSchema);
+            }
+        }
+
+        [Theory]
+        [InlineData(UnionMode.Sparse)]
+        [InlineData(UnionMode.Dense)]
+        public void 
AnEmptyUnionColumnRoundTripsThroughTheStreamFormat(UnionMode mode)
+        {
+            var union = new UnionType(new List<Field>(), new int[0], mode);
+            var schema = new Schema.Builder().Field(f => 
f.Name("u").DataType(union).Nullable(false)).Build();
+            IArrowArray column = mode == UnionMode.Sparse
+                ? new SparseUnionArray(union, 0, new List<IArrowArray>(), 
ArrowBuffer.Empty)
+                : new DenseUnionArray(union, 0, new List<IArrowArray>(), 
ArrowBuffer.Empty, ArrowBuffer.Empty);
+            var original = new RecordBatch(schema, new[] { column }, 0);
+
+            using var stream = new MemoryStream();
+            using (var writer = new ArrowStreamWriter(stream, schema, 
leaveOpen: true))
+            {
+                writer.WriteRecordBatch(original);
+                writer.WriteEnd();
+            }
+
+            stream.Position = 0;
+            using var reader = new ArrowStreamReader(stream);
+            RecordBatch read = reader.ReadNextRecordBatch();
+            var readUnion = 
(UnionType)read.Schema.GetFieldByName("u").DataType;
+            Assert.Equal(mode, readUnion.Mode);
+            Assert.Empty(readUnion.Fields);
+            Assert.Equal(0, read.Length);
+        }
+
+        /// <summary>
+        /// The schema format makes a union's typeIds optional: without it, 
the ids in the type vector are the
+        /// children's offsets. Reading a union without it threw 
ArgumentNullException, with children or without.
+        /// </summary>
+        [Theory]
+        [InlineData(0)]
+        [InlineData(2)]
+        public void AUnionWithoutTypeIds_TakesTheChildOffsets(int childCount)
+        {
+            var builder = new Google.FlatBuffers.FlatBufferBuilder(256);
+
+            var children = new 
Google.FlatBuffers.Offset<Flatbuf.Field>[childCount];
+            for (int i = 0; i < childCount; i++)
+            {
+                var childName = builder.CreateString("c" + i);
+                var intType = Flatbuf.Int.CreateInt(builder, 32, true);
+                children[i] = Flatbuf.Field.CreateField(builder, childName, 
true, Flatbuf.Type.Int, intType.Value);
+            }
+            var childrenVector = Flatbuf.Field.CreateChildrenVector(builder, 
children);
+
+            var name = builder.CreateString("u");
+            var union = Flatbuf.Union.CreateUnion(builder, 
Flatbuf.UnionMode.Dense); // no typeIds vector
+            var field = Flatbuf.Field.CreateField(
+                builder, name, false, Flatbuf.Type.Union, union.Value, 
childrenOffset: childrenVector);
+            var fields = Flatbuf.Schema.CreateFieldsVector(builder, new[] { 
field });
+            builder.Finish(Flatbuf.Schema.CreateSchema(builder, fieldsOffset: 
fields).Value);
+
+            var flatbufSchema = 
Flatbuf.Schema.GetRootAsSchema(builder.DataBuffer);
+            Assert.Equal(0, 
flatbufSchema.Fields(0).Value.Type<Flatbuf.Union>().Value.TypeIdsLength);
+
+            DictionaryMemo memo = null;
+            Schema schema = MessageSerializer.GetSchema(flatbufSchema, ref 
memo);
+            var type = (UnionType)schema.FieldsList[0].DataType;
+            Assert.Equal(UnionMode.Dense, type.Mode);
+            Assert.Equal(childCount, type.Fields.Count);
+            Assert.Equal(System.Linq.Enumerable.Range(0, childCount), 
type.TypeIds);
+        }
+    }
+}

Reply via email to