sqlparse icon indicating copy to clipboard operation
sqlparse copied to clipboard

Error paring `BETWEEN .. AND ..` clause when decimal's '0' is omitted

Open RayMei98 opened this issue 5 years ago • 1 comments

As the title mentioned. Here are my sql query and python script.

-- test_sql
select
    l_discount
from
    lineitem
where
    l_discount between .03 and .06;
statement = sqlparse.parse(test_sql)[0]

for token in statement.tokens:
    if isinstance(token, sqlparse.sql.Where):
        print(token, '\n')
        print(' tokens type '.center(35, '='), ' token value '.center(20, '='))
        for sub_token in token.tokens:
            if sub_token.value in [' ', '\n']: continue
            print(str(type(sub_token)).ljust(35, ' '),  sub_token)

The sqlparse result is:

where
    l_discount between .03 and .06; 

=========== tokens type =========== === token value ====
<class 'sqlparse.sql.Token'>        where
<class 'sqlparse.sql.Identifier'>   l_discount between
<class 'sqlparse.sql.Identifier'>   .03 and
<class 'sqlparse.sql.Token'>        .06
<class 'sqlparse.sql.Token'>        ;

The between and and keyword are parsed as Identifier with some other content. And, the result is right when the omitted '0's are added as following:

-- test_sql
select
    l_discount
from
    lineitem
where
    l_discount between 0.03 and 0.06;
where
    l_discount between 0.03 and 0.06; 

=========== tokens type =========== === token value ====
<class 'sqlparse.sql.Token'>        where
<class 'sqlparse.sql.Identifier'>   l_discount
<class 'sqlparse.sql.Token'>        between
<class 'sqlparse.sql.Token'>        0.03
<class 'sqlparse.sql.Token'>        and
<class 'sqlparse.sql.Token'>        0.06
<class 'sqlparse.sql.Token'>        ;

RayMei98 avatar Dec 31 '20 10:12 RayMei98

I've opened a PR for this. The cause is the qualified-name lexer rule ([A-ZÀ-Ü]\w*(?=\s*\.)) firing on a keyword when it's followed by a leading-dot decimal like .03 — it mistakes the decimal point for a member-access period, so between/and get lexed as names. Fix narrows the lookahead to (?=\s*\.(?!\d)) so the period only counts as member access when it isn't followed by a digit. Qualified names (schema.table, t.col, t.*) are unaffected since identifiers can't start with a digit. Added a regression test.

AmadNaseem avatar Jul 08 '26 10:07 AmadNaseem