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..eb7b24fe0869 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Apache.Arrow.Acero.csproj @@ -0,0 +1,16 @@ + + + + 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..3c245b4fbaf6 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/CLib.cs @@ -0,0 +1,72 @@ +// 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 +{ + namespace 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 { } + [StructLayout(LayoutKind.Sequential)] + public struct GArrowExecuteNodeOptions + { + IntPtr debug_opts; + } + 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 struct GArrowProjectNodeOptions { } + public struct GArrowInt32Scalar { } + public struct GList {} + + 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 + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/Declaration.cs b/csharp/src/Apache.Arrow.Acero/Declaration.cs new file mode 100644 index 000000000000..d0fc77ada9c2 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Declaration.cs @@ -0,0 +1,108 @@ +// 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.Linq; +using System.Threading.Tasks; +using Apache.Arrow.Ipc; + +namespace Apache.Arrow.Acero +{ + 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, ExecNodeFactoryRegistry registry = null) + { + _factoryName = factoryName; + _options = options; + _registry = registry ?? new DefaultExecNodeFactoryRegistry(); + + 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 Task ToRecordBatchReader(Schema schema) + { + return ToRecordBatchReader(this, schema); + } + + public static async Task ToRecordBatchReader(Declaration declaration, Schema schema) + { + var sinkNodeOptions = new SinkNodeOptions(schema); + var plan = new ExecPlan(); + + Declaration sinkNode = FromSequence( + new List + { + declaration, + new Declaration("sink", sinkNodeOptions) + }); + + sinkNode.AddToPlan(plan); + + if (!plan.Validate()) + throw new InvalidOperationException("Plan is not valid"); + + await plan.Init(); + + plan.StartProducing(); + + return sinkNodeOptions.GetRecordBatchReader(); + } + + private ExecNode AddToPlan(ExecPlan plan) + { + var inputNodes = new List(); + + foreach (Declaration input in Inputs) + { + ExecNode inputNode = input.AddToPlan(plan); + inputNodes.Add(inputNode); + } + + ExecNode node = _registry.MakeNode(_factoryName, plan, _options, inputNodes); + + plan.AddNode(node); + + 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 new file mode 100644 index 000000000000..a05159c5768e --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExceptionUtil.cs @@ -0,0 +1,29 @@ +// 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 +{ + 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 new file mode 100644 index 000000000000..92c00985834a --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExecNode.cs @@ -0,0 +1,51 @@ +// 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 System.Threading.Tasks; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + 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 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/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..f78bb5f8caee --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ExecPlan.cs @@ -0,0 +1,111 @@ +// 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 System.Runtime.InteropServices; +using System.Threading.Tasks; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class ExecPlan + { + [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 { get; } + + public List Nodes { get; internal set; } = new(); + + public unsafe ExecPlan() + { + Handle = garrow_execute_plan_new(out GError** error); + + ExceptionUtil.ThrowOnError(error); + } + + public unsafe bool Validate() + { + 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(Handle); + } + + public unsafe void Wait() + { + 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/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 new file mode 100644 index 000000000000..cd679786f4c4 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Expression.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; +using System.Runtime.InteropServices; + +namespace Apache.Arrow.Acero +{ + public abstract class Expression + { + [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 IntPtr Handle { get; protected set; } + + public override unsafe string ToString() + { + IntPtr strPtr = garrow_expression_to_string(Handle); + + return GLib.Marshaller.PtrToStringGFree(strPtr); + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/FieldExpression.cs b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs new file mode 100644 index 000000000000..19630b56fbbc --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FieldExpression.cs @@ -0,0 +1,44 @@ +// 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; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class FieldExpression : Expression + { + 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 unsafe FieldExpression(string reference) + { + _referencePtr = GLib.Marshaller.StringToPtrGStrdup(reference); + + Handle = garrow_field_expression_new(_referencePtr, out GError** error); + + ExceptionUtil.ThrowOnError(error); + } + + ~FieldExpression() + { + GLib.Marshaller.Free(_referencePtr); + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/FilterNode.cs b/csharp/src/Apache.Arrow.Acero/FilterNode.cs new file mode 100644 index 000000000000..b2cbae1be820 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FilterNode.cs @@ -0,0 +1,38 @@ +// 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 System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class FilterNode : ExecNode + { + [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 unsafe FilterNode(FilterNodeOptions options, ExecPlan plan, List nodes) + : base(plan, nodes) + { + 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 new file mode 100644 index 000000000000..7c90ec29b20c --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FilterNodeOptions.cs @@ -0,0 +1,35 @@ +// 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; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class FilterNodeOptions : ExecNodeOptions + { + [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 { get; } + + public unsafe FilterNodeOptions(Expression expr) + { + 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 new file mode 100644 index 000000000000..4f2076e5cfa8 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/FuncLoader.cs @@ -0,0 +1,119 @@ +// 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 +{ + 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()) + { + 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) + 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 new file mode 100644 index 000000000000..4f75a2763d7f --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/Function.cs @@ -0,0 +1,62 @@ +// 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; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class Function : Expression + { + 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 unsafe Function(string functionName, Expression lhs, Expression rhs) + : this(functionName, new[] { lhs, rhs }) + { + } + + public unsafe Function(string functionName, params Expression[] args) + { + _functionNamePtr = GLib.Marshaller.StringToPtrGStrdup(functionName); + _functionArgs = new GLib.List(IntPtr.Zero); + + foreach (Expression arg in args) + _functionArgs.Append(arg.Handle); + + Handle = (IntPtr)garrow_call_expression_new(_functionNamePtr, _functionArgs.Handle, null); + } + + ~Function() + { + GLib.Marshaller.Free(_functionNamePtr); + } + } + + 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..bbaaa75fbdd6 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNode.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.Collections.Generic; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class HashJoinNode : ExecNode + { + [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 unsafe HashJoinNode(HashJoinNodeOptions options, ExecPlan plan, List inputs) + : base(plan, inputs) + { + ExecNode left = inputs[0]; + ExecNode right = inputs[1]; + + 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 new file mode 100644 index 000000000000..8ce3cdf93182 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/HashJoinNodeOptions.cs @@ -0,0 +1,49 @@ +// 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 System; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class HashJoinNodeOptions : ExecNodeOptions + { + 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"); + + public unsafe GArrowHashJoinNodeOptions* Handle { get; } + + public unsafe HashJoinNodeOptions(GArrowJoinType joinType, string[] leftKeys, string[] rightKeys) + { + _leftKeysPtr = GLib.Marshaller.StringArrayToStrvPtr(leftKeys); + _rightKeysPtr = GLib.Marshaller.StringArrayToStrvPtr(leftKeys); + + Handle = garrow_hash_join_node_options_new(joinType, _leftKeysPtr, (uint)leftKeys.Length, _rightKeysPtr, (uint)rightKeys.Length, out GError** error); + + ExceptionUtil.ThrowOnError(error); + } + + ~HashJoinNodeOptions() + { + 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 new file mode 100644 index 000000000000..cd593f477376 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/LiteralExpression.cs @@ -0,0 +1,62 @@ +// 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; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class LiteralExpression : Expression + { + [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 LiteralExpression(string literal) + { + 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); + + Handle = (IntPtr)garrow_literal_expression_new((GArrowDatum*)datumPtr); + } + + public unsafe LiteralExpression(int literal) + { + GArrowInt32Scalar* scalarPtr = garrow_int32_scalar_new(literal); + GArrowScalarDatum* datumPtr = garrow_scalar_datum_new((IntPtr)scalarPtr); + + 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 new file mode 100644 index 000000000000..8f8a05f87930 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/ProjectNode.cs @@ -0,0 +1,38 @@ +// 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 System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class ProjectNode : ExecNode + { + [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 unsafe ProjectNode(ProjectNodeOptions options, ExecPlan plan, List inputs) + : base(plan, inputs) + { + 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 new file mode 100644 index 000000000000..b8e47df4af34 --- /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 System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class ProjectNodeOptions : ExecNodeOptions + { + [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"); + + public unsafe GArrowProjectNodeOptions* Handle { get; } + + public unsafe ProjectNodeOptions(List expressions, List names) + { + var list = new GLib.List(IntPtr.Zero); + + foreach (Expression expression in expressions) + list.Append(expression.Handle); + + IntPtr namesPtr = GLib.Marshaller.StringArrayToStrvPtr(names.ToArray()); + + 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 new file mode 100644 index 000000000000..4941af094dbb --- /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. + +using System.Collections.Generic; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class RecordBatchReaderSourceNode : SourceNode + { + public unsafe RecordBatchReaderSourceNode(RecordBatchReaderSourceNodeOptions options, ExecPlan plan) : base(plan, new List()) + { + 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 new file mode 100644 index 000000000000..d1ef49d3852b --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchReaderSourceNodeOptions.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.Ipc; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class RecordBatchReaderSourceNodeOptions : ExecNodeOptions + { + 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 { get; } + + public unsafe RecordBatchReaderSourceNodeOptions(IArrowArrayStream recordBatchReader) + { + _exportedRecordBatchReader = new ExportedRecordBatchReader(recordBatchReader); + + 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 new file mode 100644 index 000000000000..31c1b108276b --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNode.cs @@ -0,0 +1,42 @@ +// 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 System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + 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 + { + public unsafe RecordBatchSourceNode(RecordBatchSourceNodeOptions options, ExecPlan plan) : base(plan, new List()) + { + 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 new file mode 100644 index 000000000000..c6bd2ced5f4f --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/RecordBatchSourceNodeOptions.cs @@ -0,0 +1,38 @@ +// 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; + +namespace Apache.Arrow.Acero +{ + public class RecordBatchSourceNodeOptions : ExecNodeOptions + { + 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 { get; } + + public unsafe RecordBatchSourceNodeOptions(RecordBatch recordBatch) + { + _exportedRecordBatch = new ExportedRecordBatch(recordBatch); + + 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 new file mode 100644 index 000000000000..287fc4cacace --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/SinkNode.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; +using System.Runtime.InteropServices; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class SinkNode : ExecNode + { + [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 unsafe SinkNode(SinkNodeOptions _options, ExecPlan plan, List inputs) : base(plan, inputs) + { + 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 new file mode 100644 index 000000000000..47f2f59af867 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/SinkNodeOptions.cs @@ -0,0 +1,60 @@ +// 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.C; +using Apache.Arrow.Ipc; +using Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class SinkNodeOptions : ExecNodeOptions + { + private readonly ExportedSchema _exportedSchema; + + [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 { get; } + + public unsafe SinkNodeOptions(Schema schema) + { + _exportedSchema = new ExportedSchema(schema); + + Handle = garrow_sink_node_options_new(); + } + + public unsafe IArrowArrayStream GetRecordBatchReader() + { + 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); + + IArrowArrayStream arrayStream = CArrowArrayStreamImporter.ImportArrayStream(arrayStreamPtr); + + return arrayStream; + } + } +} diff --git a/csharp/src/Apache.Arrow.Acero/UnionNode.cs b/csharp/src/Apache.Arrow.Acero/UnionNode.cs new file mode 100644 index 000000000000..7dcb41363c66 --- /dev/null +++ b/csharp/src/Apache.Arrow.Acero/UnionNode.cs @@ -0,0 +1,74 @@ +// 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 Apache.Arrow.Acero.CLib; + +namespace Apache.Arrow.Acero +{ + public class UnionNode : ExecNode, IDisposable + { + 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 unsafe UnionNode(ExecPlan plan, List inputs) : base(plan, inputs) + { + _factoryNamePtr = GLib.Marshaller.StringToPtrGStrdup("union"); + + ExecNode lhs = inputs[0]; + ExecNode rhs = inputs[1]; + + _inputs = new GLib.List(IntPtr.Zero); + _inputs.Append((IntPtr)lhs.Handle); + _inputs.Append((IntPtr)rhs.Handle); + + _optionsPtr = (GArrowExecuteNodeOptions*)Marshal.AllocHGlobal(sizeof(GArrowExecuteNodeOptions)); + *_optionsPtr = default; + + 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/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..75cc0927b3f4 --- /dev/null +++ b/csharp/test/Apache.Arrow.Acero.Tests/DeclarationTests.cs @@ -0,0 +1,311 @@ +// 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.Acero.CLib; +using Apache.Arrow.Ipc; +using Apache.Arrow.Types; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace Apache.Arrow.Acero.Tests +{ + public class DeclarationTests + { + private readonly ITestOutputHelper _output; + + public DeclarationTests(ITestOutputHelper output) + { + _output = output; + } + + [Fact] + public async Task TestRecordBatchSource() + { + // arrange + RecordBatch recordBatch = TestData.GetCustomersRecordBatch(); + + var recordBatchSource = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(recordBatch)); + + // act + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = await recordBatchSource.ToRecordBatchReader(schema); + + // assert + Table table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + customerId | firstName | lastName | + c1 | Luke | Skywalker | + c2 | Princess | Leia | + c3 | Obi-Wan | Kenobi | + """, 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 = table.PrettyPrint(columnPadding); + + _output.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())); + + 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 + IArrowArrayStream result = await 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 + Table table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + 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); + } + + [Fact] + public async Task TestSingleFilter() + { + // arrange + RecordBatch recordBatch = TestData.GetCustomersRecordBatch(); + + var recordBatchSource = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(recordBatch)); + + var orderBy = Declaration.FromSequence(new List { + recordBatchSource, + new Declaration("filter", new FilterNodeOptions( + new Equal(new FieldExpression("firstName"), new LiteralExpression("Luke")) + )) + }); + + // act + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = await orderBy.ToRecordBatchReader(schema); + + // assert + Table table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + customerId | firstName | lastName | + c1 | Luke | Skywalker | + """, rowCount: 1); + } + + [Fact] + public async Task TestMultiFilter() + { + // arrange + RecordBatch recordBatch = TestData.GetCustomersRecordBatch(); + + var recordBatchSource = new Declaration("record_batch_source", + new RecordBatchSourceNodeOptions(recordBatch)); + + 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 + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = await orderBy.ToRecordBatchReader(schema); + + // assert + Table table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + customerId | firstName | lastName | + c1 | Luke | Skywalker | + c3 | Obi-Wan | Kenobi | + """, rowCount: 2); + } + + [Fact] + public async Task TestUnion() + { + // arrange + 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 + Schema schema = TestData.GetCustomersSchema(); + IArrowArrayStream result = await union.ToRecordBatchReader(schema); + + // assert + Table 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); + } + + [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 + IArrowArrayStream result = await project.ToRecordBatchReader( + new Schema.Builder() + .Field(new Field("fullName", StringType.Default, true)) + .Build()); + + // assert + Table table = await ConvertStreamToTable(result); + + AssertTable(table, + """ + fullName | + Skywalker, Luke | + Leia, Princess | + Kenobi, Obi-Wan | + """, rowCount: 3, columnPadding: 15); + } + + private static async Task ConvertStreamToTable(IArrowArrayStream result) + { + Schema schema = null; + + var recordBatches = new List(); + + while (true) + { + RecordBatch recordBatch = await result.ReadNextRecordBatchAsync(); + if (recordBatch == null) break; + + if (schema == null) + schema = recordBatch.Schema; + + recordBatches.Add(recordBatch); + } + + return Table.TableFromRecordBatches(schema, recordBatches); + } + + public class TestResult + { + public string TableAsString { get; set; } + public int RowCount { 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'); + } + } +} 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); + } + } +}