Skip to content

How to enforce conditions in WHERE and JOIN #1046

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

You must be logged in to vote

I would replace all the tables with a subquery that has the filter.

from sqlglot import exp, parse_one
from sqlglot.optimizer.scope import traverse_scope


def find_tables(expression: exp.Expression) -> list[exp.Table]:
    """
    Find references to physical tables in an expression.

    This excludes sqlglot Table expressions that are references to CTEs.
    """
    return [
        source
        for scope in traverse_scope(expression)
        for source in scope.sources.values()
        if isinstance(source, exp.Table)
    ]


def filter_by_cid(sql: str, cid: int) -> str:
    expression = parse_one(sql)
    for table in find_tables(expression):
        table.replace(
            exp.s…

Replies: 1 comment 6 replies

Comment options

You must be logged in to vote
6 replies
@mpf82
Comment options

@tobymao
Comment options

@barakalon
Comment options

@mpf82
Comment options

@tobymao
Comment options

Answer selected by barakalon
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