Convert filters to SQL WHERE clause
(self)
| 57 | labels: Dict[str, str] = field(default_factory=dict) |
| 58 | |
| 59 | def to_where_clause(self) -> str: |
| 60 | """Convert filters to SQL WHERE clause""" |
| 61 | conditions: List[str] = [] |
| 62 | |
| 63 | def qualify_column(col: str) -> str: |
| 64 | """Qualify ambiguous columns with table alias""" |
| 65 | if "." in col: |
| 66 | return col # Already qualified |
| 67 | return col |
| 68 | |
| 69 | def _format_value(value: Any) -> str: |
| 70 | if value is None: |
| 71 | return "NULL" |
| 72 | if isinstance(value, str): |
| 73 | escaped = value.replace("'", "''") |
| 74 | return "'" + escaped + "'" |
| 75 | return str(value) |
| 76 | |
| 77 | # Handle include filters (= / IN) |
| 78 | for col, values in self.filters.items(): |
| 79 | if not values: |
| 80 | continue |
| 81 | qualified_col = qualify_column(col) |
| 82 | if len(values) == 1: |
| 83 | value = values[0] |
| 84 | if value is None: |
| 85 | conditions.append(f"{qualified_col} IS NULL") |
| 86 | else: |
| 87 | conditions.append(f"{qualified_col} = {_format_value(value)}") |
| 88 | else: |
| 89 | formatted = [_format_value(v) for v in values if v is not None] |
| 90 | if len(formatted) != len(values): |
| 91 | # Separate NULL handling: column IS NULL OR column IN (...) |
| 92 | non_null = [v for v in values if v is not None] |
| 93 | clauses = [] |
| 94 | if non_null: |
| 95 | formatted_non_null = ", ".join(_format_value(v) for v in non_null) |
| 96 | clauses.append(f"{qualified_col} IN ({formatted_non_null})") |
| 97 | if any(v is None for v in values): |
| 98 | clauses.append(f"{qualified_col} IS NULL") |
| 99 | conditions.append("(" + " OR ".join(clauses) + ")") |
| 100 | else: |
| 101 | values_str = ", ".join(formatted) |
| 102 | conditions.append(f"{qualified_col} IN ({values_str})") |
| 103 | |
| 104 | # Handle exclude filters (!= / NOT IN) |
| 105 | for col, values in self.exclude_filters.items(): |
| 106 | if not values: |
| 107 | continue |
| 108 | qualified_col = qualify_column(col) |
| 109 | if len(values) == 1: |
| 110 | value = values[0] |
| 111 | if value is None: |
| 112 | conditions.append(f"{qualified_col} IS NOT NULL") |
| 113 | else: |
| 114 | conditions.append(f"{qualified_col} != {_format_value(value)}") |
| 115 | else: |
| 116 | non_null = [v for v in values if v is not None] |
no outgoing calls
no test coverage detected