diff --git a/book/src/super-sql/functions/strings/position.md b/book/src/super-sql/functions/strings/position.md index a8c2d213f..1b3b2ed4b 100644 --- a/book/src/super-sql/functions/strings/position.md +++ b/book/src/super-sql/functions/strings/position.md @@ -12,9 +12,14 @@ position(sub: string IN s:string) -> int64 ## Description The `position` function returns the 1-based index where string `sub` first -occurs in string `s`. If `sub` is not a sub-string of `s` then 0 is returned. +occurs in string `s`, counting Unicode code points as +[slices](../../expressions/slices.md) and [substring](substring.md) do. +If `sub` is not a sub-string of `s` then 0 is returned. The index is always 1-based, whatever the [index_base](../../declarations/pragmas.md) pragma is set to. +Subtract 1 to get a 0-based index, e.g., for a slice. Check for 0 first, +since a substring that isn't found then gives -1, and a slice that starts +at -1 begins at the last character. The second form in the synopsis is SQL syntax, and it works in pipe queries too. @@ -59,3 +64,19 @@ SELECT position('bar' IN s) AS pos # expected output {pos:4} ``` + +--- + +_Code points are counted, so subtracting 1 (after checking for 0) gives a 0-based index for a slice_ + +```mdtest-spq +# spq +values {input:this, pos:position(this, "bar")} +| values {input, pos, rest:pos > 0 ? input[pos-1:] : null} +# input +"éébar" +"foo" +# expected output +{input:"éébar",pos:3,rest:"bar"} +{input:"foo",pos:0,rest:null} +``` diff --git a/runtime/expr/function/string.go b/runtime/expr/function/string.go index be63e0d22..c7ddadd30 100644 --- a/runtime/expr/function/string.go +++ b/runtime/expr/function/string.go @@ -2,6 +2,7 @@ package function import ( "strings" + "unicode/utf8" "github.com/agnivade/levenshtein" "github.com/superdb/super" @@ -128,7 +129,9 @@ func (p *Position) Call(args ...vector.Any) vector.Any { for i := range vec.Len() { s := vector.StringValue(vec, i) sub := vector.StringValue(subVec, i) - vals[i] = int64(strings.Index(s, sub) + 1) + if before, _, ok := strings.Cut(s, sub); ok { + vals[i] = int64(utf8.RuneCountInString(before) + 1) + } } return vector.NewInt(super.TypeInt64, vals) } diff --git a/runtime/ztests/expr/function/position.yaml b/runtime/ztests/expr/function/position.yaml index 1488475c4..515ed8d2a 100644 --- a/runtime/ztests/expr/function/position.yaml +++ b/runtime/ztests/expr/function/position.yaml @@ -2,6 +2,8 @@ spq: '{sql:position(sub IN s),call:position(s, sub)}' input: | {sub:"bar",s:"foobar"} + {sub:"bar",s:"éébar"} + {sub:"ébar",s:"ééébar"} {sub:"food"::(null|string),s:"seafood"::(null|string)} {sub:"baz",s:"foobar"} {sub:null,s:"friend"} @@ -11,6 +13,8 @@ input: | output: | {sql:4,call:4} + {sql:3,call:3} + {sql:3,call:3} {sql:4,call:4} {sql:0,call:0} {sql:null,call:null}