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

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


The following commit(s) were added to refs/heads/main by this push:
     new 8900f03e feat(arrow/compute): add starts_with kernel (#1448)
8900f03e is described below

commit 8900f03ed05ef3635597410854e61145175d2e7c
Author: Harrison Crosse <[email protected]>
AuthorDate: Wed Nov 4 15:03:29 2026 -0500

    feat(arrow/compute): add starts_with kernel (#1448)
    
    ### Rationale for this change
    
    Executing a Substrait expression that calls `functions_string`
    `starts_with` fails with `not implemented: starts_with`, because
    `arrow/compute` has no such function. I added a `starts_with` function
    and mapped the Substrait call to it.
    
    iceberg-go translates prefix row filters to this call, so they fail at
    read time (https://github.com/apache/iceberg-go/issues/2416). With this
    change, those filters returned the expected rows when I ran iceberg-go
    against it locally.
    
    ### What changes are included in this PR?
    
    `starts_with` accepts `binary`, `large_binary`, `string` and
    `large_string`. Dictionary inputs are decoded and extension inputs use
    their storage type. Null inputs produce null. An empty pattern matches
    every non-null value.
    
    Substrait calls require a non-null literal pattern and accept only
    `CASE_SENSITIVE`, which is also the default. `ExprBuilder.CallScalar`
    and `NewScalarCall` can build a `starts_with` call by name.
    
    I left out:
    
    - View types. View arrays carry a variable number of data buffers, but
    `ArraySpan` holds at most three, and the `scalar` package has no view
    scalars.
    - `IgnoreCase`. Arrow C++ implements it with RE2, which folds case as
    UTF-8 for strings and as Latin-1 for binary. Matching that needs its own
    change.
    
    ### Are these changes tested?
    
    Yes. I added two tests and a serialization case.
    
    - `TestStartsWith` covers the four input types as arrays and scalars,
    nulls, empty inputs and patterns, non-UTF-8 binary, slices, chunks,
    dictionaries and invalid options.
    - `TestStartsWithExpr` runs Substrait calls on `large_string` and
    `varchar` columns. It checks that a non-literal pattern, a null pattern
    and `CASE_INSENSITIVE` return `arrow.ErrNotImplemented`.
    - `TestExpressionSerializationRoundTrip` gains a `starts_with` case.
    
    On Linux amd64, `go test -count=1 ./arrow/compute/...` passed, along
    with `gofmt`, `go vet` on the three changed packages, `go build
    ./arrow/compute/...` and `golangci-lint` on `arrow/compute/...`. The
    `prek` hooks, including the Release Audit Tool, also passed.
    
    I did not run `noasm`, arm64 or 32-bit builds.
    
    ### Are there any user-facing changes?
    
    Yes. `arrow/compute` adds `StartsWith`, `MatchSubstringOptions` and
    `RegisterScalarString`, and the default registry includes `starts_with`.
    `arrow/compute/exprs` adds `SubstraitStringFuncsURI` and maps Substrait
    `starts_with` in both directions. Setting `IgnoreCase` returns
    `arrow.ErrNotImplemented`. Existing functions are unchanged.
    
    Part of https://github.com/apache/arrow-go/issues/1329.
---
 arrow/compute/doc.go                            |   7 +-
 arrow/compute/expression.go                     |   1 +
 arrow/compute/expression_test.go                |   2 +
 arrow/compute/exprs/exec_test.go                |  63 +++++++++
 arrow/compute/exprs/types.go                    |  64 +++++++++
 arrow/compute/internal/kernels/scalar_string.go |  78 +++++++++++
 arrow/compute/registry.go                       |   1 +
 arrow/compute/scalar_string.go                  |  73 +++++++++++
 arrow/compute/scalar_string_test.go             | 165 ++++++++++++++++++++++++
 9 files changed, 451 insertions(+), 3 deletions(-)

diff --git a/arrow/compute/doc.go b/arrow/compute/doc.go
index ea0e3e0e..8271c311 100644
--- a/arrow/compute/doc.go
+++ b/arrow/compute/doc.go
@@ -27,9 +27,10 @@
 //
 // The function registry holds scalar functions (element-wise arithmetic,
 // comparisons, boolean logic, bit-wise operations, rounding, set lookup with
-// is_in, list_element and the null checks), vector functions (array_filter,
-// array_take, unique, dictionary_encode, cumulative_sum and the run-end
-// encode/decode functions) and the meta functions cast, filter, take, sort
+// is_in, prefix matching with starts_with, list_element and the null
+// checks), vector functions (array_filter, array_take, unique,
+// dictionary_encode, cumulative_sum and the run-end encode/decode
+// functions) and the meta functions cast, filter, take, sort
 // and sort_indices that dispatch to them. It also holds the scalar aggregate
 // functions count and sum, which fold a whole array into a single value
 // through the Init, Consume, Merge and Finalize lifecycle of an
diff --git a/arrow/compute/expression.go b/arrow/compute/expression.go
index 7a808280..0a7982f1 100644
--- a/arrow/compute/expression.go
+++ b/arrow/compute/expression.go
@@ -581,6 +581,7 @@ var (
                DictionaryEncodeOptions{},
                CumulativeOptions{},
                ScalarAggregateOptions{}, CountOptions{},
+               MatchSubstringOptions{},
        }
 )
 
diff --git a/arrow/compute/expression_test.go b/arrow/compute/expression_test.go
index f138e99c..e2b4a8b4 100644
--- a/arrow/compute/expression_test.go
+++ b/arrow/compute/expression_test.go
@@ -394,6 +394,8 @@ func TestExpressionSerializationRoundTrip(t *testing.T) {
                {"is_in cast", compute.NewCall("is_in", []compute.Expression{
                        compute.NewCall("cast", 
[]compute.Expression{compute.NewFieldRef("version")}, 
compute.NewCastOptions(arrow.PrimitiveTypes.Float64, true))},
                        &compute.SetLookupOptions{ValueSet: fltvalueset})},
+               {"starts_with", compute.NewCall("starts_with", 
[]compute.Expression{compute.NewFieldRef("name")},
+                       &compute.MatchSubstringOptions{Pattern: "ab", 
IgnoreCase: true})},
                {"is null", compute.IsNull(compute.NewFieldRef("validity"), 
true)},
                {"is valid", compute.IsValid(compute.NewFieldRef("validity"))},
                {"lots and", compute.And(
diff --git a/arrow/compute/exprs/exec_test.go b/arrow/compute/exprs/exec_test.go
index 4c986c9d..3711bb64 100644
--- a/arrow/compute/exprs/exec_test.go
+++ b/arrow/compute/exprs/exec_test.go
@@ -841,3 +841,66 @@ func TestDecimalFilterLarge(t *testing.T) {
                })
        }
 }
+
+func TestStartsWithExpr(t *testing.T) {
+       varchar, _, err := exprs.FromSubstraitType(&types.VarCharType{Length: 
-1}, extSet)
+       require.NoError(t, err)
+       sc := arrow.NewSchema([]arrow.Field{
+               {Name: "s", Type: arrow.BinaryTypes.LargeString, Nullable: 
true},
+               {Name: "v", Type: varchar, Nullable: true},
+       }, nil)
+
+       bldr := exprs.NewExprBuilder(extSet)
+       require.NoError(t, bldr.SetInputSchema(sc))
+       ab := bldr.Literal(expr.NewPrimitiveLiteral("ab", false))
+       caseInsensitive := []*types.FunctionOption{{Name: "case_sensitivity", 
Preference: []string{"CASE_INSENSITIVE"}}}
+
+       tests := []struct {
+               name     string
+               ex       exprs.Builder
+               expected string
+       }{
+               {"large_string", bldr.MustCallScalar("starts_with", nil, 
bldr.FieldRef("s"), ab), `[true, null, false, false]`},
+               {"varchar", bldr.MustCallScalar("starts_with", nil, 
bldr.FieldRef("v"),
+                       bldr.WrapLiteral(expr.NewLiteral(&types.VarChar{Value: 
"ab", Length: 2}, false))),
+                       `[true, false, null, true]`},
+               {"non-literal pattern", bldr.MustCallScalar("starts_with", nil, 
bldr.FieldRef("s"),
+                       bldr.Must(bldr.Cast(ab, arrow.BinaryTypes.String))), 
""},
+               {"null pattern", bldr.MustCallScalar("starts_with", nil, 
bldr.FieldRef("s"),
+                       
bldr.Literal(expr.NewNullLiteral(&types.StringType{}))), ""},
+               {"case insensitive", bldr.MustCallScalar("starts_with", 
caseInsensitive, bldr.FieldRef("s"), ab), ""},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.DefaultAllocator)
+                       defer mem.AssertSize(t, 0)
+                       ctx := 
exprs.WithExtensionIDSet(compute.WithAllocator(context.Background(), mem), 
extSet)
+
+                       ex, err := tt.ex.BuildExpr()
+                       require.NoError(t, err)
+
+                       rec, _, err := array.RecordFromJSON(mem, sc, 
strings.NewReader(`[
+                               {"s": "abc", "v": "ab"},
+                               {"s": null, "v": "b"},
+                               {"s": "xab", "v": null},
+                               {"s": "a", "v": "abab"}
+                       ]`))
+                       require.NoError(t, err)
+                       defer rec.Release()
+
+                       result, err := exprs.ExecuteScalarExpression(ctx, sc, 
ex, compute.NewDatumWithoutOwning(rec))
+                       if tt.expected == "" {
+                               assert.ErrorIs(t, err, arrow.ErrNotImplemented)
+                               return
+                       }
+                       require.NoError(t, err)
+                       defer result.Release()
+
+                       expected, _, err := array.FromJSON(mem, 
arrow.FixedWidthTypes.Boolean, strings.NewReader(tt.expected))
+                       require.NoError(t, err)
+                       defer expected.Release()
+                       assertEqual(t, expected, result)
+               })
+       }
+}
diff --git a/arrow/compute/exprs/types.go b/arrow/compute/exprs/types.go
index a9a5ec79..ecfa4a58 100644
--- a/arrow/compute/exprs/types.go
+++ b/arrow/compute/exprs/types.go
@@ -42,6 +42,7 @@ const (
        // URN for official Substrait Comparison funcs extensions
        SubstraitComparisonFuncsURI = SubstraitDefaultURIPrefix + 
"functions_comparison"
        SubstraitBooleanFuncsURI    = SubstraitDefaultURIPrefix + 
"functions_boolean"
+       SubstraitStringFuncsURI     = SubstraitDefaultURIPrefix + 
"functions_string"
 
        SubstraitIcebergSetFuncURN = "extension:apache.iceberg:functions_set"
        TimestampTzTimezone        = "UTC"
@@ -139,6 +140,19 @@ func init() {
                        panic(err)
                }
        }
