Skip to content

How to get the position of an expression when formatted as a sql string. #1072

Closed Answered by barakalon
CBQu asked this question in Q&A
Discussion options

You must be logged in to vote

One hacky idea:

After finding some_func and FROM, wrap them in a Tag expression:

from sqlglot import exp, parse_one

q = """
WITH T1 as (SELECT * FROM T2)
SELECT *
FROM (
   SELECT a, some_func(b)
   FROM T3) as T4, T1
"""
ast = parse_one(q)

# I'm not sure any of this makes sense for your use case... but you get the point

some_funcs = [
    func
    for func in ast.find_all(exp.Func)
    if func.name == "some_func"
]

for func in some_funcs:
    from_ = func.find_ancestor(exp.From)
    wrapped = exp.Tag(
        this=from_.copy(),
        prefix=f"<start>",
        postfix=f"<stop>"
    )
    from_.replace(wrapped)

print(ast.sql())
# WITH T1 AS (SELECT * FROM T2) SELECT *<start> FROM (…

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
3 replies
@CBQu
Comment options

@barakalon
Comment options

@CBQu
Comment options

Answer selected by barakalon
Comment options

You must be logged in to vote
1 reply
@CBQu
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants