|
| 1 | +"""Helpers to build metadata filter conditions with consistent semantics.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from collections.abc import Mapping |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +from sqlalchemy import and_, false, or_ |
| 8 | +from sqlalchemy.dialects.postgresql import JSONB |
| 9 | +from sqlmodel import col, func |
| 10 | + |
| 11 | +from raglite._database import _adapt_metadata |
| 12 | +from raglite._typing import MetadataFilter, MetadataValue |
| 13 | + |
| 14 | + |
| 15 | +def build_metadata_filter_condition( |
| 16 | + metadata_column: Any, |
| 17 | + metadata_filter: MetadataFilter | None, |
| 18 | + *, |
| 19 | + dialect: str, |
| 20 | +) -> Any: |
| 21 | + """Build a SQLAlchemy condition for metadata filtering. |
| 22 | +
|
| 23 | + A list of values within the same field uses OR semantics. |
| 24 | + Different fields are combined with AND semantics. |
| 25 | + """ |
| 26 | + normalized_metadata_filter = _adapt_metadata(metadata_filter) |
| 27 | + if not normalized_metadata_filter: |
| 28 | + return None |
| 29 | + |
| 30 | + field_conditions: list[Any] = [] |
| 31 | + for metadata_name, metadata_values in normalized_metadata_filter.items(): |
| 32 | + if not metadata_values: |
| 33 | + return false() # empty filters are considered unsatisfiable |
| 34 | + |
| 35 | + value_conditions: list[Any] = [] |
| 36 | + for metadata_value in metadata_values: |
| 37 | + single_value_filter = {metadata_name: [metadata_value]} |
| 38 | + if dialect == "postgresql": |
| 39 | + value_conditions.append( |
| 40 | + col(metadata_column).cast(JSONB).op("@>")(single_value_filter) # type: ignore[attr-defined] |
| 41 | + ) |
| 42 | + elif dialect == "duckdb": |
| 43 | + value_conditions.append( |
| 44 | + func.json_contains( |
| 45 | + col(metadata_column), func.json(json.dumps(single_value_filter)) |
| 46 | + ) |
| 47 | + ) |
| 48 | + else: |
| 49 | + error_message = f"Unsupported dialect: {dialect}." |
| 50 | + raise ValueError(error_message) |
| 51 | + field_conditions.append(or_(*value_conditions)) # combine values for the same field with OR |
| 52 | + return and_(*field_conditions) # combine different fields with AND |
| 53 | + |
| 54 | + |
| 55 | +def build_metadata_filter_sql( |
| 56 | + metadata_filter: Mapping[str, list[MetadataValue] | MetadataValue] | None, |
| 57 | + *, |
| 58 | + dialect: str, |
| 59 | +) -> tuple[str, dict[str, str]]: |
| 60 | + """Build SQL fragment and bound parameters for metadata filtering. |
| 61 | +
|
| 62 | + A list of values within the same field uses OR semantics. |
| 63 | + Different fields are combined with AND semantics. |
| 64 | +
|
| 65 | + Returns |
| 66 | + ------- |
| 67 | + sql_fragment : str |
| 68 | + A SQL fragment to be included in the WHERE clause, with placeholders for parameters. |
| 69 | + parameters : dict |
| 70 | + A dictionary of parameter names and their corresponding JSON string values to be used in |
| 71 | + the query execution |
| 72 | + """ |
| 73 | + normalized_metadata_filter = _adapt_metadata(metadata_filter) |
| 74 | + if not normalized_metadata_filter: |
| 75 | + return "", {} |
| 76 | + |
| 77 | + field_sql_conditions: list[str] = [] |
| 78 | + parameters: dict[str, str] = {} |
| 79 | + parameter_index = 0 |
| 80 | + |
| 81 | + for metadata_name, metadata_values in normalized_metadata_filter.items(): |
| 82 | + if not metadata_values: |
| 83 | + return " AND 1=0", {} |
| 84 | + |
| 85 | + value_sql_conditions: list[str] = [] |
| 86 | + for metadata_value in metadata_values: |
| 87 | + parameter_name = f"metadata_filter_{parameter_index}" |
| 88 | + parameter_index += 1 |
| 89 | + single_value_filter = json.dumps({metadata_name: [metadata_value]}) |
| 90 | + parameters[parameter_name] = single_value_filter |
| 91 | + |
| 92 | + if dialect == "postgresql": |
| 93 | + value_sql_conditions.append(f"metadata::jsonb @> :{parameter_name}") |
| 94 | + elif dialect == "duckdb": |
| 95 | + value_sql_conditions.append(f"json_contains(metadata, JSON(:{parameter_name}))") |
| 96 | + else: |
| 97 | + error_message = f"Unsupported dialect: {dialect}." |
| 98 | + raise ValueError(error_message) |
| 99 | + field_sql_conditions.append(f"({' OR '.join(value_sql_conditions)})") |
| 100 | + return f" AND {' AND '.join(field_sql_conditions)}", parameters |
0 commit comments