klahnakoski / mo-sql-parsing

Let's make a SQL parser so we can provide a familiar interface to non-sql datastores!
Mozilla Public License 2.0
255 stars 58 forks source link

There seems to be a problem handling SELECT * #209

Closed engigu closed 10 months ago

engigu commented 10 months ago
In [1]: from  mo_sql_parsing import parse, format

In [2]: a = "select * from ta where id = 'xxxx'"

In [3]: format(parse(a), should_quote=lambda x: '`', ansi_quotes=False)
Out[3]: "SELECT `*` FROM `ta` WHERE `id` = 'xxxx'"

`*` is not what I want.

klahnakoski commented 10 months ago

@EngiGu Good day! Thank you for reporting this. I can not reproduce this problem, maybe you are using an old version? The current version is https://pypi.org/project/mo-sql-parsing/9.460.23319/

    def test_issue_209_lambda(self):
        sql = "select * from ta where id = 'xxxx'"
        expected = "SELECT * FROM ta WHERE id = 'xxxx'"
        result = format(parse(sql))
        self.assertEqual(result, expected)
klahnakoski commented 10 months ago

nm, I see those parameters are important. working...

klahnakoski commented 10 months ago

I have long forgotten about the should_quote parameter; it is expecting a function that will return truthy if the identifier should be quoted. In your case the lambda is returning "`", which is truthy, so it will quote everything, including "*".

I suggest letting the formatter decide the quotes, or you make one that excludes "*" and reserved words: https://github.com/klahnakoski/mo-sql-parsing/blob/dacb3c81dca1a4defae54ee0660c0dde610d282b/mo_sql_parsing/formatting.py#L43

klahnakoski commented 10 months ago

https://github.com/klahnakoski/mo-sql-parsing/commit/dacb3c81dca1a4defae54ee0660c0dde610d282b#diff-cd5f399e744183b535ca91e4e632eab3b83851537259d8a92f1950a31a81991fR93

engigu commented 10 months ago

Thank you, I know how to do it now, close.