Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion book/src/super-sql/functions/strings/position.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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}
```
5 changes: 4 additions & 1 deletion runtime/expr/function/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package function

import (
"strings"
"unicode/utf8"

"github.com/agnivade/levenshtein"
"github.com/superdb/super"
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 4 additions & 0 deletions runtime/ztests/expr/function/position.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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}
Expand Down
Loading