taozhi8833998 / node-sql-parser

Parse simple SQL statements into an abstract syntax tree (AST) with the visited tableList and convert it back to SQL
https://taozhi8833998.github.io/node-sql-parser/
Apache License 2.0
816 stars 181 forks source link

SQL with multiple JSONB WHERE clauses generates the wrong AST #2043

Closed adamtowerz closed 3 months ago

adamtowerz commented 3 months ago

Describe the bug

SELECT company.name
FROM company
WHERE company.categories ->> 'items' ILIKE '%Health Care%'
  OR company.categories ->> 'items' ILIKE '%Health & Wellness%'

generates an AST with the following where:

{
  "type": "column_ref",
  "table": "company",
  "column": {
    "expr": {
      "type": "default",
      "value": "categories"
    }
  },
  "jsonb": [
    {
      "type": "json",
      "op": "->>",
      "right": {
        "type": "expr",
        "expr": {
          "type": "binary_expr",
          "operator": "OR",
          "left": {
            "type": "binary_expr",
            "operator": "ILIKE",
            "left": {
              "type": "single_quote_string",
              "value": "items"
            },
            "right": {
              "type": "single_quote_string",
              "value": "%Health Care%"
            }
          },
          "right": {
            "type": "column_ref",
            "table": "company",
            "column": {
              "expr": {
                "type": "default",
                "value": "categories"
              }
            },
            "jsonb": [
              {
                "type": "json",
                "op": "->>",
                "right": {
                  "type": "expr",
                  "expr": {
                    "type": "binary_expr",
                    "operator": "ILIKE",
                    "left": {
                      "type": "single_quote_string",
                      "value": "items"
                    },
                    "right": {
                      "type": "single_quote_string",
                      "value": "%Health & Wellness%"
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  ]
}

Database Engine PostgreSQL

To Reproduce See description

Expected behavior I think the operator precedence over ->> is wrong as I would expect the root node to be a binary expr with operator "OR" and the left and right to be the JSONB operation comparisons

taozhi8833998 commented 3 months ago

@adamtowerz fixed it.

adamtowerz commented 3 months ago

Thank you so much! Legendary speed.