From be1420f1bc3c1fe9b0a8efd0bbbf69b77b19337c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toma=C5=BE=20Jerman?= Date: Fri, 29 Nov 2019 13:00:55 +0100 Subject: [PATCH] Fix QL parsing for nested expressions & formatting Parsing: ((A) AND (B)) got parsed into [ASTNodes{A}] istead of [ASTNodes{A}, ASTNode{AND}, ASTNodes{B}]. Formatting into SQL: [ASTNodes{A}, ASTNode{AND}, ASTNodes{B}] got formatted into A AND B instead of (A) AND (B). --- pkg/ql/ast_parser.go | 8 ++++++++ pkg/ql/squirrel.go | 8 +++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/pkg/ql/ast_parser.go b/pkg/ql/ast_parser.go index 5c1e8f244..514c6610b 100644 --- a/pkg/ql/ast_parser.go +++ b/pkg/ql/ast_parser.go @@ -194,11 +194,19 @@ checkToken: goto next case PARENTHESIS_OPEN: p.level++ + dpth := p.level if sub, err := p.parseExpr(p.nextToken()); err != nil { return nil, err } else { list = append(list, sub) } + // Allow parent level to continue parsing. + // Example: ((A) AND (B)) + // +1 since PARENTHESIS_CLOSE decrease level + if p.level > 0 && (p.level+1) != dpth { + p.nextToken() + goto next + } default: return nil, fmt.Errorf("unexpected token while parsing expression (%v)", t) } diff --git a/pkg/ql/squirrel.go b/pkg/ql/squirrel.go index 2128b21ce..c613cc91f 100644 --- a/pkg/ql/squirrel.go +++ b/pkg/ql/squirrel.go @@ -18,7 +18,13 @@ func (nn ASTNodes) ToSql() (out string, args []interface{}, err error) { if _out, _args, err = s.ToSql(); err != nil { return } else { - out = out + _out + if _, ok := s.(ASTNodes); ok { + // Nested nodes should be wrapped + // Example: ((A) AND (B)) + out = out + "(" + _out + ")" + } else { + out = out + _out + } args = append(args, _args...) }