Skip to content
Open
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
36 changes: 21 additions & 15 deletions book/src/super-sql/functions/strings/grep.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,9 @@ The `grep` function searches all of the strings in its input value `e`
[regular expression](../../queries.md#regular-expression).
If the pattern matches for any string, then the result is `true`. Otherwise, it is `false`.

>[!NOTE]
> If `re` can match only one fixed string, as when it has no regular
> expression metacharacters (e.g., `"baz"`), `grep` looks for that string as
> a substring and ignores case, as a
> [keyword search](../../operators/search.md#keyword) does.
> Otherwise, the match is case-sensitive, so
> to ignore case in a regular expression, start it with `(?i)`.
The match is case-sensitive, unlike a
[keyword search](../../operators/search.md#keyword). To ignore case, start
`re` with `(?i)`.

The entire input value is traversed:
* for records, each field value is traversed or descended if a complex type,
Expand Down Expand Up @@ -91,18 +87,28 @@ grep('b.*', s.ok())

---

_A pattern without metacharacters ignores case, but a regular expression doesn't_
_Start the pattern with `(?i)` to ignore case_

```mdtest-spq
# spq
values {
input: this,
plain: grep("BAZ", this),
regexp: grep("B.Z", this),
ignore_case: grep("(?i)B.Z", this)
}
values {input:this, match_case:grep("BAZ", this), ignore_case:grep("(?i)BAZ", this)}
# input
"baz"
# expected output
{input:"baz",plain:true,regexp:false,ignore_case:true}
{input:"baz",match_case:false,ignore_case:true}
```

---

_The pattern can come from the input_

```mdtest-spq
# spq
values {input:this, match:grep(pattern, s)}
# input
{pattern:"foo|baz",s:"baz"}
{pattern:"^a",s:"bar"}
# expected output
{input:{pattern:"foo|baz",s:"baz"},match:true}
{input:{pattern:"^a",s:"bar"},match:false}
```
19 changes: 11 additions & 8 deletions book/src/super-sql/operators/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,18 @@ followed by any of these characters or digits `0` through `9`.

A keyword search is equivalent to
```
grep(<keyword>, this)
grep(<pattern>, this)
```
where `<keyword>` is the quoted string-literal of the unquoted string.
where `<pattern>` is a quoted string literal that holds `(?i)` followed by
the keyword, with any regular expression metacharacters escaped, so that it
matches the keyword's text as is and ignores case.
For example,
```
search foo
```
is equivalent to
```
where grep("foo", this)
where grep("(?i)foo", this)
```

Note that the shorthand `?` may be used in lieu of the "search" keyword.
Expand Down Expand Up @@ -135,8 +137,9 @@ of the same text.
A search for a value `<value>` represented as the string `<string>` is
equivalent to
```
<value> in this or grep(<string>, this)
<value> in this or grep(<pattern>, this)
```
where `<pattern>` is formed from `<string>` as for a keyword.
For example,
```
search 123 and 10.0.0.1
Expand All @@ -147,8 +150,8 @@ which can be abbreviated
```
is equivalent to
```
where (123 in this or grep("123", this))
and (10.0.0.1 in this or grep("10.0.0.1", this))
where (123 in this or grep("(?i)123", this))
and (10.0.0.1 in this or grep("(?i)10\\.0\\.0\\.1", this))
```

Complex values are not supported as search terms but may be queried with
Expand Down Expand Up @@ -193,15 +196,15 @@ For example,
```
means
```
((not grep("foo", this)) and grep("bar", this)) or grep("baz", this)
((not grep("(?i)foo", this)) and grep("(?i)bar", this)) or grep("(?i)baz", this)
```
while
```
? foo (bar or baz)
```
means
```
grep("foo", this) and (grep("bar", this) or grep("baz", this))
grep("(?i)foo", this) and (grep("(?i)bar", this) or grep("(?i)baz", this))
```

## Examples
Expand Down
26 changes: 26 additions & 0 deletions bsup/ztests/grep-pushdown.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# grep over this skips frames that can't contain a literal or case-insensitive
# literal pattern, but not when it searches a computed value.

script: |
seq 100 | super -o t.bsup -framecap 10 -inputcap 10 -c 'values {s:f"foo{this}"}' -
for q in "grep('foo18', this)" "grep('FOO18', this)" "grep('(?i)FOO18', this)" "grep('zzz', [this, 'zzz'])"; do
echo "=== $q"
super -stats -s -c "where $q | count()" t.bsup 2> stats
grep -o 'frames_skipped_search_filter:[0-9]*' stats
done

outputs:
- name: stdout
data: |
=== grep('foo18', this)
1
frames_skipped_search_filter:9
=== grep('FOO18', this)
0
frames_skipped_search_filter:10
=== grep('(?i)FOO18', this)
1
frames_skipped_search_filter:9
=== grep('zzz', [this, 'zzz'])
100
frames_skipped_search_filter:0
3 changes: 2 additions & 1 deletion compiler/optimizer/pruner.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,8 @@ func regexpPrefix(s string) string {
if re.Op == syntax.OpConcat &&
len(re.Sub) >= 2 &&
re.Sub[0].Op == syntax.OpBeginText &&
re.Sub[1].Op == syntax.OpLiteral {
re.Sub[1].Op == syntax.OpLiteral &&
re.Sub[1].Flags&syntax.FoldCase == 0 {
return string(re.Sub[1].Rune)
}
return ""
Expand Down
17 changes: 17 additions & 0 deletions compiler/rungen/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package rungen
import (
"github.com/superdb/super"
"github.com/superdb/super/compiler/dag"
samexpr "github.com/superdb/super/runtime/sam/expr"
"github.com/superdb/super/runtime/search"
"github.com/superdb/super/sup"
"golang.org/x/text/unicode/norm"
Expand Down Expand Up @@ -62,6 +63,22 @@ func CompileSearch(sctx *super.Context, e dag.Expr) (search.Expr, error) {
}
pattern := norm.NFC.Bytes(literal.Bytes())
return search.NewExprForStringCase(string(pattern)), nil
case *dag.RegexpSearchExpr:
if _, ok := e.Expr.(*dag.ThisExpr); !ok {
return nil, nil
}
literal, fold, ok := samexpr.ParseLiteral(e.Pattern)
if !ok {
return nil, nil
}
if !fold {
return search.NewExprForString(literal), nil
}
expr := search.NewExprForStringCase(literal)
if odd := samexpr.OddFoldVariants(literal); expr != nil && len(odd) > 0 {
expr = search.NewOrExpr(expr, search.NewExprForAnyString(odd))
}
return expr, nil
default:
return nil, nil
}
Expand Down
11 changes: 1 addition & 10 deletions compiler/semantic/expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -868,19 +868,10 @@ func (t *translator) semCallByName(call *ast.CallExpr, name string, args []sem.E
if !ok {
return sem.NewCall(call, "grep", args), super.TypeBool
}
re, err := expr.CompileRegexp(pattern)
if err != nil {
if _, err := expr.CompileRegexp(pattern); err != nil {
t.error(call.Args[0], err)
return badExpr, t.checker.unknown
}
if s, ok := re.LiteralPrefix(); ok {
return &sem.SearchTermExpr{
Node: call,
Text: s,
Value: sup.QuotedString(s),
Expr: args[1],
}, super.TypeBool
}
return &sem.RegexpSearchExpr{
Node: call,
Pattern: pattern,
Expand Down
6 changes: 3 additions & 3 deletions compiler/sfmt/ztests/switch.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ outputs:
===
null
| switch
case search("a") (
case regexp_search(r"a", this) (
head 1
| output main
)
case search("c") (
case regexp_search(r"c", this) (
tail 1
| output main
)
Expand All @@ -39,7 +39,7 @@ outputs:
===
null
| switch
case search("a") (
case regexp_search(r"a", this) (
head 1
| output main
)
Expand Down
13 changes: 13 additions & 0 deletions compiler/ztests/pruner-regexp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ script: |
echo // ===
echo '{x:"a"}' | super -o x.parquet -
super -s -c "SELECT x FROM x.parquet WHERE x LIKE 'a%'"
echo // ===
super compile -C -O -dynamic 'from test.bsup | where grep("(?i)^cslab", x)'
echo // ===
echo '{x:"cslab1"}' | super -o y.bsup -
super -s -c "from y.bsup | where grep('(?i)^cslab', x) | count()"

outputs:
- name: stdout
Expand Down Expand Up @@ -41,3 +46,11 @@ outputs:
{x:"a"}
// ===
{x:"a"}
// ===
file test.bsup format bsup
data-filter project [x] (
regexp_search(r"(?i)^cslab", x)
)
| output main
// ===
1
5 changes: 5 additions & 0 deletions compiler/ztests/sql/like.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ script: |
super -s -c "from s.json | values a LIKE 'f%'"
echo ===
super -s -c "from s.json | values a NOT LIKE 'f%'"
echo ===
super -s -c "from s.json | values {exact:a LIKE 'foo', part:a LIKE 'oo', not_part:a NOT LIKE 'oo'}"

inputs:
- name: s.json
Expand All @@ -25,3 +27,6 @@ outputs:
===
false
true
===
{exact:true,part:false,not_part:true}
{exact:false,part:false,not_part:true}
55 changes: 41 additions & 14 deletions runtime/expr/function/grep.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package function

import (
"regexp"

"github.com/superdb/super"
"github.com/superdb/super/runtime/expr"
"github.com/superdb/super/vector"
Expand All @@ -9,8 +11,10 @@ import (

type Grep struct {
sctx *super.Context
expr expr.Evaluator
search expr.Evaluator
err error
pattern string
cached bool
}

func (g *Grep) Call(args ...vector.Any) vector.Any {
Expand All @@ -28,25 +32,48 @@ func (g *Grep) Call(args ...vector.Any) vector.Any {
return vec
}
if _, ok := vector.Under(patternVec).(*vector.Const); ok {
pattern := vector.StringValue(patternVec, 0)
if g.expr == nil || g.pattern != pattern {
pattern = norm.NFC.String(pattern)
g.expr = expr.NewSearchString(g.sctx, pattern, &expr.This{})
g.pattern = pattern
if err := g.compile(vector.StringValue(patternVec, 0)); err != nil {
return vector.NewWrappedError(g.sctx, regexpErrMsg("grep", err), patternVec)
}
return g.expr.Eval(inputVec)
return g.search.Eval(inputVec)
}
var index [1]uint32
out := vector.NewFalse(patternVec.Len())
errMsg := vector.NewStringEmpty(0)
var errs, matches []uint32
for i := range patternVec.Len() {
pattern := vector.StringValue(patternVec, i)
pattern = norm.NFC.String(pattern)
search := expr.NewSearchString(g.sctx, pattern, &expr.This{})
if err := g.compile(vector.StringValue(patternVec, i)); err != nil {
errMsg.Append(regexpErrMsg("grep", err))
errs = append(errs, i)
continue
}
index[0] = i
v := search.Eval(vector.Pick(inputVec, index[:]))
v := g.search.Eval(vector.Pick(inputVec, index[:]))
if vector.BoolValue(v, 0) {
out.Set(i)
matches = append(matches, i-uint32(len(errs)))
}
}
return out
out := vector.NewFalse(patternVec.Len() - uint32(len(errs)))
for _, k := range matches {
out.Set(k)
}
if len(errs) == 0 {
return out
}
c := vector.NewCombiner(out)
c.Add(errs, vector.NewVecWrappedError(g.sctx, errMsg, vector.Pick(patternVec, errs)))
return c.Result()
}

func (g *Grep) compile(pattern string) error {
if g.cached && g.pattern == pattern {
return g.err
}
g.pattern, g.cached = pattern, true
re, err := regexp.Compile(norm.NFC.String(pattern))
if err != nil {
g.search, g.err = nil, err
return err
}
g.search, g.err = expr.NewSearchRegexp(g.sctx, re, &expr.This{}), nil
return nil
}
Loading
Loading