Skip to content
Merged
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
25 changes: 25 additions & 0 deletions core/ast/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Shared AST helpers (small utilities used across files)."""

from __future__ import annotations

from typing import List

from core.ast.node import Node, OperatorNode, UnaryOperatorNode


def flatten_logical_operands(node: Node, op_name: str) -> List[Node]:
"""Flatten a left-associative tree of binary ``op_name`` (e.g. AND/OR).

Unary operators are excluded even if they subtype :class:`OperatorNode`.
"""
op_upper = op_name.upper()
if (
isinstance(node, OperatorNode)
and not isinstance(node, UnaryOperatorNode)
and node.name.upper() == op_upper
):
out: List[Node] = []
for child in list(node.children):
out.extend(flatten_logical_operands(child, op_name))
return out
return [node]
9 changes: 8 additions & 1 deletion core/query_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
JoinNode,
SubqueryNode,
)
from core.ast.enums import NodeType, JoinType, SortOrder
from core.ast.enums import NodeType, JoinType
from core.ast.node import Node
from core.ast.utils import flatten_logical_operands

class QueryFormatter:
def format(self, query: Node) -> str:
Expand Down Expand Up @@ -368,6 +369,12 @@ def format_expression(node: Node):

if op_name == 'sub' and len(children) == 2 and children[0].type == NodeType.LITERAL and children[0].value == 0:
return {'neg': format_expression(children[1])}

# Flatten left-associative AND/OR trees into the list form mo_sql_parsing expects.
if op_name in ("and", "or"):
flat = flatten_logical_operands(node, node.name.upper())
rendered = [format_expression(c) for c in flat]
return {op_name: rendered}

left = format_expression(children[0])

Expand Down
3 changes: 3 additions & 0 deletions core/query_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,9 @@ def parse_expression(self, expr, aliases: dict = None) -> Node:

# Special cases first
if 'all_columns' in expr:
qualifier = expr['all_columns']
if qualifier and qualifier != '*':
return ColumnNode('*', _parent_alias=qualifier)
return ColumnNode('*')
if 'literal' in expr:
# mo_sql_parsing uses {'literal': [..]} for IN literal lists and
Expand Down
Loading
Loading