|
| 1 | +// Package regexp provides additional regular expression functions. |
| 2 | +// |
| 3 | +// It provides the following Unicode aware functions: |
| 4 | +// - regexp_like(), |
| 5 | +// - regexp_substr(), |
| 6 | +// - regexp_replace(), |
| 7 | +// - and a REGEXP operator. |
| 8 | +// |
| 9 | +// The implementation uses Go [regexp/syntax] for regular expressions. |
| 10 | +// |
| 11 | +// https://github.com/nalgeon/sqlean/blob/main/docs/regexp.md |
| 12 | +package regexp |
| 13 | + |
| 14 | +import ( |
| 15 | + "regexp" |
| 16 | + |
| 17 | + "github.com/ncruces/go-sqlite3" |
| 18 | +) |
| 19 | + |
| 20 | +// Register registers Unicode aware functions for a database connection. |
| 21 | +func Register(db *sqlite3.Conn) { |
| 22 | + flags := sqlite3.DETERMINISTIC | sqlite3.INNOCUOUS |
| 23 | + |
| 24 | + db.CreateFunction("regexp", 2, flags, regex) |
| 25 | + db.CreateFunction("regexp_like", 2, flags, regexLike) |
| 26 | + db.CreateFunction("regexp_substr", 2, flags, regexSubstr) |
| 27 | + db.CreateFunction("regexp_replace", 3, flags, regexReplace) |
| 28 | +} |
| 29 | + |
| 30 | +func load(ctx sqlite3.Context, i int, expr string) (*regexp.Regexp, error) { |
| 31 | + re, ok := ctx.GetAuxData(i).(*regexp.Regexp) |
| 32 | + if !ok { |
| 33 | + r, err := regexp.Compile(expr) |
| 34 | + if err != nil { |
| 35 | + return nil, err |
| 36 | + } |
| 37 | + re = r |
| 38 | + ctx.SetAuxData(0, r) |
| 39 | + } |
| 40 | + return re, nil |
| 41 | +} |
| 42 | + |
| 43 | +func regex(ctx sqlite3.Context, arg ...sqlite3.Value) { |
| 44 | + re, err := load(ctx, 0, arg[0].Text()) |
| 45 | + if err != nil { |
| 46 | + ctx.ResultError(err) |
| 47 | + } else { |
| 48 | + ctx.ResultBool(re.Match(arg[1].RawText())) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +func regexLike(ctx sqlite3.Context, arg ...sqlite3.Value) { |
| 53 | + re, err := load(ctx, 1, arg[1].Text()) |
| 54 | + if err != nil { |
| 55 | + ctx.ResultError(err) |
| 56 | + } else { |
| 57 | + ctx.ResultBool(re.Match(arg[0].RawText())) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func regexSubstr(ctx sqlite3.Context, arg ...sqlite3.Value) { |
| 62 | + re, err := load(ctx, 1, arg[1].Text()) |
| 63 | + if err != nil { |
| 64 | + ctx.ResultError(err) |
| 65 | + } else { |
| 66 | + ctx.ResultRawText(re.Find(arg[0].RawText())) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func regexReplace(ctx sqlite3.Context, arg ...sqlite3.Value) { |
| 71 | + re, err := load(ctx, 1, arg[1].Text()) |
| 72 | + if err != nil { |
| 73 | + ctx.ResultError(err) |
| 74 | + } else { |
| 75 | + ctx.ResultRawText(re.ReplaceAll(arg[0].RawText(), arg[2].RawText())) |
| 76 | + } |
| 77 | +} |
0 commit comments