"""Shared query modification utilities for SQL and builder classes.
This module provides pure functions for building SQL expressions that can be
shared by both the immutable SQL class and the mutable builder classes. All
functions are designed to be mypyc-compatible with no dynamic dispatch.
The utilities are organized in layers:
- Expression factories: Create comparison expressions (eq, lt, like, etc.)
- Condition builders: Create parameterized WHERE conditions
- Expression modifiers: Apply WHERE, LIMIT, OFFSET to expressions
- CTE utilities: Safe CTE extraction and reattachment
"""
from collections.abc import Callable
from typing import Any
from sqlglot import exp
from sqlspec.exceptions import SQLSpecError
__all__ = (
"apply_column_pruning",
"apply_limit",
"apply_offset",
"apply_or_where",
"apply_select_only",
"apply_where",
"create_between_condition",
"create_condition",
"create_exists_condition",
"create_in_condition",
"create_not_exists_condition",
"create_not_in_condition",
"expr_eq",
"expr_gt",
"expr_gte",
"expr_ilike",
"expr_is_not_null",
"expr_is_null",
"expr_like",
"expr_lt",
"expr_lte",
"expr_neq",
"expr_not_like",
"extract_column_name",
"parse_column_for_condition",
"safe_modify_with_cte",
)
# Type alias for condition factory functions
ConditionFactory = Callable[[exp.Expr, exp.Placeholder], exp.Expr]
_TABLE_QUALIFIED_PARTS = 2
_DATABASE_QUALIFIED_PARTS = 3
_CATALOG_QUALIFIED_PARTS = 4
# =============================================================================
# Expression Factories
# =============================================================================
def expr_eq(col: exp.Expr, placeholder: exp.Placeholder) -> exp.Expr:
"""Create equality expression: column = :param."""
return exp.EQ(this=col, expression=placeholder)