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 0bcf7df  Resolve extension types when importing C array streams (#472)
0bcf7df is described below

commit 0bcf7dfd3c42c413085ad3fa25ece353505e74a1
Author: Curt Hagenlocher <[email protected]>
AuthorDate: Sun Oct 18 16:27:33 2026 -0700

    Resolve extension types when importing C array streams (#472)
    
    ## What's Changed
    
    Adds overloads that take an `ExtensionTypeRegistry`:
    
    ```csharp
    CArrowArrayStreamImporter.ImportArrayStream(CArrowArrayStream* ptr, 
ExtensionTypeRegistry extensionRegistry)
    
CArrowDeviceArrayStreamImporter.ImportDeviceArrayStream(CArrowDeviceArrayStream*
 ptr, ExtensionTypeRegistry extensionRegistry)
    ```
    
    These import the stream's schema with the registry. The record batch
    importer already builds extension arrays when a field's type is an
    `ExtensionType`, so a `arrow.uuid` column from a native producer now
    comes back as a `GuidType` field with a `GuidArray`, rather than a
    `FixedSizeBinaryArray` that only has the extension name in its metadata.
    The existing overloads behave as before. The device stream importer had
    the same gap, so it gets the same overload.
    
    ### Nested fields
    
    `CArrowSchemaImporter` previously applied the registry only to top-level
    fields, so `list<arrow.uuid>` still imported as a list of
    `FixedSizeBinary` even with a registry. The registry is now threaded
    through child fields of list, large list, list view, large list view,
    fixed-size list, struct, map, union and run-end encoded types, and
    dictionary value types. This affects `ImportSchema` and `ImportField`
    with a registry as well as the new stream overloads. As a side effect,
    `GetAsSchema` no longer parses the top-level fields twice when a
    registry is given.
    
    ### Tests
    
    - Stream import with and without a registry, for both the array stream
    and device array stream importers.
    - Schema import resolving `arrow.uuid` nested inside each of the types
    listed above, including `list<list<uuid>>`.
    - A `list<uuid>` stream end to end, including `GetSlicedValues`
    returning `GuidArray`s (#468).
    - A pyarrow-produced stream with top-level and list-nested `arrow.uuid`
    columns.
    
    Closes #466.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 src/Apache.Arrow/C/CArrowArrayStreamImporter.cs    |  24 ++-
 .../C/CArrowDeviceArrayStreamImporter.cs           |  25 ++-
 src/Apache.Arrow/C/CArrowSchemaImporter.cs         |  46 +++---
 .../CDataInterfacePythonTests.cs                   |  51 +++++++
 .../CDeviceDataInterfaceTests.cs                   |  32 ++++
 test/Apache.Arrow.Tests/ExtensionTypeTests.cs      | 170 +++++++++++++++++++++
 6 files changed, 316 insertions(+), 32 deletions(-)

diff --git a/src/Apache.Arrow/C/CArrowArrayStreamImporter.cs 
b/src/Apache.Arrow/C/CArrowArrayStreamImporter.cs
index fe0a307..bbe7c67 100644
--- a/src/Apache.Arrow/C/CArrowArrayStreamImporter.cs
+++ b/src/Apache.Arrow/C/CArrowArrayStreamImporter.cs
@@ -47,7 +47,25 @@ namespace Apache.Arrow.C
         /// <returns>The imported C# array stream</returns>
         public static unsafe IArrowArrayStream 
ImportArrayStream(CArrowArrayStream* ptr)
         {
-            return new ImportedArrowArrayStream(ptr);
+            return new ImportedArrowArrayStream(ptr, null);
+        }
+
+        /// <summary>
+        /// Import C pointer as an <see cref="IArrowArrayStream"/>, resolving 
extension types
+        /// from the given registry.
+        /// </summary>
+        /// <remarks>
+        /// Fields whose extension type is found in <paramref 
name="extensionRegistry"/> are
+        /// imported with that type, and their columns are returned as 
extension arrays.
+        /// This will call the release callback on the passed struct if the 
function fails.
+        /// Otherwise, the release callback is called when the 
IArrowArrayStream is disposed.
+        /// </remarks>
+        /// <param name="ptr">The pointer to the stream being imported</param>
+        /// <param name="extensionRegistry">The registry used to resolve 
extension types</param>
+        /// <returns>The imported C# array stream</returns>
+        public static unsafe IArrowArrayStream 
ImportArrayStream(CArrowArrayStream* ptr, ExtensionTypeRegistry 
extensionRegistry)
+        {
+            return new ImportedArrowArrayStream(ptr, extensionRegistry);
         }
 
         private sealed unsafe class ImportedArrowArrayStream : 
IArrowArrayStream
@@ -70,7 +88,7 @@ namespace Apache.Arrow.C
                 return StringUtil.PtrToStringUtf8(error);
             }
 
-            public ImportedArrowArrayStream(CArrowArrayStream* cArrayStream)
+            public ImportedArrowArrayStream(CArrowArrayStream* cArrayStream, 
ExtensionTypeRegistry extensionRegistry)
             {
                 if (cArrayStream == null)
                 {
@@ -91,7 +109,7 @@ namespace Apache.Arrow.C
                 {
                     throw new Exception(GetLastError(cArrayStream, errno));
                 }
-                _schema = CArrowSchemaImporter.ImportSchema(&cSchema);
+                _schema = CArrowSchemaImporter.ImportSchema(&cSchema, 
extensionRegistry);
 
                 _cArrayStream = *cArrayStream;
                 cArrayStream->release = default;
diff --git a/src/Apache.Arrow/C/CArrowDeviceArrayStreamImporter.cs 
b/src/Apache.Arrow/C/CArrowDeviceArrayStreamImporter.cs
index 793ae43..6536716 100644
--- a/src/Apache.Arrow/C/CArrowDeviceArrayStreamImporter.cs
+++ b/src/Apache.Arrow/C/CArrowDeviceArrayStreamImporter.cs
@@ -36,6 +36,25 @@ namespace Apache.Arrow.C
         /// <param name="ptr">The pointer to the device array stream being 
imported</param>
         /// <returns>The imported C# array stream</returns>
         public static unsafe IArrowArrayStream 
ImportDeviceArrayStream(CArrowDeviceArrayStream* ptr)
+        {
+            return ImportDeviceArrayStream(ptr, null);
+        }
+
+        /// <summary>
+        /// Import C pointer as an <see cref="IArrowArrayStream"/>, resolving 
extension types
+        /// from the given registry.
+        /// </summary>
+        /// <remarks>
+        /// Fields whose extension type is found in <paramref 
name="extensionRegistry"/> are
+        /// imported with that type, and their columns are returned as 
extension arrays.
+        /// This will call the release callback on the passed struct if the 
function fails.
+        /// Otherwise, the release callback is called when the 
IArrowArrayStream is disposed.
+        /// Only CPU device streams are supported.
+        /// </remarks>
+        /// <param name="ptr">The pointer to the device array stream being 
imported</param>
+        /// <param name="extensionRegistry">The registry used to resolve 
extension types</param>
+        /// <returns>The imported C# array stream</returns>
+        public static unsafe IArrowArrayStream 
ImportDeviceArrayStream(CArrowDeviceArrayStream* ptr, ExtensionTypeRegistry 
extensionRegistry)
         {
             if (ptr == null)
             {
@@ -47,7 +66,7 @@ namespace Apache.Arrow.C
                     $"Importing device array streams from device type 
{ptr->device_type} is not supported. Only CPU streams can be imported.");
             }
 
-            return new ImportedArrowDeviceArrayStream(ptr);
+            return new ImportedArrowDeviceArrayStream(ptr, extensionRegistry);
         }
 
         private sealed unsafe class ImportedArrowDeviceArrayStream : 
IArrowArrayStream
@@ -77,7 +96,7 @@ namespace Apache.Arrow.C
                 return StringUtil.PtrToStringUtf8(error);
             }
 
-            public ImportedArrowDeviceArrayStream(CArrowDeviceArrayStream* 
cDeviceArrayStream)
+            public ImportedArrowDeviceArrayStream(CArrowDeviceArrayStream* 
cDeviceArrayStream, ExtensionTypeRegistry extensionRegistry)
             {
                 if (cDeviceArrayStream == null)
                 {
@@ -102,7 +121,7 @@ namespace Apache.Arrow.C
                 {
                     throw new Exception(GetLastError(cDeviceArrayStream, 
errno));
                 }
-                _schema = CArrowSchemaImporter.ImportSchema(&cSchema);
+                _schema = CArrowSchemaImporter.ImportSchema(&cSchema, 
extensionRegistry);
 
                 _cDeviceArrayStream = *cDeviceArrayStream;
                 cDeviceArrayStream->release = default;
diff --git a/src/Apache.Arrow/C/CArrowSchemaImporter.cs 
b/src/Apache.Arrow/C/CArrowSchemaImporter.cs
index c9559ba..4bf7f44 100644
--- a/src/Apache.Arrow/C/CArrowSchemaImporter.cs
+++ b/src/Apache.Arrow/C/CArrowSchemaImporter.cs
@@ -159,6 +159,15 @@ namespace Apache.Arrow.C
             }
 
             public ArrowType GetAsType()
+            {
+                return GetAsType(null);
+            }
+
+            /// <summary>
+            /// Gets the type, resolving extension types of nested fields from
+            /// <paramref name="extensionRegistry"/> if it is not null.
+            /// </summary>
+            public ArrowType GetAsType(ExtensionTypeRegistry extensionRegistry)
             {
                 var format = StringUtil.PtrToStringUtf8(_cSchema->format);
                 if (_cSchema->dictionary != null)
@@ -177,7 +186,7 @@ namespace Apache.Arrow.C
                     };
 
                     var dictionarySchema = new 
ImportedArrowSchema(_cSchema->dictionary, isRoot: false);
-                    ArrowType dictionaryType = dictionarySchema.GetAsType();
+                    ArrowType dictionaryType = 
dictionarySchema.GetAsType(extensionRegistry);
 
                     bool ordered = 
_cSchema->GetFlag(CArrowSchema.ArrowFlagDictionaryOrdered);
 
@@ -198,7 +207,7 @@ namespace Apache.Arrow.C
                     }
                     childSchema = new 
ImportedArrowSchema(_cSchema->GetChild(0), isRoot: false);
 
-                    Field childField = childSchema.GetAsField();
+                    Field childField = 
childSchema.GetAsField(extensionRegistry);
 
                     return format switch
                     {
@@ -211,7 +220,7 @@ namespace Apache.Arrow.C
                 }
                 else if (format == "+s")
                 {
-                    return new StructType(ParseChildren("struct"));
+                    return new StructType(ParseChildren("struct", 
extensionRegistry));
                 }
                 else if (format.StartsWith("+w:"))
                 {
@@ -229,14 +238,14 @@ namespace Apache.Arrow.C
                     }
                     childSchema = new 
ImportedArrowSchema(_cSchema->GetChild(0), isRoot: false);
 
-                    Field childField = childSchema.GetAsField();
+                    Field childField = 
childSchema.GetAsField(extensionRegistry);
 
                     return new FixedSizeListType(childField, width);
                 }
                 else if (format == "+m")
                 {
                     return new MapType(
-                        ParseChildren("map").Single(),
+                        ParseChildren("map", extensionRegistry).Single(),
                         (_cSchema->flags & 
CArrowSchema.ArrowFlagMapKeysSorted) != 0);
                 }
                 else if (format == "+r")
@@ -245,7 +254,7 @@ namespace Apache.Arrow.C
                     {
                         throw new InvalidDataException("Expected run-end 
encoded type to have exactly two children.");
                     }
-                    List<Field> reeChildren = ParseChildren("run-end encoded");
+                    List<Field> reeChildren = ParseChildren("run-end encoded", 
extensionRegistry);
                     return new RunEndEncodedType(reeChildren[0], 
reeChildren[1]);
                 }
 
@@ -316,7 +325,7 @@ namespace Apache.Arrow.C
                         pos = next + 1;
                     } while (pos < format.Length);
 
-                    return new UnionType(ParseChildren("union"), typeIds, 
unionMode);
+                    return new UnionType(ParseChildren("union", 
extensionRegistry), typeIds, unionMode);
                 }
 
                 return format switch
@@ -372,7 +381,7 @@ namespace Apache.Arrow.C
 
                 bool nullable = 
_cSchema->GetFlag(CArrowSchema.ArrowFlagNullable);
 
-                IArrowType type = GetAsType();
+                IArrowType type = GetAsType(extensionRegistry);
                 IReadOnlyDictionary<string, string> metadata = 
GetMetadata(_cSchema->metadata);
 
                 // Resolve extension type from metadata
@@ -398,24 +407,9 @@ namespace Apache.Arrow.C
 
             public Schema GetAsSchema(ExtensionTypeRegistry extensionRegistry)
             {
-                ArrowType fullType = GetAsType();
+                ArrowType fullType = GetAsType(extensionRegistry);
                 if (fullType is StructType structType)
                 {
-                    // Re-resolve fields with extension registry
-                    if (extensionRegistry != null)
-                    {
-                        var fields = new List<Field>();
-                        for (int i = 0; i < _cSchema->n_children; i++)
-                        {
-                            if (_cSchema->GetChild(i) == null)
-                            {
-                                throw new InvalidDataException("Expected 
struct type child to be non-null.");
-                            }
-                            var childSchema = new 
ImportedArrowSchema(_cSchema->GetChild(i), isRoot: false);
-                            
fields.Add(childSchema.GetAsField(extensionRegistry));
-                        }
-                        return new Schema(fields, 
GetMetadata(_cSchema->metadata));
-                    }
                     return new Schema(structType.Fields, 
GetMetadata(_cSchema->metadata));
                 }
                 else
@@ -424,7 +418,7 @@ namespace Apache.Arrow.C
                 }
             }
 
-            private List<Field> ParseChildren(string typeName)
+            private List<Field> ParseChildren(string typeName, 
ExtensionTypeRegistry extensionRegistry)
             {
                 var child_schemas = new 
ImportedArrowSchema[_cSchema->n_children];
 
@@ -437,7 +431,7 @@ namespace Apache.Arrow.C
                     child_schemas[i] = new 
ImportedArrowSchema(_cSchema->GetChild(i), isRoot: false);
                 }
 
-                return child_schemas.Select(schema => 
schema.GetAsField()).ToList();
+                return child_schemas.Select(schema => 
schema.GetAsField(extensionRegistry)).ToList();
             }
 
             private unsafe static IReadOnlyDictionary<string, string> 
GetMetadata(byte* metadata)
diff --git a/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs 
b/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs
index f233266..ee5134a 100644
--- a/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs
+++ b/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs
@@ -1174,6 +1174,57 @@ namespace Apache.Arrow.Tests
             CArrowArray.Free(cArray);
         }
 
+        [SkippableFact]
+        public unsafe void ImportArrayStreamWithExtensionTypes()
+        {
+            // Import a pyarrow stream with arrow.uuid at the top level and 
nested
+            // in a list, and verify that both resolve when given a registry.
+
+            Guid guid1 = Guid.Parse("01234567-89ab-cdef-0123-456789abcdef");
+            Guid guid2 = Guid.Parse("fedcba98-7654-3210-fedc-ba9876543210");
+
+            CArrowArrayStream* cArrayStream = CArrowArrayStream.Create();
+
+            using (Py.GIL())
+            {
+                dynamic pa = Py.Import("pyarrow");
+                dynamic uuid_mod = Py.Import("uuid");
+                PyObject bytes1 = uuid_mod.UUID(guid1.ToString()).bytes;
+                PyObject bytes2 = uuid_mod.UUID(guid2.ToString()).bytes;
+
+                dynamic table = pa.table(
+                    new PyList(new PyObject[]
+                    {
+                        pa.array(new PyList(new PyObject[] { bytes1, 
PyObject.None }), type: pa.uuid()),
+                        // pa.array can't convert nested Python values to 
list<uuid>.
+                        pa.ListArray.from_arrays(
+                            pa.array(new[] { 0, 2, 3 }, type: pa.int32()),
+                            pa.array(new PyList(new PyObject[] { bytes1, 
bytes2, bytes2 }), type: pa.uuid())),
+                    }),
+                    new[] { "uuid", "uuid_list" });
+
+                dynamic batchReader = 
pa.RecordBatchReader.from_batches(table.schema, table.to_batches());
+
+                long streamPtr = ((IntPtr)cArrayStream).ToInt64();
+                batchReader._export_to_c(streamPtr);
+            }
+
+            var registry = new ExtensionTypeRegistry();
+            registry.Register(GuidExtensionDefinition.Instance);
+
+            using IArrowArrayStream stream = 
CArrowArrayStreamImporter.ImportArrayStream(cArrayStream, registry);
+            CArrowArrayStream.Free(cArrayStream);
+
+            using RecordBatch batch = stream.ReadNextRecordBatchAsync().Result;
+
+            GuidArray uuids = Assert.IsType<GuidArray>(batch.Column("uuid"));
+            Assert.Equal(new Guid?[] { guid1, null }, uuids);
+
+            ListArray uuidLists = 
Assert.IsType<ListArray>(batch.Column("uuid_list"));
+            Assert.Equal(new Guid?[] { guid1, guid2 }, 
Assert.IsType<GuidArray>(uuidLists.GetSlicedValues(0)));
+            Assert.Equal(new Guid?[] { guid2 }, 
Assert.IsType<GuidArray>(uuidLists.GetSlicedValues(1)));
+        }
+
         [SkippableFact]
         public unsafe void ExportBool8Array()
         {
diff --git a/test/Apache.Arrow.Tests/CDeviceDataInterfaceTests.cs 
b/test/Apache.Arrow.Tests/CDeviceDataInterfaceTests.cs
index 7d416b7..3954d9c 100644
--- a/test/Apache.Arrow.Tests/CDeviceDataInterfaceTests.cs
+++ b/test/Apache.Arrow.Tests/CDeviceDataInterfaceTests.cs
@@ -245,6 +245,38 @@ namespace Apache.Arrow.Tests
             CArrowDeviceArrayStream.Free(ptr);
         }
 
+        [Fact]
+        public async Task ImportDeviceStreamWithExtensionRegistry()
+        {
+            var registry = new ExtensionTypeRegistry();
+            registry.Register(GuidExtensionDefinition.Instance);
+
+            var values = new Guid?[] { Guid.NewGuid(), null, Guid.NewGuid() };
+            GuidArray.Builder builder = new GuidArray.Builder();
+            
builder.Append(values[0].Value).AppendNull().Append(values[2].Value);
+            var schema = new Schema(new[] { new Field("guids", 
GuidType.Default, true) }, null);
+            RecordBatch batch = new RecordBatch(schema, new[] { 
builder.Build() }, values.Length);
+            IArrowArrayStream arrayStream = new TestArrayStream(schema, batch);
+
+            IArrowArrayStream imported;
+            unsafe
+            {
+                CArrowDeviceArrayStream* ptr = 
CArrowDeviceArrayStream.Create();
+                CArrowDeviceArrayStreamExporter.ExportArrayStream(arrayStream, 
ptr);
+                imported = 
CArrowDeviceArrayStreamImporter.ImportDeviceArrayStream(ptr, registry);
+                CArrowDeviceArrayStream.Free(ptr);
+            }
+
+            using (imported)
+            {
+                
Assert.IsType<GuidType>(imported.Schema.FieldsList[0].DataType);
+
+                using RecordBatch importedBatch = await 
imported.ReadNextRecordBatchAsync();
+                GuidArray guids = 
Assert.IsType<GuidArray>(importedBatch.Column(0));
+                Assert.Equal(values, guids);
+            }
+        }
+
         [Fact]
         public async Task ExportImportDeviceStreamRoundTrip()
         {
diff --git a/test/Apache.Arrow.Tests/ExtensionTypeTests.cs 
b/test/Apache.Arrow.Tests/ExtensionTypeTests.cs
index 8f8dbd0..308ca26 100644
--- a/test/Apache.Arrow.Tests/ExtensionTypeTests.cs
+++ b/test/Apache.Arrow.Tests/ExtensionTypeTests.cs
@@ -16,7 +16,11 @@
 using System;
 using System.Collections.Generic;
 using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
 using Apache.Arrow.Arrays;
+using Apache.Arrow.C;
 using Apache.Arrow.Ipc;
 using Apache.Arrow.Types;
 using Xunit;
@@ -347,5 +351,171 @@ namespace Apache.Arrow.Tests
                 Apache.Arrow.C.CArrowSchema.Free(cSchema);
             }
         }
+
+        [Fact]
+        public async Task CDataArrayStreamWithRegistry()
+        {
+            var registry = new ExtensionTypeRegistry();
+            registry.Register(GuidExtensionDefinition.Instance);
+
+            var values = new Guid?[] { Guid.NewGuid(), null, Guid.NewGuid() };
+            RecordBatch batch = BuildGuidRecordBatch(values);
+
+            IArrowArrayStream imported;
+            unsafe
+            {
+                CArrowArrayStream* cStream = CArrowArrayStream.Create();
+                CArrowArrayStreamExporter.ExportArrayStream(new 
SingleBatchStream(batch), cStream);
+                imported = 
CArrowArrayStreamImporter.ImportArrayStream(cStream, registry);
+                CArrowArrayStream.Free(cStream);
+            }
+
+            using (imported)
+            {
+                
Assert.IsType<GuidType>(imported.Schema.FieldsList[0].DataType);
+
+                using RecordBatch importedBatch = await 
imported.ReadNextRecordBatchAsync();
+                GuidArray guids = 
Assert.IsType<GuidArray>(importedBatch.Column(0));
+                Assert.Equal(values, guids);
+
+                Assert.Null(await imported.ReadNextRecordBatchAsync());
+            }
+        }
+
+        [Fact]
+        public async Task CDataArrayStreamWithoutRegistry()
+        {
+            RecordBatch batch = BuildGuidRecordBatch(new Guid?[] { 
Guid.NewGuid() });
+
+            IArrowArrayStream imported;
+            unsafe
+            {
+                CArrowArrayStream* cStream = CArrowArrayStream.Create();
+                CArrowArrayStreamExporter.ExportArrayStream(new 
SingleBatchStream(batch), cStream);
+                imported = 
CArrowArrayStreamImporter.ImportArrayStream(cStream);
+                CArrowArrayStream.Free(cStream);
+            }
+
+            using (imported)
+            {
+                Field field = imported.Schema.FieldsList[0];
+                Assert.IsType<FixedSizeBinaryType>(field.DataType);
+                Assert.Equal("arrow.uuid", 
field.Metadata["ARROW:extension:name"]);
+
+                using RecordBatch importedBatch = await 
imported.ReadNextRecordBatchAsync();
+                Assert.IsType<FixedSizeBinaryArray>(importedBatch.Column(0));
+            }
+        }
+
+        [Fact]
+        public unsafe void CDataSchemaResolvesNestedExtensionTypes()
+        {
+            var registry = new ExtensionTypeRegistry();
+            registry.Register(GuidExtensionDefinition.Instance);
+
+            Field Item() => new Field("item", GuidType.Default, true);
+            var schema = new Schema(new[]
+            {
+                new Field("list", new ListType(Item()), true),
+                new Field("large_list", new LargeListType(Item()), true),
+                new Field("list_view", new ListViewType(Item()), true),
+                new Field("large_list_view", new LargeListViewType(Item()), 
true),
+                new Field("fixed_size_list", new FixedSizeListType(Item(), 2), 
true),
+                new Field("list_of_list", new ListType(new Field("item", new 
ListType(Item()), true)), true),
+                new Field("struct", new StructType(new[] { Item() }), true),
+                new Field("map", new MapType(new Field("key", 
StringType.Default, false), Item()), true),
+                new Field("union", new UnionType(new[] { Item() }, new[] { 0 
}, UnionMode.Sparse), true),
+                new Field("ree", new RunEndEncodedType(Int32Type.Default, 
GuidType.Default), true),
+                new Field("dictionary", new DictionaryType(Int32Type.Default, 
new ListType(Item()), false), true),
+            }, null);
+
+            var cSchema = CArrowSchema.Create();
+            try
+            {
+                CArrowSchemaExporter.ExportSchema(schema, cSchema);
+                Schema imported = CArrowSchemaImporter.ImportSchema(cSchema, 
registry);
+
+                Assert.Equal(schema.FieldsList.Count, 
imported.FieldsList.Count);
+                foreach (Field field in imported.FieldsList)
+                {
+                    Assert.True(ContainsGuidType(field.DataType), $"Field 
'{field.Name}' did not resolve arrow.uuid: {field.DataType}");
+                }
+            }
+            finally
+            {
+                CArrowSchema.Free(cSchema);
+            }
+
+            static bool ContainsGuidType(IArrowType type) => type switch
+            {
+                GuidType => true,
+                DictionaryType dictionary => 
ContainsGuidType(dictionary.ValueType),
+                NestedType nested => nested.Fields.Any(f => 
ContainsGuidType(f.DataType)),
+                _ => false,
+            };
+        }
+
+        [Fact]
+        public async Task CDataArrayStreamResolvesListOfExtensionType()
+        {
+            var registry = new ExtensionTypeRegistry();
+            registry.Register(GuidExtensionDefinition.Instance);
+
+            var values = new Guid?[] { Guid.NewGuid(), null, Guid.NewGuid() };
+            GuidArray guids = 
(GuidArray)BuildGuidRecordBatch(values).Column(0);
+            var listType = new ListType(new Field("item", GuidType.Default, 
true));
+            var list = new ListArray(listType, 2,
+                new 
ArrowBuffer.Builder<int>().Append(0).Append(1).Append(3).Build(),
+                guids, ArrowBuffer.Empty);
+            var schema = new Schema(new[] { new Field("guid_lists", listType, 
true) }, null);
+            RecordBatch batch = new RecordBatch(schema, new[] { list }, 
list.Length);
+
+            IArrowArrayStream imported;
+            unsafe
+            {
+                CArrowArrayStream* cStream = CArrowArrayStream.Create();
+                CArrowArrayStreamExporter.ExportArrayStream(new 
SingleBatchStream(batch), cStream);
+                imported = 
CArrowArrayStreamImporter.ImportArrayStream(cStream, registry);
+                CArrowArrayStream.Free(cStream);
+            }
+
+            using (imported)
+            {
+                ListType importedType = 
Assert.IsType<ListType>(imported.Schema.FieldsList[0].DataType);
+                Assert.IsType<GuidType>(importedType.ValueDataType);
+
+                using RecordBatch importedBatch = await 
imported.ReadNextRecordBatchAsync();
+                ListArray importedList = 
Assert.IsType<ListArray>(importedBatch.Column(0));
+                Assert.IsType<GuidArray>(importedList.Values);
+                Assert.Equal(new Guid?[] { values[0] }, 
Assert.IsType<GuidArray>(importedList.GetSlicedValues(0)));
+                Assert.Equal(new Guid?[] { values[1], values[2] }, 
Assert.IsType<GuidArray>(importedList.GetSlicedValues(1)));
+            }
+        }
+
+        private sealed class SingleBatchStream : IArrowArrayStream
+        {
+            private RecordBatch _batch;
+
+            public SingleBatchStream(RecordBatch batch)
+            {
+                Schema = batch.Schema;
+                _batch = batch;
+            }
+
+            public Schema Schema { get; }
+
+            public ValueTask<RecordBatch> 
ReadNextRecordBatchAsync(CancellationToken cancellationToken = default)
+            {
+                RecordBatch result = _batch;
+                _batch = null;
+                return new ValueTask<RecordBatch>(result);
+            }
+
+            public void Dispose()
+            {
+                _batch?.Dispose();
+                _batch = null;
+            }
+        }
     }
 }

Reply via email to