How do you remove a node from the tree? #462
-
I'm trying to achieve something to this effect:
But I can't figure out what method is available for this, or how to do this otherwise. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
It's a bit tricky to just delete a node, you could do return exp.TRUE to replace the node with a TRUE constant. you could then use the optimizer's simplify functionality to remove unnecessary TRUE statements another way is that you can replace the parent with a new expression with this part removed so def transform(node):
if ...is_parent...:
return condition_with_predicate_removed |
Beta Was this translation helpful? Give feedback.
-
@g-u-t-h-m-a-n you can now also do the following (relevant commit): from sqlglot import exp, parse_one
expression_tree = parse_one("SELECT a, b FROM x")
def fun(node):
if isinstance(node, exp.Column) and node.name == "b":
return None
return node
transformed_tree = expression_tree.transform(fun)
transformed_tree.sql() Which outputs: SELECT a FROM x Also, you can remove specific nodes by calling their pop method. |
Beta Was this translation helpful? Give feedback.
@g-u-t-h-m-a-n you can now also do the following (relevant commit):
Which outputs:
Also, you can remove specific nodes by calling their pop method.