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
18 changes: 12 additions & 6 deletions explain_my_code/adapters/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,21 +488,27 @@ def comparison(self, expression: Any) -> Node:
)

def boolean(self, expression: Any) -> Node:
"""One BOOLOP for a whole `a AND b AND c` run, as Python's `ast.BoolOp` gives.

sqlglot nests the run left-deep, one `And` per operator. Lowering that shape
made a node per operator, each re-rendering and re-measuring everything under
it, so a long WHERE clause was quadratic and hit the recursion limit. It also
scored cognitive complexity per operator rather than per run.
"""
operator = "AND" if isinstance(expression, exp.And) else "OR"
operands = list(expression.flatten())
node = Node(
kind=Kind.BOOLOP,
span=self.span_for(expression),
name=operator,
meta={
"op": operator.lower(),
"operand_count": 2,
"operands": [
self.sql_of(expression.this, 24),
self.sql_of(expression.expression, 24),
],
"operand_count": len(operands),
"operands": [self.sql_of(operand, 24) for operand in operands[:8]],
},
)
node.extend(self.children(expression))
for operand in operands:
node.extend(self.lower(operand))
return node

def function(self, expression: Any) -> Node:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,24 @@ async def load(urls):
assert {"comprehension", "async-await", "error-handling"} <= concept_ids(analysis)


def test_a_long_where_clause_is_one_boolean_run():
"""sqlglot nests `a AND b AND ...` one level per operator; lowered as-is, a
1,000-term WHERE clause took ~9s and then hit the recursion limit."""
conditions = " AND ".join(f"c{i} = {i}" for i in range(1_000))
result = explain(f"SELECT a FROM t WHERE {conditions};", language=Language.SQL)
assert not result.analysis.degraded
runs = [n for n in result.analysis.root.walk() if n.kind.value == "boolop"]
assert [n.meta["operand_count"] for n in runs] == [1_000]


def test_sql_and_python_score_boolean_runs_alike():
sql = analyze("SELECT 1 FROM t WHERE a = 1 AND (b = 2 OR c = 3) AND d = 4;", Language.SQL)
python = analyze("x = a == 1 and (b == 2 or c == 3) and d == 4\n")
assert (sql.metrics.cyclomatic, sql.metrics.cognitive) == (
python.metrics.cyclomatic, python.metrics.cognitive,
) == (4, 2)


def test_sql_concepts_are_language_scoped():
python = analyze("def f():\n return 1\n")
assert not {c for c in concept_ids(python) if c.startswith("sql-")}
Expand Down
Loading