+
+       err := DefaultExtensionIDRegistry.AddSubstraitScalarToArrow(
+               extensions.ID{URN: SubstraitStringFuncsURI, Name: 
"starts_with"},
+               startsWithSubstraitToArrowFunc)
+       if err != nil {
+               panic(err)
+       }
+
+       err = DefaultExtensionIDRegistry.AddArrowToSubstrait("starts_with",
+               simpleMapArrowToSubstraitFunc(SubstraitStringFuncsURI))
+       if err != nil {
+               panic(err)
+       }
 }
 
 type overflowBehavior string
@@ -169,6 +183,22 @@ var overflowParser = enumParser[overflowBehavior]{
        },
 }
 
+type caseSensitivity string
+
+const (
+       caseSensitive        caseSensitivity = "CASE_SENSITIVE"
+       caseInsensitive      caseSensitivity = "CASE_INSENSITIVE"
+       caseInsensitiveASCII caseSensitivity = "CASE_INSENSITIVE_ASCII"
+)
+
+var caseSensitivityParser = enumParser[caseSensitivity]{
+       values: map[caseSensitivity]struct{}{
+               caseSensitive:        {},
+               caseInsensitive:      {},
+               caseInsensitiveASCII: {},
+       },
+}
+
 func parseOption[typ ~string](sf *expr.ScalarFunction, optionName string, 
parser *enumParser[typ], implemented []typ, def typ) (typ, error) {
        opts := sf.GetOption(optionName)
        if len(opts) == 0 {
@@ -234,6 +264,40 @@ func setLookupFuncSubstraitToArrowFunc(sf 
*expr.ScalarFunction, input []compute.
        return
 }
 
+// startsWithSubstraitToArrowFunc supports only CASE_SENSITIVE.
+// A case_sensitivity preference list without CASE_SENSITIVE returns an
+// error wrapping arrow.ErrNotImplemented. Arrow C++ maps
+// CASE_INSENSITIVE to ignore_case=true.
+func startsWithSubstraitToArrowFunc(sf *expr.ScalarFunction, input 
[]compute.Datum) (fname string, args []compute.Datum, opts 
compute.FunctionOptions, err error) {
+       if len(input) != 2 {
+               return "", nil, nil, fmt.Errorf("%w: starts_with expects 2 
arguments, got %d",
+                       arrow.ErrNotImplemented, len(input))
+       }
+
+       if _, err := parseOption(sf, "case_sensitivity", &caseSensitivityParser,
+               []caseSensitivity{caseSensitive}, caseSensitive); err != nil {
+               return "", nil, nil, fmt.Errorf("%w: starts_with 
case_sensitivity %v", err, sf.GetOption("case_sensitivity"))
+       }
+
+       if _, ok := sf.Arg(1).(expr.Literal); !ok {
+               return "", nil, nil, fmt.Errorf("%w: starts_with pattern must 
be a literal", arrow.ErrNotImplemented)
+       }
+
+       sc := input[1].(*compute.ScalarDatum).Value
+       if !sc.IsValid() {
+               return "", nil, nil, fmt.Errorf("%w: starts_with pattern must 
not be null", arrow.ErrNotImplemented)
+       }
+       if ext, ok := sc.(*scalar.Extension); ok {
+               sc = ext.Value
+       }
+       pattern, ok := sc.(scalar.BinaryScalar)
+       if !ok {
+               return "", nil, nil, fmt.Errorf("%w: starts_with pattern of 
type %s", arrow.ErrNotImplemented, sc.DataType())
+       }
+
+       return "starts_with", input[:1], 
&compute.MatchSubstringOptions{Pattern: string(pattern.Data())}, nil
+}
+
 func simpleMapSubstraitToArrowFunc(sf *expr.ScalarFunction, input 
[]compute.Datum) (fname string, args []compute.Datum, opts 
compute.FunctionOptions, err error) {
        args = input
 
diff --git a/arrow/compute/internal/kernels/scalar_string.go 
b/arrow/compute/internal/kernels/scalar_string.go
new file mode 100644
index 00000000..9ac96bcd
--- /dev/null
+++ b/arrow/compute/internal/kernels/scalar_string.go
@@ -0,0 +1,78 @@
+// 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.
+
+package kernels
+
+import (
+       "bytes"
+       "fmt"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/compute/exec"
+)
+
+// MatchSubstringOptions controls the substring matching functions such as
+// starts_with, which match Pattern as a literal byte sequence.
+type MatchSubstringOptions struct {
+       Pattern    string `compute:"pattern"`
+       IgnoreCase bool   `compute:"ignore_case"`
+}
+
+func (MatchSubstringOptions) TypeName() string { return 
"MatchSubstringOptions" }
+
+type matchSubstringState struct {
+       pattern []byte
+}
+
+func initMatchSubstring(_ *exec.KernelCtx, args exec.KernelInitArgs) 
(exec.KernelState, error) {
+       opts, ok := args.Options.(MatchSubstringOptions)
+       if p, isPtr := args.Options.(*MatchSubstringOptions); isPtr && p != nil 
{
+               opts, ok = *p, true
+       }
+       if !ok {
+               return nil, fmt.Errorf("%w: attempted to initialize kernel 
state from invalid function options",
+                       arrow.ErrInvalid)
+       }
+
+       if opts.IgnoreCase {
+               return nil, fmt.Errorf("%w: case-insensitive substring 
matching", arrow.ErrNotImplemented)
+       }
+       return matchSubstringState{pattern: []byte(opts.Pattern)}, nil
+}
+
+func startsWith(ctx *exec.KernelCtx, v []byte, _ *error) bool {
+       return bytes.HasPrefix(v, ctx.State.(matchSubstringState).pattern)
+}
+
+// GetStartsWithKernels returns the kernels for the starts_with function
+// over the base binary and string types.
+func GetStartsWithKernels() []exec.ScalarKernel {
+       out := exec.NewOutputType(arrow.FixedWidthTypes.Boolean)
+       kernels := make([]exec.ScalarKernel, 0, len(baseBinaryTypes))
+       for _, ty := range baseBinaryTypes {
+               var ex exec.ArrayKernelExec
+               if arrow.IsLargeBinaryLike(ty.ID()) {
+                       ex = ScalarUnaryNotNullBinaryArgBoolOut[int64](false, 
startsWith)
+               } else {
+                       ex = ScalarUnaryNotNullBinaryArgBoolOut[int32](false, 
startsWith)
+               }
+               k := 
exec.NewScalarKernel([]exec.InputType{exec.NewExactInput(ty)}, out, ex, 
initMatchSubstring)
+               k.NullHandling = exec.NullIntersection
+               k.MemAlloc = exec.MemPrealloc
+               kernels = append(kernels, k)
+       }
+       return kernels
+}
diff --git a/arrow/compute/registry.go b/arrow/compute/registry.go
index 03d4df81..6b80337d 100644
--- a/arrow/compute/registry.go
+++ b/arrow/compute/registry.go
@@ -58,6 +58,7 @@ func GetFunctionRegistry() FunctionRegistry {
                RegisterVectorCumulative(registry)
                RegisterVectorRunEndFuncs(registry)
                RegisterScalarSetLookup(registry)
+               RegisterScalarString(registry)
                RegisterScalarAggregates(registry)
        })
        return registry
diff --git a/arrow/compute/scalar_string.go b/arrow/compute/scalar_string.go
new file mode 100644
index 00000000..4eca046a
--- /dev/null
+++ b/arrow/compute/scalar_string.go
@@ -0,0 +1,73 @@
+// 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.
+
+package compute
+
+import (
+       "context"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/compute/exec"
+       "github.com/apache/arrow-go/v18/arrow/compute/internal/kernels"
+)
+
+// MatchSubstringOptions controls the substring matching functions such as
+// starts_with, which match Pattern as a literal byte sequence. Setting
+// IgnoreCase makes them return arrow.ErrNotImplemented.
+type MatchSubstringOptions = kernels.MatchSubstringOptions
+
+var startsWithDoc = FunctionDoc{
+       Summary: "Check if strings start with a literal pattern",
+       Description: "For each string in \"strings\", emit true iff it starts 
with a\n" +
+               "given pattern. The pattern must be given in 
MatchSubstringOptions.\n" +
+               "Null inputs emit null. Dictionary inputs are decoded to their 
value\n" +
+               "type, and extension inputs use their storage type.",
+       ArgNames:        []string{"strings"},
+       OptionsType:     "MatchSubstringOptions",
+       OptionsRequired: true,
+}
+
+type matchSubstringFunc struct {
+       ScalarFunction
+}
+
+func (fn *matchSubstringFunc) Execute(ctx context.Context, opts 
FunctionOptions, args ...Datum) (Datum, error) {
+       return execInternal(ctx, fn, opts, -1, args...)
+}
+
+func (fn *matchSubstringFunc) DispatchBest(vals ...arrow.DataType) 
(exec.Kernel, error) {
+       ensureDictionaryDecoded(vals...)
+       ensureNoExtensionType(vals...)
+       return fn.DispatchExact(vals...)
+}
+
+// RegisterScalarString registers the starts_with function.
+func RegisterScalarString(reg FunctionRegistry) {
+       fn := &matchSubstringFunc{*NewScalarFunction("starts_with", Unary(), 
startsWithDoc)}
+       for _, k := range kernels.GetStartsWithKernels() {
+               if err := fn.AddKernel(k); err != nil {
+                       panic(err)
+               }
+       }
+       reg.AddFunction(fn, false)
+}
+
+// StartsWith returns, for each value in input, whether it starts with
+// opts.Pattern. Null values produce null. Dictionary inputs are decoded
+// to their value type, and extension inputs use their storage type.
+func StartsWith(ctx context.Context, opts MatchSubstringOptions, input Datum) 
(Datum, error) {
+       return CallFunction(ctx, "starts_with", &opts, input)
+}
diff --git a/arrow/compute/scalar_string_test.go 
b/arrow/compute/scalar_string_test.go
new file mode 100644
index 00000000..744844d7
--- /dev/null
+++ b/arrow/compute/scalar_string_test.go
@@ -0,0 +1,165 @@
+// 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.
+
+package compute_test
+
+import (
+       "context"
+       "strings"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/compute"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func checkStartsWith(t *testing.T, ctx context.Context, pattern string, input, 
expected compute.Datum) {
+       t.Helper()
+       got, err := compute.StartsWith(ctx, 
compute.MatchSubstringOptions{Pattern: pattern}, input)
+       require.NoError(t, err)
+       defer got.Release()
+       assertDatumsEqual(t, expected, got, nil, nil)
+}
+
+func TestStartsWith(t *testing.T) {
+       newCtx := func(t *testing.T) (context.Context, memory.Allocator) {
+               mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+               t.Cleanup(func() { mem.AssertSize(t, 0) })
+               return compute.WithAllocator(context.Background(), mem), mem
+       }
+       fromJSON := func(t *testing.T, mem memory.Allocator, dt arrow.DataType, 
json string) arrow.Array {
+               arr, _, err := array.FromJSON(mem, dt, strings.NewReader(json))
+               require.NoError(t, err)
+               return arr
+       }
+
+       tests := []struct {
+               name, pattern, input, expected string
+       }{
+               {"mixed", "ab", `["", "a", "ab", "abc", "ba", "xabc", null]`, 
`[false, false, true, true, false, false, null]`},
+               {"empty pattern", "", `["", "a", null]`, `[true, true, null]`},
+               {"all null", "ab", `[null, null]`, `[null, null]`},
+               {"empty", "ab", `[]`, `[]`},
+       }
+
+       for _, dt := range []arrow.DataType{
+               arrow.BinaryTypes.Binary, arrow.BinaryTypes.LargeBinary,
+               arrow.BinaryTypes.String, arrow.BinaryTypes.LargeString,
+       } {
+               for _, tt := range tests {
+                       t.Run(dt.String()+"/"+tt.name, func(t *testing.T) {
+                               ctx, mem := newCtx(t)
+
+                               strs := fromJSON(t, mem, 
arrow.BinaryTypes.String, tt.input)
+                               defer strs.Release()
+                               input, err := compute.CastArray(ctx, strs, 
compute.SafeCastOptions(dt))
+                               require.NoError(t, err)
+                               defer input.Release()
+                               expected := fromJSON(t, mem, 
arrow.FixedWidthTypes.Boolean, tt.expected)
+                               defer expected.Release()
+
+                               checkScalarUnary(t, "starts_with", 
compute.NewDatumWithoutOwning(input),
+                                       
compute.NewDatumWithoutOwning(expected), 
&compute.MatchSubstringOptions{Pattern: tt.pattern})
+                       })
+               }
+       }
+
+       t.Run("non-utf8 binary", func(t *testing.T) {
+               ctx, mem := newCtx(t)
+               input := fromJSON(t, mem, arrow.BinaryTypes.Binary, `["//5h", 
"/w==", "Yf8=", ""]`)
+               defer input.Release()
+               expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, true, false, false]`)
+               defer expected.Release()
+
+               checkStartsWith(t, ctx, "\xff", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+       })
+
+       t.Run("sliced", func(t *testing.T) {
+               ctx, mem := newCtx(t)
+               full := fromJSON(t, mem, arrow.BinaryTypes.String,
+                       `["ab", null, "x", "abc", null, "ab", "b", "abd", "a", 
"ab"]`)
+               defer full.Release()
+               input := array.NewSlice(full, 3, 9)
+               defer input.Release()
+               expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, null, true, false, true, false]`)
+               defer expected.Release()
+
+               checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+       })
+
+       t.Run("chunked", func(t *testing.T) {
+               ctx, mem := newCtx(t)
+               var chunks []arrow.Array
+               for _, json := range []string{`["ab", null]`, `[]`, `["xab", 
"abc"]`} {
+                       c := fromJSON(t, mem, arrow.BinaryTypes.String, json)
+                       defer c.Release()
+                       chunks = append(chunks, c)
+               }
+               input := arrow.NewChunked(arrow.BinaryTypes.String, chunks)
+               defer input.Release()
+               want := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, `[true, 
null, false, true]`)
+               defer want.Release()
+               expected := arrow.NewChunked(arrow.FixedWidthTypes.Boolean, 
[]arrow.Array{want})
+               defer expected.Release()
+
+               checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+       })
+
+       t.Run("dictionary", func(t *testing.T) {
+               ctx, mem := newCtx(t)
+               dict := fromJSON(t, mem, arrow.BinaryTypes.String, `["ab", 
null, "xab"]`)
+               defer dict.Release()
+               indices := fromJSON(t, mem, arrow.PrimitiveTypes.Int8, `[0, 1, 
2, null, 0]`)
+               defer indices.Release()
+               input := array.NewDictionaryArray(&arrow.DictionaryType{
+                       IndexType: arrow.PrimitiveTypes.Int8, ValueType: 
arrow.BinaryTypes.String}, indices, dict)
+               defer input.Release()
+               expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, null, false, null, true]`)
+               defer expected.Release()
+
+               checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+       })
+
+       t.Run("options", func(t *testing.T) {
+               fn, ok := 
compute.GetFunctionRegistry().GetFunction("starts_with")
+               require.True(t, ok)
+               assert.NoError(t, fn.Validate())
+
+               ctx, mem := newCtx(t)
+               arr := fromJSON(t, mem, arrow.BinaryTypes.String, `["ab", "b"]`)
+               defer arr.Release()
+               input := compute.NewDatumWithoutOwning(arr)
+               expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, false]`)
+               defer expected.Release()
+
+               got, err := compute.CallFunction(ctx, "starts_with", 
compute.MatchSubstringOptions{Pattern: "a"}, input)
+               require.NoError(t, err)
+               defer got.Release()
+               assertDatumsEqual(t, compute.NewDatumWithoutOwning(expected), 
got, nil, nil)
+
+               _, err = compute.CallFunction(ctx, "starts_with", nil, input)
+               assert.ErrorIs(t, err, arrow.ErrInvalid)
+               _, err = compute.CallFunction(ctx, "starts_with", 
(*compute.MatchSubstringOptions)(nil), input)
+               assert.ErrorIs(t, err, arrow.ErrInvalid)
+               _, err = compute.CallFunction(ctx, "starts_with", 
&compute.ArithmeticOptions{}, input)
+               assert.ErrorIs(t, err, arrow.ErrInvalid)
+               _, err = compute.StartsWith(ctx, 
compute.MatchSubstringOptions{Pattern: "a", IgnoreCase: true}, input)
+               assert.ErrorIs(t, err, arrow.ErrNotImplemented)
+       })
+}

Reply via email to