Skip to content

optimize: simplify_parens removes parentheses around predicates in arithmetic context (MySQL), changing semantics #7338

@MuSilk

Description

@MuSilk

Summary

sqlglot.optimizer.simplify.simplify_parens() can drop parentheses around a comparison used as a numeric term (MySQL treats boolean as 0/1). This changes operator precedence and rewrites x - (a < b) into x - a < b-style logic, which is not equivalent.

Input:

SELECT
  *
FROM A
WHERE
  a - (b < c) >= 0

Run simplify (or any optimizer flow that includes it).

expr = optimizer.optimize(view_sql, dialect='mysql', rules=[
            simplify,
        ])

Expected

Preserve semantics of subtracting a boolean-as-int term, i.e. keep -(predicate) grouped, or rewrite equivalently (e.g. CASE WHEN ... THEN 1 ELSE 0 END), but do not change it into a different comparison.

Actual

SELECT
  *
FROM A
WHERE
  a - b < c >= 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions