Replies: 1 comment
-
Here is a naive approach: from sqlglot import parse_one, exp
q = """
SELECT
T3.born_state
FROM department AS T1
JOIN management AS T2
ON T1.department_id = T2.department_id
JOIN head AS T3
ON T2.head_id = T3.head_id
WHERE
T1.name = 'Treasury'
INTERSECT
SELECT
T3.born_state
FROM department AS T1
JOIN management AS T2
ON T1.department_id = T2.department_id
JOIN head AS T3
ON T2.head_id = T3.head_id
WHERE
T1.name = 'Homeland Security'
"""
ast = parse_one(q)
for alias in ast.find_all(exp.Alias):
alias.replace(alias.this)
for alias in ast.find_all(exp.TableAlias):
alias.pop()
for column in ast.find_all(exp.Column):
column.set("table", None)
print(ast.sql(pretty=True)) SELECT
born_state
FROM department
JOIN management
ON department_id = department_id
JOIN head
ON head_id = head_id
WHERE
name = 'Treasury'
INTERSECT
SELECT
born_state
FROM department
JOIN management
ON department_id = department_id
JOIN head
ON head_id = head_id
WHERE
name = 'Homeland Security' Now, of course, the result is not a valid query. This leaves ambiguous columns (e.g. To do this safely, you'd want to use
And if you want to remove out column aliases and you might have subqueries, you'd need to propagate name changes up the scope tree. You can look in |
Beta Was this translation helpful? Give feedback.
-
Hi,
Is it possible to remove aliases in a query automatically with sqlglot?
For example, given query:
SELECT T3.born_state FROM department AS T1 JOIN management AS T2 ON T1.department_id = T2.department_id JOIN head AS T3 ON T2.head_id = T3.head_id WHERE T1.name = 'Treasury' INTERSECT SELECT T3.born_state FROM department AS T1 JOIN management AS T2 ON T1.department_id = T2.department_id JOIN head AS T3 ON T2.head_id = T3.head_id WHERE T1.name = 'Homeland Security'
I want it to rewrite the query to not have any "AS".
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions