Skip to content

Programmatic creation / modification of SQL #906

Closed Answered by georgesittas
darugar asked this question in Q&A
Discussion options

You must be logged in to vote

Hey,

Yes, this is a reasonable use of SQLGlot. There's a dedicated section in the README for building/modifying SQL. In most cases, you can simply traverse the AST and apply any transformations you want, either manually or using some helpers (e.g. find, find_all, transform, walk etc).

For your example, I'd do something like:

import sqlglot

expression = sqlglot.parse_one(query)
tables = expression.find_all(sqlglot.exp.Table)

if any(table.alias_or_name == target_table_name for table in tables):
    expression.where(some_condition, copy=False)  # some_condition can be either an exp.Expression or a string.

Let me know if you have any question and I'll try to help.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by georgesittas
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants