From bff3f2bea38bf33f570daf6c3451867b09b9419e Mon Sep 17 00:00:00 2001 From: Dave Searle Date: Mon, 4 Sep 2023 14:40:06 +0100 Subject: [PATCH 1/6] [C#] Initial commit to add support for Apache Acero Adds support for Apache Acero. --- csharp/Apache.Arrow.sln | 20 +- .../Apache.Arrow.Acero.csproj | 12 + .../AsyncRecordBatchStream.cs | 46 ++++ csharp/src/Apache.Arrow.Acero/CLib.cs | 206 +++++++++++++++++ csharp/src/Apache.Arrow.Acero/Declaration.cs | 120 ++++++++++ csharp/src/Apache.Arrow.Acero/ExecNode.cs | 24 ++ .../src/Apache.Arrow.Acero/ExecNodeOptions.cs | 21 ++ csharp/src/Apache.Arrow.Acero/ExecPlan.cs | 47 ++++ csharp/src/Apache.Arrow.Acero/ExportUtil.cs | 67 ++++++ csharp/src/Apache.Arrow.Acero/Expression.cs | 24 ++ .../src/Apache.Arrow.Acero/FieldExpression.cs | 36 +++ csharp/src/Apache.Arrow.Acero/FilterNode.cs | 34 +++ .../Apache.Arrow.Acero/FilterNodeOptions.cs | 40 ++++ csharp/src/Apache.Arrow.Acero/Function.cs | 61 ++++++ csharp/src/Apache.Arrow.Acero/HashJoinNode.cs | 37 ++++ .../Apache.Arrow.Acero/HashJoinNodeOptions.cs | 57 +++++ .../Apache.Arrow.Acero/LiteralExpression.cs | 40 ++++ .../RecordBatchReaderSourceNode.cs | 32 +++ .../RecordBatchReaderSourceNodeOptions.cs | 37 ++++ .../RecordBatchSourceNode.cs | 32 +++ .../RecordBatchSourceNodeOptions.cs | 34 +++ csharp/src/Apache.Arrow.Acero/SinkNode.cs | 34 +++ .../src/Apache.Arrow.Acero/SinkNodeOptions.cs | 47 ++++ .../Apache.Arrow.Acero.Tests.csproj | 18 ++ .../DeclarationTests.cs | 207 ++++++++++++++++++ .../test/Apache.Arrow.Acero.Tests/TestData.cs | 80 +++++++ 26 files changed, 1409 insertions(+), 4 deletions(-) create mode 100644 csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj create mode 100644 csharp/src/Apache.Arrow.Acero/AsyncRecordBatchStream.cs create mode 100644 csharp/src/Apache.Arrow.Acero/CLib.cs create mode 100644 csharp/src/Apache.Arrow.Acero/Declaration.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ExecNode.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ExecNodeOptions.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ExecPlan.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ExportUtil.cs create mode 100644 csharp/src/Apache.Arrow.Acero/Expression.cs create mode 100644 csharp/src/Apache.Arrow.Acero/FieldExpression.cs create mode 100644 csharp/src/Apache.Arrow.Acero/FilterNode.cs create mode 100644 csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs create mode 100644 csharp/src/Apache.Arrow.Acero/Function.cs create mode 100644 csharp/src/Apache.Arrow.Acero/HashJoinNode.cs create mode 100644 csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs create mode 100644 csharp/src/Apache.Arrow.Acero/LiteralExpression.cs create mode 100644 csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs create mode 100644 csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs create mode 100644 csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs create mode 100644 csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs create mode 100644 csharp/src/Apache.Arrow.Acero/SinkNode.cs create mode 100644 csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs create mode 100644 csharp/test/Apache.Arrow.Acero.Tests/Apache.Arrow.Acero.Tests.csproj create mode 100644 csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs create mode 100644 csharp/test/Apache.Arrow.Acero.Tests/TestData.cs diff --git a/csharp/Apache.Arrow.sln b/csharp/Apache.Arrow.sln index 7e7f7c6331e8..cc36c8e0eb25 100644 --- a/csharp/Apache.Arrow.sln +++ b/csharp/Apache.Arrow.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29926.136 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33205.214 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Apache.Arrow", "src\Apache.Arrow\Apache.Arrow.csproj", "{BA6B2B0D-EAAE-4183-8A39-1B9CF571F71F}" EndProject @@ -23,9 +23,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Apache.Arrow.Compression", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Apache.Arrow.Compression.Tests", "test\Apache.Arrow.Compression.Tests\Apache.Arrow.Compression.Tests.csproj", "{5D7FF380-B7DF-4752-B415-7C08C70C9F06}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Apache.Arrow.Flight.Sql.Tests", "test\Apache.Arrow.Flight.Sql.Tests\Apache.Arrow.Flight.Sql.Tests.csproj", "{DCC99EB1-4E60-4F0D-AEA9-C44A4C0C8B1D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Apache.Arrow.Flight.Sql.Tests", "test\Apache.Arrow.Flight.Sql.Tests\Apache.Arrow.Flight.Sql.Tests.csproj", "{DCC99EB1-4E60-4F0D-AEA9-C44A4C0C8B1D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Apache.Arrow.Flight.Sql", "src\Apache.Arrow.Flight.Sql\Apache.Arrow.Flight.Sql.csproj", "{2ADE087A-B424-4895-8CC5-10170D10BA62}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Apache.Arrow.Flight.Sql", "src\Apache.Arrow.Flight.Sql\Apache.Arrow.Flight.Sql.csproj", "{2ADE087A-B424-4895-8CC5-10170D10BA62}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Apache.Arrow.Acero", "src\Apache.Arrow.Acero\Apache.Arrow.Acero.csproj", "{E4D30783-5506-4E62-8491-4191A249B335}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Apache.Arrow.Acero.Tests", "test\Apache.Arrow.Acero.Tests\Apache.Arrow.Acero.Tests.csproj", "{A5D6A064-9AC2-4C60-9BF5-E6C834A90232}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -81,6 +85,14 @@ Global {2ADE087A-B424-4895-8CC5-10170D10BA62}.Debug|Any CPU.Build.0 = Debug|Any CPU {2ADE087A-B424-4895-8CC5-10170D10BA62}.Release|Any CPU.ActiveCfg = Release|Any CPU {2ADE087A-B424-4895-8CC5-10170D10BA62}.Release|Any CPU.Build.0 = Release|Any CPU + {E4D30783-5506-4E62-8491-4191A249B335}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4D30783-5506-4E62-8491-4191A249B335}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4D30783-5506-4E62-8491-4191A249B335}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4D30783-5506-4E62-8491-4191A249B335}.Release|Any CPU.Build.0 = Release|Any CPU + {A5D6A064-9AC2-4C60-9BF5-E6C834A90232}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5D6A064-9AC2-4C60-9BF5-E6C834A90232}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5D6A064-9AC2-4C60-9BF5-E6C834A90232}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A5D6A064-9AC2-4C60-9BF5-E6C834A90232}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj b/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj new file mode 100644 index 000000000000..9483cf28eead --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj @@ -0,0 +1,12 @@ + + + + net7.0 + true + + + + + + + diff --git a/csharp/src/Apache.Arrow.Acero/AsyncRecordBatchStream.cs b/csharp/src/Apache.Arrow.Acero/AsyncRecordBatchStream.cs new file mode 100644 index 000000000000..dc8708ed5f53 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/AsyncRecordBatchStream.cs @@ -0,0 +1,46 @@ +// 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 Apache.Arrow.Ipc; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Apache.Arrow.Acero +{ + public class AsyncRecordBatchStream : IArrowArrayStream + { + private readonly IAsyncEnumerator _recordBatchEnumerator; + private readonly Schema _schema; + + public Schema Schema => _schema; + + public AsyncRecordBatchStream(IAsyncEnumerable _recordBatches, Schema schema) + { + _recordBatchEnumerator = _recordBatches.GetAsyncEnumerator(); + _schema = schema; + } + + public async ValueTask ReadNextRecordBatchAsync(CancellationToken cancellationToken = default) + { + await _recordBatchEnumerator.MoveNextAsync(); + return _recordBatchEnumerator.Current; + } + + public void Dispose() + { + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/CLib.cs b/csharp/src/Apache.Arrow.Acero/CLib.cs new file mode 100644 index 000000000000..4713a3d1fd04 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/CLib.cs @@ -0,0 +1,206 @@ +// 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 Apache.Arrow.C; +using System; +using System.Runtime.InteropServices; + +namespace Apache.Arrow.Acero +{ + public class CLib + { + public struct GError { } + public struct GArrowExecutePlan { } + public struct GArrowSourceNodeOptions { } + public struct GArrowRecordBatch { } + public struct GArrowSchema { } + public struct GArrowField { } + public struct GArrowExecuteNode { } + public struct GArrowHashJoinNodeOptions { } + public struct GArrowSinkNodeOptions { } + public struct GArrowRecordBatchReader { } + public struct GArrowExecuteNodeOptions { } + public struct GArrowFilterNodeOptions { } + public struct GArrowExpression { } + public struct GArrowCallExpression { } + public struct GArrowFunctionOptions { } + public struct GArrowFieldExpression { } + public struct GArrowDatum { } + public struct GArrowScalarDatum { } + public struct GArrowBuffer { } + public struct GArrowStringScalar { } + public struct GArrowInt8Scalar { } + public struct GArrowSortOptions { } + public struct GArrowSortKey { } + + public enum GArrowJoinType + { + GARROW_JOIN_TYPE_LEFT_SEMI, + GARROW_JOIN_TYPE_RIGHT_SEMI, + GARROW_JOIN_TYPE_LEFT_ANTI, + GARROW_JOIN_TYPE_RIGHT_ANTI, + GARROW_JOIN_TYPE_INNER, + GARROW_JOIN_TYPE_LEFT_OUTER, + GARROW_JOIN_TYPE_RIGHT_OUTER, + GARROW_JOIN_TYPE_FULL_OUTER + } + + public enum GArrowSortOrder + { + GARROW_SORT_ORDER_ASCENDING, + GARROW_SORT_ORDER_DESCENDING + } + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_new")] + public static extern unsafe GArrowExecutePlan* garrow_execute_plan_new(GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch")] + public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch(GArrowRecordBatch* record_batch); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_import")] + public static extern unsafe GArrowRecordBatch* garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_import")] + public static extern unsafe GArrowSchema* garrow_schema_import(CArrowSchema* c_abi_schema, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_get_field")] + public static extern unsafe GArrowField* garrow_schema_get_field(GArrowSchema* schema, uint i); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_is_nullable")] + public static extern unsafe bool garrow_field_is_nullable(GArrowField* field); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_hash_join_node_options_new")] + public static extern unsafe GArrowHashJoinNodeOptions* garrow_hash_join_node_options_new(GArrowJoinType type, IntPtr left_keys, uint n_left_keys, IntPtr right_keys, uint n_right_keys, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_hash_join_node")] + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_hash_join_node(GArrowExecutePlan* plan, GArrowExecuteNode* left, GArrowExecuteNode* right, GArrowHashJoinNodeOptions* options, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_source_node")] + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_source_node(GArrowExecutePlan* plan, GArrowSourceNodeOptions* options, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_validate")] + public static extern unsafe bool garrow_execute_plan_validate(GArrowExecutePlan* plan, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_new")] + public static extern unsafe GArrowSinkNodeOptions* garrow_sink_node_options_new(); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_sink_node")] + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_sink_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowSinkNodeOptions* options, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_start")] + public static extern unsafe void garrow_execute_plan_start(GArrowExecutePlan* plan); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_wait")] + public static extern unsafe void garrow_execute_plan_wait(GArrowExecutePlan* plan); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_get_reader")] + public static extern unsafe GArrowRecordBatchReader* garrow_sink_node_options_get_reader(GArrowSinkNodeOptions* options, GArrowSchema* schema); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_export")] + public static extern unsafe CArrowArrayStream* garrow_record_batch_reader_export(GArrowRecordBatchReader* reader, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_import")] + public static extern unsafe GArrowRecordBatchReader* garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch_reader")] + public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch_reader(GArrowRecordBatchReader* reader); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_filter_node")] + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_filter_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowFilterNodeOptions* options, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_filter_node_options_new")] + public static extern unsafe GArrowFilterNodeOptions* garrow_filter_node_options_new(IntPtr expression); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_call_expression_new")] + public static extern unsafe GArrowCallExpression* garrow_call_expression_new(IntPtr function, IntPtr arguments, GArrowFunctionOptions* options); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_expression_new")] + public static extern unsafe GArrowFieldExpression* garrow_field_expression_new(IntPtr reference, GError** error); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_literal_expression_new")] + public static extern unsafe GArrowFieldExpression* garrow_literal_expression_new(GArrowDatum* datum); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_scalar_datum_new")] + public static extern unsafe GArrowScalarDatum* garrow_scalar_datum_new(IntPtr value); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new")] + public static extern unsafe GArrowBuffer* garrow_buffer_new(IntPtr data, long size); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new_bytes")] + public static extern unsafe GArrowBuffer* garrow_buffer_new_bytes(IntPtr data); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_string_scalar_new")] + public static extern unsafe GArrowStringScalar* garrow_string_scalar_new(GArrowBuffer* value); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_expression_to_string")] + public static extern unsafe IntPtr garrow_expression_to_string(IntPtr expression); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_int64_scalar_new")] + public static extern unsafe GArrowInt8Scalar* garrow_int64_scalar_new(long value); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_options_new")] + public static extern unsafe GArrowSortOptions* garrow_sort_options_new(GList* sort_keys); + + [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_key_new")] + public static extern unsafe GArrowSortKey* garrow_sort_key_new(IntPtr target, GArrowSortOrder order, GError** error); + } + + [StructLayout(LayoutKind.Sequential)] + public unsafe struct GList + { + public IntPtr data; + public GList* next; + public GList* prev; + } + + internal static class StringUtil + { + public static unsafe byte* ToCStringUtf8(string str) + { + var utf8 = System.Text.Encoding.UTF8; + int byteCount = utf8.GetByteCount(str); + byte* byteArray = (byte*)Marshal.AllocHGlobal(byteCount + 1); + + fixed (char* chars = str) + { + utf8.GetBytes(chars, str.Length, byteArray, byteCount); + } + + // Need to make sure it is null-terminated. + byteArray[byteCount] = 0; + + return byteArray; + } + + public static unsafe string PtrToStringUtf8(byte* ptr) + { +#if NETSTANDARD2_1_OR_GREATER + return Marshal.PtrToStringUTF8(ptr); +#else + if (ptr == null) + { + return null; + } + + int length; + for (length = 0; ptr[length] != '\0'; ++length) + { + } + + return System.Text.Encoding.UTF8.GetString(ptr, length); +#endif + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/Declaration.cs b/csharp/src/Apache.Arrow.Acero/Declaration.cs new file mode 100644 index 000000000000..7ce74887d4d2 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Declaration.cs @@ -0,0 +1,120 @@ +// 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 Apache.Arrow.Ipc; + +using System; +using System.Collections.Generic; +using System.Linq; +using Apache.Arrow.Ipc; + +namespace Apache.Arrow.Acero +{ + public class Declaration + { + private readonly string _factoryName; + private readonly ExecNodeOptions _options; + + public List Inputs { get; set; } = new(); + + public Declaration(string factoryName, ExecNodeOptions options, List inputs = null) + { + _factoryName = factoryName; + _options = options; + + if (inputs != null) Inputs = inputs; + } + + public static Declaration FromSequence(List decls) + { + var items = decls.ToList(); + + Declaration first = items.Last(); + items.RemoveAt(items.Count - 1); + + Declaration receiver = first; + + while (items.Any()) + { + Declaration input = items.Last(); + items.RemoveAt(items.Count - 1); + + receiver.Inputs.Add(input); + receiver = receiver.Inputs.First(); + } + + return first; + } + + public IArrowArrayStream ToRecordBatchReader(Schema schema) + { + return ToRecordBatchReader(this, schema); + } + + public static IArrowArrayStream ToRecordBatchReader(Declaration declaration, Schema schema) + { + var sinkNodeOptions = new SinkNodeOptions(schema); + var plan = new ExecPlan(); + + Declaration sinkNode = FromSequence( + new List + { + declaration, + new Declaration("table_sink", sinkNodeOptions) + }); + + sinkNode.AddToPlan(plan); + + if (!plan.Validate()) + throw new InvalidOperationException("Plan is not valid"); + + plan.StartProducing(); + plan.Wait(); + + return sinkNodeOptions.GetRecordBatchReader(); + } + + private ExecNode AddToPlan(ExecPlan plan) + { + var nodes = new List(); + + foreach (var input in Inputs) + { + var node = input.AddToPlan(plan); + nodes.Add(node); + } + + switch (_factoryName) + { + case "table_sink": + return new SinkNode(_options as SinkNodeOptions, plan, nodes); + + case "record_batch_source": + return new RecordBatchSourceNode(_options as RecordBatchSourceNodeOptions, plan); + + case "record_batch_reader_source": + return new RecordBatchReaderSourceNode(_options as RecordBatchReaderSourceNodeOptions, plan); + + case "hashjoin": + return new HashJoinNode(_options as HashJoinNodeOptions, plan, nodes); + + case "filter": + return new FilterNode(_options as FilterNodeOptions, plan, nodes); + + default: + throw new Exception($"Unknown factory {_factoryName}"); + } + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExecNode.cs b/csharp/src/Apache.Arrow.Acero/ExecNode.cs new file mode 100644 index 000000000000..0bd5f8d54608 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExecNode.cs @@ -0,0 +1,24 @@ +// 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 static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public abstract class ExecNode + { + public abstract unsafe GArrowExecuteNode* GetPtr(); + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExecNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/ExecNodeOptions.cs new file mode 100644 index 000000000000..88ecbe5c2c5d --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExecNodeOptions.cs @@ -0,0 +1,21 @@ +// 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. + +namespace Apache.Arrow.Acero +{ + public abstract class ExecNodeOptions + { + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExecPlan.cs b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs new file mode 100644 index 000000000000..a5822b53204f --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs @@ -0,0 +1,47 @@ +// 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. + +namespace Apache.Arrow.Acero +{ + public class ExecPlan + { + private unsafe CLib.GArrowExecutePlan* _planPtr; + + public unsafe ExecPlan() + { + _planPtr = CLib.garrow_execute_plan_new(null); + } + + public unsafe bool Validate() + { + return CLib.garrow_execute_plan_validate(_planPtr, null); + } + + public unsafe void StartProducing() + { + CLib.garrow_execute_plan_start(_planPtr); + } + + public unsafe void Wait() + { + CLib.garrow_execute_plan_wait(_planPtr); + } + + internal unsafe CLib.GArrowExecutePlan* GetPtr() + { + return _planPtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs new file mode 100644 index 000000000000..5ded131e2ac7 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs @@ -0,0 +1,67 @@ +// 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 Apache.Arrow.C; +using Apache.Arrow.Ipc; + +namespace Apache.Arrow.Acero +{ + internal static class ExportUtil + { + public static unsafe CLib.GArrowSchema* ExportAndGetSchemaPtr(Schema schema) + { + // allocate a C ABI ArrowSchema + CArrowSchema* cSchema = CArrowSchema.Create(); + + // export the c# schema to the newly allocated CArrowSchema + CArrowSchemaExporter.ExportSchema(schema, cSchema); + + // Import CArrowSchema into a GArrowSchema + var gSchema = CLib.garrow_schema_import(cSchema, null); + + return gSchema; + } + + public static unsafe CLib.GArrowRecordBatch* ExportAndGetRecordBatchPtr(RecordBatch recordBatch, Schema schema) + { + var schemaPtr = ExportAndGetSchemaPtr(schema); + + // allocate a C ABI CArrowArray + CArrowArray* cArray = CArrowArray.Create(); + + // export the c# record batch to the CArrowArray + CArrowArrayExporter.ExportRecordBatch(recordBatch, cArray); + + // import the CArrowArray into a gArrowRecordBatch + var gRecordBatch = CLib.garrow_record_batch_import(cArray, schemaPtr, null); + + return gRecordBatch; + } + + public static unsafe CLib.GArrowRecordBatchReader* ExportAndGetRecordBatchReaderPtr(IArrowArrayStream recordBatchReader) + { + // Allocate a CArrowArray + CArrowArrayStream* cArrayStream = CArrowArrayStream.Create(); + + // export the c# record batch to the CArrowArray + CArrowArrayStreamExporter.ExportArrayStream(recordBatchReader, cArrayStream); + + // next import the c arrow as a gArrowRecordBatch + var gRecordBatchReader = CLib.garrow_record_batch_reader_import(cArrayStream, null); + + return gRecordBatchReader; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/Expression.cs b/csharp/src/Apache.Arrow.Acero/Expression.cs new file mode 100644 index 000000000000..fc2e25ecff77 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Expression.cs @@ -0,0 +1,24 @@ +// 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; + +namespace Apache.Arrow.Acero +{ + public abstract class Expression + { + public abstract IntPtr GetPtr(); + } +} diff --git a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs new file mode 100644 index 000000000000..d380768889f1 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs @@ -0,0 +1,36 @@ +// 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; + +namespace Apache.Arrow.Acero +{ + public class FieldExpression : Expression + { + private IntPtr _ptr; + + public unsafe FieldExpression(string field) + { + var reference = (nint)StringUtil.ToCStringUtf8(field); + + _ptr = (nint)CLib.garrow_field_expression_new(reference, null); + } + + public override IntPtr GetPtr() + { + return _ptr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/FilterNode.cs b/csharp/src/Apache.Arrow.Acero/FilterNode.cs new file mode 100644 index 000000000000..294855f61632 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FilterNode.cs @@ -0,0 +1,34 @@ +// 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.Collections.Generic; + +namespace Apache.Arrow.Acero +{ + public class FilterNode : ExecNode + { + private unsafe CLib.GArrowExecuteNode* _nodePtr; + + public unsafe FilterNode(FilterNodeOptions options, ExecPlan plan, List nodes) + { + _nodePtr = CLib.garrow_execute_plan_build_filter_node(plan.GetPtr(), nodes[0].GetPtr(), options.GetPtr(), null); + } + + public override unsafe CLib.GArrowExecuteNode* GetPtr() + { + return _nodePtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs new file mode 100644 index 000000000000..7545524136ff --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs @@ -0,0 +1,40 @@ +// 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 static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class FilterNodeOptions : ExecNodeOptions + { + private unsafe GArrowFilterNodeOptions* _optionsPtr; + + public unsafe FilterNodeOptions(Expression expr) + { + _optionsPtr = CLib.garrow_filter_node_options_new(expr.GetPtr()); + + var strPtr = CLib.garrow_expression_to_string(expr.GetPtr()); + var str = StringUtil.PtrToStringUtf8((byte*)strPtr); + + Console.WriteLine(str); + } + + internal unsafe GArrowFilterNodeOptions* GetPtr() + { + return _optionsPtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/Function.cs b/csharp/src/Apache.Arrow.Acero/Function.cs new file mode 100644 index 000000000000..7f3c0d3d53fd --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Function.cs @@ -0,0 +1,61 @@ +// 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.Runtime.InteropServices; + +namespace Apache.Arrow.Acero +{ + public class Function : Expression + { + private IntPtr _ptr; + + public unsafe Function(string functionName, Expression lhs, Expression rhs) + { + var functionNamePtr = StringUtil.ToCStringUtf8(functionName); + + var rhsItem = new GList + { + data = rhs.GetPtr() + }; + + var lhsItem = new GList + { + data = lhs.GetPtr(), + next = &rhsItem + }; + + IntPtr glistPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(lhsItem, glistPtr, false); + + _ptr = (nint)CLib.garrow_call_expression_new((IntPtr)functionNamePtr, glistPtr, null); + } + + public override IntPtr GetPtr() + { + return _ptr; + } + } + + public class Equal : Function + { + public Equal(Expression lhs, Expression rhs) : base("equal", lhs, rhs) { } + } + + public class Or : Function + { + public Or(Expression lhs, Expression rhs) : base("or", lhs, rhs) { } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs new file mode 100644 index 000000000000..cd5e0f1fe458 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs @@ -0,0 +1,37 @@ +// 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.Collections.Generic; + +namespace Apache.Arrow.Acero +{ + public class HashJoinNode : ExecNode + { + private unsafe CLib.GArrowExecuteNode* _nodePtr; + + public unsafe HashJoinNode(HashJoinNodeOptions options, ExecPlan plan, List inputs) + { + var left = inputs[0]; + var right = inputs[1]; + + _nodePtr = CLib.garrow_execute_plan_build_hash_join_node(plan.GetPtr(), left.GetPtr(), right.GetPtr(), options.GetPtr(), null); + } + + public override unsafe CLib.GArrowExecuteNode* GetPtr() + { + return _nodePtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs new file mode 100644 index 000000000000..61647213de24 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs @@ -0,0 +1,57 @@ +// 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.Runtime.InteropServices; +using static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class HashJoinNodeOptions : ExecNodeOptions + { + private unsafe GArrowHashJoinNodeOptions* _optionsPtr; + + public unsafe HashJoinNodeOptions(GArrowJoinType joinType, string[] leftKeys, string[] rightKeys) + { + var leftKeysPtr = GetStringArrayPtr(leftKeys); + var rightKeysPtr = GetStringArrayPtr(rightKeys); + + _optionsPtr = garrow_hash_join_node_options_new(joinType, leftKeysPtr, (uint)leftKeys.Length, rightKeysPtr, (uint)rightKeys.Length, null); + } + + public IntPtr GetStringArrayPtr(params string[] arguments) + { + List allocatedMemory = new List(); + + int sizeOfIntPtr = Marshal.SizeOf(typeof(IntPtr)); + IntPtr pointersToArguments = Marshal.AllocHGlobal(sizeOfIntPtr * arguments.Length); + + for (int i = 0; i < arguments.Length; ++i) + { + IntPtr pointerToArgument = Marshal.StringToHGlobalAnsi(arguments[i]); + allocatedMemory.Add(pointerToArgument); + Marshal.WriteIntPtr(pointersToArguments, i * sizeOfIntPtr, pointerToArgument); + } + + return pointersToArguments; + } + + internal unsafe GArrowHashJoinNodeOptions* GetPtr() + { + return _optionsPtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs new file mode 100644 index 000000000000..436fdfc881a1 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs @@ -0,0 +1,40 @@ +// 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 static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class LiteralExpression : Expression + { + private IntPtr _ptr; + + public unsafe LiteralExpression(string literal) + { + var dataPtr = (nint)StringUtil.ToCStringUtf8(literal); + var bufferPtr = CLib.garrow_buffer_new(dataPtr, literal.Length); + var scalarPtr = CLib.garrow_string_scalar_new(bufferPtr); + var datumPtr = (nint)CLib.garrow_scalar_datum_new((nint)scalarPtr); + + _ptr = (nint)CLib.garrow_literal_expression_new((GArrowDatum*)datumPtr); + } + + public override IntPtr GetPtr() + { + return _ptr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs new file mode 100644 index 000000000000..e070c06b0fbd --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs @@ -0,0 +1,32 @@ +// 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. + +namespace Apache.Arrow.Acero +{ + public class RecordBatchReaderSourceNode : ExecNode + { + private unsafe CLib.GArrowExecuteNode* _nodePtr; + + public unsafe RecordBatchReaderSourceNode(RecordBatchReaderSourceNodeOptions options, ExecPlan plan) + { + _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), null); + } + + public override unsafe CLib.GArrowExecuteNode* GetPtr() + { + return _nodePtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs new file mode 100644 index 000000000000..1be20c5df3b3 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs @@ -0,0 +1,37 @@ +// 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 Apache.Arrow.C; +using Apache.Arrow.Ipc; + +namespace Apache.Arrow.Acero +{ + public class RecordBatchReaderSourceNodeOptions : ExecNodeOptions + { + private unsafe CLib.GArrowSourceNodeOptions* _optionsPtr; + + public unsafe RecordBatchReaderSourceNodeOptions(IArrowArrayStream recordBatchReader) + { + var recordBatchReaderPtr = ExportUtil.ExportAndGetRecordBatchReaderPtr(recordBatchReader); + + _optionsPtr = CLib.garrow_source_node_options_new_record_batch_reader(recordBatchReaderPtr); + } + + internal unsafe CLib.GArrowSourceNodeOptions* GetPtr() + { + return _optionsPtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs new file mode 100644 index 000000000000..7418af51a421 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs @@ -0,0 +1,32 @@ +// 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. + +namespace Apache.Arrow.Acero +{ + public class RecordBatchSourceNode : ExecNode + { + private unsafe CLib.GArrowExecuteNode* _nodePtr; + + public unsafe RecordBatchSourceNode(RecordBatchSourceNodeOptions options, ExecPlan plan) + { + _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), null); + } + + public override unsafe CLib.GArrowExecuteNode* GetPtr() + { + return _nodePtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs new file mode 100644 index 000000000000..a8679372fb28 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs @@ -0,0 +1,34 @@ +// 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. + +namespace Apache.Arrow.Acero +{ + public class RecordBatchSourceNodeOptions : ExecNodeOptions + { + private unsafe CLib.GArrowSourceNodeOptions* _optionsPtr; + + public unsafe RecordBatchSourceNodeOptions(RecordBatch recordBatch, Schema schema) + { + var recordBatchPtr = ExportUtil.ExportAndGetRecordBatchPtr(recordBatch, schema); + + _optionsPtr = CLib.garrow_source_node_options_new_record_batch(recordBatchPtr); + } + + internal unsafe CLib.GArrowSourceNodeOptions* GetPtr() + { + return _optionsPtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/SinkNode.cs b/csharp/src/Apache.Arrow.Acero/SinkNode.cs new file mode 100644 index 000000000000..4a11473d5185 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/SinkNode.cs @@ -0,0 +1,34 @@ +// 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.Collections.Generic; + +namespace Apache.Arrow.Acero +{ + public class SinkNode : ExecNode + { + private unsafe CLib.GArrowExecuteNode* _nodePtr; + + public unsafe SinkNode(SinkNodeOptions _options, ExecPlan plan, List inputs) + { + _nodePtr = CLib.garrow_execute_plan_build_sink_node(plan.GetPtr(), inputs[0].GetPtr(), _options.GetPtr(), null); + } + + public unsafe override CLib.GArrowExecuteNode* GetPtr() + { + return _nodePtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs new file mode 100644 index 000000000000..4eb46fb71feb --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs @@ -0,0 +1,47 @@ +// 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 Apache.Arrow.C; +using Apache.Arrow.Ipc; + +namespace Apache.Arrow.Acero +{ + public class SinkNodeOptions : ExecNodeOptions + { + private readonly unsafe CLib.GArrowSinkNodeOptions* _optionsPtr; + private readonly Schema _schema; + + public unsafe SinkNodeOptions(Schema schema) + { + _optionsPtr = CLib.garrow_sink_node_options_new(); + _schema = schema; + } + + public unsafe IArrowArrayStream GetRecordBatchReader() + { + var schemaPtr = ExportUtil.ExportAndGetSchemaPtr(_schema); + var recordBatchReaderPtr = CLib.garrow_sink_node_options_get_reader(_optionsPtr, schemaPtr); + var arrayStreamPtr = CLib.garrow_record_batch_reader_export(recordBatchReaderPtr, null); + var arrayStream = CArrowArrayStreamImporter.ImportArrayStream(arrayStreamPtr); + + return arrayStream; + } + + internal unsafe CLib.GArrowSinkNodeOptions* GetPtr() + { + return _optionsPtr; + } + } +} diff --git a/csharp/test/Apache.Arrow.Acero.Tests/Apache.Arrow.Acero.Tests.csproj b/csharp/test/Apache.Arrow.Acero.Tests/Apache.Arrow.Acero.Tests.csproj new file mode 100644 index 000000000000..c99f0e78a235 --- /dev/null +++ b/csharp/test/Apache.Arrow.Acero.Tests/Apache.Arrow.Acero.Tests.csproj @@ -0,0 +1,18 @@ + + + + net7.0 + + + + + + + + + + + + + + diff --git a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs new file mode 100644 index 000000000000..4bcbaec507d6 --- /dev/null +++ b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs @@ -0,0 +1,207 @@ +// 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 Apache.Arrow.Ipc; +using Apache.Arrow.Types; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using Xunit; +using static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero.Tests +{ + public class DeclarationTests + { + [Fact] + public async Task TestRecordBatchSource() + { + // arrange + var schema = TestData.GetCustomersSchema(); + var recordBatch = TestData.GetCustomersRecordBatch(); + + var recordBatchSource = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(recordBatch, schema)); + + // act + var result = recordBatchSource.ToRecordBatchReader(schema); + + // assert + var table = await ConvertStreamToTable(result, schema); + + AssertTable(table, + """ + c1 | Luke | Skywalker | + c2 | Princess | Leia | + c3 | Obi-Wan | Kenobi | + """, rowCount: 3); + } + + private void AssertTable(Table table, string expected, int? rowCount = null) + { + var actual = PrintPrintTable(table); + Console.WriteLine(actual); + + Assert.Equal(expected, actual); + + if (rowCount.HasValue) + Assert.Equal(rowCount.Value, table.RowCount); + } + + [Fact] + public async Task TestHashJoin() + { + // arrange + var left = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch(), TestData.GetCustomersSchema())); + + var right = new Declaration("record_batch_reader_source", + new RecordBatchReaderSourceNodeOptions(TestData.GetOrdersRecordBatchStream())); + + var hashJoinOptions = new HashJoinNodeOptions( + GArrowJoinType.GARROW_JOIN_TYPE_INNER, + new string[] { "customerId" }, + new string[] { "customerId" }); + + var hashJoin = new Declaration("hashjoin", + options: hashJoinOptions, inputs: new List { left, right }); + + // act + var result = hashJoin.ToRecordBatchReader(GetOutputSchema()); + + // assert + var table = await ConvertStreamToTable(result, GetOutputSchema()); + + AssertTable(table, + """ + c1 | Luke | Skywalker | o1 | c1 | p1 | + c2 | Princess | Leia | o2 | c2 | p2 | + c3 | Obi-Wan | Kenobi | o3 | c3 | p3 | + """, rowCount: 3); + } + + [Fact] + public async Task TestSingleFilter() + { + // arrange + var schema = TestData.GetCustomersSchema(); + var recordBatch = TestData.GetCustomersRecordBatch(); + + var recordBatchSource = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(recordBatch, schema)); + + var orderBy = Declaration.FromSequence(new List { + recordBatchSource, + new Declaration("filter", new FilterNodeOptions( + new Equal(new FieldExpression("firstName"), new LiteralExpression("Luke")) + )) + }); + + // act + var result = orderBy.ToRecordBatchReader(schema); + + // assert + var table = await ConvertStreamToTable(result, schema); + + AssertTable(table, + """ + c1 | Luke | Skywalker | + """, rowCount: 1); + } + + [Fact] + public async Task TestMultiFilter() + { + // arrange + var schema = TestData.GetCustomersSchema(); + var recordBatch = TestData.GetCustomersRecordBatch(); + + var recordBatchSource = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(recordBatch, schema)); + + var orderBy = Declaration.FromSequence(new List { + recordBatchSource, + new Declaration("filter", new FilterNodeOptions( + new Or( + new Equal(new FieldExpression("firstName"), new LiteralExpression("Luke")), + new Equal(new FieldExpression("lastName"), new LiteralExpression("Kenobi")) + ))) + }); + + // act + var result = orderBy.ToRecordBatchReader(schema); + + // assert + var table = await ConvertStreamToTable(result, schema); + + AssertTable(table, + """ + c1 | Luke | Skywalker | + c3 | Obi-Wan | Kenobi | + """, rowCount: 2); + } + + private async Task ConvertStreamToTable(IArrowArrayStream result, Schema schema) + { + var recordBatches = new List(); + + while (true) + { + var recordBatch = await result.ReadNextRecordBatchAsync(); + if (recordBatch == null) break; + recordBatches.Add(recordBatch); + } + + return Table.TableFromRecordBatches(schema, recordBatches); + } + + public string PrintPrintTable(Table table) + { + var sb = new StringBuilder(); + + for (var i = 0; i < table.RowCount; i++) + { + for (var j = 0; j < table.ColumnCount; j++) + { + var array = table.Column(j).Data.Array(0) as StringArray; + sb.Append(array.GetString(i) + " | "); + } + + sb.AppendLine(); + } + + return sb.ToString().Trim('\n').Trim('\r'); + } + + public class TestResult + { + public string TableAsString { get; set; } + public int RowCount { get; set; } + } + + public Schema GetOutputSchema() + { + return new Schema.Builder() + .Field(new Field("customerId", StringType.Default, true)) + .Field(new Field("firstName", StringType.Default, true)) + .Field(new Field("lastName", StringType.Default, true)) + .Field(new Field("orderId", StringType.Default, true)) + .Field(new Field("customerId", StringType.Default, true)) + .Field(new Field("productId", StringType.Default, true)) + .Build(); + } + } +} diff --git a/csharp/test/Apache.Arrow.Acero.Tests/TestData.cs b/csharp/test/Apache.Arrow.Acero.Tests/TestData.cs new file mode 100644 index 000000000000..c7b16eee186e --- /dev/null +++ b/csharp/test/Apache.Arrow.Acero.Tests/TestData.cs @@ -0,0 +1,80 @@ +// 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.Collections.Generic; +using Apache.Arrow.Ipc; +using Apache.Arrow.Types; + +namespace Apache.Arrow.Acero.Tests +{ + public static class TestData + { + public static Schema GetCustomersSchema() + { + return new Schema.Builder() + .Field(new Field("customerId", StringType.Default, true)) + .Field(new Field("firstName", StringType.Default, true)) + .Field(new Field("lastName", StringType.Default, true)) + .Build(); + } + + public static RecordBatch GetCustomersRecordBatch() + { + var schema = GetCustomersSchema(); + + return new RecordBatch(schema, new[] + { + new StringArray.Builder().AppendRange(new[] { "c1", "c2", "c3", "c4" }).Build(), + new StringArray.Builder().AppendRange(new[] { "Luke", "Princess", "Obi-Wan", "Darth" }).Build(), + new StringArray.Builder().AppendRange(new[] { "Skywalker", "Leia", "Kenobi", "Vader" }).Build(), + }, 3); + } + + public static Schema GetOrdersSchema() + { + return new Schema.Builder() + .Field(new Field("orderId", StringType.Default, true)) + .Field(new Field("customerId", StringType.Default, true)) + .Field(new Field("productId", StringType.Default, true)) + .Build(); + } + + public static IArrowArrayStream GetOrdersRecordBatchStream() + { + var schema = GetOrdersSchema(); + + return new AsyncRecordBatchStream(GetOrdersRecordBatchStreamInternal(), schema); + } + + public static async IAsyncEnumerable GetOrdersRecordBatchStreamInternal() + { + var schema = GetOrdersSchema(); + + yield return new RecordBatch(schema, new[] + { + new StringArray.Builder().AppendRange(new[] { "o1", "o2", "o3" }).Build(), + new StringArray.Builder().AppendRange(new[] { "c1", "c2", "c3" }).Build(), + new StringArray.Builder().AppendRange(new[] { "p1", "p2", "p3" }).Build(), + }, 3); + + yield return new RecordBatch(schema, new[] + { + new StringArray.Builder().AppendRange(new[] { "o4", "o5", "o6" }).Build(), + new StringArray.Builder().AppendRange(new[] { "c4", "c5", "c6" }).Build(), + new StringArray.Builder().AppendRange(new[] { "p4", "p5", "p6" }).Build(), + }, 3); + } + } +} From c50892e25f79e3022c5c37dcbd126cf096469c92 Mon Sep 17 00:00:00 2001 From: Dave Searle Date: Tue, 5 Sep 2023 15:22:25 +0100 Subject: [PATCH 2/6] [C#] Implement union node --- .../Apache.Arrow.Acero.csproj | 4 + csharp/src/Apache.Arrow.Acero/CLib.cs | 106 +++++---------- csharp/src/Apache.Arrow.Acero/Declaration.cs | 5 +- csharp/src/Apache.Arrow.Acero/ExecNode.cs | 1 + csharp/src/Apache.Arrow.Acero/ExportUtil.cs | 4 +- .../RecordBatchSourceNodeOptions.cs | 4 +- csharp/src/Apache.Arrow.Acero/StringUtil.cs | 43 ++++++ csharp/src/Apache.Arrow.Acero/UnionNode.cs | 44 +++++++ .../DeclarationTests.cs | 123 +++++++++++++----- 9 files changed, 230 insertions(+), 104 deletions(-) create mode 100644 csharp/src/Apache.Arrow.Acero/StringUtil.cs create mode 100644 csharp/src/Apache.Arrow.Acero/UnionNode.cs diff --git a/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj b/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj index 9483cf28eead..eb7b24fe0869 100644 --- a/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj +++ b/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj @@ -5,6 +5,10 @@ true + + + + diff --git a/csharp/src/Apache.Arrow.Acero/CLib.cs b/csharp/src/Apache.Arrow.Acero/CLib.cs index 4713a3d1fd04..098c4a4b11c5 100644 --- a/csharp/src/Apache.Arrow.Acero/CLib.cs +++ b/csharp/src/Apache.Arrow.Acero/CLib.cs @@ -63,98 +63,103 @@ public enum GArrowSortOrder GARROW_SORT_ORDER_DESCENDING } - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_new")] + public const string DllName = "libarrow-glib-1300.dll"; + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_new")] public static extern unsafe GArrowExecutePlan* garrow_execute_plan_new(GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch")] public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch(GArrowRecordBatch* record_batch); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_import")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_import")] public static extern unsafe GArrowRecordBatch* garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_import")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_import")] public static extern unsafe GArrowSchema* garrow_schema_import(CArrowSchema* c_abi_schema, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_get_field")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_get_field")] public static extern unsafe GArrowField* garrow_schema_get_field(GArrowSchema* schema, uint i); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_is_nullable")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_is_nullable")] public static extern unsafe bool garrow_field_is_nullable(GArrowField* field); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_hash_join_node_options_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_hash_join_node_options_new")] public static extern unsafe GArrowHashJoinNodeOptions* garrow_hash_join_node_options_new(GArrowJoinType type, IntPtr left_keys, uint n_left_keys, IntPtr right_keys, uint n_right_keys, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_hash_join_node")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_hash_join_node")] public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_hash_join_node(GArrowExecutePlan* plan, GArrowExecuteNode* left, GArrowExecuteNode* right, GArrowHashJoinNodeOptions* options, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_source_node")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_source_node")] public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_source_node(GArrowExecutePlan* plan, GArrowSourceNodeOptions* options, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_validate")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_validate")] public static extern unsafe bool garrow_execute_plan_validate(GArrowExecutePlan* plan, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_new")] public static extern unsafe GArrowSinkNodeOptions* garrow_sink_node_options_new(); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_sink_node")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_sink_node")] public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_sink_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowSinkNodeOptions* options, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_start")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_start")] public static extern unsafe void garrow_execute_plan_start(GArrowExecutePlan* plan); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_wait")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_wait")] public static extern unsafe void garrow_execute_plan_wait(GArrowExecutePlan* plan); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_get_reader")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_get_reader")] public static extern unsafe GArrowRecordBatchReader* garrow_sink_node_options_get_reader(GArrowSinkNodeOptions* options, GArrowSchema* schema); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_export")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_export")] public static extern unsafe CArrowArrayStream* garrow_record_batch_reader_export(GArrowRecordBatchReader* reader, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_import")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_import")] public static extern unsafe GArrowRecordBatchReader* garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch_reader")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch_reader")] public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch_reader(GArrowRecordBatchReader* reader); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_filter_node")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_filter_node")] public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_filter_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowFilterNodeOptions* options, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_filter_node_options_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_filter_node_options_new")] public static extern unsafe GArrowFilterNodeOptions* garrow_filter_node_options_new(IntPtr expression); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_call_expression_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_call_expression_new")] public static extern unsafe GArrowCallExpression* garrow_call_expression_new(IntPtr function, IntPtr arguments, GArrowFunctionOptions* options); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_expression_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_expression_new")] public static extern unsafe GArrowFieldExpression* garrow_field_expression_new(IntPtr reference, GError** error); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_literal_expression_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_literal_expression_new")] public static extern unsafe GArrowFieldExpression* garrow_literal_expression_new(GArrowDatum* datum); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_scalar_datum_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_scalar_datum_new")] public static extern unsafe GArrowScalarDatum* garrow_scalar_datum_new(IntPtr value); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new")] public static extern unsafe GArrowBuffer* garrow_buffer_new(IntPtr data, long size); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new_bytes")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new_bytes")] public static extern unsafe GArrowBuffer* garrow_buffer_new_bytes(IntPtr data); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_string_scalar_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_string_scalar_new")] public static extern unsafe GArrowStringScalar* garrow_string_scalar_new(GArrowBuffer* value); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_expression_to_string")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_expression_to_string")] public static extern unsafe IntPtr garrow_expression_to_string(IntPtr expression); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_int64_scalar_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_int64_scalar_new")] public static extern unsafe GArrowInt8Scalar* garrow_int64_scalar_new(long value); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_options_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_options_new")] public static extern unsafe GArrowSortOptions* garrow_sort_options_new(GList* sort_keys); - [DllImport("libarrow-glib-1300.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_key_new")] + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_key_new")] public static extern unsafe GArrowSortKey* garrow_sort_key_new(IntPtr target, GArrowSortOrder order, GError** error); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_node")] + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_node(GArrowExecutePlan* plan, IntPtr factory_name, IntPtr inputs, IntPtr options, out GError **error); } [StructLayout(LayoutKind.Sequential)] @@ -164,43 +169,4 @@ public unsafe struct GList public GList* next; public GList* prev; } - - internal static class StringUtil - { - public static unsafe byte* ToCStringUtf8(string str) - { - var utf8 = System.Text.Encoding.UTF8; - int byteCount = utf8.GetByteCount(str); - byte* byteArray = (byte*)Marshal.AllocHGlobal(byteCount + 1); - - fixed (char* chars = str) - { - utf8.GetBytes(chars, str.Length, byteArray, byteCount); - } - - // Need to make sure it is null-terminated. - byteArray[byteCount] = 0; - - return byteArray; - } - - public static unsafe string PtrToStringUtf8(byte* ptr) - { -#if NETSTANDARD2_1_OR_GREATER - return Marshal.PtrToStringUTF8(ptr); -#else - if (ptr == null) - { - return null; - } - - int length; - for (length = 0; ptr[length] != '\0'; ++length) - { - } - - return System.Text.Encoding.UTF8.GetString(ptr, length); -#endif - } - } } diff --git a/csharp/src/Apache.Arrow.Acero/Declaration.cs b/csharp/src/Apache.Arrow.Acero/Declaration.cs index 7ce74887d4d2..4e427a30a15b 100644 --- a/csharp/src/Apache.Arrow.Acero/Declaration.cs +++ b/csharp/src/Apache.Arrow.Acero/Declaration.cs @@ -28,7 +28,7 @@ public class Declaration public List Inputs { get; set; } = new(); - public Declaration(string factoryName, ExecNodeOptions options, List inputs = null) + public Declaration(string factoryName, ExecNodeOptions options = null, List inputs = null) { _factoryName = factoryName; _options = options; @@ -112,6 +112,9 @@ private ExecNode AddToPlan(ExecPlan plan) case "filter": return new FilterNode(_options as FilterNodeOptions, plan, nodes); + case "union": + return new UnionNode(plan, nodes); + default: throw new Exception($"Unknown factory {_factoryName}"); } diff --git a/csharp/src/Apache.Arrow.Acero/ExecNode.cs b/csharp/src/Apache.Arrow.Acero/ExecNode.cs index 0bd5f8d54608..95fe1b1d3cfe 100644 --- a/csharp/src/Apache.Arrow.Acero/ExecNode.cs +++ b/csharp/src/Apache.Arrow.Acero/ExecNode.cs @@ -20,5 +20,6 @@ namespace Apache.Arrow.Acero public abstract class ExecNode { public abstract unsafe GArrowExecuteNode* GetPtr(); + } } diff --git a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs index 5ded131e2ac7..61a091e09267 100644 --- a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs +++ b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs @@ -34,9 +34,9 @@ internal static class ExportUtil return gSchema; } - public static unsafe CLib.GArrowRecordBatch* ExportAndGetRecordBatchPtr(RecordBatch recordBatch, Schema schema) + public static unsafe CLib.GArrowRecordBatch* ExportAndGetRecordBatchPtr(RecordBatch recordBatch) { - var schemaPtr = ExportAndGetSchemaPtr(schema); + var schemaPtr = ExportAndGetSchemaPtr(recordBatch.Schema); // allocate a C ABI CArrowArray CArrowArray* cArray = CArrowArray.Create(); diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs index a8679372fb28..a4bb192607f4 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs @@ -19,9 +19,9 @@ public class RecordBatchSourceNodeOptions : ExecNodeOptions { private unsafe CLib.GArrowSourceNodeOptions* _optionsPtr; - public unsafe RecordBatchSourceNodeOptions(RecordBatch recordBatch, Schema schema) + public unsafe RecordBatchSourceNodeOptions(RecordBatch recordBatch) { - var recordBatchPtr = ExportUtil.ExportAndGetRecordBatchPtr(recordBatch, schema); + var recordBatchPtr = ExportUtil.ExportAndGetRecordBatchPtr(recordBatch); _optionsPtr = CLib.garrow_source_node_options_new_record_batch(recordBatchPtr); } diff --git a/csharp/src/Apache.Arrow.Acero/StringUtil.cs b/csharp/src/Apache.Arrow.Acero/StringUtil.cs new file mode 100644 index 000000000000..29154a494b8b --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/StringUtil.cs @@ -0,0 +1,43 @@ +using System.Runtime.InteropServices; + +namespace Apache.Arrow.Acero +{ + internal static class StringUtil + { + public static unsafe byte* ToCStringUtf8(string str) + { + var utf8 = System.Text.Encoding.UTF8; + int byteCount = utf8.GetByteCount(str); + byte* byteArray = (byte*)Marshal.AllocHGlobal(byteCount + 1); + + fixed (char* chars = str) + { + utf8.GetBytes(chars, str.Length, byteArray, byteCount); + } + + // Need to make sure it is null-terminated. + byteArray[byteCount] = 0; + + return byteArray; + } + + public static unsafe string PtrToStringUtf8(byte* ptr) + { +#if NETSTANDARD2_1_OR_GREATER + return Marshal.PtrToStringUTF8(ptr); +#else + if (ptr == null) + { + return null; + } + + int length; + for (length = 0; ptr[length] != '\0'; ++length) + { + } + + return System.Text.Encoding.UTF8.GetString(ptr, length); +#endif + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/UnionNode.cs b/csharp/src/Apache.Arrow.Acero/UnionNode.cs new file mode 100644 index 000000000000..7dad911fc278 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/UnionNode.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class UnionNode : ExecNode + { + private unsafe CLib.GArrowExecuteNode* _nodePtr; + + public unsafe UnionNode(ExecPlan plan, List nodes) + { + var factoryName = "union"; + var factoryNamePtr = (IntPtr)StringUtil.ToCStringUtf8(factoryName); + + var lhs = nodes[0]; + var rhs = nodes[1]; + + var list = new GLib.List(IntPtr.Zero); + list.Append((IntPtr)lhs.GetPtr()); + list.Append((IntPtr)rhs.GetPtr()); + + // todo: using this ptr causes the following error + // g_object_new_valist: invalid unclassed object pointer for value type 'GArrowExecuteNodeOptions' + IntPtr optionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(new GArrowExecuteNodeOptions(), optionsPtr, false); + + // for now just use the sink options + var optionsPtr2 = garrow_sink_node_options_new(); + + GError** error; + + _nodePtr = garrow_execute_plan_build_node(plan.GetPtr(), factoryNamePtr, list.Handle, (IntPtr)optionsPtr2, out error); + + if ((IntPtr)error != IntPtr.Zero) + { + throw new GLib.GException((IntPtr)error); + } + } + + public override unsafe GArrowExecuteNode* GetPtr() => _nodePtr; + } +} diff --git a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs index 4bcbaec507d6..a6a32806ff10 100644 --- a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs +++ b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs @@ -15,45 +15,54 @@ using Apache.Arrow.Ipc; using Apache.Arrow.Types; -using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xunit; +using Xunit.Abstractions; using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero.Tests { public class DeclarationTests { + private readonly ITestOutputHelper _output; + + public DeclarationTests(ITestOutputHelper output) + { + _output = output; + } + [Fact] public async Task TestRecordBatchSource() { // arrange - var schema = TestData.GetCustomersSchema(); var recordBatch = TestData.GetCustomersRecordBatch(); var recordBatchSource = new Declaration("record_batch_source", - new RecordBatchSourceNodeOptions(recordBatch, schema)); + new RecordBatchSourceNodeOptions(recordBatch)); // act + var schema = TestData.GetCustomersSchema(); var result = recordBatchSource.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result, schema); + var table = await ConvertStreamToTable(result); AssertTable(table, """ - c1 | Luke | Skywalker | - c2 | Princess | Leia | - c3 | Obi-Wan | Kenobi | + customerId | firstName | lastName | + c1 | Luke | Skywalker | + c2 | Princess | Leia | + c3 | Obi-Wan | Kenobi | """, rowCount: 3); } private void AssertTable(Table table, string expected, int? rowCount = null) { var actual = PrintPrintTable(table); - Console.WriteLine(actual); + + _output.WriteLine(actual); Assert.Equal(expected, actual); @@ -66,7 +75,7 @@ public async Task TestHashJoin() { // arrange var left = new Declaration("record_batch_source", - new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch(), TestData.GetCustomersSchema())); + new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch())); var right = new Declaration("record_batch_reader_source", new RecordBatchReaderSourceNodeOptions(TestData.GetOrdersRecordBatchStream())); @@ -80,16 +89,18 @@ public async Task TestHashJoin() options: hashJoinOptions, inputs: new List { left, right }); // act - var result = hashJoin.ToRecordBatchReader(GetOutputSchema()); + var schema = GetOutputSchema(); + var result = hashJoin.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result, GetOutputSchema()); + var table = await ConvertStreamToTable(result); AssertTable(table, """ - c1 | Luke | Skywalker | o1 | c1 | p1 | - c2 | Princess | Leia | o2 | c2 | p2 | - c3 | Obi-Wan | Kenobi | o3 | c3 | p3 | + customerId | firstName | lastName | orderId | customerId | productId | + c1 | Luke | Skywalker | o1 | c1 | p1 | + c2 | Princess | Leia | o2 | c2 | p2 | + c3 | Obi-Wan | Kenobi | o3 | c3 | p3 | """, rowCount: 3); } @@ -97,11 +108,10 @@ public async Task TestHashJoin() public async Task TestSingleFilter() { // arrange - var schema = TestData.GetCustomersSchema(); var recordBatch = TestData.GetCustomersRecordBatch(); var recordBatchSource = new Declaration("record_batch_source", - new RecordBatchSourceNodeOptions(recordBatch, schema)); + new RecordBatchSourceNodeOptions(recordBatch)); var orderBy = Declaration.FromSequence(new List { recordBatchSource, @@ -111,14 +121,16 @@ public async Task TestSingleFilter() }); // act + var schema = TestData.GetCustomersSchema(); var result = orderBy.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result, schema); + var table = await ConvertStreamToTable(result); AssertTable(table, """ - c1 | Luke | Skywalker | + customerId | firstName | lastName | + c1 | Luke | Skywalker | """, rowCount: 1); } @@ -126,11 +138,10 @@ public async Task TestSingleFilter() public async Task TestMultiFilter() { // arrange - var schema = TestData.GetCustomersSchema(); var recordBatch = TestData.GetCustomersRecordBatch(); var recordBatchSource = new Declaration("record_batch_source", - new RecordBatchSourceNodeOptions(recordBatch, schema)); + new RecordBatchSourceNodeOptions(recordBatch)); var orderBy = Declaration.FromSequence(new List { recordBatchSource, @@ -142,44 +153,98 @@ public async Task TestMultiFilter() }); // act + var schema = TestData.GetCustomersSchema(); var result = orderBy.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result, schema); + var table = await ConvertStreamToTable(result); AssertTable(table, """ - c1 | Luke | Skywalker | - c3 | Obi-Wan | Kenobi | + customerId | firstName | lastName | + c1 | Luke | Skywalker | + c3 | Obi-Wan | Kenobi | """, rowCount: 2); } - private async Task
ConvertStreamToTable(IArrowArrayStream result, Schema schema) + [Fact] + public async Task TestUnion() { - var recordBatches = new List(); + // arrange + var schema = TestData.GetCustomersSchema(); + var left = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch())); + + var right = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch())); + + var union = new Declaration("union", inputs: new List { left, right }); + + // act + var result = union.ToRecordBatchReader(schema); + + // assert + var table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + customerId | firstName | lastName | + c1 | Luke | Skywalker | + c2 | Princess | Leia | + c3 | Obi-Wan | Kenobi | + c1 | Luke | Skywalker | + c2 | Princess | Leia | + c3 | Obi-Wan | Kenobi | + """, rowCount: 6); + } + + private async Task
ConvertStreamToTable(IArrowArrayStream result) + { + Schema schema = null; + + var recordBatches = new List(); + while (true) { var recordBatch = await result.ReadNextRecordBatchAsync(); if (recordBatch == null) break; + + if (schema == null) + schema = recordBatch.Schema; + recordBatches.Add(recordBatch); } return Table.TableFromRecordBatches(schema, recordBatches); } - public string PrintPrintTable(Table table) + public static string PrintPrintTable(Table table) { var sb = new StringBuilder(); + for (var i = 0; i < table.ColumnCount; i++) + { + sb.Append(table.Column(i).Name.PadRight(10) + " | "); + } + + sb.AppendLine(); + for (var i = 0; i < table.RowCount; i++) { for (var j = 0; j < table.ColumnCount; j++) { - var array = table.Column(j).Data.Array(0) as StringArray; - sb.Append(array.GetString(i) + " | "); - } + var sliced = table.Column(j).Slice(i, 1); + for (var k = 0; k < sliced.Data.ArrayCount; k++) + { + if (sliced.Data.Array(k).Length == 0) + continue; + + var data = sliced.Data.Array(k) as StringArray; + sb.Append(data.GetString(0).PadRight(10) + " | "); + } + } sb.AppendLine(); } From 5f71c02f1abbf426935213c5e49855ae1d0e43ef Mon Sep 17 00:00:00 2001 From: Dave Searle Date: Thu, 7 Sep 2023 16:49:10 +0100 Subject: [PATCH 3/6] [C#] Implement project node Implement project node. Improve error handling and general tidy up of code. --- csharp/src/Apache.Arrow.Acero/CLib.cs | 38 +++++--- csharp/src/Apache.Arrow.Acero/Declaration.cs | 11 ++- .../src/Apache.Arrow.Acero/ExceptionUtil.cs | 14 +++ csharp/src/Apache.Arrow.Acero/ExecNode.cs | 1 - csharp/src/Apache.Arrow.Acero/ExecPlan.cs | 16 +++- csharp/src/Apache.Arrow.Acero/ExportUtil.cs | 16 +++- csharp/src/Apache.Arrow.Acero/Expression.cs | 6 ++ .../src/Apache.Arrow.Acero/FieldExpression.cs | 7 +- csharp/src/Apache.Arrow.Acero/FilterNode.cs | 9 +- .../Apache.Arrow.Acero/FilterNodeOptions.cs | 6 -- csharp/src/Apache.Arrow.Acero/Function.cs | 23 ++--- csharp/src/Apache.Arrow.Acero/HashJoinNode.cs | 11 ++- .../Apache.Arrow.Acero/HashJoinNodeOptions.cs | 26 +---- .../Apache.Arrow.Acero/LiteralExpression.cs | 14 ++- csharp/src/Apache.Arrow.Acero/ProjectNode.cs | 39 ++++++++ .../Apache.Arrow.Acero/ProjectNodeOptions.cs | 43 +++++++++ .../RecordBatchReaderSourceNode.cs | 8 +- .../RecordBatchSourceNode.cs | 8 +- csharp/src/Apache.Arrow.Acero/SinkNode.cs | 7 +- .../src/Apache.Arrow.Acero/SinkNodeOptions.cs | 9 +- csharp/src/Apache.Arrow.Acero/StringUtil.cs | 21 ++++- csharp/src/Apache.Arrow.Acero/UnionNode.cs | 5 +- .../DeclarationTests.cs | 94 ++++++++++++++----- 23 files changed, 328 insertions(+), 104 deletions(-) create mode 100644 csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ProjectNode.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs diff --git a/csharp/src/Apache.Arrow.Acero/CLib.cs b/csharp/src/Apache.Arrow.Acero/CLib.cs index 098c4a4b11c5..9811a976ffbb 100644 --- a/csharp/src/Apache.Arrow.Acero/CLib.cs +++ b/csharp/src/Apache.Arrow.Acero/CLib.cs @@ -44,6 +44,8 @@ public struct GArrowStringScalar { } public struct GArrowInt8Scalar { } public struct GArrowSortOptions { } public struct GArrowSortKey { } + public struct GArrowProjectNodeOptions { } + public struct GArrowInt32Scalar { } public enum GArrowJoinType { @@ -66,16 +68,16 @@ public enum GArrowSortOrder public const string DllName = "libarrow-glib-1300.dll"; [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_new")] - public static extern unsafe GArrowExecutePlan* garrow_execute_plan_new(GError** error); + public static extern unsafe GArrowExecutePlan* garrow_execute_plan_new(out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch")] public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch(GArrowRecordBatch* record_batch); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_import")] - public static extern unsafe GArrowRecordBatch* garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, GError** error); + public static extern unsafe GArrowRecordBatch* garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_import")] - public static extern unsafe GArrowSchema* garrow_schema_import(CArrowSchema* c_abi_schema, GError** error); + public static extern unsafe GArrowSchema* garrow_schema_import(CArrowSchema* c_abi_schema, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_get_field")] public static extern unsafe GArrowField* garrow_schema_get_field(GArrowSchema* schema, uint i); @@ -84,22 +86,22 @@ public enum GArrowSortOrder public static extern unsafe bool garrow_field_is_nullable(GArrowField* field); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_hash_join_node_options_new")] - public static extern unsafe GArrowHashJoinNodeOptions* garrow_hash_join_node_options_new(GArrowJoinType type, IntPtr left_keys, uint n_left_keys, IntPtr right_keys, uint n_right_keys, GError** error); + public static extern unsafe GArrowHashJoinNodeOptions* garrow_hash_join_node_options_new(GArrowJoinType type, IntPtr left_keys, uint n_left_keys, IntPtr right_keys, uint n_right_keys, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_hash_join_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_hash_join_node(GArrowExecutePlan* plan, GArrowExecuteNode* left, GArrowExecuteNode* right, GArrowHashJoinNodeOptions* options, GError** error); + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_hash_join_node(GArrowExecutePlan* plan, GArrowExecuteNode* left, GArrowExecuteNode* right, GArrowHashJoinNodeOptions* options, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_source_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_source_node(GArrowExecutePlan* plan, GArrowSourceNodeOptions* options, GError** error); + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_source_node(GArrowExecutePlan* plan, GArrowSourceNodeOptions* options, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_validate")] - public static extern unsafe bool garrow_execute_plan_validate(GArrowExecutePlan* plan, GError** error); + public static extern unsafe bool garrow_execute_plan_validate(GArrowExecutePlan* plan, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_new")] public static extern unsafe GArrowSinkNodeOptions* garrow_sink_node_options_new(); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_sink_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_sink_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowSinkNodeOptions* options, GError** error); + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_sink_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowSinkNodeOptions* options, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_start")] public static extern unsafe void garrow_execute_plan_start(GArrowExecutePlan* plan); @@ -111,16 +113,16 @@ public enum GArrowSortOrder public static extern unsafe GArrowRecordBatchReader* garrow_sink_node_options_get_reader(GArrowSinkNodeOptions* options, GArrowSchema* schema); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_export")] - public static extern unsafe CArrowArrayStream* garrow_record_batch_reader_export(GArrowRecordBatchReader* reader, GError** error); + public static extern unsafe CArrowArrayStream* garrow_record_batch_reader_export(GArrowRecordBatchReader* reader, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_import")] - public static extern unsafe GArrowRecordBatchReader* garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, GError** error); + public static extern unsafe GArrowRecordBatchReader* garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch_reader")] public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch_reader(GArrowRecordBatchReader* reader); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_filter_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_filter_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowFilterNodeOptions* options, GError** error); + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_filter_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowFilterNodeOptions* options, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_filter_node_options_new")] public static extern unsafe GArrowFilterNodeOptions* garrow_filter_node_options_new(IntPtr expression); @@ -129,7 +131,7 @@ public enum GArrowSortOrder public static extern unsafe GArrowCallExpression* garrow_call_expression_new(IntPtr function, IntPtr arguments, GArrowFunctionOptions* options); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_expression_new")] - public static extern unsafe GArrowFieldExpression* garrow_field_expression_new(IntPtr reference, GError** error); + public static extern unsafe GArrowFieldExpression* garrow_field_expression_new(IntPtr reference, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_literal_expression_new")] public static extern unsafe GArrowFieldExpression* garrow_literal_expression_new(GArrowDatum* datum); @@ -156,10 +158,20 @@ public enum GArrowSortOrder public static extern unsafe GArrowSortOptions* garrow_sort_options_new(GList* sort_keys); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_key_new")] - public static extern unsafe GArrowSortKey* garrow_sort_key_new(IntPtr target, GArrowSortOrder order, GError** error); + public static extern unsafe GArrowSortKey* garrow_sort_key_new(IntPtr target, GArrowSortOrder order, out GError** error); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_node")] public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_node(GArrowExecutePlan* plan, IntPtr factory_name, IntPtr inputs, IntPtr options, out GError **error); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_project_node_options_new")] + public static extern unsafe GArrowProjectNodeOptions* garrow_project_node_options_new(GList* expressions, IntPtr names, int n_names); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_project_node")] + public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_project_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowProjectNodeOptions* options, out GError** error); + + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_int32_scalar_new")] + public static extern unsafe GArrowInt32Scalar* garrow_int32_scalar_new(int value); } [StructLayout(LayoutKind.Sequential)] diff --git a/csharp/src/Apache.Arrow.Acero/Declaration.cs b/csharp/src/Apache.Arrow.Acero/Declaration.cs index 4e427a30a15b..d1610981a47d 100644 --- a/csharp/src/Apache.Arrow.Acero/Declaration.cs +++ b/csharp/src/Apache.Arrow.Acero/Declaration.cs @@ -71,7 +71,7 @@ public static IArrowArrayStream ToRecordBatchReader(Declaration declaration, Sch new List { declaration, - new Declaration("table_sink", sinkNodeOptions) + new Declaration("sink", sinkNodeOptions) }); sinkNode.AddToPlan(plan); @@ -89,15 +89,15 @@ private ExecNode AddToPlan(ExecPlan plan) { var nodes = new List(); - foreach (var input in Inputs) + foreach (Declaration input in Inputs) { - var node = input.AddToPlan(plan); + ExecNode node = input.AddToPlan(plan); nodes.Add(node); } switch (_factoryName) { - case "table_sink": + case "sink": return new SinkNode(_options as SinkNodeOptions, plan, nodes); case "record_batch_source": @@ -115,6 +115,9 @@ private ExecNode AddToPlan(ExecPlan plan) case "union": return new UnionNode(plan, nodes); + case "project": + return new ProjectNode(_options as ProjectNodeOptions, plan, nodes); + default: throw new Exception($"Unknown factory {_factoryName}"); } diff --git a/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs b/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs new file mode 100644 index 000000000000..5ea3dfde5cb4 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs @@ -0,0 +1,14 @@ +using System; +using static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public static class ExceptionUtil + { + public static unsafe void ThrowOnError(GError** error) + { + if ((IntPtr)error != IntPtr.Zero) + throw new GLib.GException((IntPtr)error); + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExecNode.cs b/csharp/src/Apache.Arrow.Acero/ExecNode.cs index 95fe1b1d3cfe..0bd5f8d54608 100644 --- a/csharp/src/Apache.Arrow.Acero/ExecNode.cs +++ b/csharp/src/Apache.Arrow.Acero/ExecNode.cs @@ -20,6 +20,5 @@ namespace Apache.Arrow.Acero public abstract class ExecNode { public abstract unsafe GArrowExecuteNode* GetPtr(); - } } diff --git a/csharp/src/Apache.Arrow.Acero/ExecPlan.cs b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs index a5822b53204f..16a778519746 100644 --- a/csharp/src/Apache.Arrow.Acero/ExecPlan.cs +++ b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs @@ -13,6 +13,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +using static Apache.Arrow.Acero.CLib; + namespace Apache.Arrow.Acero { public class ExecPlan @@ -21,12 +23,22 @@ public class ExecPlan public unsafe ExecPlan() { - _planPtr = CLib.garrow_execute_plan_new(null); + GError** error; + + _planPtr = CLib.garrow_execute_plan_new(out error); + + ExceptionUtil.ThrowOnError(error); } public unsafe bool Validate() { - return CLib.garrow_execute_plan_validate(_planPtr, null); + GError** error; + + var valid = CLib.garrow_execute_plan_validate(_planPtr, out error); + + ExceptionUtil.ThrowOnError(error); + + return valid; } public unsafe void StartProducing() diff --git a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs index 61a091e09267..59f7a81e910c 100644 --- a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs +++ b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs @@ -15,6 +15,7 @@ using Apache.Arrow.C; using Apache.Arrow.Ipc; +using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { @@ -29,7 +30,10 @@ internal static class ExportUtil CArrowSchemaExporter.ExportSchema(schema, cSchema); // Import CArrowSchema into a GArrowSchema - var gSchema = CLib.garrow_schema_import(cSchema, null); + GError** error; + var gSchema = CLib.garrow_schema_import(cSchema, out error); + + ExceptionUtil.ThrowOnError(error); return gSchema; } @@ -45,7 +49,10 @@ internal static class ExportUtil CArrowArrayExporter.ExportRecordBatch(recordBatch, cArray); // import the CArrowArray into a gArrowRecordBatch - var gRecordBatch = CLib.garrow_record_batch_import(cArray, schemaPtr, null); + GError** error; + var gRecordBatch = CLib.garrow_record_batch_import(cArray, schemaPtr, out error); + + ExceptionUtil.ThrowOnError(error); return gRecordBatch; } @@ -59,7 +66,10 @@ internal static class ExportUtil CArrowArrayStreamExporter.ExportArrayStream(recordBatchReader, cArrayStream); // next import the c arrow as a gArrowRecordBatch - var gRecordBatchReader = CLib.garrow_record_batch_reader_import(cArrayStream, null); + GError** error; + var gRecordBatchReader = CLib.garrow_record_batch_reader_import(cArrayStream, out error); + + ExceptionUtil.ThrowOnError(error); return gRecordBatchReader; } diff --git a/csharp/src/Apache.Arrow.Acero/Expression.cs b/csharp/src/Apache.Arrow.Acero/Expression.cs index fc2e25ecff77..df420e0623e2 100644 --- a/csharp/src/Apache.Arrow.Acero/Expression.cs +++ b/csharp/src/Apache.Arrow.Acero/Expression.cs @@ -20,5 +20,11 @@ namespace Apache.Arrow.Acero public abstract class Expression { public abstract IntPtr GetPtr(); + + public override unsafe string ToString() + { + var strPtr = CLib.garrow_expression_to_string(GetPtr()); + return StringUtil.PtrToStringUtf8((byte*)strPtr); + } } } diff --git a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs index d380768889f1..b792bee32eeb 100644 --- a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs +++ b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs @@ -14,6 +14,7 @@ // limitations under the License. using System; +using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { @@ -25,7 +26,11 @@ public unsafe FieldExpression(string field) { var reference = (nint)StringUtil.ToCStringUtf8(field); - _ptr = (nint)CLib.garrow_field_expression_new(reference, null); + GError** error; + + _ptr = (IntPtr)CLib.garrow_field_expression_new(reference, out error); + + ExceptionUtil.ThrowOnError(error); } public override IntPtr GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/FilterNode.cs b/csharp/src/Apache.Arrow.Acero/FilterNode.cs index 294855f61632..ec7e09865481 100644 --- a/csharp/src/Apache.Arrow.Acero/FilterNode.cs +++ b/csharp/src/Apache.Arrow.Acero/FilterNode.cs @@ -14,6 +14,7 @@ // limitations under the License. using System.Collections.Generic; +using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { @@ -22,8 +23,12 @@ public class FilterNode : ExecNode private unsafe CLib.GArrowExecuteNode* _nodePtr; public unsafe FilterNode(FilterNodeOptions options, ExecPlan plan, List nodes) - { - _nodePtr = CLib.garrow_execute_plan_build_filter_node(plan.GetPtr(), nodes[0].GetPtr(), options.GetPtr(), null); + { + GError** error; + + _nodePtr = CLib.garrow_execute_plan_build_filter_node(plan.GetPtr(), nodes[0].GetPtr(), options.GetPtr(), out error); + + ExceptionUtil.ThrowOnError(error); } public override unsafe CLib.GArrowExecuteNode* GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs index 7545524136ff..ae7eecbdc1a4 100644 --- a/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs @@ -13,7 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero @@ -25,11 +24,6 @@ public class FilterNodeOptions : ExecNodeOptions public unsafe FilterNodeOptions(Expression expr) { _optionsPtr = CLib.garrow_filter_node_options_new(expr.GetPtr()); - - var strPtr = CLib.garrow_expression_to_string(expr.GetPtr()); - var str = StringUtil.PtrToStringUtf8((byte*)strPtr); - - Console.WriteLine(str); } internal unsafe GArrowFilterNodeOptions* GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/Function.cs b/csharp/src/Apache.Arrow.Acero/Function.cs index 7f3c0d3d53fd..1418c8b45872 100644 --- a/csharp/src/Apache.Arrow.Acero/Function.cs +++ b/csharp/src/Apache.Arrow.Acero/Function.cs @@ -14,7 +14,6 @@ // limitations under the License. using System; -using System.Runtime.InteropServices; namespace Apache.Arrow.Acero { @@ -23,24 +22,20 @@ public class Function : Expression private IntPtr _ptr; public unsafe Function(string functionName, Expression lhs, Expression rhs) + : this(functionName, new[] { lhs, rhs }) { - var functionNamePtr = StringUtil.ToCStringUtf8(functionName); + } - var rhsItem = new GList - { - data = rhs.GetPtr() - }; + public unsafe Function(string functionName, params Expression[] args) + { + var functionNamePtr = StringUtil.ToCStringUtf8(functionName); - var lhsItem = new GList - { - data = lhs.GetPtr(), - next = &rhsItem - }; + var list = new GLib.List(IntPtr.Zero); - IntPtr glistPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); - Marshal.StructureToPtr(lhsItem, glistPtr, false); + foreach (var arg in args) + list.Append(arg.GetPtr()); - _ptr = (nint)CLib.garrow_call_expression_new((IntPtr)functionNamePtr, glistPtr, null); + _ptr = (IntPtr)CLib.garrow_call_expression_new((IntPtr)functionNamePtr, list.Handle, null); } public override IntPtr GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs index cd5e0f1fe458..56dfc814a225 100644 --- a/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs @@ -14,6 +14,7 @@ // limitations under the License. using System.Collections.Generic; +using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { @@ -23,10 +24,14 @@ public class HashJoinNode : ExecNode public unsafe HashJoinNode(HashJoinNodeOptions options, ExecPlan plan, List inputs) { - var left = inputs[0]; - var right = inputs[1]; + ExecNode left = inputs[0]; + ExecNode right = inputs[1]; - _nodePtr = CLib.garrow_execute_plan_build_hash_join_node(plan.GetPtr(), left.GetPtr(), right.GetPtr(), options.GetPtr(), null); + GError** error; + + _nodePtr = CLib.garrow_execute_plan_build_hash_join_node(plan.GetPtr(), left.GetPtr(), right.GetPtr(), options.GetPtr(), out error); + + ExceptionUtil.ThrowOnError(error); } public override unsafe CLib.GArrowExecuteNode* GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs index 61647213de24..488454390561 100644 --- a/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs @@ -13,9 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero @@ -26,27 +23,14 @@ public class HashJoinNodeOptions : ExecNodeOptions public unsafe HashJoinNodeOptions(GArrowJoinType joinType, string[] leftKeys, string[] rightKeys) { - var leftKeysPtr = GetStringArrayPtr(leftKeys); - var rightKeysPtr = GetStringArrayPtr(rightKeys); + var leftKeysPtr = StringUtil.GetStringArrayPtr(leftKeys); + var rightKeysPtr = StringUtil.GetStringArrayPtr(rightKeys); - _optionsPtr = garrow_hash_join_node_options_new(joinType, leftKeysPtr, (uint)leftKeys.Length, rightKeysPtr, (uint)rightKeys.Length, null); - } - - public IntPtr GetStringArrayPtr(params string[] arguments) - { - List allocatedMemory = new List(); - - int sizeOfIntPtr = Marshal.SizeOf(typeof(IntPtr)); - IntPtr pointersToArguments = Marshal.AllocHGlobal(sizeOfIntPtr * arguments.Length); + GError** error; - for (int i = 0; i < arguments.Length; ++i) - { - IntPtr pointerToArgument = Marshal.StringToHGlobalAnsi(arguments[i]); - allocatedMemory.Add(pointerToArgument); - Marshal.WriteIntPtr(pointersToArguments, i * sizeOfIntPtr, pointerToArgument); - } + _optionsPtr = garrow_hash_join_node_options_new(joinType, leftKeysPtr, (uint)leftKeys.Length, rightKeysPtr, (uint)rightKeys.Length, out error); - return pointersToArguments; + ExceptionUtil.ThrowOnError(error); } internal unsafe GArrowHashJoinNodeOptions* GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs index 436fdfc881a1..080cd59145a9 100644 --- a/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs +++ b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs @@ -24,12 +24,20 @@ public class LiteralExpression : Expression public unsafe LiteralExpression(string literal) { - var dataPtr = (nint)StringUtil.ToCStringUtf8(literal); + var dataPtr = (IntPtr)StringUtil.ToCStringUtf8(literal); var bufferPtr = CLib.garrow_buffer_new(dataPtr, literal.Length); var scalarPtr = CLib.garrow_string_scalar_new(bufferPtr); - var datumPtr = (nint)CLib.garrow_scalar_datum_new((nint)scalarPtr); + var datumPtr = (IntPtr)CLib.garrow_scalar_datum_new((IntPtr)scalarPtr); - _ptr = (nint)CLib.garrow_literal_expression_new((GArrowDatum*)datumPtr); + _ptr = (IntPtr)CLib.garrow_literal_expression_new((GArrowDatum*)datumPtr); + } + + public unsafe LiteralExpression(int literal) + { + var scalarPtr = CLib.garrow_int32_scalar_new(literal); + var datumPtr = (IntPtr)CLib.garrow_scalar_datum_new((IntPtr)scalarPtr); + + _ptr = (IntPtr)CLib.garrow_literal_expression_new((GArrowDatum*)datumPtr); } public override IntPtr GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/ProjectNode.cs b/csharp/src/Apache.Arrow.Acero/ProjectNode.cs new file mode 100644 index 000000000000..7e95b8ea787c --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ProjectNode.cs @@ -0,0 +1,39 @@ +// 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.Collections.Generic; +using static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class ProjectNode : ExecNode + { + private unsafe CLib.GArrowExecuteNode* _nodePtr; + + public unsafe ProjectNode(ProjectNodeOptions options, ExecPlan plan, List nodes) + { + GError** error; + + _nodePtr = CLib.garrow_execute_plan_build_project_node(plan.GetPtr(), nodes[0].GetPtr(), options.GetPtr(), out error); + + ExceptionUtil.ThrowOnError(error); + } + + public override unsafe CLib.GArrowExecuteNode* GetPtr() + { + return _nodePtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs new file mode 100644 index 000000000000..36607ca9d8c1 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs @@ -0,0 +1,43 @@ +// 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 static Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class ProjectNodeOptions : ExecNodeOptions + { + private unsafe GArrowProjectNodeOptions* _optionsPtr; + + public unsafe ProjectNodeOptions(List expressions, List names) + { + var list = new GLib.List(IntPtr.Zero); + + foreach (var expression in expressions) + list.Append(expression.GetPtr()); + + var namesPtr = StringUtil.GetStringArrayPtr(names.ToArray()); + + _optionsPtr = CLib.garrow_project_node_options_new((GList*)list.Handle, namesPtr, names.Count); + } + + internal unsafe GArrowProjectNodeOptions* GetPtr() + { + return _optionsPtr; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs index e070c06b0fbd..fa9302695e69 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs @@ -13,6 +13,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +using static Apache.Arrow.Acero.CLib; + namespace Apache.Arrow.Acero { public class RecordBatchReaderSourceNode : ExecNode @@ -21,7 +23,11 @@ public class RecordBatchReaderSourceNode : ExecNode public unsafe RecordBatchReaderSourceNode(RecordBatchReaderSourceNodeOptions options, ExecPlan plan) { - _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), null); + GError** error; + + _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), out error); + + ExceptionUtil.ThrowOnError(error); } public override unsafe CLib.GArrowExecuteNode* GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs index 7418af51a421..0dc6797c83cb 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs @@ -13,6 +13,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +using static Apache.Arrow.Acero.CLib; + namespace Apache.Arrow.Acero { public class RecordBatchSourceNode : ExecNode @@ -21,7 +23,11 @@ public class RecordBatchSourceNode : ExecNode public unsafe RecordBatchSourceNode(RecordBatchSourceNodeOptions options, ExecPlan plan) { - _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), null); + GError** error; + + _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), out error); + + ExceptionUtil.ThrowOnError(error); } public override unsafe CLib.GArrowExecuteNode* GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/SinkNode.cs b/csharp/src/Apache.Arrow.Acero/SinkNode.cs index 4a11473d5185..b9084d7b9632 100644 --- a/csharp/src/Apache.Arrow.Acero/SinkNode.cs +++ b/csharp/src/Apache.Arrow.Acero/SinkNode.cs @@ -14,6 +14,7 @@ // limitations under the License. using System.Collections.Generic; +using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { @@ -23,7 +24,11 @@ public class SinkNode : ExecNode public unsafe SinkNode(SinkNodeOptions _options, ExecPlan plan, List inputs) { - _nodePtr = CLib.garrow_execute_plan_build_sink_node(plan.GetPtr(), inputs[0].GetPtr(), _options.GetPtr(), null); + GError** error; + + _nodePtr = CLib.garrow_execute_plan_build_sink_node(plan.GetPtr(), inputs[0].GetPtr(), _options.GetPtr(), out error); + + ExceptionUtil.ThrowOnError(error); } public unsafe override CLib.GArrowExecuteNode* GetPtr() diff --git a/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs index 4eb46fb71feb..6c9b060bcdf7 100644 --- a/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs @@ -15,6 +15,7 @@ using Apache.Arrow.C; using Apache.Arrow.Ipc; +using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { @@ -33,7 +34,13 @@ public unsafe IArrowArrayStream GetRecordBatchReader() { var schemaPtr = ExportUtil.ExportAndGetSchemaPtr(_schema); var recordBatchReaderPtr = CLib.garrow_sink_node_options_get_reader(_optionsPtr, schemaPtr); - var arrayStreamPtr = CLib.garrow_record_batch_reader_export(recordBatchReaderPtr, null); + + GError** error; + + var arrayStreamPtr = CLib.garrow_record_batch_reader_export(recordBatchReaderPtr, out error); + + ExceptionUtil.ThrowOnError(error); + var arrayStream = CArrowArrayStreamImporter.ImportArrayStream(arrayStreamPtr); return arrayStream; diff --git a/csharp/src/Apache.Arrow.Acero/StringUtil.cs b/csharp/src/Apache.Arrow.Acero/StringUtil.cs index 29154a494b8b..bfce48dc96db 100644 --- a/csharp/src/Apache.Arrow.Acero/StringUtil.cs +++ b/csharp/src/Apache.Arrow.Acero/StringUtil.cs @@ -1,9 +1,28 @@ -using System.Runtime.InteropServices; +using System.Collections.Generic; +using System; +using System.Runtime.InteropServices; namespace Apache.Arrow.Acero { internal static class StringUtil { + public static IntPtr GetStringArrayPtr(params string[] arguments) + { + List allocatedMemory = new List(); + + int sizeOfIntPtr = Marshal.SizeOf(typeof(IntPtr)); + IntPtr pointersToArguments = Marshal.AllocHGlobal(sizeOfIntPtr * arguments.Length); + + for (int i = 0; i < arguments.Length; ++i) + { + IntPtr pointerToArgument = Marshal.StringToHGlobalAnsi(arguments[i]); + allocatedMemory.Add(pointerToArgument); + Marshal.WriteIntPtr(pointersToArguments, i * sizeOfIntPtr, pointerToArgument); + } + + return pointersToArguments; + } + public static unsafe byte* ToCStringUtf8(string str) { var utf8 = System.Text.Encoding.UTF8; diff --git a/csharp/src/Apache.Arrow.Acero/UnionNode.cs b/csharp/src/Apache.Arrow.Acero/UnionNode.cs index 7dad911fc278..a2382e3c7bd1 100644 --- a/csharp/src/Apache.Arrow.Acero/UnionNode.cs +++ b/csharp/src/Apache.Arrow.Acero/UnionNode.cs @@ -33,10 +33,7 @@ public unsafe UnionNode(ExecPlan plan, List nodes) _nodePtr = garrow_execute_plan_build_node(plan.GetPtr(), factoryNamePtr, list.Handle, (IntPtr)optionsPtr2, out error); - if ((IntPtr)error != IntPtr.Zero) - { - throw new GLib.GException((IntPtr)error); - } + ExceptionUtil.ThrowOnError(error); } public override unsafe GArrowExecuteNode* GetPtr() => _nodePtr; diff --git a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs index a6a32806ff10..db941e437060 100644 --- a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs +++ b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs @@ -15,6 +15,7 @@ using Apache.Arrow.Ipc; using Apache.Arrow.Types; +using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; @@ -58,9 +59,9 @@ public async Task TestRecordBatchSource() """, rowCount: 3); } - private void AssertTable(Table table, string expected, int? rowCount = null) + private void AssertTable(Table table, string expected, int? rowCount = null, int columnPadding = 10) { - var actual = PrintPrintTable(table); + var actual = PrintPrintTable(table, columnPadding); _output.WriteLine(actual); @@ -89,8 +90,15 @@ public async Task TestHashJoin() options: hashJoinOptions, inputs: new List { left, right }); // act - var schema = GetOutputSchema(); - var result = hashJoin.ToRecordBatchReader(schema); + var result = hashJoin.ToRecordBatchReader( + new Schema.Builder() + .Field(new Field("customerId", StringType.Default, true)) + .Field(new Field("firstName", StringType.Default, true)) + .Field(new Field("lastName", StringType.Default, true)) + .Field(new Field("orderId", StringType.Default, true)) + .Field(new Field("customerId", StringType.Default, true)) + .Field(new Field("productId", StringType.Default, true)) + .Build()); // assert var table = await ConvertStreamToTable(result); @@ -171,8 +179,6 @@ public async Task TestMultiFilter() public async Task TestUnion() { // arrange - var schema = TestData.GetCustomersSchema(); - var left = new Declaration("record_batch_source", new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch())); @@ -182,6 +188,7 @@ public async Task TestUnion() var union = new Declaration("union", inputs: new List { left, right }); // act + var schema = TestData.GetCustomersSchema(); var result = union.ToRecordBatchReader(schema); // assert @@ -199,6 +206,45 @@ public async Task TestUnion() """, rowCount: 6); } + [Fact] + public async Task TestProjection() + { + // arrange + var customers = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch())); + + var project = Declaration.FromSequence(new List { + customers, + new Declaration("project", new ProjectNodeOptions( + new List { + new Function( + "binary_join_element_wise", + new FieldExpression("lastName"), + new FieldExpression("firstName"), + new LiteralExpression(", ") + ) + }, + new List { "fullName" })) + }); + + // act + var result = project.ToRecordBatchReader( + new Schema.Builder() + .Field(new Field("fullName", StringType.Default, true)) + .Build()); + + // assert + var table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + fullName | + Skywalker, Luke | + Leia, Princess | + Kenobi, Obi-Wan | + """, rowCount: 3, columnPadding: 15); + } + private async Task
ConvertStreamToTable(IArrowArrayStream result) { Schema schema = null; @@ -219,13 +265,13 @@ private async Task
ConvertStreamToTable(IArrowArrayStream result) return Table.TableFromRecordBatches(schema, recordBatches); } - public static string PrintPrintTable(Table table) + public static string PrintPrintTable(Table table, int columnPadding = 10) { var sb = new StringBuilder(); for (var i = 0; i < table.ColumnCount; i++) { - sb.Append(table.Column(i).Name.PadRight(10) + " | "); + sb.Append(table.Column(i).Name.PadRight(columnPadding) + " | "); } sb.AppendLine(); @@ -241,8 +287,24 @@ public static string PrintPrintTable(Table table) if (sliced.Data.Array(k).Length == 0) continue; - var data = sliced.Data.Array(k) as StringArray; - sb.Append(data.GetString(0).PadRight(10) + " | "); + var data = sliced.Data.Array(k); + string value; + + switch (data) + { + case StringArray stringArray: + value = stringArray.GetString(0); + break; + + case Int32Array int32Array: + value = int32Array.GetValue(0).ToString(); + break; + + default: + throw new Exception("Array type not supported"); + } + + sb.Append(value.PadRight(columnPadding) + " | "); } } sb.AppendLine(); @@ -256,17 +318,5 @@ public class TestResult public string TableAsString { get; set; } public int RowCount { get; set; } } - - public Schema GetOutputSchema() - { - return new Schema.Builder() - .Field(new Field("customerId", StringType.Default, true)) - .Field(new Field("firstName", StringType.Default, true)) - .Field(new Field("lastName", StringType.Default, true)) - .Field(new Field("orderId", StringType.Default, true)) - .Field(new Field("customerId", StringType.Default, true)) - .Field(new Field("productId", StringType.Default, true)) - .Build(); - } } } From bae90c8d16fa12aec45d1601924588478241e7f1 Mon Sep 17 00:00:00 2001 From: Dave Searle Date: Fri, 8 Sep 2023 17:38:36 +0100 Subject: [PATCH 4/6] [C#] Move external function declarations inside relevant classes --- csharp/src/Apache.Arrow.Acero/CLib.cs | 123 +----------------- .../src/Apache.Arrow.Acero/ExceptionUtil.cs | 2 +- csharp/src/Apache.Arrow.Acero/ExecNode.cs | 10 +- csharp/src/Apache.Arrow.Acero/ExecPlan.cs | 40 +++--- csharp/src/Apache.Arrow.Acero/ExportUtil.cs | 47 +++---- csharp/src/Apache.Arrow.Acero/Expression.cs | 13 +- .../src/Apache.Arrow.Acero/FieldExpression.cs | 23 ++-- csharp/src/Apache.Arrow.Acero/FilterNode.cs | 20 +-- .../Apache.Arrow.Acero/FilterNodeOptions.cs | 19 +-- csharp/src/Apache.Arrow.Acero/FuncLoader.cs | 98 ++++++++++++++ csharp/src/Apache.Arrow.Acero/Function.cs | 27 ++-- csharp/src/Apache.Arrow.Acero/HashJoinNode.cs | 22 ++-- .../Apache.Arrow.Acero/HashJoinNodeOptions.cs | 27 ++-- .../Apache.Arrow.Acero/LiteralExpression.cs | 48 ++++--- csharp/src/Apache.Arrow.Acero/ProjectNode.cs | 20 +-- .../Apache.Arrow.Acero/ProjectNodeOptions.cs | 24 ++-- .../RecordBatchReaderSourceNode.cs | 17 +-- .../RecordBatchReaderSourceNodeOptions.cs | 20 +-- .../RecordBatchSourceNode.cs | 25 ++-- .../RecordBatchSourceNodeOptions.cs | 20 +-- csharp/src/Apache.Arrow.Acero/SinkNode.cs | 20 +-- .../src/Apache.Arrow.Acero/SinkNodeOptions.cs | 37 +++--- csharp/src/Apache.Arrow.Acero/StringUtil.cs | 62 --------- csharp/src/Apache.Arrow.Acero/UnionNode.cs | 50 ++++--- .../DeclarationTests.cs | 60 ++++----- 25 files changed, 441 insertions(+), 433 deletions(-) create mode 100644 csharp/src/Apache.Arrow.Acero/FuncLoader.cs delete mode 100644 csharp/src/Apache.Arrow.Acero/StringUtil.cs diff --git a/csharp/src/Apache.Arrow.Acero/CLib.cs b/csharp/src/Apache.Arrow.Acero/CLib.cs index 9811a976ffbb..ae597e48d216 100644 --- a/csharp/src/Apache.Arrow.Acero/CLib.cs +++ b/csharp/src/Apache.Arrow.Acero/CLib.cs @@ -13,13 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Apache.Arrow.C; -using System; -using System.Runtime.InteropServices; - namespace Apache.Arrow.Acero { - public class CLib + namespace CLib { public struct GError { } public struct GArrowExecutePlan { } @@ -46,6 +42,7 @@ public struct GArrowSortOptions { } public struct GArrowSortKey { } public struct GArrowProjectNodeOptions { } public struct GArrowInt32Scalar { } + public struct GList {} public enum GArrowJoinType { @@ -64,121 +61,5 @@ public enum GArrowSortOrder GARROW_SORT_ORDER_ASCENDING, GARROW_SORT_ORDER_DESCENDING } - - public const string DllName = "libarrow-glib-1300.dll"; - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_new")] - public static extern unsafe GArrowExecutePlan* garrow_execute_plan_new(out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch")] - public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch(GArrowRecordBatch* record_batch); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_import")] - public static extern unsafe GArrowRecordBatch* garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_import")] - public static extern unsafe GArrowSchema* garrow_schema_import(CArrowSchema* c_abi_schema, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_schema_get_field")] - public static extern unsafe GArrowField* garrow_schema_get_field(GArrowSchema* schema, uint i); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_is_nullable")] - public static extern unsafe bool garrow_field_is_nullable(GArrowField* field); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_hash_join_node_options_new")] - public static extern unsafe GArrowHashJoinNodeOptions* garrow_hash_join_node_options_new(GArrowJoinType type, IntPtr left_keys, uint n_left_keys, IntPtr right_keys, uint n_right_keys, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_hash_join_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_hash_join_node(GArrowExecutePlan* plan, GArrowExecuteNode* left, GArrowExecuteNode* right, GArrowHashJoinNodeOptions* options, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_source_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_source_node(GArrowExecutePlan* plan, GArrowSourceNodeOptions* options, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_validate")] - public static extern unsafe bool garrow_execute_plan_validate(GArrowExecutePlan* plan, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_new")] - public static extern unsafe GArrowSinkNodeOptions* garrow_sink_node_options_new(); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_sink_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_sink_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowSinkNodeOptions* options, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_start")] - public static extern unsafe void garrow_execute_plan_start(GArrowExecutePlan* plan); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_wait")] - public static extern unsafe void garrow_execute_plan_wait(GArrowExecutePlan* plan); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sink_node_options_get_reader")] - public static extern unsafe GArrowRecordBatchReader* garrow_sink_node_options_get_reader(GArrowSinkNodeOptions* options, GArrowSchema* schema); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_export")] - public static extern unsafe CArrowArrayStream* garrow_record_batch_reader_export(GArrowRecordBatchReader* reader, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_record_batch_reader_import")] - public static extern unsafe GArrowRecordBatchReader* garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_source_node_options_new_record_batch_reader")] - public static extern unsafe GArrowSourceNodeOptions* garrow_source_node_options_new_record_batch_reader(GArrowRecordBatchReader* reader); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_filter_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_filter_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowFilterNodeOptions* options, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_filter_node_options_new")] - public static extern unsafe GArrowFilterNodeOptions* garrow_filter_node_options_new(IntPtr expression); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_call_expression_new")] - public static extern unsafe GArrowCallExpression* garrow_call_expression_new(IntPtr function, IntPtr arguments, GArrowFunctionOptions* options); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_field_expression_new")] - public static extern unsafe GArrowFieldExpression* garrow_field_expression_new(IntPtr reference, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_literal_expression_new")] - public static extern unsafe GArrowFieldExpression* garrow_literal_expression_new(GArrowDatum* datum); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_scalar_datum_new")] - public static extern unsafe GArrowScalarDatum* garrow_scalar_datum_new(IntPtr value); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new")] - public static extern unsafe GArrowBuffer* garrow_buffer_new(IntPtr data, long size); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_buffer_new_bytes")] - public static extern unsafe GArrowBuffer* garrow_buffer_new_bytes(IntPtr data); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_string_scalar_new")] - public static extern unsafe GArrowStringScalar* garrow_string_scalar_new(GArrowBuffer* value); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_expression_to_string")] - public static extern unsafe IntPtr garrow_expression_to_string(IntPtr expression); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_int64_scalar_new")] - public static extern unsafe GArrowInt8Scalar* garrow_int64_scalar_new(long value); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_options_new")] - public static extern unsafe GArrowSortOptions* garrow_sort_options_new(GList* sort_keys); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_sort_key_new")] - public static extern unsafe GArrowSortKey* garrow_sort_key_new(IntPtr target, GArrowSortOrder order, out GError** error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_node(GArrowExecutePlan* plan, IntPtr factory_name, IntPtr inputs, IntPtr options, out GError **error); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_project_node_options_new")] - public static extern unsafe GArrowProjectNodeOptions* garrow_project_node_options_new(GList* expressions, IntPtr names, int n_names); - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_execute_plan_build_project_node")] - public static extern unsafe GArrowExecuteNode* garrow_execute_plan_build_project_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowProjectNodeOptions* options, out GError** error); - - - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "garrow_int32_scalar_new")] - public static extern unsafe GArrowInt32Scalar* garrow_int32_scalar_new(int value); - } - - [StructLayout(LayoutKind.Sequential)] - public unsafe struct GList - { - public IntPtr data; - public GList* next; - public GList* prev; } } diff --git a/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs b/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs index 5ea3dfde5cb4..32dd30bb24d9 100644 --- a/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs +++ b/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs @@ -1,5 +1,5 @@ using System; -using static Apache.Arrow.Acero.CLib; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { diff --git a/csharp/src/Apache.Arrow.Acero/ExecNode.cs b/csharp/src/Apache.Arrow.Acero/ExecNode.cs index 0bd5f8d54608..1deb4ff9963e 100644 --- a/csharp/src/Apache.Arrow.Acero/ExecNode.cs +++ b/csharp/src/Apache.Arrow.Acero/ExecNode.cs @@ -13,12 +13,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -using static Apache.Arrow.Acero.CLib; +using System; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public abstract class ExecNode { - public abstract unsafe GArrowExecuteNode* GetPtr(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_node(GArrowExecutePlan* plan, IntPtr factory_name, IntPtr inputs, IntPtr options, out GError** error); + protected static d_garrow_execute_plan_build_node garrow_execute_plan_build_node = FuncLoader.LoadFunction("garrow_execute_plan_build_node"); + + public abstract unsafe GArrowExecuteNode* Handle { get; } } } diff --git a/csharp/src/Apache.Arrow.Acero/ExecPlan.cs b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs index 16a778519746..88ea185c21a7 100644 --- a/csharp/src/Apache.Arrow.Acero/ExecPlan.cs +++ b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs @@ -13,28 +13,43 @@ // See the License for the specific language governing permissions and // limitations under the License. -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class ExecPlan { - private unsafe CLib.GArrowExecutePlan* _planPtr; + private readonly unsafe GArrowExecutePlan* _planPtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowExecutePlan* d_garrow_execute_plan_new(out GError** error); + private static d_garrow_execute_plan_new garrow_execute_plan_new = FuncLoader.LoadFunction("garrow_execute_plan_new"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate bool d_garrow_execute_plan_validate(GArrowExecutePlan* plan, out GError** error); + private static d_garrow_execute_plan_validate garrow_execute_plan_validate = FuncLoader.LoadFunction("garrow_execute_plan_validate"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate bool d_garrow_execute_plan_start(GArrowExecutePlan* plan); + private static d_garrow_execute_plan_start garrow_execute_plan_start = FuncLoader.LoadFunction("garrow_execute_plan_start"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate bool d_garrow_execute_plan_wait(GArrowExecutePlan* plan); + private static d_garrow_execute_plan_wait garrow_execute_plan_wait = FuncLoader.LoadFunction("garrow_execute_plan_wait"); + + public unsafe GArrowExecutePlan* Handle => _planPtr; public unsafe ExecPlan() { - GError** error; - - _planPtr = CLib.garrow_execute_plan_new(out error); + _planPtr = garrow_execute_plan_new(out GError** error); ExceptionUtil.ThrowOnError(error); } public unsafe bool Validate() { - GError** error; - - var valid = CLib.garrow_execute_plan_validate(_planPtr, out error); + bool valid = garrow_execute_plan_validate(_planPtr, out GError** error); ExceptionUtil.ThrowOnError(error); @@ -43,17 +58,12 @@ public unsafe bool Validate() public unsafe void StartProducing() { - CLib.garrow_execute_plan_start(_planPtr); + garrow_execute_plan_start(_planPtr); } public unsafe void Wait() { - CLib.garrow_execute_plan_wait(_planPtr); - } - - internal unsafe CLib.GArrowExecutePlan* GetPtr() - { - return _planPtr; + garrow_execute_plan_wait(_planPtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs index 59f7a81e910c..99dee93fea6a 100644 --- a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs +++ b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs @@ -13,61 +13,56 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; using Apache.Arrow.C; using Apache.Arrow.Ipc; -using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { internal static class ExportUtil { - public static unsafe CLib.GArrowSchema* ExportAndGetSchemaPtr(Schema schema) + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowRecordBatch* d_garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, out GError** error); + private static d_garrow_record_batch_import garrow_record_batch_import = FuncLoader.LoadFunction("garrow_record_batch_import"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowSchema* d_garrow_schema_import(CArrowSchema* c_abi_schema, out GError** error); + private static d_garrow_schema_import garrow_schema_import = FuncLoader.LoadFunction("garrow_schema_import"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowRecordBatchReader* d_garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, out GError** error); + private static d_garrow_record_batch_reader_import garrow_record_batch_reader_import = FuncLoader.LoadFunction("garrow_record_batch_reader_import"); + + public static unsafe GArrowSchema* ExportAndGetSchemaPtr(Schema schema) { - // allocate a C ABI ArrowSchema CArrowSchema* cSchema = CArrowSchema.Create(); - - // export the c# schema to the newly allocated CArrowSchema CArrowSchemaExporter.ExportSchema(schema, cSchema); - - // Import CArrowSchema into a GArrowSchema - GError** error; - var gSchema = CLib.garrow_schema_import(cSchema, out error); + GArrowSchema* gSchema = garrow_schema_import(cSchema, out GError** error); ExceptionUtil.ThrowOnError(error); return gSchema; } - public static unsafe CLib.GArrowRecordBatch* ExportAndGetRecordBatchPtr(RecordBatch recordBatch) + public static unsafe GArrowRecordBatch* ExportAndGetRecordBatchPtr(RecordBatch recordBatch) { - var schemaPtr = ExportAndGetSchemaPtr(recordBatch.Schema); + GArrowSchema* schemaPtr = ExportAndGetSchemaPtr(recordBatch.Schema); - // allocate a C ABI CArrowArray CArrowArray* cArray = CArrowArray.Create(); - - // export the c# record batch to the CArrowArray CArrowArrayExporter.ExportRecordBatch(recordBatch, cArray); - - // import the CArrowArray into a gArrowRecordBatch - GError** error; - var gRecordBatch = CLib.garrow_record_batch_import(cArray, schemaPtr, out error); + GArrowRecordBatch* gRecordBatch = garrow_record_batch_import(cArray, schemaPtr, out GError** error); ExceptionUtil.ThrowOnError(error); return gRecordBatch; } - public static unsafe CLib.GArrowRecordBatchReader* ExportAndGetRecordBatchReaderPtr(IArrowArrayStream recordBatchReader) + public static unsafe GArrowRecordBatchReader* ExportAndGetRecordBatchReaderPtr(IArrowArrayStream recordBatchReader) { - // Allocate a CArrowArray CArrowArrayStream* cArrayStream = CArrowArrayStream.Create(); - - // export the c# record batch to the CArrowArray CArrowArrayStreamExporter.ExportArrayStream(recordBatchReader, cArrayStream); - - // next import the c arrow as a gArrowRecordBatch - GError** error; - var gRecordBatchReader = CLib.garrow_record_batch_reader_import(cArrayStream, out error); + GArrowRecordBatchReader* gRecordBatchReader = garrow_record_batch_reader_import(cArrayStream, out GError** error); ExceptionUtil.ThrowOnError(error); diff --git a/csharp/src/Apache.Arrow.Acero/Expression.cs b/csharp/src/Apache.Arrow.Acero/Expression.cs index df420e0623e2..51fa3c744b74 100644 --- a/csharp/src/Apache.Arrow.Acero/Expression.cs +++ b/csharp/src/Apache.Arrow.Acero/Expression.cs @@ -14,17 +14,24 @@ // limitations under the License. using System; +using System.Runtime.InteropServices; namespace Apache.Arrow.Acero { public abstract class Expression { - public abstract IntPtr GetPtr(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate IntPtr d_garrow_expression_to_string(IntPtr expression); + private static d_garrow_expression_to_string garrow_expression_to_string = FuncLoader.LoadFunction("garrow_expression_to_string"); + + public abstract IntPtr Handle { get; } public override unsafe string ToString() { - var strPtr = CLib.garrow_expression_to_string(GetPtr()); - return StringUtil.PtrToStringUtf8((byte*)strPtr); + IntPtr strPtr = garrow_expression_to_string(Handle); + string str = GLib.Marshaller.PtrToStringGFree(strPtr); + + return str; } } } diff --git a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs index b792bee32eeb..5349c8e3b2be 100644 --- a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs +++ b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs @@ -14,28 +14,33 @@ // limitations under the License. using System; -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class FieldExpression : Expression { - private IntPtr _ptr; + private readonly IntPtr _expressionPtr; + private readonly IntPtr _referencePtr; - public unsafe FieldExpression(string field) - { - var reference = (nint)StringUtil.ToCStringUtf8(field); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate IntPtr d_garrow_field_expression_new(IntPtr reference, out GError** error); + private static d_garrow_field_expression_new garrow_field_expression_new = FuncLoader.LoadFunction("garrow_field_expression_new"); - GError** error; + public override IntPtr Handle => _expressionPtr; - _ptr = (IntPtr)CLib.garrow_field_expression_new(reference, out error); + public unsafe FieldExpression(string reference) + { + _referencePtr = GLib.Marshaller.StringToPtrGStrdup(reference); + _expressionPtr = garrow_field_expression_new(_referencePtr, out GError** error); ExceptionUtil.ThrowOnError(error); } - public override IntPtr GetPtr() + ~FieldExpression() { - return _ptr; + GLib.Marshaller.Free(_referencePtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/FilterNode.cs b/csharp/src/Apache.Arrow.Acero/FilterNode.cs index ec7e09865481..0d0063a6144d 100644 --- a/csharp/src/Apache.Arrow.Acero/FilterNode.cs +++ b/csharp/src/Apache.Arrow.Acero/FilterNode.cs @@ -14,26 +14,26 @@ // limitations under the License. using System.Collections.Generic; -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class FilterNode : ExecNode { - private unsafe CLib.GArrowExecuteNode* _nodePtr; + private readonly unsafe GArrowExecuteNode* _nodePtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_filter_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowFilterNodeOptions* options, out GError** error); + protected static d_garrow_execute_plan_build_filter_node garrow_execute_plan_build_filter_node = FuncLoader.LoadFunction("garrow_execute_plan_build_filter_node"); + + public override unsafe GArrowExecuteNode* Handle => _nodePtr; public unsafe FilterNode(FilterNodeOptions options, ExecPlan plan, List nodes) { - GError** error; - - _nodePtr = CLib.garrow_execute_plan_build_filter_node(plan.GetPtr(), nodes[0].GetPtr(), options.GetPtr(), out error); + _nodePtr = garrow_execute_plan_build_filter_node(plan.Handle, nodes[0].Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } - - public override unsafe CLib.GArrowExecuteNode* GetPtr() - { - return _nodePtr; - } } } diff --git a/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs index ae7eecbdc1a4..fdd2d677b1b8 100644 --- a/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs @@ -13,22 +13,25 @@ // See the License for the specific language governing permissions and // limitations under the License. -using static Apache.Arrow.Acero.CLib; +using System; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class FilterNodeOptions : ExecNodeOptions { - private unsafe GArrowFilterNodeOptions* _optionsPtr; + private readonly unsafe GArrowFilterNodeOptions* _optionsPtr; - public unsafe FilterNodeOptions(Expression expr) - { - _optionsPtr = CLib.garrow_filter_node_options_new(expr.GetPtr()); - } + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowFilterNodeOptions* d_garrow_filter_node_options_new(IntPtr expression); + protected static d_garrow_filter_node_options_new garrow_filter_node_options_new = FuncLoader.LoadFunction("garrow_filter_node_options_new"); - internal unsafe GArrowFilterNodeOptions* GetPtr() + public unsafe GArrowFilterNodeOptions* Handle => _optionsPtr; + + public unsafe FilterNodeOptions(Expression expr) { - return _optionsPtr; + _optionsPtr = garrow_filter_node_options_new(expr.Handle); } } } diff --git a/csharp/src/Apache.Arrow.Acero/FuncLoader.cs b/csharp/src/Apache.Arrow.Acero/FuncLoader.cs new file mode 100644 index 000000000000..12ff16b440e1 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FuncLoader.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.InteropServices; + +namespace Apache.Arrow.Acero +{ + internal class FuncLoader + { + const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000; + + private class Windows + { + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] + public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern IntPtr LoadLibrary(string lpszLib); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern IntPtr AddDllDirectory(string newDirectory); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool SetDefaultDllDirectories(uint directoryFlags); + } + + private class Linux + { + [DllImport("libdl.so.2")] + public static extern IntPtr dlopen(string path, int flags); + + [DllImport("libdl.so.2")] + public static extern IntPtr dlsym(IntPtr handle, string symbol); + } + + private const int RTLD_LAZY = 0x0001; + private const int RTLD_GLOBAL = 0x0100; + + public static IntPtr LoadLibrary(string libName) + { + if (OperatingSystem.IsWindows()) + { + Windows.AddDllDirectory("C:\\msys64\\mingw64\\bin"); + Windows.SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + + IntPtr ptr = Windows.LoadLibrary(libName); + int error = Marshal.GetLastWin32Error(); + + if (error > 0) + throw new DllNotFoundException($"Could not load {libName}"); + + return ptr; + } + + if (OperatingSystem.IsLinux()) + return Linux.dlopen(libName, RTLD_GLOBAL | RTLD_LAZY); + + return IntPtr.Zero; + } + + public static IntPtr GetProcAddress(IntPtr library, string function) + { + if (OperatingSystem.IsWindows()) + return Windows.GetProcAddress(library, function); + + if (OperatingSystem.IsLinux()) + return Linux.dlsym(library, function); + + return IntPtr.Zero; + } + + public static T LoadFunction(IntPtr procAddress) + { + if (procAddress == IntPtr.Zero) + return default(T); + + return Marshal.GetDelegateForFunctionPointer(procAddress); + } + + private static IntPtr NativeLibrary = GetNativeLibrary(); + + private static IntPtr GetNativeLibrary() + { + if (OperatingSystem.IsWindows()) + return LoadLibrary("libarrow-glib-1300.dll"); + + if (OperatingSystem.IsLinux()) + return LoadLibrary("libarrow-glib.so"); + + return IntPtr.Zero; + } + + public static T LoadFunction(string function) + { + IntPtr procAddress = GetProcAddress(NativeLibrary, function); + + return LoadFunction(procAddress); + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/Function.cs b/csharp/src/Apache.Arrow.Acero/Function.cs index 1418c8b45872..a5aa9aa2983f 100644 --- a/csharp/src/Apache.Arrow.Acero/Function.cs +++ b/csharp/src/Apache.Arrow.Acero/Function.cs @@ -14,12 +14,22 @@ // limitations under the License. using System; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class Function : Expression { - private IntPtr _ptr; + private readonly IntPtr _expressionPtr; + private readonly IntPtr _functionNamePtr; + private readonly GLib.List _functionArgs; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowFilterNodeOptions* d_garrow_call_expression_new(IntPtr function, IntPtr arguments, GArrowFunctionOptions* options); + private static d_garrow_call_expression_new garrow_call_expression_new = FuncLoader.LoadFunction("garrow_call_expression_new"); + + public override IntPtr Handle => _expressionPtr; public unsafe Function(string functionName, Expression lhs, Expression rhs) : this(functionName, new[] { lhs, rhs }) @@ -28,19 +38,18 @@ public unsafe Function(string functionName, Expression lhs, Expression rhs) public unsafe Function(string functionName, params Expression[] args) { - var functionNamePtr = StringUtil.ToCStringUtf8(functionName); - - var list = new GLib.List(IntPtr.Zero); + _functionNamePtr = GLib.Marshaller.StringToPtrGStrdup(functionName); + _functionArgs = new GLib.List(IntPtr.Zero); - foreach (var arg in args) - list.Append(arg.GetPtr()); + foreach (Expression arg in args) + _functionArgs.Append(arg.Handle); - _ptr = (IntPtr)CLib.garrow_call_expression_new((IntPtr)functionNamePtr, list.Handle, null); + _expressionPtr = (IntPtr)garrow_call_expression_new(_functionNamePtr, _functionArgs.Handle, null); } - public override IntPtr GetPtr() + ~Function() { - return _ptr; + GLib.Marshaller.Free(_functionNamePtr); } } diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs index 56dfc814a225..5b35ffe206b4 100644 --- a/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs @@ -14,29 +14,29 @@ // limitations under the License. using System.Collections.Generic; -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class HashJoinNode : ExecNode { - private unsafe CLib.GArrowExecuteNode* _nodePtr; + private readonly unsafe GArrowExecuteNode* _nodePtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_hash_join_node(GArrowExecutePlan* plan, GArrowExecuteNode* left, GArrowExecuteNode* right, GArrowHashJoinNodeOptions* options, out GError** error); + private static d_garrow_execute_plan_build_hash_join_node garrow_execute_plan_build_hash_join_node = FuncLoader.LoadFunction("garrow_execute_plan_build_hash_join_node"); + + public override unsafe GArrowExecuteNode* Handle => _nodePtr; public unsafe HashJoinNode(HashJoinNodeOptions options, ExecPlan plan, List inputs) { ExecNode left = inputs[0]; ExecNode right = inputs[1]; - GError** error; - - _nodePtr = CLib.garrow_execute_plan_build_hash_join_node(plan.GetPtr(), left.GetPtr(), right.GetPtr(), options.GetPtr(), out error); + _nodePtr = garrow_execute_plan_build_hash_join_node(plan.Handle, left.Handle, right.Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); - } - - public override unsafe CLib.GArrowExecuteNode* GetPtr() - { - return _nodePtr; - } + } } } diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs index 488454390561..5d24d1d16dee 100644 --- a/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs @@ -13,29 +13,38 @@ // See the License for the specific language governing permissions and // limitations under the License. -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using System; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class HashJoinNodeOptions : ExecNodeOptions { - private unsafe GArrowHashJoinNodeOptions* _optionsPtr; + private readonly unsafe GArrowHashJoinNodeOptions* _optionsPtr; + private readonly IntPtr _leftKeysPtr; + private readonly IntPtr _rightKeysPtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowHashJoinNodeOptions* d_garrow_hash_join_node_options_new(GArrowJoinType type, IntPtr left_keys, uint n_left_keys, IntPtr right_keys, uint n_right_keys, out GError** error); + private static d_garrow_hash_join_node_options_new garrow_hash_join_node_options_new = FuncLoader.LoadFunction("garrow_hash_join_node_options_new"); + + internal unsafe GArrowHashJoinNodeOptions* Handle => _optionsPtr; public unsafe HashJoinNodeOptions(GArrowJoinType joinType, string[] leftKeys, string[] rightKeys) { - var leftKeysPtr = StringUtil.GetStringArrayPtr(leftKeys); - var rightKeysPtr = StringUtil.GetStringArrayPtr(rightKeys); - - GError** error; + _leftKeysPtr = GLib.Marshaller.StringArrayToStrvPtr(leftKeys); + _rightKeysPtr = GLib.Marshaller.StringArrayToStrvPtr(leftKeys); - _optionsPtr = garrow_hash_join_node_options_new(joinType, leftKeysPtr, (uint)leftKeys.Length, rightKeysPtr, (uint)rightKeys.Length, out error); + _optionsPtr = garrow_hash_join_node_options_new(joinType, _leftKeysPtr, (uint)leftKeys.Length, _rightKeysPtr, (uint)rightKeys.Length, out GError** error); ExceptionUtil.ThrowOnError(error); } - internal unsafe GArrowHashJoinNodeOptions* GetPtr() + ~HashJoinNodeOptions() { - return _optionsPtr; + GLib.Marshaller.StrFreeV(_leftKeysPtr); + GLib.Marshaller.StrFreeV(_rightKeysPtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs index 080cd59145a9..82a5925d2455 100644 --- a/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs +++ b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs @@ -14,35 +14,53 @@ // limitations under the License. using System; -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class LiteralExpression : Expression { - private IntPtr _ptr; + private unsafe readonly GArrowFieldExpression* _expressionPtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowFieldExpression* d_garrow_literal_expression_new(GArrowDatum* datum); + private static d_garrow_literal_expression_new garrow_literal_expression_new = FuncLoader.LoadFunction("garrow_literal_expression_new"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowScalarDatum* d_garrow_scalar_datum_new(IntPtr value); + private static d_garrow_scalar_datum_new garrow_scalar_datum_new = FuncLoader.LoadFunction("garrow_scalar_datum_new"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowBuffer* d_garrow_buffer_new(IntPtr data, long size); + private static d_garrow_buffer_new garrow_buffer_new = FuncLoader.LoadFunction("garrow_buffer_new"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowStringScalar* d_garrow_string_scalar_new(GArrowBuffer* value); + private static d_garrow_string_scalar_new garrow_string_scalar_new = FuncLoader.LoadFunction("garrow_string_scalar_new"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowInt32Scalar* d_garrow_int32_scalar_new(int value); + private static d_garrow_int32_scalar_new garrow_int32_scalar_new = FuncLoader.LoadFunction("garrow_int32_scalar_new"); + + public unsafe override IntPtr Handle => (IntPtr)_expressionPtr; public unsafe LiteralExpression(string literal) { - var dataPtr = (IntPtr)StringUtil.ToCStringUtf8(literal); - var bufferPtr = CLib.garrow_buffer_new(dataPtr, literal.Length); - var scalarPtr = CLib.garrow_string_scalar_new(bufferPtr); - var datumPtr = (IntPtr)CLib.garrow_scalar_datum_new((IntPtr)scalarPtr); + IntPtr dataPtr = GLib.Marshaller.StringToPtrGStrdup(literal); + GArrowBuffer* bufferPtr = garrow_buffer_new(dataPtr, literal.Length); + GArrowStringScalar* scalarPtr = garrow_string_scalar_new(bufferPtr); + GArrowScalarDatum* datumPtr = garrow_scalar_datum_new((IntPtr)scalarPtr); - _ptr = (IntPtr)CLib.garrow_literal_expression_new((GArrowDatum*)datumPtr); + _expressionPtr = garrow_literal_expression_new((GArrowDatum*)datumPtr); } public unsafe LiteralExpression(int literal) { - var scalarPtr = CLib.garrow_int32_scalar_new(literal); - var datumPtr = (IntPtr)CLib.garrow_scalar_datum_new((IntPtr)scalarPtr); - - _ptr = (IntPtr)CLib.garrow_literal_expression_new((GArrowDatum*)datumPtr); - } + GArrowInt32Scalar* scalarPtr = garrow_int32_scalar_new(literal); + GArrowScalarDatum* datumPtr = garrow_scalar_datum_new((IntPtr)scalarPtr); - public override IntPtr GetPtr() - { - return _ptr; + _expressionPtr = garrow_literal_expression_new((GArrowDatum*)datumPtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/ProjectNode.cs b/csharp/src/Apache.Arrow.Acero/ProjectNode.cs index 7e95b8ea787c..d4ac2d277c2d 100644 --- a/csharp/src/Apache.Arrow.Acero/ProjectNode.cs +++ b/csharp/src/Apache.Arrow.Acero/ProjectNode.cs @@ -14,26 +14,26 @@ // limitations under the License. using System.Collections.Generic; -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class ProjectNode : ExecNode { - private unsafe CLib.GArrowExecuteNode* _nodePtr; + private unsafe GArrowExecuteNode* _nodePtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_project_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowProjectNodeOptions* options, out GError** error); + protected static d_garrow_execute_plan_build_project_node garrow_execute_plan_build_project_node = FuncLoader.LoadFunction("garrow_execute_plan_build_project_node"); + + public override unsafe GArrowExecuteNode* Handle => _nodePtr; public unsafe ProjectNode(ProjectNodeOptions options, ExecPlan plan, List nodes) { - GError** error; - - _nodePtr = CLib.garrow_execute_plan_build_project_node(plan.GetPtr(), nodes[0].GetPtr(), options.GetPtr(), out error); + _nodePtr = garrow_execute_plan_build_project_node(plan.Handle, nodes[0].Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } - - public override unsafe CLib.GArrowExecuteNode* GetPtr() - { - return _nodePtr; - } } } diff --git a/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs index 36607ca9d8c1..3995fb3ab478 100644 --- a/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs @@ -15,29 +15,31 @@ using System; using System.Collections.Generic; -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class ProjectNodeOptions : ExecNodeOptions { - private unsafe GArrowProjectNodeOptions* _optionsPtr; + private readonly unsafe GArrowProjectNodeOptions* _optionsPtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowProjectNodeOptions* d_garrow_project_node_options_new(GList* expressions, IntPtr names, int n_names); + private static d_garrow_project_node_options_new garrow_project_node_options_new = FuncLoader.LoadFunction("garrow_project_node_options_new"); + + internal unsafe GArrowProjectNodeOptions* Handle => _optionsPtr; public unsafe ProjectNodeOptions(List expressions, List names) { var list = new GLib.List(IntPtr.Zero); - foreach (var expression in expressions) - list.Append(expression.GetPtr()); + foreach (Expression expression in expressions) + list.Append(expression.Handle); - var namesPtr = StringUtil.GetStringArrayPtr(names.ToArray()); + IntPtr namesPtr = GLib.Marshaller.StringArrayToStrvPtr(names.ToArray()); - _optionsPtr = CLib.garrow_project_node_options_new((GList*)list.Handle, namesPtr, names.Count); - } - - internal unsafe GArrowProjectNodeOptions* GetPtr() - { - return _optionsPtr; + _optionsPtr = garrow_project_node_options_new((GList*)list.Handle, namesPtr, names.Count); } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs index fa9302695e69..463a59978b51 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs @@ -13,26 +13,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -using static Apache.Arrow.Acero.CLib; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { - public class RecordBatchReaderSourceNode : ExecNode + public class RecordBatchReaderSourceNode : SourceNode { - private unsafe CLib.GArrowExecuteNode* _nodePtr; + private unsafe GArrowExecuteNode* _nodePtr; + + public override unsafe GArrowExecuteNode* Handle => _nodePtr; public unsafe RecordBatchReaderSourceNode(RecordBatchReaderSourceNodeOptions options, ExecPlan plan) { - GError** error; - - _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), out error); + _nodePtr = garrow_execute_plan_build_source_node(plan.Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } - - public override unsafe CLib.GArrowExecuteNode* GetPtr() - { - return _nodePtr; - } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs index 1be20c5df3b3..c77d6e368fce 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs @@ -13,25 +13,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -using Apache.Arrow.C; +using System.Runtime.InteropServices; using Apache.Arrow.Ipc; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class RecordBatchReaderSourceNodeOptions : ExecNodeOptions { - private unsafe CLib.GArrowSourceNodeOptions* _optionsPtr; + private readonly unsafe GArrowSourceNodeOptions* _optionsPtr; - public unsafe RecordBatchReaderSourceNodeOptions(IArrowArrayStream recordBatchReader) - { - var recordBatchReaderPtr = ExportUtil.ExportAndGetRecordBatchReaderPtr(recordBatchReader); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowSourceNodeOptions* d_garrow_source_node_options_new_record_batch_reader(GArrowRecordBatchReader* reader); + protected static d_garrow_source_node_options_new_record_batch_reader garrow_source_node_options_new_record_batch_reader = FuncLoader.LoadFunction("garrow_source_node_options_new_record_batch_reader"); - _optionsPtr = CLib.garrow_source_node_options_new_record_batch_reader(recordBatchReaderPtr); - } + public unsafe GArrowSourceNodeOptions* Handle => _optionsPtr; - internal unsafe CLib.GArrowSourceNodeOptions* GetPtr() + public unsafe RecordBatchReaderSourceNodeOptions(IArrowArrayStream recordBatchReader) { - return _optionsPtr; + GArrowRecordBatchReader* recordBatchReaderPtr = ExportUtil.ExportAndGetRecordBatchReaderPtr(recordBatchReader); + + _optionsPtr = garrow_source_node_options_new_record_batch_reader(recordBatchReaderPtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs index 0dc6797c83cb..b540d2ef3063 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs @@ -13,26 +13,29 @@ // See the License for the specific language governing permissions and // limitations under the License. -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { - public class RecordBatchSourceNode : ExecNode + public abstract class SourceNode : ExecNode { - private unsafe CLib.GArrowExecuteNode* _nodePtr; + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_source_node(GArrowExecutePlan* plan, GArrowSourceNodeOptions* options, out GError** error); + protected static d_garrow_execute_plan_build_source_node garrow_execute_plan_build_source_node = FuncLoader.LoadFunction("garrow_execute_plan_build_source_node"); + } + + public class RecordBatchSourceNode : SourceNode + { + private unsafe GArrowExecuteNode* _nodePtr; + + public override unsafe GArrowExecuteNode* Handle => _nodePtr; public unsafe RecordBatchSourceNode(RecordBatchSourceNodeOptions options, ExecPlan plan) { - GError** error; - - _nodePtr = CLib.garrow_execute_plan_build_source_node(plan.GetPtr(), options.GetPtr(), out error); + _nodePtr = garrow_execute_plan_build_source_node(plan.Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } - - public override unsafe CLib.GArrowExecuteNode* GetPtr() - { - return _nodePtr; - } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs index a4bb192607f4..c9c7a614ba14 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs @@ -13,22 +13,26 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; + namespace Apache.Arrow.Acero { public class RecordBatchSourceNodeOptions : ExecNodeOptions { - private unsafe CLib.GArrowSourceNodeOptions* _optionsPtr; + private readonly unsafe GArrowSourceNodeOptions* _optionsPtr; - public unsafe RecordBatchSourceNodeOptions(RecordBatch recordBatch) - { - var recordBatchPtr = ExportUtil.ExportAndGetRecordBatchPtr(recordBatch); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowSourceNodeOptions* d_garrow_source_node_options_new_record_batch(GArrowRecordBatch* record_batch); + protected static d_garrow_source_node_options_new_record_batch garrow_source_node_options_new_record_batch = FuncLoader.LoadFunction("garrow_source_node_options_new_record_batch"); - _optionsPtr = CLib.garrow_source_node_options_new_record_batch(recordBatchPtr); - } + public unsafe GArrowSourceNodeOptions* Handle => _optionsPtr; - internal unsafe CLib.GArrowSourceNodeOptions* GetPtr() + public unsafe RecordBatchSourceNodeOptions(RecordBatch recordBatch) { - return _optionsPtr; + GArrowRecordBatch* recordBatchPtr = ExportUtil.ExportAndGetRecordBatchPtr(recordBatch); + + _optionsPtr = garrow_source_node_options_new_record_batch(recordBatchPtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/SinkNode.cs b/csharp/src/Apache.Arrow.Acero/SinkNode.cs index b9084d7b9632..3bcf1c9d7534 100644 --- a/csharp/src/Apache.Arrow.Acero/SinkNode.cs +++ b/csharp/src/Apache.Arrow.Acero/SinkNode.cs @@ -14,26 +14,26 @@ // limitations under the License. using System.Collections.Generic; -using static Apache.Arrow.Acero.CLib; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class SinkNode : ExecNode { - private unsafe CLib.GArrowExecuteNode* _nodePtr; + private readonly unsafe GArrowExecuteNode* _nodePtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_sink_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowSinkNodeOptions* options, out GError** error); + protected static d_garrow_execute_plan_build_sink_node garrow_execute_plan_build_sink_node = FuncLoader.LoadFunction("garrow_execute_plan_build_sink_node"); + + public override unsafe GArrowExecuteNode* Handle => _nodePtr; public unsafe SinkNode(SinkNodeOptions _options, ExecPlan plan, List inputs) { - GError** error; - - _nodePtr = CLib.garrow_execute_plan_build_sink_node(plan.GetPtr(), inputs[0].GetPtr(), _options.GetPtr(), out error); + _nodePtr = garrow_execute_plan_build_sink_node(plan.Handle, inputs[0].Handle, _options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } - - public unsafe override CLib.GArrowExecuteNode* GetPtr() - { - return _nodePtr; - } } } diff --git a/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs index 6c9b060bcdf7..e50338fdf178 100644 --- a/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs @@ -13,42 +13,49 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Runtime.InteropServices; using Apache.Arrow.C; using Apache.Arrow.Ipc; -using static Apache.Arrow.Acero.CLib; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class SinkNodeOptions : ExecNodeOptions { - private readonly unsafe CLib.GArrowSinkNodeOptions* _optionsPtr; + private readonly unsafe GArrowSinkNodeOptions* _optionsPtr; private readonly Schema _schema; + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowSinkNodeOptions* d_garrow_sink_node_options_new(); + protected static d_garrow_sink_node_options_new garrow_sink_node_options_new = FuncLoader.LoadFunction("garrow_sink_node_options_new"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate GArrowRecordBatchReader* d_garrow_sink_node_options_get_reader(GArrowSinkNodeOptions* options, GArrowSchema* schema); + protected static d_garrow_sink_node_options_get_reader garrow_sink_node_options_get_reader = FuncLoader.LoadFunction("garrow_sink_node_options_get_reader"); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate CArrowArrayStream* d_garrow_record_batch_reader_export(GArrowRecordBatchReader* reader, out GError** error); + private static d_garrow_record_batch_reader_export garrow_record_batch_reader_export = FuncLoader.LoadFunction("garrow_record_batch_reader_export"); + + internal unsafe GArrowSinkNodeOptions* Handle => _optionsPtr; + public unsafe SinkNodeOptions(Schema schema) { - _optionsPtr = CLib.garrow_sink_node_options_new(); + _optionsPtr = garrow_sink_node_options_new(); _schema = schema; } public unsafe IArrowArrayStream GetRecordBatchReader() { - var schemaPtr = ExportUtil.ExportAndGetSchemaPtr(_schema); - var recordBatchReaderPtr = CLib.garrow_sink_node_options_get_reader(_optionsPtr, schemaPtr); - - GError** error; - - var arrayStreamPtr = CLib.garrow_record_batch_reader_export(recordBatchReaderPtr, out error); + GArrowSchema* schemaPtr = ExportUtil.ExportAndGetSchemaPtr(_schema); + GArrowRecordBatchReader* recordBatchReaderPtr = garrow_sink_node_options_get_reader(_optionsPtr, schemaPtr); + CArrowArrayStream* arrayStreamPtr = garrow_record_batch_reader_export(recordBatchReaderPtr, out GError** error); ExceptionUtil.ThrowOnError(error); - var arrayStream = CArrowArrayStreamImporter.ImportArrayStream(arrayStreamPtr); + IArrowArrayStream arrayStream = CArrowArrayStreamImporter.ImportArrayStream(arrayStreamPtr); return arrayStream; } - - internal unsafe CLib.GArrowSinkNodeOptions* GetPtr() - { - return _optionsPtr; - } } } diff --git a/csharp/src/Apache.Arrow.Acero/StringUtil.cs b/csharp/src/Apache.Arrow.Acero/StringUtil.cs deleted file mode 100644 index bfce48dc96db..000000000000 --- a/csharp/src/Apache.Arrow.Acero/StringUtil.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; -using System; -using System.Runtime.InteropServices; - -namespace Apache.Arrow.Acero -{ - internal static class StringUtil - { - public static IntPtr GetStringArrayPtr(params string[] arguments) - { - List allocatedMemory = new List(); - - int sizeOfIntPtr = Marshal.SizeOf(typeof(IntPtr)); - IntPtr pointersToArguments = Marshal.AllocHGlobal(sizeOfIntPtr * arguments.Length); - - for (int i = 0; i < arguments.Length; ++i) - { - IntPtr pointerToArgument = Marshal.StringToHGlobalAnsi(arguments[i]); - allocatedMemory.Add(pointerToArgument); - Marshal.WriteIntPtr(pointersToArguments, i * sizeOfIntPtr, pointerToArgument); - } - - return pointersToArguments; - } - - public static unsafe byte* ToCStringUtf8(string str) - { - var utf8 = System.Text.Encoding.UTF8; - int byteCount = utf8.GetByteCount(str); - byte* byteArray = (byte*)Marshal.AllocHGlobal(byteCount + 1); - - fixed (char* chars = str) - { - utf8.GetBytes(chars, str.Length, byteArray, byteCount); - } - - // Need to make sure it is null-terminated. - byteArray[byteCount] = 0; - - return byteArray; - } - - public static unsafe string PtrToStringUtf8(byte* ptr) - { -#if NETSTANDARD2_1_OR_GREATER - return Marshal.PtrToStringUTF8(ptr); -#else - if (ptr == null) - { - return null; - } - - int length; - for (length = 0; ptr[length] != '\0'; ++length) - { - } - - return System.Text.Encoding.UTF8.GetString(ptr, length); -#endif - } - } -} diff --git a/csharp/src/Apache.Arrow.Acero/UnionNode.cs b/csharp/src/Apache.Arrow.Acero/UnionNode.cs index a2382e3c7bd1..8cd63c800cd3 100644 --- a/csharp/src/Apache.Arrow.Acero/UnionNode.cs +++ b/csharp/src/Apache.Arrow.Acero/UnionNode.cs @@ -1,41 +1,57 @@ -using System; +// 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.Runtime.InteropServices; -using static Apache.Arrow.Acero.CLib; +using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class UnionNode : ExecNode { - private unsafe CLib.GArrowExecuteNode* _nodePtr; + private readonly unsafe GArrowExecuteNode* _nodePtr; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected unsafe delegate IntPtr d_garrow_sink_node_options_new(); + protected static d_garrow_sink_node_options_new garrow_sink_node_options_new = FuncLoader.LoadFunction("garrow_sink_node_options_new"); + + public override unsafe GArrowExecuteNode* Handle => _nodePtr; public unsafe UnionNode(ExecPlan plan, List nodes) { - var factoryName = "union"; - var factoryNamePtr = (IntPtr)StringUtil.ToCStringUtf8(factoryName); + string factoryName = "union"; + IntPtr factoryNamePtr = GLib.Marshaller.StringToPtrGStrdup(factoryName); - var lhs = nodes[0]; - var rhs = nodes[1]; + ExecNode lhs = nodes[0]; + ExecNode rhs = nodes[1]; var list = new GLib.List(IntPtr.Zero); - list.Append((IntPtr)lhs.GetPtr()); - list.Append((IntPtr)rhs.GetPtr()); + list.Append((IntPtr)lhs.Handle); + list.Append((IntPtr)rhs.Handle); // todo: using this ptr causes the following error // g_object_new_valist: invalid unclassed object pointer for value type 'GArrowExecuteNodeOptions' - IntPtr optionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); - Marshal.StructureToPtr(new GArrowExecuteNodeOptions(), optionsPtr, false); + //IntPtr optionsPtr = GLib.Marshaller.StructureToPtrAlloc(new GArrowExecuteNodeOptions()); // for now just use the sink options - var optionsPtr2 = garrow_sink_node_options_new(); + IntPtr optionsPtr2 = garrow_sink_node_options_new(); - GError** error; - - _nodePtr = garrow_execute_plan_build_node(plan.GetPtr(), factoryNamePtr, list.Handle, (IntPtr)optionsPtr2, out error); + _nodePtr = garrow_execute_plan_build_node(plan.Handle, factoryNamePtr, list.Handle, optionsPtr2, out GError** error); ExceptionUtil.ThrowOnError(error); } - - public override unsafe GArrowExecuteNode* GetPtr() => _nodePtr; } } diff --git a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs index db941e437060..ab1ab621c907 100644 --- a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs +++ b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Apache.Arrow.Acero.CLib; using Apache.Arrow.Ipc; using Apache.Arrow.Types; using System; @@ -21,7 +22,6 @@ using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; -using static Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero.Tests { @@ -38,17 +38,17 @@ public DeclarationTests(ITestOutputHelper output) public async Task TestRecordBatchSource() { // arrange - var recordBatch = TestData.GetCustomersRecordBatch(); + RecordBatch recordBatch = TestData.GetCustomersRecordBatch(); var recordBatchSource = new Declaration("record_batch_source", new RecordBatchSourceNodeOptions(recordBatch)); // act - var schema = TestData.GetCustomersSchema(); - var result = recordBatchSource.ToRecordBatchReader(schema); + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = recordBatchSource.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result); + Table table = await ConvertStreamToTable(result); AssertTable(table, """ @@ -61,7 +61,7 @@ public async Task TestRecordBatchSource() private void AssertTable(Table table, string expected, int? rowCount = null, int columnPadding = 10) { - var actual = PrintPrintTable(table, columnPadding); + string actual = PrintPrintTable(table, columnPadding); _output.WriteLine(actual); @@ -86,11 +86,11 @@ public async Task TestHashJoin() new string[] { "customerId" }, new string[] { "customerId" }); - var hashJoin = new Declaration("hashjoin", + var hashJoin = new Declaration("hashjoin", options: hashJoinOptions, inputs: new List { left, right }); // act - var result = hashJoin.ToRecordBatchReader( + IArrowArrayStream result = hashJoin.ToRecordBatchReader( new Schema.Builder() .Field(new Field("customerId", StringType.Default, true)) .Field(new Field("firstName", StringType.Default, true)) @@ -101,7 +101,7 @@ public async Task TestHashJoin() .Build()); // assert - var table = await ConvertStreamToTable(result); + Table table = await ConvertStreamToTable(result); AssertTable(table, """ @@ -116,7 +116,7 @@ public async Task TestHashJoin() public async Task TestSingleFilter() { // arrange - var recordBatch = TestData.GetCustomersRecordBatch(); + RecordBatch recordBatch = TestData.GetCustomersRecordBatch(); var recordBatchSource = new Declaration("record_batch_source", new RecordBatchSourceNodeOptions(recordBatch)); @@ -129,11 +129,11 @@ public async Task TestSingleFilter() }); // act - var schema = TestData.GetCustomersSchema(); - var result = orderBy.ToRecordBatchReader(schema); + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = orderBy.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result); + Table table = await ConvertStreamToTable(result); AssertTable(table, """ @@ -146,7 +146,7 @@ public async Task TestSingleFilter() public async Task TestMultiFilter() { // arrange - var recordBatch = TestData.GetCustomersRecordBatch(); + RecordBatch recordBatch = TestData.GetCustomersRecordBatch(); var recordBatchSource = new Declaration("record_batch_source", new RecordBatchSourceNodeOptions(recordBatch)); @@ -161,11 +161,11 @@ public async Task TestMultiFilter() }); // act - var schema = TestData.GetCustomersSchema(); - var result = orderBy.ToRecordBatchReader(schema); + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = orderBy.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result); + Table table = await ConvertStreamToTable(result); AssertTable(table, """ @@ -188,11 +188,11 @@ public async Task TestUnion() var union = new Declaration("union", inputs: new List { left, right }); // act - var schema = TestData.GetCustomersSchema(); - var result = union.ToRecordBatchReader(schema); + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = union.ToRecordBatchReader(schema); // assert - var table = await ConvertStreamToTable(result); + Table table = await ConvertStreamToTable(result); AssertTable(table, """ @@ -228,13 +228,13 @@ public async Task TestProjection() }); // act - var result = project.ToRecordBatchReader( + IArrowArrayStream result = project.ToRecordBatchReader( new Schema.Builder() .Field(new Field("fullName", StringType.Default, true)) .Build()); // assert - var table = await ConvertStreamToTable(result); + Table table = await ConvertStreamToTable(result); AssertTable(table, """ @@ -250,10 +250,10 @@ private async Task
ConvertStreamToTable(IArrowArrayStream result) Schema schema = null; var recordBatches = new List(); - + while (true) { - var recordBatch = await result.ReadNextRecordBatchAsync(); + RecordBatch recordBatch = await result.ReadNextRecordBatchAsync(); if (recordBatch == null) break; if (schema == null) @@ -269,25 +269,25 @@ public static string PrintPrintTable(Table table, int columnPadding = 10) { var sb = new StringBuilder(); - for (var i = 0; i < table.ColumnCount; i++) + for (int i = 0; i < table.ColumnCount; i++) { sb.Append(table.Column(i).Name.PadRight(columnPadding) + " | "); } sb.AppendLine(); - for (var i = 0; i < table.RowCount; i++) + for (int i = 0; i < table.RowCount; i++) { - for (var j = 0; j < table.ColumnCount; j++) + for (int j = 0; j < table.ColumnCount; j++) { - var sliced = table.Column(j).Slice(i, 1); + Column sliced = table.Column(j).Slice(i, 1); - for (var k = 0; k < sliced.Data.ArrayCount; k++) + for (int k = 0; k < sliced.Data.ArrayCount; k++) { if (sliced.Data.Array(k).Length == 0) continue; - var data = sliced.Data.Array(k); + Array data = sliced.Data.Array(k); string value; switch (data) From 174b9a98eddfca06c258b9f1d0773eb2ae25e282 Mon Sep 17 00:00:00 2001 From: Dave Searle Date: Mon, 11 Sep 2023 11:42:50 +0100 Subject: [PATCH 5/6] [C#] Allow Declaration to specify which registry is used to build ExecNodes. Provide default ExecNode registry. General tidy up --- csharp/src/Apache.Arrow.Acero/CLib.cs | 9 +- csharp/src/Apache.Arrow.Acero/Declaration.cs | 45 +++----- .../DefaultExecNodeFactoryRegistry.cs | 58 ++++++++++ .../src/Apache.Arrow.Acero/ExceptionUtil.cs | 17 ++- csharp/src/Apache.Arrow.Acero/ExecNode.cs | 25 ++++- csharp/src/Apache.Arrow.Acero/ExecPlan.cs | 56 ++++++++-- csharp/src/Apache.Arrow.Acero/ExportUtil.cs | 72 ------------ .../Apache.Arrow.Acero/ExportedRecordBatch.cs | 43 +++++++ .../ExportedRecordBatchReader.cs | 41 +++++++ .../src/Apache.Arrow.Acero/ExportedSchema.cs | 39 +++++++ csharp/src/Apache.Arrow.Acero/Expression.cs | 5 +- .../src/Apache.Arrow.Acero/FieldExpression.cs | 6 +- csharp/src/Apache.Arrow.Acero/FilterNode.cs | 9 +- .../Apache.Arrow.Acero/FilterNodeOptions.cs | 6 +- csharp/src/Apache.Arrow.Acero/FuncLoader.cs | 29 ++++- csharp/src/Apache.Arrow.Acero/Function.cs | 5 +- csharp/src/Apache.Arrow.Acero/HashJoinNode.cs | 11 +- .../Apache.Arrow.Acero/HashJoinNodeOptions.cs | 5 +- .../Apache.Arrow.Acero/LiteralExpression.cs | 8 +- csharp/src/Apache.Arrow.Acero/ProjectNode.cs | 11 +- .../Apache.Arrow.Acero/ProjectNodeOptions.cs | 6 +- .../RecordBatchReaderSourceNode.cs | 11 +- .../RecordBatchReaderSourceNodeOptions.cs | 8 +- .../RecordBatchSourceNode.cs | 13 ++- .../RecordBatchSourceNodeOptions.cs | 8 +- csharp/src/Apache.Arrow.Acero/SinkNode.cs | 10 +- .../src/Apache.Arrow.Acero/SinkNodeOptions.cs | 13 +-- csharp/src/Apache.Arrow.Acero/UnionNode.cs | 55 +++++---- .../DeclarationTests.cs | 105 ++++++++---------- .../TableExtensions.cs | 71 ++++++++++++ 30 files changed, 527 insertions(+), 273 deletions(-) create mode 100644 csharp/src/Apache.Arrow.Acero/DefaultExecNodeFactoryRegistry.cs delete mode 100644 csharp/src/Apache.Arrow.Acero/ExportUtil.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ExportedRecordBatch.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ExportedRecordBatchReader.cs create mode 100644 csharp/src/Apache.Arrow.Acero/ExportedSchema.cs create mode 100644 csharp/test/Apache.Arrow.Acero.Tests/TableExtensions.cs diff --git a/csharp/src/Apache.Arrow.Acero/CLib.cs b/csharp/src/Apache.Arrow.Acero/CLib.cs index ae597e48d216..3c245b4fbaf6 100644 --- a/csharp/src/Apache.Arrow.Acero/CLib.cs +++ b/csharp/src/Apache.Arrow.Acero/CLib.cs @@ -13,6 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System; +using System.Runtime.InteropServices; + namespace Apache.Arrow.Acero { namespace CLib @@ -27,7 +30,11 @@ public struct GArrowExecuteNode { } public struct GArrowHashJoinNodeOptions { } public struct GArrowSinkNodeOptions { } public struct GArrowRecordBatchReader { } - public struct GArrowExecuteNodeOptions { } + [StructLayout(LayoutKind.Sequential)] + public struct GArrowExecuteNodeOptions + { + IntPtr debug_opts; + } public struct GArrowFilterNodeOptions { } public struct GArrowExpression { } public struct GArrowCallExpression { } diff --git a/csharp/src/Apache.Arrow.Acero/Declaration.cs b/csharp/src/Apache.Arrow.Acero/Declaration.cs index d1610981a47d..c5773eb9954a 100644 --- a/csharp/src/Apache.Arrow.Acero/Declaration.cs +++ b/csharp/src/Apache.Arrow.Acero/Declaration.cs @@ -12,11 +12,11 @@ // 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 Apache.Arrow.Ipc; using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Apache.Arrow.Ipc; namespace Apache.Arrow.Acero @@ -25,13 +25,15 @@ public class Declaration { private readonly string _factoryName; private readonly ExecNodeOptions _options; + private readonly ExecNodeFactoryRegistry _registry; public List Inputs { get; set; } = new(); - public Declaration(string factoryName, ExecNodeOptions options = null, List inputs = null) + public Declaration(string factoryName, ExecNodeOptions options = null, List inputs = null, ExecNodeFactoryRegistry registry = null) { _factoryName = factoryName; _options = options; + _registry = registry ?? new DefaultExecNodeFactoryRegistry(); if (inputs != null) Inputs = inputs; } @@ -57,12 +59,12 @@ public static Declaration FromSequence(List decls) return first; } - public IArrowArrayStream ToRecordBatchReader(Schema schema) + public Task ToRecordBatchReader(Schema schema) { return ToRecordBatchReader(this, schema); } - public static IArrowArrayStream ToRecordBatchReader(Declaration declaration, Schema schema) + public static async Task ToRecordBatchReader(Declaration declaration, Schema schema) { var sinkNodeOptions = new SinkNodeOptions(schema); var plan = new ExecPlan(); @@ -79,6 +81,8 @@ public static IArrowArrayStream ToRecordBatchReader(Declaration declaration, Sch if (!plan.Validate()) throw new InvalidOperationException("Plan is not valid"); + await plan.Init(); + plan.StartProducing(); plan.Wait(); @@ -87,40 +91,19 @@ public static IArrowArrayStream ToRecordBatchReader(Declaration declaration, Sch private ExecNode AddToPlan(ExecPlan plan) { - var nodes = new List(); + var inputNodes = new List(); foreach (Declaration input in Inputs) { - ExecNode node = input.AddToPlan(plan); - nodes.Add(node); + ExecNode inputNode = input.AddToPlan(plan); + inputNodes.Add(inputNode); } - switch (_factoryName) - { - case "sink": - return new SinkNode(_options as SinkNodeOptions, plan, nodes); - - case "record_batch_source": - return new RecordBatchSourceNode(_options as RecordBatchSourceNodeOptions, plan); - - case "record_batch_reader_source": - return new RecordBatchReaderSourceNode(_options as RecordBatchReaderSourceNodeOptions, plan); + ExecNode node = _registry.MakeNode(_factoryName, plan, _options, inputNodes); - case "hashjoin": - return new HashJoinNode(_options as HashJoinNodeOptions, plan, nodes); + plan.AddNode(node); - case "filter": - return new FilterNode(_options as FilterNodeOptions, plan, nodes); - - case "union": - return new UnionNode(plan, nodes); - - case "project": - return new ProjectNode(_options as ProjectNodeOptions, plan, nodes); - - default: - throw new Exception($"Unknown factory {_factoryName}"); - } + return node; } } } diff --git a/csharp/src/Apache.Arrow.Acero/DefaultExecNodeFactoryRegistry.cs b/csharp/src/Apache.Arrow.Acero/DefaultExecNodeFactoryRegistry.cs new file mode 100644 index 000000000000..08b629280800 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/DefaultExecNodeFactoryRegistry.cs @@ -0,0 +1,58 @@ +// 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; + +namespace Apache.Arrow.Acero +{ + public abstract class ExecNodeFactoryRegistry + { + public abstract ExecNode MakeNode(string factoryName, ExecPlan plan, ExecNodeOptions options, List inputs); + } + + public class DefaultExecNodeFactoryRegistry : ExecNodeFactoryRegistry + { + public override ExecNode MakeNode(string factoryName, ExecPlan plan, ExecNodeOptions options, List inputs) + { + switch (factoryName) + { + case "sink": + return new SinkNode(options as SinkNodeOptions, plan, inputs); + + case "record_batch_source": + return new RecordBatchSourceNode(options as RecordBatchSourceNodeOptions, plan); + + case "record_batch_reader_source": + return new RecordBatchReaderSourceNode(options as RecordBatchReaderSourceNodeOptions, plan); + + case "hashjoin": + return new HashJoinNode(options as HashJoinNodeOptions, plan, inputs); + + case "filter": + return new FilterNode(options as FilterNodeOptions, plan, inputs); + + case "union": + return new UnionNode(plan, inputs); + + case "project": + return new ProjectNode(options as ProjectNodeOptions, plan, inputs); + + default: + throw new InvalidOperationException($"Unknown factory {factoryName}"); + } + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs b/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs index 32dd30bb24d9..a05159c5768e 100644 --- a/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs +++ b/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs @@ -1,4 +1,19 @@ -using System; +// 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 Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero diff --git a/csharp/src/Apache.Arrow.Acero/ExecNode.cs b/csharp/src/Apache.Arrow.Acero/ExecNode.cs index 1deb4ff9963e..92c00985834a 100644 --- a/csharp/src/Apache.Arrow.Acero/ExecNode.cs +++ b/csharp/src/Apache.Arrow.Acero/ExecNode.cs @@ -14,17 +14,38 @@ // limitations under the License. using System; +using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Threading.Tasks; using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { - public abstract class ExecNode + public abstract class ExecNode : IDisposable { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_node(GArrowExecutePlan* plan, IntPtr factory_name, IntPtr inputs, IntPtr options, out GError** error); protected static d_garrow_execute_plan_build_node garrow_execute_plan_build_node = FuncLoader.LoadFunction("garrow_execute_plan_build_node"); - public abstract unsafe GArrowExecuteNode* Handle { get; } + public unsafe GArrowExecuteNode* Handle { get; protected set; } + + public ExecPlan Plan { get; } + + public ExecNode Output { get; set; } + + public List Inputs { get; } + + public ExecNode(ExecPlan plan, List inputs) + { + Plan = plan; + Inputs = inputs; + + foreach (ExecNode input in inputs) + input.Output = this; + } + + public virtual Task Init() => Task.CompletedTask; + + public abstract void Dispose(); } } diff --git a/csharp/src/Apache.Arrow.Acero/ExecPlan.cs b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs index 88ea185c21a7..f78bb5f8caee 100644 --- a/csharp/src/Apache.Arrow.Acero/ExecPlan.cs +++ b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs @@ -13,15 +13,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Threading.Tasks; using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class ExecPlan { - private readonly unsafe GArrowExecutePlan* _planPtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate GArrowExecutePlan* d_garrow_execute_plan_new(out GError** error); private static d_garrow_execute_plan_new garrow_execute_plan_new = FuncLoader.LoadFunction("garrow_execute_plan_new"); @@ -38,32 +38,74 @@ public class ExecPlan private unsafe delegate bool d_garrow_execute_plan_wait(GArrowExecutePlan* plan); private static d_garrow_execute_plan_wait garrow_execute_plan_wait = FuncLoader.LoadFunction("garrow_execute_plan_wait"); - public unsafe GArrowExecutePlan* Handle => _planPtr; + public unsafe GArrowExecutePlan* Handle { get; } + + public List Nodes { get; internal set; } = new(); public unsafe ExecPlan() { - _planPtr = garrow_execute_plan_new(out GError** error); + Handle = garrow_execute_plan_new(out GError** error); ExceptionUtil.ThrowOnError(error); } public unsafe bool Validate() { - bool valid = garrow_execute_plan_validate(_planPtr, out GError** error); + bool valid = garrow_execute_plan_validate(Handle, out GError** error); ExceptionUtil.ThrowOnError(error); return valid; } + public async Task Init() + { + ExecNode[] sortedNodes = TopoSort(); + + foreach (ExecNode node in sortedNodes) + await node.Init(); + } + public unsafe void StartProducing() { - garrow_execute_plan_start(_planPtr); + garrow_execute_plan_start(Handle); } public unsafe void Wait() { - garrow_execute_plan_wait(_planPtr); + garrow_execute_plan_wait(Handle); + } + + internal void AddNode(ExecNode node) + { + Nodes.Add(node); + } + + /// + /// Sort nodes, producers precede consumers + /// https://github.com/apache/arrow/blob/main/cpp/src/arrow/acero/exec_plan.cc#L239 + /// + /// Sorted nodes + public ExecNode[] TopoSort() + { + var visited = new List(); + var sorted = new ExecNode[Nodes.Count]; + + foreach (ExecNode node in Nodes) + Visit(node); + + return sorted; + + void Visit(ExecNode node) + { + if (visited.Contains(node)) return; + + foreach (ExecNode input in node.Inputs) + Visit(input); + + sorted[visited.Count] = node; + visited.Add(node); + } } } } diff --git a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs b/csharp/src/Apache.Arrow.Acero/ExportUtil.cs deleted file mode 100644 index 99dee93fea6a..000000000000 --- a/csharp/src/Apache.Arrow.Acero/ExportUtil.cs +++ /dev/null @@ -1,72 +0,0 @@ -// 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.Runtime.InteropServices; -using Apache.Arrow.Acero.CLib; -using Apache.Arrow.C; -using Apache.Arrow.Ipc; - -namespace Apache.Arrow.Acero -{ - internal static class ExportUtil - { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private unsafe delegate GArrowRecordBatch* d_garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, out GError** error); - private static d_garrow_record_batch_import garrow_record_batch_import = FuncLoader.LoadFunction("garrow_record_batch_import"); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private unsafe delegate GArrowSchema* d_garrow_schema_import(CArrowSchema* c_abi_schema, out GError** error); - private static d_garrow_schema_import garrow_schema_import = FuncLoader.LoadFunction("garrow_schema_import"); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private unsafe delegate GArrowRecordBatchReader* d_garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, out GError** error); - private static d_garrow_record_batch_reader_import garrow_record_batch_reader_import = FuncLoader.LoadFunction("garrow_record_batch_reader_import"); - - public static unsafe GArrowSchema* ExportAndGetSchemaPtr(Schema schema) - { - CArrowSchema* cSchema = CArrowSchema.Create(); - CArrowSchemaExporter.ExportSchema(schema, cSchema); - GArrowSchema* gSchema = garrow_schema_import(cSchema, out GError** error); - - ExceptionUtil.ThrowOnError(error); - - return gSchema; - } - - public static unsafe GArrowRecordBatch* ExportAndGetRecordBatchPtr(RecordBatch recordBatch) - { - GArrowSchema* schemaPtr = ExportAndGetSchemaPtr(recordBatch.Schema); - - CArrowArray* cArray = CArrowArray.Create(); - CArrowArrayExporter.ExportRecordBatch(recordBatch, cArray); - GArrowRecordBatch* gRecordBatch = garrow_record_batch_import(cArray, schemaPtr, out GError** error); - - ExceptionUtil.ThrowOnError(error); - - return gRecordBatch; - } - - public static unsafe GArrowRecordBatchReader* ExportAndGetRecordBatchReaderPtr(IArrowArrayStream recordBatchReader) - { - CArrowArrayStream* cArrayStream = CArrowArrayStream.Create(); - CArrowArrayStreamExporter.ExportArrayStream(recordBatchReader, cArrayStream); - GArrowRecordBatchReader* gRecordBatchReader = garrow_record_batch_reader_import(cArrayStream, out GError** error); - - ExceptionUtil.ThrowOnError(error); - - return gRecordBatchReader; - } - } -} diff --git a/csharp/src/Apache.Arrow.Acero/ExportedRecordBatch.cs b/csharp/src/Apache.Arrow.Acero/ExportedRecordBatch.cs new file mode 100644 index 000000000000..2e26a7dcd72e --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExportedRecordBatch.cs @@ -0,0 +1,43 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; +using Apache.Arrow.C; + +namespace Apache.Arrow.Acero +{ + public class ExportedRecordBatch + { + private readonly ExportedSchema _exportedSchema; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowRecordBatch* d_garrow_record_batch_import(CArrowArray* c_abi_array, GArrowSchema* schema, out GError** error); + private static d_garrow_record_batch_import garrow_record_batch_import = FuncLoader.LoadFunction("garrow_record_batch_import"); + + public unsafe GArrowRecordBatch* Handle { get; } + + public unsafe ExportedRecordBatch(RecordBatch recordBatch) + { + _exportedSchema = new ExportedSchema(recordBatch.Schema); + + CArrowArray* cArray = CArrowArray.Create(); + CArrowArrayExporter.ExportRecordBatch(recordBatch, cArray); + Handle = garrow_record_batch_import(cArray, _exportedSchema.Handle, out GError** error); + + ExceptionUtil.ThrowOnError(error); + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExportedRecordBatchReader.cs b/csharp/src/Apache.Arrow.Acero/ExportedRecordBatchReader.cs new file mode 100644 index 000000000000..f5731287cb65 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExportedRecordBatchReader.cs @@ -0,0 +1,41 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; +using Apache.Arrow.C; +using Apache.Arrow.Ipc; + +namespace Apache.Arrow.Acero +{ + public class ExportedRecordBatchReader + { + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowRecordBatchReader* d_garrow_record_batch_reader_import(CArrowArrayStream* c_abi_array_stream, out GError** error); + private static d_garrow_record_batch_reader_import garrow_record_batch_reader_import = FuncLoader.LoadFunction("garrow_record_batch_reader_import"); + + public unsafe GArrowRecordBatchReader* Handle { get; } + + public unsafe ExportedRecordBatchReader(IArrowArrayStream recordBatchReader) + { + CArrowArrayStream* cArrayStream = CArrowArrayStream.Create(); + CArrowArrayStreamExporter.ExportArrayStream(recordBatchReader, cArrayStream); + + Handle = garrow_record_batch_reader_import(cArrayStream, out GError** error); + + ExceptionUtil.ThrowOnError(error); + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/ExportedSchema.cs b/csharp/src/Apache.Arrow.Acero/ExportedSchema.cs new file mode 100644 index 000000000000..61be34803a45 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExportedSchema.cs @@ -0,0 +1,39 @@ +// 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.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; +using Apache.Arrow.C; + +namespace Apache.Arrow.Acero +{ + public class ExportedSchema + { + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private unsafe delegate GArrowSchema* d_garrow_schema_import(CArrowSchema* c_abi_schema, out GError** error); + private static d_garrow_schema_import garrow_schema_import = FuncLoader.LoadFunction("garrow_schema_import"); + + public unsafe GArrowSchema* Handle { get; } + + public unsafe ExportedSchema(Schema schema) + { + CArrowSchema* cSchema = CArrowSchema.Create(); + CArrowSchemaExporter.ExportSchema(schema, cSchema); + Handle = garrow_schema_import(cSchema, out GError** error); + + ExceptionUtil.ThrowOnError(error); + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/Expression.cs b/csharp/src/Apache.Arrow.Acero/Expression.cs index 51fa3c744b74..cd679786f4c4 100644 --- a/csharp/src/Apache.Arrow.Acero/Expression.cs +++ b/csharp/src/Apache.Arrow.Acero/Expression.cs @@ -24,14 +24,13 @@ public abstract class Expression private unsafe delegate IntPtr d_garrow_expression_to_string(IntPtr expression); private static d_garrow_expression_to_string garrow_expression_to_string = FuncLoader.LoadFunction("garrow_expression_to_string"); - public abstract IntPtr Handle { get; } + public IntPtr Handle { get; protected set; } public override unsafe string ToString() { IntPtr strPtr = garrow_expression_to_string(Handle); - string str = GLib.Marshaller.PtrToStringGFree(strPtr); - return str; + return GLib.Marshaller.PtrToStringGFree(strPtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs index 5349c8e3b2be..19630b56fbbc 100644 --- a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs +++ b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs @@ -21,19 +21,17 @@ namespace Apache.Arrow.Acero { public class FieldExpression : Expression { - private readonly IntPtr _expressionPtr; private readonly IntPtr _referencePtr; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate IntPtr d_garrow_field_expression_new(IntPtr reference, out GError** error); private static d_garrow_field_expression_new garrow_field_expression_new = FuncLoader.LoadFunction("garrow_field_expression_new"); - public override IntPtr Handle => _expressionPtr; - public unsafe FieldExpression(string reference) { _referencePtr = GLib.Marshaller.StringToPtrGStrdup(reference); - _expressionPtr = garrow_field_expression_new(_referencePtr, out GError** error); + + Handle = garrow_field_expression_new(_referencePtr, out GError** error); ExceptionUtil.ThrowOnError(error); } diff --git a/csharp/src/Apache.Arrow.Acero/FilterNode.cs b/csharp/src/Apache.Arrow.Acero/FilterNode.cs index 0d0063a6144d..b2cbae1be820 100644 --- a/csharp/src/Apache.Arrow.Acero/FilterNode.cs +++ b/csharp/src/Apache.Arrow.Acero/FilterNode.cs @@ -21,19 +21,18 @@ namespace Apache.Arrow.Acero { public class FilterNode : ExecNode { - private readonly unsafe GArrowExecuteNode* _nodePtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_filter_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowFilterNodeOptions* options, out GError** error); protected static d_garrow_execute_plan_build_filter_node garrow_execute_plan_build_filter_node = FuncLoader.LoadFunction("garrow_execute_plan_build_filter_node"); - public override unsafe GArrowExecuteNode* Handle => _nodePtr; - public unsafe FilterNode(FilterNodeOptions options, ExecPlan plan, List nodes) + : base(plan, nodes) { - _nodePtr = garrow_execute_plan_build_filter_node(plan.Handle, nodes[0].Handle, options.Handle, out GError** error); + Handle = garrow_execute_plan_build_filter_node(plan.Handle, nodes[0].Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } + + public override void Dispose() { } } } diff --git a/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs index fdd2d677b1b8..7c90ec29b20c 100644 --- a/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs @@ -21,17 +21,15 @@ namespace Apache.Arrow.Acero { public class FilterNodeOptions : ExecNodeOptions { - private readonly unsafe GArrowFilterNodeOptions* _optionsPtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowFilterNodeOptions* d_garrow_filter_node_options_new(IntPtr expression); protected static d_garrow_filter_node_options_new garrow_filter_node_options_new = FuncLoader.LoadFunction("garrow_filter_node_options_new"); - public unsafe GArrowFilterNodeOptions* Handle => _optionsPtr; + public unsafe GArrowFilterNodeOptions* Handle { get; } public unsafe FilterNodeOptions(Expression expr) { - _optionsPtr = garrow_filter_node_options_new(expr.Handle); + Handle = garrow_filter_node_options_new(expr.Handle); } } } diff --git a/csharp/src/Apache.Arrow.Acero/FuncLoader.cs b/csharp/src/Apache.Arrow.Acero/FuncLoader.cs index 12ff16b440e1..4f2076e5cfa8 100644 --- a/csharp/src/Apache.Arrow.Acero/FuncLoader.cs +++ b/csharp/src/Apache.Arrow.Acero/FuncLoader.cs @@ -1,4 +1,19 @@ -using System; +// 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.Runtime.InteropServices; namespace Apache.Arrow.Acero @@ -38,10 +53,16 @@ public static IntPtr LoadLibrary(string libName) { if (OperatingSystem.IsWindows()) { - Windows.AddDllDirectory("C:\\msys64\\mingw64\\bin"); - Windows.SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); - IntPtr ptr = Windows.LoadLibrary(libName); + + if (ptr == IntPtr.Zero) + { + Windows.AddDllDirectory("C:\\msys64\\mingw64\\bin"); + Windows.SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + + ptr = Windows.LoadLibrary(libName); + } + int error = Marshal.GetLastWin32Error(); if (error > 0) diff --git a/csharp/src/Apache.Arrow.Acero/Function.cs b/csharp/src/Apache.Arrow.Acero/Function.cs index a5aa9aa2983f..4f75a2763d7f 100644 --- a/csharp/src/Apache.Arrow.Acero/Function.cs +++ b/csharp/src/Apache.Arrow.Acero/Function.cs @@ -21,7 +21,6 @@ namespace Apache.Arrow.Acero { public class Function : Expression { - private readonly IntPtr _expressionPtr; private readonly IntPtr _functionNamePtr; private readonly GLib.List _functionArgs; @@ -29,8 +28,6 @@ public class Function : Expression private unsafe delegate GArrowFilterNodeOptions* d_garrow_call_expression_new(IntPtr function, IntPtr arguments, GArrowFunctionOptions* options); private static d_garrow_call_expression_new garrow_call_expression_new = FuncLoader.LoadFunction("garrow_call_expression_new"); - public override IntPtr Handle => _expressionPtr; - public unsafe Function(string functionName, Expression lhs, Expression rhs) : this(functionName, new[] { lhs, rhs }) { @@ -44,7 +41,7 @@ public unsafe Function(string functionName, params Expression[] args) foreach (Expression arg in args) _functionArgs.Append(arg.Handle); - _expressionPtr = (IntPtr)garrow_call_expression_new(_functionNamePtr, _functionArgs.Handle, null); + Handle = (IntPtr)garrow_call_expression_new(_functionNamePtr, _functionArgs.Handle, null); } ~Function() diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs index 5b35ffe206b4..bbaaa75fbdd6 100644 --- a/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNode.cs @@ -21,22 +21,21 @@ namespace Apache.Arrow.Acero { public class HashJoinNode : ExecNode { - private readonly unsafe GArrowExecuteNode* _nodePtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_hash_join_node(GArrowExecutePlan* plan, GArrowExecuteNode* left, GArrowExecuteNode* right, GArrowHashJoinNodeOptions* options, out GError** error); private static d_garrow_execute_plan_build_hash_join_node garrow_execute_plan_build_hash_join_node = FuncLoader.LoadFunction("garrow_execute_plan_build_hash_join_node"); - public override unsafe GArrowExecuteNode* Handle => _nodePtr; - public unsafe HashJoinNode(HashJoinNodeOptions options, ExecPlan plan, List inputs) + : base(plan, inputs) { ExecNode left = inputs[0]; ExecNode right = inputs[1]; - _nodePtr = garrow_execute_plan_build_hash_join_node(plan.Handle, left.Handle, right.Handle, options.Handle, out GError** error); + Handle = garrow_execute_plan_build_hash_join_node(plan.Handle, left.Handle, right.Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); - } + } + + public override void Dispose() { } } } diff --git a/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs index 5d24d1d16dee..8ce3cdf93182 100644 --- a/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs @@ -21,7 +21,6 @@ namespace Apache.Arrow.Acero { public class HashJoinNodeOptions : ExecNodeOptions { - private readonly unsafe GArrowHashJoinNodeOptions* _optionsPtr; private readonly IntPtr _leftKeysPtr; private readonly IntPtr _rightKeysPtr; @@ -29,14 +28,14 @@ public class HashJoinNodeOptions : ExecNodeOptions private unsafe delegate GArrowHashJoinNodeOptions* d_garrow_hash_join_node_options_new(GArrowJoinType type, IntPtr left_keys, uint n_left_keys, IntPtr right_keys, uint n_right_keys, out GError** error); private static d_garrow_hash_join_node_options_new garrow_hash_join_node_options_new = FuncLoader.LoadFunction("garrow_hash_join_node_options_new"); - internal unsafe GArrowHashJoinNodeOptions* Handle => _optionsPtr; + public unsafe GArrowHashJoinNodeOptions* Handle { get; } public unsafe HashJoinNodeOptions(GArrowJoinType joinType, string[] leftKeys, string[] rightKeys) { _leftKeysPtr = GLib.Marshaller.StringArrayToStrvPtr(leftKeys); _rightKeysPtr = GLib.Marshaller.StringArrayToStrvPtr(leftKeys); - _optionsPtr = garrow_hash_join_node_options_new(joinType, _leftKeysPtr, (uint)leftKeys.Length, _rightKeysPtr, (uint)rightKeys.Length, out GError** error); + Handle = garrow_hash_join_node_options_new(joinType, _leftKeysPtr, (uint)leftKeys.Length, _rightKeysPtr, (uint)rightKeys.Length, out GError** error); ExceptionUtil.ThrowOnError(error); } diff --git a/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs index 82a5925d2455..cd593f477376 100644 --- a/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs +++ b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs @@ -21,8 +21,6 @@ namespace Apache.Arrow.Acero { public class LiteralExpression : Expression { - private unsafe readonly GArrowFieldExpression* _expressionPtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate GArrowFieldExpression* d_garrow_literal_expression_new(GArrowDatum* datum); private static d_garrow_literal_expression_new garrow_literal_expression_new = FuncLoader.LoadFunction("garrow_literal_expression_new"); @@ -43,8 +41,6 @@ public class LiteralExpression : Expression private unsafe delegate GArrowInt32Scalar* d_garrow_int32_scalar_new(int value); private static d_garrow_int32_scalar_new garrow_int32_scalar_new = FuncLoader.LoadFunction("garrow_int32_scalar_new"); - public unsafe override IntPtr Handle => (IntPtr)_expressionPtr; - public unsafe LiteralExpression(string literal) { IntPtr dataPtr = GLib.Marshaller.StringToPtrGStrdup(literal); @@ -52,7 +48,7 @@ public unsafe LiteralExpression(string literal) GArrowStringScalar* scalarPtr = garrow_string_scalar_new(bufferPtr); GArrowScalarDatum* datumPtr = garrow_scalar_datum_new((IntPtr)scalarPtr); - _expressionPtr = garrow_literal_expression_new((GArrowDatum*)datumPtr); + Handle = (IntPtr)garrow_literal_expression_new((GArrowDatum*)datumPtr); } public unsafe LiteralExpression(int literal) @@ -60,7 +56,7 @@ public unsafe LiteralExpression(int literal) GArrowInt32Scalar* scalarPtr = garrow_int32_scalar_new(literal); GArrowScalarDatum* datumPtr = garrow_scalar_datum_new((IntPtr)scalarPtr); - _expressionPtr = garrow_literal_expression_new((GArrowDatum*)datumPtr); + Handle = (IntPtr)garrow_literal_expression_new((GArrowDatum*)datumPtr); } } } diff --git a/csharp/src/Apache.Arrow.Acero/ProjectNode.cs b/csharp/src/Apache.Arrow.Acero/ProjectNode.cs index d4ac2d277c2d..8f8a05f87930 100644 --- a/csharp/src/Apache.Arrow.Acero/ProjectNode.cs +++ b/csharp/src/Apache.Arrow.Acero/ProjectNode.cs @@ -21,19 +21,18 @@ namespace Apache.Arrow.Acero { public class ProjectNode : ExecNode { - private unsafe GArrowExecuteNode* _nodePtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_project_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowProjectNodeOptions* options, out GError** error); protected static d_garrow_execute_plan_build_project_node garrow_execute_plan_build_project_node = FuncLoader.LoadFunction("garrow_execute_plan_build_project_node"); - public override unsafe GArrowExecuteNode* Handle => _nodePtr; - - public unsafe ProjectNode(ProjectNodeOptions options, ExecPlan plan, List nodes) + public unsafe ProjectNode(ProjectNodeOptions options, ExecPlan plan, List inputs) + : base(plan, inputs) { - _nodePtr = garrow_execute_plan_build_project_node(plan.Handle, nodes[0].Handle, options.Handle, out GError** error); + Handle = garrow_execute_plan_build_project_node(plan.Handle, inputs[0].Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } + + public override void Dispose() { } } } diff --git a/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs index 3995fb3ab478..b8e47df4af34 100644 --- a/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/ProjectNodeOptions.cs @@ -22,13 +22,11 @@ namespace Apache.Arrow.Acero { public class ProjectNodeOptions : ExecNodeOptions { - private readonly unsafe GArrowProjectNodeOptions* _optionsPtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate GArrowProjectNodeOptions* d_garrow_project_node_options_new(GList* expressions, IntPtr names, int n_names); private static d_garrow_project_node_options_new garrow_project_node_options_new = FuncLoader.LoadFunction("garrow_project_node_options_new"); - internal unsafe GArrowProjectNodeOptions* Handle => _optionsPtr; + public unsafe GArrowProjectNodeOptions* Handle { get; } public unsafe ProjectNodeOptions(List expressions, List names) { @@ -39,7 +37,7 @@ public unsafe ProjectNodeOptions(List expressions, List name IntPtr namesPtr = GLib.Marshaller.StringArrayToStrvPtr(names.ToArray()); - _optionsPtr = garrow_project_node_options_new((GList*)list.Handle, namesPtr, names.Count); + Handle = garrow_project_node_options_new((GList*)list.Handle, namesPtr, names.Count); } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs index 463a59978b51..4941af094dbb 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNode.cs @@ -13,21 +13,20 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Collections.Generic; using Apache.Arrow.Acero.CLib; namespace Apache.Arrow.Acero { public class RecordBatchReaderSourceNode : SourceNode { - private unsafe GArrowExecuteNode* _nodePtr; - - public override unsafe GArrowExecuteNode* Handle => _nodePtr; - - public unsafe RecordBatchReaderSourceNode(RecordBatchReaderSourceNodeOptions options, ExecPlan plan) + public unsafe RecordBatchReaderSourceNode(RecordBatchReaderSourceNodeOptions options, ExecPlan plan) : base(plan, new List()) { - _nodePtr = garrow_execute_plan_build_source_node(plan.Handle, options.Handle, out GError** error); + Handle = garrow_execute_plan_build_source_node(plan.Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } + + public override void Dispose() { } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs index c77d6e368fce..d1ef49d3852b 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.cs @@ -21,19 +21,19 @@ namespace Apache.Arrow.Acero { public class RecordBatchReaderSourceNodeOptions : ExecNodeOptions { - private readonly unsafe GArrowSourceNodeOptions* _optionsPtr; + private readonly ExportedRecordBatchReader _exportedRecordBatchReader; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowSourceNodeOptions* d_garrow_source_node_options_new_record_batch_reader(GArrowRecordBatchReader* reader); protected static d_garrow_source_node_options_new_record_batch_reader garrow_source_node_options_new_record_batch_reader = FuncLoader.LoadFunction("garrow_source_node_options_new_record_batch_reader"); - public unsafe GArrowSourceNodeOptions* Handle => _optionsPtr; + public unsafe GArrowSourceNodeOptions* Handle { get; } public unsafe RecordBatchReaderSourceNodeOptions(IArrowArrayStream recordBatchReader) { - GArrowRecordBatchReader* recordBatchReaderPtr = ExportUtil.ExportAndGetRecordBatchReaderPtr(recordBatchReader); + _exportedRecordBatchReader = new ExportedRecordBatchReader(recordBatchReader); - _optionsPtr = garrow_source_node_options_new_record_batch_reader(recordBatchReaderPtr); + Handle = garrow_source_node_options_new_record_batch_reader(_exportedRecordBatchReader.Handle); } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs index b540d2ef3063..31c1b108276b 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Collections.Generic; using System.Runtime.InteropServices; using Apache.Arrow.Acero.CLib; @@ -23,19 +24,19 @@ public abstract class SourceNode : ExecNode [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_source_node(GArrowExecutePlan* plan, GArrowSourceNodeOptions* options, out GError** error); protected static d_garrow_execute_plan_build_source_node garrow_execute_plan_build_source_node = FuncLoader.LoadFunction("garrow_execute_plan_build_source_node"); + + protected SourceNode(ExecPlan plan, List inputs) : base(plan, inputs) { } } public class RecordBatchSourceNode : SourceNode { - private unsafe GArrowExecuteNode* _nodePtr; - - public override unsafe GArrowExecuteNode* Handle => _nodePtr; - - public unsafe RecordBatchSourceNode(RecordBatchSourceNodeOptions options, ExecPlan plan) + public unsafe RecordBatchSourceNode(RecordBatchSourceNodeOptions options, ExecPlan plan) : base(plan, new List()) { - _nodePtr = garrow_execute_plan_build_source_node(plan.Handle, options.Handle, out GError** error); + Handle = garrow_execute_plan_build_source_node(plan.Handle, options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } + + public override void Dispose() { } } } diff --git a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs index c9c7a614ba14..c6bd2ced5f4f 100644 --- a/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs @@ -20,19 +20,19 @@ namespace Apache.Arrow.Acero { public class RecordBatchSourceNodeOptions : ExecNodeOptions { - private readonly unsafe GArrowSourceNodeOptions* _optionsPtr; + private readonly ExportedRecordBatch _exportedRecordBatch; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowSourceNodeOptions* d_garrow_source_node_options_new_record_batch(GArrowRecordBatch* record_batch); protected static d_garrow_source_node_options_new_record_batch garrow_source_node_options_new_record_batch = FuncLoader.LoadFunction("garrow_source_node_options_new_record_batch"); - public unsafe GArrowSourceNodeOptions* Handle => _optionsPtr; + public unsafe GArrowSourceNodeOptions* Handle { get; } public unsafe RecordBatchSourceNodeOptions(RecordBatch recordBatch) { - GArrowRecordBatch* recordBatchPtr = ExportUtil.ExportAndGetRecordBatchPtr(recordBatch); + _exportedRecordBatch = new ExportedRecordBatch(recordBatch); - _optionsPtr = garrow_source_node_options_new_record_batch(recordBatchPtr); + Handle = garrow_source_node_options_new_record_batch(_exportedRecordBatch.Handle); } } } diff --git a/csharp/src/Apache.Arrow.Acero/SinkNode.cs b/csharp/src/Apache.Arrow.Acero/SinkNode.cs index 3bcf1c9d7534..287fc4cacace 100644 --- a/csharp/src/Apache.Arrow.Acero/SinkNode.cs +++ b/csharp/src/Apache.Arrow.Acero/SinkNode.cs @@ -21,19 +21,17 @@ namespace Apache.Arrow.Acero { public class SinkNode : ExecNode { - private readonly unsafe GArrowExecuteNode* _nodePtr; - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowExecuteNode* d_garrow_execute_plan_build_sink_node(GArrowExecutePlan* plan, GArrowExecuteNode* input, GArrowSinkNodeOptions* options, out GError** error); protected static d_garrow_execute_plan_build_sink_node garrow_execute_plan_build_sink_node = FuncLoader.LoadFunction("garrow_execute_plan_build_sink_node"); - public override unsafe GArrowExecuteNode* Handle => _nodePtr; - - public unsafe SinkNode(SinkNodeOptions _options, ExecPlan plan, List inputs) + public unsafe SinkNode(SinkNodeOptions _options, ExecPlan plan, List inputs) : base(plan, inputs) { - _nodePtr = garrow_execute_plan_build_sink_node(plan.Handle, inputs[0].Handle, _options.Handle, out GError** error); + Handle = garrow_execute_plan_build_sink_node(plan.Handle, inputs[0].Handle, _options.Handle, out GError** error); ExceptionUtil.ThrowOnError(error); } + + public override void Dispose() { } } } diff --git a/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs index e50338fdf178..47f2f59af867 100644 --- a/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs +++ b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs @@ -22,8 +22,7 @@ namespace Apache.Arrow.Acero { public class SinkNodeOptions : ExecNodeOptions { - private readonly unsafe GArrowSinkNodeOptions* _optionsPtr; - private readonly Schema _schema; + private readonly ExportedSchema _exportedSchema; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate GArrowSinkNodeOptions* d_garrow_sink_node_options_new(); @@ -37,18 +36,18 @@ public class SinkNodeOptions : ExecNodeOptions private unsafe delegate CArrowArrayStream* d_garrow_record_batch_reader_export(GArrowRecordBatchReader* reader, out GError** error); private static d_garrow_record_batch_reader_export garrow_record_batch_reader_export = FuncLoader.LoadFunction("garrow_record_batch_reader_export"); - internal unsafe GArrowSinkNodeOptions* Handle => _optionsPtr; + internal unsafe GArrowSinkNodeOptions* Handle { get; } public unsafe SinkNodeOptions(Schema schema) { - _optionsPtr = garrow_sink_node_options_new(); - _schema = schema; + _exportedSchema = new ExportedSchema(schema); + + Handle = garrow_sink_node_options_new(); } public unsafe IArrowArrayStream GetRecordBatchReader() { - GArrowSchema* schemaPtr = ExportUtil.ExportAndGetSchemaPtr(_schema); - GArrowRecordBatchReader* recordBatchReaderPtr = garrow_sink_node_options_get_reader(_optionsPtr, schemaPtr); + GArrowRecordBatchReader* recordBatchReaderPtr = garrow_sink_node_options_get_reader(Handle, _exportedSchema.Handle); CArrowArrayStream* arrayStreamPtr = garrow_record_batch_reader_export(recordBatchReaderPtr, out GError** error); ExceptionUtil.ThrowOnError(error); diff --git a/csharp/src/Apache.Arrow.Acero/UnionNode.cs b/csharp/src/Apache.Arrow.Acero/UnionNode.cs index 8cd63c800cd3..7dcb41363c66 100644 --- a/csharp/src/Apache.Arrow.Acero/UnionNode.cs +++ b/csharp/src/Apache.Arrow.Acero/UnionNode.cs @@ -20,38 +20,55 @@ namespace Apache.Arrow.Acero { - public class UnionNode : ExecNode + public class UnionNode : ExecNode, IDisposable { - private readonly unsafe GArrowExecuteNode* _nodePtr; + private readonly unsafe GArrowExecuteNodeOptions* _optionsPtr; + private readonly IntPtr _factoryNamePtr; + private readonly GLib.List _inputs; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] protected unsafe delegate IntPtr d_garrow_sink_node_options_new(); protected static d_garrow_sink_node_options_new garrow_sink_node_options_new = FuncLoader.LoadFunction("garrow_sink_node_options_new"); - public override unsafe GArrowExecuteNode* Handle => _nodePtr; - - public unsafe UnionNode(ExecPlan plan, List nodes) + public unsafe UnionNode(ExecPlan plan, List inputs) : base(plan, inputs) { - string factoryName = "union"; - IntPtr factoryNamePtr = GLib.Marshaller.StringToPtrGStrdup(factoryName); - - ExecNode lhs = nodes[0]; - ExecNode rhs = nodes[1]; + _factoryNamePtr = GLib.Marshaller.StringToPtrGStrdup("union"); - var list = new GLib.List(IntPtr.Zero); - list.Append((IntPtr)lhs.Handle); - list.Append((IntPtr)rhs.Handle); + ExecNode lhs = inputs[0]; + ExecNode rhs = inputs[1]; - // todo: using this ptr causes the following error - // g_object_new_valist: invalid unclassed object pointer for value type 'GArrowExecuteNodeOptions' - //IntPtr optionsPtr = GLib.Marshaller.StructureToPtrAlloc(new GArrowExecuteNodeOptions()); + _inputs = new GLib.List(IntPtr.Zero); + _inputs.Append((IntPtr)lhs.Handle); + _inputs.Append((IntPtr)rhs.Handle); - // for now just use the sink options - IntPtr optionsPtr2 = garrow_sink_node_options_new(); + _optionsPtr = (GArrowExecuteNodeOptions*)Marshal.AllocHGlobal(sizeof(GArrowExecuteNodeOptions)); + *_optionsPtr = default; - _nodePtr = garrow_execute_plan_build_node(plan.Handle, factoryNamePtr, list.Handle, optionsPtr2, out GError** error); + Handle = garrow_execute_plan_build_node(plan.Handle, _factoryNamePtr, _inputs.Handle, (IntPtr)_optionsPtr, out GError** error); ExceptionUtil.ThrowOnError(error); } + + public override void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual unsafe void Dispose(bool disposing) + { + if (disposing) + { + _inputs.Dispose(); + } + + GLib.Marshaller.Free(_factoryNamePtr); + Marshal.FreeHGlobal((IntPtr)_optionsPtr); + } + + ~UnionNode() + { + Dispose(false); + } } } diff --git a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs index ab1ab621c907..75cc0927b3f4 100644 --- a/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs +++ b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs @@ -16,9 +16,7 @@ using Apache.Arrow.Acero.CLib; using Apache.Arrow.Ipc; using Apache.Arrow.Types; -using System; using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; @@ -45,7 +43,7 @@ public async Task TestRecordBatchSource() // act Schema schema = TestData.GetCustomersSchema(); - IArrowArrayStream result = recordBatchSource.ToRecordBatchReader(schema); + IArrowArrayStream result = await recordBatchSource.ToRecordBatchReader(schema); // assert Table table = await ConvertStreamToTable(result); @@ -59,9 +57,48 @@ public async Task TestRecordBatchSource() """, rowCount: 3); } + [Fact] + public async Task TestNestedDeclarations() + { + // arrange + var left = Declaration.FromSequence(new List { + new Declaration("record_batch_source", new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch())), + new Declaration("filter", new FilterNodeOptions( + new Equal(new FieldExpression("firstName"), new LiteralExpression("Luke")) + )) + }); + + var right = Declaration.FromSequence(new List { + new Declaration("record_batch_source", new RecordBatchSourceNodeOptions(TestData.GetCustomersRecordBatch())), + new Declaration("filter", new FilterNodeOptions( + new Equal(new FieldExpression("firstName"), new LiteralExpression("Luke")) + )) + }); + + var union = new Declaration("union", inputs: new List { left, right }); + + // act + IArrowArrayStream result = await union.ToRecordBatchReader( + new Schema.Builder() + .Field(new Field("customerId", StringType.Default, true)) + .Field(new Field("firstName", StringType.Default, true)) + .Field(new Field("lastName", StringType.Default, true)) + .Build()); + + // assert + Table table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + customerId | firstName | lastName | + c1 | Luke | Skywalker | + c1 | Luke | Skywalker | + """, rowCount: 2); + } + private void AssertTable(Table table, string expected, int? rowCount = null, int columnPadding = 10) { - string actual = PrintPrintTable(table, columnPadding); + string actual = table.PrettyPrint(columnPadding); _output.WriteLine(actual); @@ -90,7 +127,7 @@ public async Task TestHashJoin() options: hashJoinOptions, inputs: new List { left, right }); // act - IArrowArrayStream result = hashJoin.ToRecordBatchReader( + IArrowArrayStream result = await hashJoin.ToRecordBatchReader( new Schema.Builder() .Field(new Field("customerId", StringType.Default, true)) .Field(new Field("firstName", StringType.Default, true)) @@ -130,7 +167,7 @@ public async Task TestSingleFilter() // act Schema schema = TestData.GetCustomersSchema(); - IArrowArrayStream result = orderBy.ToRecordBatchReader(schema); + IArrowArrayStream result = await orderBy.ToRecordBatchReader(schema); // assert Table table = await ConvertStreamToTable(result); @@ -162,7 +199,7 @@ public async Task TestMultiFilter() // act Schema schema = TestData.GetCustomersSchema(); - IArrowArrayStream result = orderBy.ToRecordBatchReader(schema); + IArrowArrayStream result = await orderBy.ToRecordBatchReader(schema); // assert Table table = await ConvertStreamToTable(result); @@ -189,7 +226,7 @@ public async Task TestUnion() // act Schema schema = TestData.GetCustomersSchema(); - IArrowArrayStream result = union.ToRecordBatchReader(schema); + IArrowArrayStream result = await union.ToRecordBatchReader(schema); // assert Table table = await ConvertStreamToTable(result); @@ -228,7 +265,7 @@ public async Task TestProjection() }); // act - IArrowArrayStream result = project.ToRecordBatchReader( + IArrowArrayStream result = await project.ToRecordBatchReader( new Schema.Builder() .Field(new Field("fullName", StringType.Default, true)) .Build()); @@ -245,7 +282,7 @@ public async Task TestProjection() """, rowCount: 3, columnPadding: 15); } - private async Task
ConvertStreamToTable(IArrowArrayStream result) + private static async Task
ConvertStreamToTable(IArrowArrayStream result) { Schema schema = null; @@ -265,54 +302,6 @@ private async Task
ConvertStreamToTable(IArrowArrayStream result) return Table.TableFromRecordBatches(schema, recordBatches); } - public static string PrintPrintTable(Table table, int columnPadding = 10) - { - var sb = new StringBuilder(); - - for (int i = 0; i < table.ColumnCount; i++) - { - sb.Append(table.Column(i).Name.PadRight(columnPadding) + " | "); - } - - sb.AppendLine(); - - for (int i = 0; i < table.RowCount; i++) - { - for (int j = 0; j < table.ColumnCount; j++) - { - Column sliced = table.Column(j).Slice(i, 1); - - for (int k = 0; k < sliced.Data.ArrayCount; k++) - { - if (sliced.Data.Array(k).Length == 0) - continue; - - Array data = sliced.Data.Array(k); - string value; - - switch (data) - { - case StringArray stringArray: - value = stringArray.GetString(0); - break; - - case Int32Array int32Array: - value = int32Array.GetValue(0).ToString(); - break; - - default: - throw new Exception("Array type not supported"); - } - - sb.Append(value.PadRight(columnPadding) + " | "); - } - } - sb.AppendLine(); - } - - return sb.ToString().Trim('\n').Trim('\r'); - } - public class TestResult { public string TableAsString { get; set; } diff --git a/csharp/test/Apache.Arrow.Acero.Tests/TableExtensions.cs b/csharp/test/Apache.Arrow.Acero.Tests/TableExtensions.cs new file mode 100644 index 000000000000..533f6581933f --- /dev/null +++ b/csharp/test/Apache.Arrow.Acero.Tests/TableExtensions.cs @@ -0,0 +1,71 @@ +// 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.Text; + +namespace Apache.Arrow.Acero.Tests +{ + public static class TableExtensions + { + public static string PrettyPrint(this Table table, int columnPadding = 10) + { + var sb = new StringBuilder(); + + for (int i = 0; i < table.ColumnCount; i++) + { + sb.Append(table.Column(i).Name.PadRight(columnPadding) + " | "); + } + + sb.AppendLine(); + + for (int i = 0; i < table.RowCount; i++) + { + for (int j = 0; j < table.ColumnCount; j++) + { + Column sliced = table.Column(j).Slice(i, 1); + + for (int k = 0; k < sliced.Data.ArrayCount; k++) + { + if (sliced.Data.Array(k).Length == 0) + continue; + + Array data = sliced.Data.Array(k); + string value; + + switch (data) + { + case StringArray stringArray: + value = stringArray.GetString(0); + break; + + case Int32Array int32Array: + value = int32Array.GetValue(0).ToString(); + break; + + default: + throw new InvalidOperationException("Array type not supported"); + } + + sb.Append(value.PadRight(columnPadding) + " | "); + } + } + sb.AppendLine(); + } + + return sb.ToString().Trim('\n', '\r'); + } + } +} From 6058f30aff7abf1bc61461f7dc2f03aff1004cce Mon Sep 17 00:00:00 2001 From: Dave Searle Date: Thu, 28 Sep 2023 22:29:45 +0100 Subject: [PATCH 6/6] [C#] Do not wait for plan to finish before returning in ToRecordBatchReader --- csharp/src/Apache.Arrow.Acero/Declaration.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/csharp/src/Apache.Arrow.Acero/Declaration.cs b/csharp/src/Apache.Arrow.Acero/Declaration.cs index c5773eb9954a..d0fc77ada9c2 100644 --- a/csharp/src/Apache.Arrow.Acero/Declaration.cs +++ b/csharp/src/Apache.Arrow.Acero/Declaration.cs @@ -84,7 +84,6 @@ public static async Task ToRecordBatchReader(Declaration decl await plan.Init(); plan.StartProducing(); - plan.Wait(); return sinkNodeOptions.GetRecordBatchReader(); }