andialbrecht / sqlparse

A non-validating SQL parser module for Python
BSD 3-Clause "New" or "Revised" License
3.71k stars 693 forks source link

Comparison issue #649

Open lanfangping opened 2 years ago

lanfangping commented 2 years ago

Hi

I found a problem with parsing selection SQL which selects from one table. When I parse the following SQL

select * from policy1 where path != 2 and dest = 1

The parse tree is as follows:

|- 0 DML 'select'
|- 1 Whitespace ' '
|- 2 Wildcard '*'
|- 3 Whitespace ' '
|- 4 Keyword 'from'
|- 5 Whitespace ' '
|- 6 Identifier 'policy1'
|  `- 0 Name 'policy1'
|- 7 Whitespace ' '
`- 8 Where 'where ...'
   |- 0 Keyword 'where'
   |- 1 Whitespace ' '
   |- 2 Keyword 'path'
   |- 3 Whitespace ' '
   |- 4 Comparison '!='
   |- 5 Whitespace ' '
   |- 6 Integer '2'
   |- 7 Whitespace ' '
   |- 8 Keyword 'and'
   |- 9 Whitespace ' '
   `- 10 Comparison 'dest =...'
      |- 0 Identifier 'dest'
      |  `- 0 Name 'dest'
      |- 1 Whitespace ' '
      |- 2 Comparison '='
      |- 3 Whitespace ' '
      `- 4 Integer '1'

We can see that index 8 Where class, the first Comparison only contains operator but the second Comparison contains the whole "dest = 1".

However, if I specified the table of the column in the where clause such as the following SQL:

select * from policy1 where policy1.path != 2 and policy1.dest = 1

It works well. The parse tree is as follows.

|- 0 DML 'select'
|- 1 Whitespace ' '
|- 2 Wildcard '*'
|- 3 Whitespace ' '
|- 4 Keyword 'from'
|- 5 Whitespace ' '
|- 6 Identifier 'policy1'
|  `- 0 Name 'policy1'
|- 7 Whitespace ' '
`- 8 Where 'where ...'
   |- 0 Keyword 'where'
   |- 1 Whitespace ' '
   |- 2 Comparison 'policy...'
   |  |- 0 Identifier 'policy...'
   |  |  |- 0 Name 'policy1'
   |  |  |- 1 Punctuation '.'
   |  |  `- 2 Name 'path'
   |  |- 1 Whitespace ' '
   |  |- 2 Comparison '!='
   |  |- 3 Whitespace ' '
   |  `- 4 Integer '2'
   |- 3 Whitespace ' '
   |- 4 Keyword 'and'
   |- 5 Whitespace ' '
   `- 6 Comparison 'policy...'
      |- 0 Identifier 'policy...'
      |  |- 0 Name 'policy1'
      |  |- 1 Punctuation '.'
      |  `- 2 Name 'dest'
      |- 1 Whitespace ' '
      |- 2 Comparison '='
      |- 3 Whitespace ' '
      `- 4 Integer '1'

Is it any way to make the parse tree correctly like the second tree shows but using the first SQL?