forked from aakash-rajur/sqlxgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_where_false.go
61 lines (47 loc) · 1.15 KB
/
handle_where_false.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package prepare
import (
"fmt"
"regexp"
"strings"
"github.com/joomcode/errorx"
)
func handleWhereFalseClause(query string) (string, error) {
whereContexts, err := splitWhereContexts(query)
if err != nil {
return "", errorx.InternalError.Wrap(err, "failed to find where contexts")
}
whereRe, err := whereFalseRegexPattern()
if err != nil {
return "", errorx.IllegalFormat.Wrap(err, "failed to compile where regex")
}
cursor := query
for _, whereContext := range whereContexts {
preparedPartial := whereRe.ReplaceAllString(whereContext, "$1 false and (\n$2\n)\n$3")
cursor = strings.ReplaceAll(cursor, whereContext, preparedPartial)
}
return cursor, nil
}
func whereFalseRegexPattern() (*regexp.Regexp, error) {
followedByTokens := strings.Join(
[]string{
`returning`,
`group by`,
`order by`,
`limit`,
`offset`,
`;\s*\z`,
`\z`,
},
"|",
)
followedByTokensPartial := fmt.Sprintf(`(%s)`, followedByTokens)
pattern := strings.Join(
[]string{
`(where)`, // where anchor
`\s*([\w\W\s\S]*?)\s*`, // all where conditions
followedByTokensPartial,
},
"",
)
return regexp.Compile(pattern)
}