diff --git a/book/src/super-sql/functions/strings/grep.md b/book/src/super-sql/functions/strings/grep.md index 16d8c48f11..849a31d9ae 100644 --- a/book/src/super-sql/functions/strings/grep.md +++ b/book/src/super-sql/functions/strings/grep.md @@ -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, @@ -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} ``` diff --git a/book/src/super-sql/operators/search.md b/book/src/super-sql/operators/search.md index 83e34621a5..1b3ea8c962 100644 --- a/book/src/super-sql/operators/search.md +++ b/book/src/super-sql/operators/search.md @@ -95,16 +95,18 @@ followed by any of these characters or digits `0` through `9`. A keyword search is equivalent to ``` -grep(, this) +grep(, this) ``` -where `` is the quoted string-literal of the unquoted string. +where `` 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. @@ -135,8 +137,9 @@ of the same text. A search for a value `` represented as the string `` is equivalent to ``` - in this or grep(, this) + in this or grep(, this) ``` +where `` is formed from `` as for a keyword. For example, ``` search 123 and 10.0.0.1 @@ -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 @@ -193,7 +196,7 @@ 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 ``` @@ -201,7 +204,7 @@ while ``` 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 diff --git a/bsup/ztests/grep-pushdown.yaml b/bsup/ztests/grep-pushdown.yaml new file mode 100644 index 0000000000..7bd4e28a81 --- /dev/null +++ b/bsup/ztests/grep-pushdown.yaml @@ -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 diff --git a/compiler/optimizer/pruner.go b/compiler/optimizer/pruner.go index a089582946..593c16c827 100644 --- a/compiler/optimizer/pruner.go +++ b/compiler/optimizer/pruner.go @@ -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 "" diff --git a/compiler/rungen/search.go b/compiler/rungen/search.go index 83097509f5..22abab389a 100644 --- a/compiler/rungen/search.go +++ b/compiler/rungen/search.go @@ -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" @@ -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 } diff --git a/compiler/semantic/expr.go b/compiler/semantic/expr.go index 382727b9d4..a8b288f54d 100644 --- a/compiler/semantic/expr.go +++ b/compiler/semantic/expr.go @@ -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, diff --git a/compiler/sfmt/ztests/switch.yaml b/compiler/sfmt/ztests/switch.yaml index aad4159a2a..a3b85e4fd4 100644 --- a/compiler/sfmt/ztests/switch.yaml +++ b/compiler/sfmt/ztests/switch.yaml @@ -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 ) @@ -39,7 +39,7 @@ outputs: === null | switch - case search("a") ( + case regexp_search(r"a", this) ( head 1 | output main ) diff --git a/compiler/ztests/pruner-regexp.yaml b/compiler/ztests/pruner-regexp.yaml index f42a05c1b5..abc0d4bdaf 100644 --- a/compiler/ztests/pruner-regexp.yaml +++ b/compiler/ztests/pruner-regexp.yaml @@ -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 @@ -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 diff --git a/compiler/ztests/sql/like.yaml b/compiler/ztests/sql/like.yaml index 1fbc329155..7643222cd6 100644 --- a/compiler/ztests/sql/like.yaml +++ b/compiler/ztests/sql/like.yaml @@ -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 @@ -25,3 +27,6 @@ outputs: === false true + === + {exact:true,part:false,not_part:true} + {exact:false,part:false,not_part:true} diff --git a/runtime/expr/function/grep.go b/runtime/expr/function/grep.go index 9b860793cf..a09c431674 100644 --- a/runtime/expr/function/grep.go +++ b/runtime/expr/function/grep.go @@ -1,6 +1,8 @@ package function import ( + "regexp" + "github.com/superdb/super" "github.com/superdb/super/runtime/expr" "github.com/superdb/super/vector" @@ -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 { @@ -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 } diff --git a/runtime/expr/search.go b/runtime/expr/search.go index 2c31b3b146..9d38d4a406 100644 --- a/runtime/expr/search.go +++ b/runtime/expr/search.go @@ -1,12 +1,16 @@ package expr import ( + "bytes" "net/netip" "regexp" "slices" + "unicode" + "unicode/utf8" "unsafe" "github.com/superdb/super" + "github.com/superdb/super/pkg/stringsearch" "github.com/superdb/super/runtime/sam/expr" "github.com/superdb/super/vector" ) @@ -46,7 +50,56 @@ func NewSearch(sctx *super.Context, s string, val super.Value, e Evaluator) Eval } func NewSearchRegexp(sctx *super.Context, re *regexp.Regexp, e Evaluator) Evaluator { - return &search{sctx, e, nil, re.Match} + return &search{sctx, e, nil, regexpPred(re)} +} + +// regexpPred returns a function equivalent to re.Match that avoids the +// regexp engine when re is a literal or a case-insensitive literal. +func regexpPred(re *regexp.Regexp) func([]byte) bool { + literal, fold, ok := expr.ParseLiteral(re.String()) + if !ok { + return re.Match + } + if !fold { + b := []byte(literal) + return func(s []byte) bool { + return bytes.Contains(s, b) + } + } + contains := foldContains(literal) + var odd [][]byte + for _, o := range expr.OddFoldVariants(literal) { + odd = append(odd, []byte(o)) + } + return func(s []byte) bool { + if contains(s) { + return true + } + for _, o := range odd { + if bytes.Contains(s, o) { + return re.Match(s) + } + } + return false + } +} + +// foldContains returns a function that reports whether its argument contains +// literal, ignoring case as StringContainsFold does. +func foldContains(literal string) func([]byte) bool { + for _, r := range literal { + if r >= utf8.RuneSelf && (unicode.SimpleFold(r) != r || unicode.ToLower(r) != r) { + return func(s []byte) bool { + return expr.StringContainsFold(string(s), literal) + } + } + } + // Ignoring ASCII case is enough when no other letter in literal has a + // case variant, as long as NewCaseFinder's lowering leaves it as is. + f := stringsearch.NewCaseFinder(literal) + return func(s []byte) bool { + return f.Next(unsafe.String(unsafe.SliceData(s), len(s))) >= 0 + } } func NewSearchString(sctx *super.Context, s string, e Evaluator) Evaluator { diff --git a/runtime/sam/expr/filter.go b/runtime/sam/expr/filter.go index f1a3d89144..1c03d73e58 100644 --- a/runtime/sam/expr/filter.go +++ b/runtime/sam/expr/filter.go @@ -1,7 +1,11 @@ package expr import ( + "regexp/syntax" + "slices" "strings" + "unicode" + "unicode/utf8" "github.com/superdb/super" ) @@ -27,6 +31,32 @@ func StringContainsFold(a, b string) bool { return false } +// ParseLiteral reports whether pattern is a regular expression that matches +// just a literal string, such as "foo", or the literal ignoring case, such as +// "(?i)foo". If so, it returns the literal and whether case is ignored. +func ParseLiteral(pattern string) (string, bool, bool) { + re, err := syntax.Parse(pattern, syntax.Perl) + if err != nil || re.Op != syntax.OpLiteral || slices.Contains(re.Rune, utf8.RuneError) { + return "", false, false + } + return string(re.Rune), re.Flags&syntax.FoldCase != 0, true +} + +// OddFoldVariants returns the case variants of the letters in literal whose +// UTF-8 encodings have a different length (e.g., the Kelvin sign for "k"), +// which StringContainsFold doesn't match. +func OddFoldVariants(literal string) []string { + var odd []string + for _, r := range literal { + for f := unicode.SimpleFold(r); f != r; f = unicode.SimpleFold(f) { + if utf8.RuneLen(f) != utf8.RuneLen(r) && !slices.Contains(odd, string(f)) { + odd = append(odd, string(f)) + } + } + } + return odd +} + func IsTrue(val super.Value) bool { return val.Deunion().Ptr().AsBool() } diff --git a/runtime/search/expr.go b/runtime/search/expr.go index 116a5c0f53..4853eb49e2 100644 --- a/runtime/search/expr.go +++ b/runtime/search/expr.go @@ -1,6 +1,7 @@ package search import ( + "strings" "unicode/utf8" "github.com/superdb/super/pkg/stringsearch" @@ -69,3 +70,16 @@ func NewExprForStringCase(pattern string) Expr { } return &leaf{stringsearch.NewCaseFinder(pattern).Next} } + +// NewExprForAnyString returns an Expr that is true for text containing any of +// patterns. Unlike NewExprForString, it is meant for short patterns. +func NewExprForAnyString(patterns []string) Expr { + return &leaf{func(text string) int { + for _, p := range patterns { + if i := strings.Index(text, p); i >= 0 { + return i + } + } + return -1 + }} +} diff --git a/runtime/ztests/expr/function/grep-nfc.yaml b/runtime/ztests/expr/function/grep-nfc.yaml new file mode 100644 index 0000000000..f97cff1b56 --- /dev/null +++ b/runtime/ztests/expr/function/grep-nfc.yaml @@ -0,0 +1,12 @@ +# A computed pattern is normalized to NFC, as strings read from SUP and JSON +# are, so a decomposed pattern from CSV matches a precomposed string. + +script: | + printf 'p,s\ncafe\314\201,caf\303\251\ncaf\303\251,caf\303\251\n' > nfc.csv + super -s -c "from nfc.csv | values grep(p, s)" + +outputs: + - name: stdout + data: | + true + true diff --git a/runtime/ztests/expr/function/grep.yaml b/runtime/ztests/expr/function/grep.yaml index 1df8679350..3dabe7bfc5 100644 --- a/runtime/ztests/expr/function/grep.yaml +++ b/runtime/ztests/expr/function/grep.yaml @@ -1,6 +1,5 @@ # This test tests grep as a function call which only happens when the pattern -# arg is not a glob, regular expression, or resolvable to a string at compile -# time. +# arg is not resolvable to a string at compile time. spq: | [grep(pattern,this),grep(pattern,input)] @@ -30,3 +29,60 @@ output: | [true,true] [error({message:"grep: pattern argument must be a string",on:1}),error({message:"grep: pattern argument must be a string",on:1})] [error({message:"grep: pattern argument must be a string",on:null}),error({message:"grep: pattern argument must be a string",on:null})] + +--- + +# A computed pattern is a case-sensitive regular expression. + +spq: values grep(pattern, s) + +input: | + {pattern:"BAZ",s:"baz"} + {pattern:"(?i)BAZ",s:"baz"} + {pattern:"foo|baz",s:"baz"} + {pattern:"foo|baz",s:"qux"} + {pattern:"(",s:"baz"} + {pattern:"(",s:"("} + {pattern:"b.z",s:"bar"} + +output: | + false + true + true + false + error({message:"grep: invalid regular expression: missing closing )",on:"("}) + error({message:"grep: invalid regular expression: missing closing )",on:"("}) + false + +--- + +# A constant pattern is a case-sensitive regular expression too. + +spq: values {match_case:grep("BAZ", this), ignore_case:grep("(?i)BAZ", this), literal:grep("baz", this)} + +input: | + "baz" + "BAZ" + +output: | + {match_case:false,ignore_case:true,literal:true} + {match_case:true,ignore_case:true,literal:false} + +--- + +# Anchors keep their meaning in a pattern that is otherwise a literal, and so +# do non-ASCII letters in a case-insensitive one. + +spq: values {s, const:grep("^foo$", s), computed:grep(p, s), dotted_i:grep("(?i)İa", s)} + +input: | + {s:"xfooy",p:"^foo$"} + {s:"foo",p:"^foo$"} + {s:"İA",p:"^foo$"} + {s:"xia",p:"^foo$"} + +output: | + {s:"xfooy",const:false,computed:false,dotted_i:false} + {s:"foo",const:true,computed:true,dotted_i:false} + {s:"İA",const:false,computed:false,dotted_i:true} + {s:"xia",const:false,computed:false,dotted_i:false}