Convert a sql query using sqlglot replace method

651 views Asked by At

I want to achieve the following sql query conversion using sqlglot

select * from table where date > abc.def(2 * days) to

select * from table where date > {@abc.def(2 * days).xyz(yyyy)}

For the first conversion i.e abc to {@abc}, I used the following replacement and it worked:

tree = sqlglot.parse_one(query)
tree.find(sqlglot.exp.Var).replace(sqlglot.exp.Var(this="{@abc"))

Can somebody help with the next conversion i.e def(2 * days) to def(2 * days).xyz(yyy)}

1

There are 1 answers

1
Toby Mao On BEST ANSWER
from sqlglot import parse_one, exp

expr = parse_one("select * from table where date > abc.def(2 * days)")

dot = expr.find(exp.Dot)

dot.replace(exp.Dot.build([dot.copy(), exp.func("xyz", "yyyy")]))

print(expr.sql())

Results in:

'SELECT * FROM table WHERE date > abc.DEF(2 * days).XYZ(yyyy)'