tobymao / sqlglot

Python SQL Parser and Transpiler
https://sqlglot.com/
MIT License
6.73k stars 703 forks source link

TOP for Azure? #4385

Closed RedTailedHawk closed 19 hours ago

RedTailedHawk commented 20 hours ago
parse_tree = (
    exp
    .select("a", "b")
    .from_("x")
    .where("b < 4")
    .limit(10)
)

generator = Generator(pretty = True, pad = 4, dialect = "tsql")

print(generator.generate(parse_tree))
SELECT
    a,
    b
FROM x
WHERE
    b < 4
LIMIT 10

But I need TOP for an Azure database.

SELECT TOP 10
    a,
    b
FROM x
WHERE
    b < 4

Is tsql the wrong dialect here?

VaggelisD commented 19 hours ago

Hey @RedTailedHawk,

Did you get this example from our docs? You should use .sql() to generate an AST:

>>> parse_tree = exp.select("a", "b").from_("x").where("b < 4").limit(10)
>>> parse_tree.sql('tsql')
'SELECT TOP 10 a, b FROM x WHERE b < 4'
RedTailedHawk commented 19 hours ago

I think you meant that .sql() should be used to generate the SQL (not an AST). But OK, this seems to be working better, thanks.

print(parse_tree.sql("tsql", pretty = True, pad = 4))

SELECT
TOP 10
    a,
    b
FROM x
WHERE
    brand < 4

But just curious why generator.generate(parse_tree) doesn't work?

tobymao commented 19 hours ago

because that's not the right generator, you need the tsql generator which is a subclass. you can't get it by instantiating the base generator