Source code for imednet.utils.filters

"""Utility functions for building API filter strings.

This module provides functionality to construct filter query parameters
for iMednet API endpoints based on the reference documentation.
"""

import functools
import re
import types
import weakref
from collections.abc import Collection, Mapping, Sequence
from datetime import UTC, date, datetime
from enum import Enum
from typing import Annotated, Any, Literal, TypeVar, Union, get_args, get_origin

from imednet.utils.dates import (
    format_iso_datetime,
    normalize_utc_timestamp_bound,
    parse_iso_datetime,
)

# Pre-compiled regexes for performance to avoid re-compilation in loops
_UNSAFE_CHARS_REGEX = re.compile(r"[^A-Za-z0-9_.-]")
_ISO_DATE_ONLY_REGEX = re.compile(r"^\d{4}-\d{2}-\d{2}$")
_ISO_8601_TIMESTAMP_REGEX = re.compile(
    r"^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)?$"
)

CANONICAL_UTC_ATTRIBUTES: frozenset[str] = frozenset(
    {"dateCreated", "dateModified", "lastUpdated", "dateCoded"}
)
VISIT_SCHEDULE_DATE_ATTRIBUTES: frozenset[str] = frozenset(
    {"startDate", "endDate", "dueDate", "visitDate"}
)

ORDERED_FILTER_OPERATORS: tuple[str, ...] = ("<=", ">=", "!=", "==", "=~", "<", ">")
ALLOWED_OPERATORS = frozenset({"<", "<=", ">", ">=", "==", "!="})
RECORD_DATA_OPERATORS = frozenset(ORDERED_FILTER_OPERATORS)
_OPERATOR_CHARS = frozenset("<>=!~")

T = TypeVar("T")


class _QuotedFilterStr(str):
    """String subclass marking a scalar token that was explicitly double-quoted."""

    __slots__ = ()


@functools.lru_cache(maxsize=128)
def _snake_to_camel(text: str) -> str:
    """Convert a snake_case string to camelCase."""
    if "_" not in text:
        return text
    parts = text.split("_")
    first, rest = parts[0], parts[1:]
    return first + "".join(word.capitalize() for word in rest)


_CAMEL_BOUNDARY_RE = re.compile(r"(?<!^)(?=[A-Z])")


@functools.lru_cache(maxsize=128)
def _camel_to_snake(text: str) -> str:
    """Convert a camelCase string to snake_case."""
    return _CAMEL_BOUNDARY_RE.sub("_", text).lower()


def _tokenize_filter_string(filter_str: str) -> tuple[list[tuple[str, str]], bool]:
    """Tokenize ``filter_str`` outside double quotes into ``(tokens, in_quotes)``.

    Token kinds:
    - ``"SEG"``: contiguous clause characters (including quoted substrings)
    - ``"AND"``: ``;`` or whitespace-bounded ``and`` (case-insensitive)
    - ``"OR"``: ``,`` or whitespace-bounded ``or`` (case-insensitive)
    - ``"WS"``: unquoted intra-clause or leading/trailing whitespace
    """
    raw_tokens: list[tuple[str, str]] = []
    buf: list[str] = []
    in_quotes = False
    escape = False

    for char in filter_str:
        if escape:
            buf.append(char)
            escape = False
            continue
        if char == "\\" and in_quotes:
            buf.append(char)
            escape = True
            continue
        if char == '"':
            buf.append(char)
            in_quotes = not in_quotes
            continue
        if not in_quotes:
            if char == ";":
                if buf:
                    raw_tokens.append(("SEG", "".join(buf)))
                    buf = []
                raw_tokens.append(("AND", ";"))
                continue
            if char == ",":
                if buf:
                    raw_tokens.append(("SEG", "".join(buf)))
                    buf = []
                raw_tokens.append(("OR", ","))
                continue
            if char.isspace():
                if buf:
                    raw_tokens.append(("SEG", "".join(buf)))
                    buf = []
                if not raw_tokens or raw_tokens[-1][0] != "WS":
                    raw_tokens.append(("WS", " "))
                continue
        buf.append(char)

    if buf:
        raw_tokens.append(("SEG", "".join(buf)))

    collapsed: list[tuple[str, str]] = []
    idx = 0
    total = len(raw_tokens)
    while idx < total:
        if (
            collapsed
            and collapsed[-1][0] == "SEG"
            and idx + 3 < total
            and raw_tokens[idx][0] == "WS"
            and raw_tokens[idx + 1][0] == "SEG"
            and raw_tokens[idx + 1][1].lower() in ("and", "or")
            and raw_tokens[idx + 2][0] == "WS"
            and raw_tokens[idx + 3][0] == "SEG"
        ):
            word = raw_tokens[idx + 1][1].lower()
            collapsed.append(("AND" if word == "and" else "OR", word))
            idx += 3
            continue
        collapsed.append(raw_tokens[idx])
        idx += 1

    return collapsed, in_quotes


def _scan_filter_string(filter_str: str) -> tuple[bool, bool, bool, bool]:
    """Scan filter string returning (has_and, has_or, has_whitespace, in_quotes)."""
    tokens, in_quotes = _tokenize_filter_string(filter_str)
    has_and = any(kind == "AND" for kind, _ in tokens)
    has_or = any(kind == "OR" for kind, _ in tokens)
    has_whitespace = any(kind == "WS" for kind, _ in tokens)
    return has_and, has_or, has_whitespace, in_quotes


def _split_filter_clauses(filter_str: str) -> tuple[list[str], str | None]:
    """Split a filter expression on ';'/and or ','/or outside quotation marks."""
    tokens, _ = _tokenize_filter_string(filter_str)
    clauses: list[str] = []
    current: list[str] = []
    connector: str | None = None

    for kind, text in tokens:
        if kind in ("AND", "OR"):
            connector = ";" if kind == "AND" else ","
            clauses.append("".join(current))
            current = []
        else:
            current.append(text)

    clauses.append("".join(current))
    return clauses, connector


[docs]def normalize_filter_connectors(filter_str: str) -> str: """Normalize word connectors ('and'/'or') to canonical ';' or ',' delimiters.""" stripped = filter_str.strip() if not stripped or stripped.lower() == "none": return filter_str clauses, connector = _split_filter_clauses(filter_str) if connector is None: return clauses[0] if clauses else filter_str return connector.join(clauses)
def _parse_clause_operator(clause: str) -> tuple[str, str, str] | None: """Parse (attribute, operator, raw_value) from a single filter clause.""" quote_idx = clause.find('"') prefix = clause if quote_idx == -1 else clause[:quote_idx] op_start = -1 for idx, char in enumerate(prefix): if char in _OPERATOR_CHARS: op_start = idx break if op_start == -1: return None op_end = op_start while op_end < len(prefix) and prefix[op_end] in _OPERATOR_CHARS: op_end += 1 attr = clause[:op_start] op = clause[op_start:op_end] val = clause[op_end:] if not attr or not val: raise ValueError(f"Malformed filter clause '{clause}': missing attribute or value") return attr, op, val
[docs]def extract_filter_attributes(filter_str: str) -> list[str]: """Extract attribute names from a raw filter expression.""" stripped = filter_str.strip() if not stripped or stripped.lower() == "none": return [] clauses, _ = _split_filter_clauses(stripped) attributes: list[str] = [] for clause in clauses: if not clause: continue parsed = _parse_clause_operator(clause) attributes.append(parsed[0] if parsed is not None else clause) return attributes
[docs]def validate_filter_operator(operator: str, *, allow_regex: bool = False) -> None: """Validate that an operator matches allowed tokens and contains no whitespace. Args: operator: The operator string to validate. allow_regex: Whether to allow the ``=~`` operator (for ``recordDataFilter``). Raises: ValueError: If operator contains whitespace or is not in the allowed set. """ if not isinstance(operator, str) or not operator: raise ValueError("Filter operator must be a non-empty string") if any(c.isspace() for c in operator): raise ValueError(f"Filter operator '{operator}' cannot contain whitespace") allowed = RECORD_DATA_OPERATORS if allow_regex else ALLOWED_OPERATORS if operator not in allowed: raise ValueError( f"Invalid filter operator '{operator}'. Allowed operators: {sorted(allowed)}" )
_MODEL_FIELD_TYPES_CACHE: weakref.WeakKeyDictionary[type[Any], dict[str, str]] = ( weakref.WeakKeyDictionary() ) _MODEL_FILTER_KEYS_CACHE: weakref.WeakKeyDictionary[type[Any], frozenset[str]] = ( weakref.WeakKeyDictionary() ) _MODEL_SORT_KEYS_CACHE: weakref.WeakKeyDictionary[type[Any], frozenset[str]] = ( weakref.WeakKeyDictionary() ) _ASCII_INT_RE = re.compile(r"^-?[0-9]+$") _ASCII_FLOAT_RE = re.compile(r"^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$") _UNPADDED_ASCII_INT_RE = re.compile(r"^(?:0|[1-9][0-9]*)$") _SORT_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") _SORT_VAR_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_:-]*$") def _unwrap_annotation_variants(annotation: Any) -> list[Any]: """Unwrap Optional, Union, and Annotated wrappers into leaf annotations.""" origin = get_origin(annotation) if origin is Annotated: args = get_args(annotation) return _unwrap_annotation_variants(args[0]) if args else [Any] if origin is Union or origin is types.UnionType: variants: list[Any] = [] for arg in get_args(annotation): if arg is type(None): continue variants.extend(_unwrap_annotation_variants(arg)) return variants return [annotation] def _classify_single_type(tp: Any) -> str: """Classify a single leaf type annotation into a filter scalar kind.""" if tp is bool: return "bool" origin = get_origin(tp) if origin is Literal: lit_vals = [v for v in get_args(tp) if v is not None] if lit_vals and all(isinstance(v, bool) for v in lit_vals): return "bool" if lit_vals and all(isinstance(v, str) for v in lit_vals): return "str" if lit_vals and all(isinstance(v, int) and not isinstance(v, bool) for v in lit_vals): return "int" if lit_vals and all( isinstance(v, (int, float)) and not isinstance(v, bool) for v in lit_vals ): return "float" return "other" if isinstance(tp, type): if issubclass(tp, str) or issubclass(tp, (date, datetime)): return "str" if issubclass(tp, int): return "int" if issubclass(tp, float): return "float" if issubclass(tp, Enum): return "str" return "other" def _classify_field_annotation(annotation: Any) -> str: """Resolve the canonical scalar kind ('str', 'int', 'float', 'bool', or 'other').""" variants = _unwrap_annotation_variants(annotation) if not variants: return "other" kinds = {_classify_single_type(v) for v in variants} if len(kinds) == 1: return next(iter(kinds)) return "other" def _get_model_field_types(model: type[Any]) -> dict[str, str]: """Return mapping of allowed snake_case/camelCase/alias keys to scalar kinds.""" cached = _MODEL_FIELD_TYPES_CACHE.get(model) if cached is not None: return cached model_fields = getattr(model, "model_fields", None) if not isinstance(model_fields, dict): return {} field_types: dict[str, str] = {} for field_name, field_info in model_fields.items(): kind = _classify_field_annotation(getattr(field_info, "annotation", Any)) field_types[field_name] = kind field_types[_snake_to_camel(field_name)] = kind alias = getattr(field_info, "alias", None) if isinstance(alias, str) and alias: field_types[alias] = kind validation_alias = getattr(field_info, "validation_alias", None) if isinstance(validation_alias, str) and validation_alias: field_types[validation_alias] = kind _MODEL_FIELD_TYPES_CACHE[model] = field_types return field_types def _get_model_filter_keys(model: type[Any]) -> frozenset[str]: """Return allowed snake_case and camelCase filter attribute names for a model.""" cached = _MODEL_FILTER_KEYS_CACHE.get(model) if cached is not None: return cached field_types = _get_model_field_types(model) if not field_types: return frozenset() result = frozenset(field_types.keys()) _MODEL_FILTER_KEYS_CACHE[model] = result return result def _is_collection_annotation(annotation: Any) -> bool: """Return True if ``annotation`` unwraps to a nested collection or mapping container.""" for variant in _unwrap_annotation_variants(annotation): origin = get_origin(variant) if origin in (list, dict, set, tuple, frozenset, Sequence, Collection, Mapping): return True if isinstance(variant, type) and issubclass(variant, (list, dict, set, tuple, frozenset)): return True return False
[docs]def derive_model_sort_attributes( model: type[Any], *, local_attributes: Collection[str] | None = None, ) -> frozenset[str]: """Derive canonical camelCase sortable property names from scalar ``MODEL`` aliases.""" if not isinstance(model, type): return frozenset() if not local_attributes: cached = _MODEL_SORT_KEYS_CACHE.get(model) if cached is not None: return cached model_fields = getattr(model, "model_fields", None) if not isinstance(model_fields, dict): return frozenset() local_camel = ( frozenset(_snake_to_camel(attr) for attr in local_attributes) if local_attributes else frozenset() ) is_query_model = getattr(model, "__name__", None) == "Query" sortable: set[str] = set() for field_name, field_info in model_fields.items(): if _is_collection_annotation(getattr(field_info, "annotation", Any)): continue if is_query_model and field_name == "status": continue alias = getattr(field_info, "alias", None) canonical = alias if isinstance(alias, str) and alias else _snake_to_camel(field_name) if canonical in local_camel: continue sortable.add(canonical) result = frozenset(sortable) if not local_attributes: _MODEL_SORT_KEYS_CACHE[model] = result return result
[docs]def compile_sort_parameter( sort_value: str | Sequence[str], *, sort_attributes: Collection[str] | None = None, model: type[Any] | None = None, allow_record_data: bool | None = None, endpoint_name: str | None = None, ) -> str | list[str]: """Validate and compile a ``sort`` argument into wire ``<property>,<asc|desc>`` parameter(s). Normalizes ``snake_case`` property names to ``camelCase`` (preserving ``<Variable>`` casing on ``recordData.<Variable>`` when permitted), validates against endpoint ``sort_attributes`` (or ``model`` scalar aliases), and returns a ``list[str]`` when multiple sort clauses are specified so HTTP clients emit repeated ``sort`` parameters. Raises: ConfigurationError: If syntax, direction, or attribute validation fails. """ from imednet.errors.validation import ConfigurationError raw_clauses: list[str] = [] if isinstance(sort_value, str): if not sort_value or not sort_value.strip(): raise ConfigurationError("Sort parameter cannot be empty.") raw_clauses.extend(sort_value.split(";")) elif isinstance(sort_value, Sequence) and not isinstance(sort_value, (bytes, bytearray)): if not sort_value: raise ConfigurationError("Sort parameter cannot be empty.") for item in sort_value: if not isinstance(item, str) or not item.strip(): raise ConfigurationError( f"Sort parameter entries must be non-empty strings, got {item!r}." ) raw_clauses.extend(item.split(";")) else: raise ConfigurationError( "Sort parameter must be a string or sequence of strings, " f"got {type(sort_value).__name__}." ) effective_allowed: frozenset[str] | None if sort_attributes is not None: effective_allowed = frozenset(sort_attributes) elif model is not None: effective_allowed = derive_model_sort_attributes(model) else: effective_allowed = None effective_allow_record_data = ( allow_record_data if allow_record_data is not None else bool(model is not None and getattr(model, "__name__", None) == "Record") ) target_label = endpoint_name or (model.__name__ if model is not None else "endpoint") def _format_allowed() -> str: if effective_allowed is None: return "any" if not effective_allowed: return "none" base = ", ".join(sorted(effective_allowed)) if effective_allow_record_data: return f"{base}, recordData.<Variable>" return base compiled: list[str] = [] seen_props: set[str] = set() for raw_clause in raw_clauses: part = raw_clause.strip() if not part: raise ConfigurationError( f"Invalid sort parameter '{sort_value}': sort clause cannot be empty." ) pieces = part.split(",") if len(pieces) != 2: raise ConfigurationError( f"Invalid sort parameter '{part}': expected '<property>,<asc|desc>'." ) raw_prop, raw_dir = pieces[0].strip(), pieces[1].strip() if not raw_prop or any(ch.isspace() for ch in raw_prop): raise ConfigurationError( f"Invalid sort property '{raw_prop}' in '{part}': expected '<property>,<asc|desc>'." ) direction = raw_dir.lower() if direction not in ("asc", "desc"): raise ConfigurationError( f"Invalid sort direction '{raw_dir}' in '{part}': expected 'asc' or 'desc'." ) if raw_prop.startswith(("recordData.", "record_data.")): if not effective_allow_record_data: raise ConfigurationError( f"Unsupported sort attribute '{raw_prop}' for {target_label}. " f"Allowed sort attributes: {_format_allowed()}." ) var_name = raw_prop.split(".", 1)[1] if not var_name or not _SORT_VAR_PATTERN.fullmatch(var_name): raise ConfigurationError( f"Invalid recordData sort variable '{raw_prop}': " "expected 'recordData.<Variable>'." ) canonical_prop = f"recordData.{var_name}" else: if not _SORT_KEY_PATTERN.fullmatch(raw_prop): raise ConfigurationError( f"Unsupported sort attribute '{raw_prop}' for {target_label}. " f"Allowed sort attributes: {_format_allowed()}." ) canonical_prop = _snake_to_camel(raw_prop) if effective_allowed is not None and canonical_prop not in effective_allowed: label = f"{raw_prop} ({canonical_prop})" if raw_prop != canonical_prop else raw_prop raise ConfigurationError( f"Unsupported sort attribute '{label}' for {target_label}. " f"Allowed sort attributes: {_format_allowed()}." ) if canonical_prop in seen_props: raise ConfigurationError( f"Duplicate sort attribute '{canonical_prop}' in sort parameter." ) seen_props.add(canonical_prop) compiled.append(f"{canonical_prop},{direction}") return compiled[0] if len(compiled) == 1 else compiled
def _is_visit_model(model: type[Any] | None) -> bool: """Return True when ``model`` represents the Visit resource.""" return model is not None and getattr(model, "__name__", None) == "Visit" def _compile_visit_schedule_date_value(val: Any, *, attr_name: str) -> str: """Compile a Visit schedule date value to ``YYYY-MM-DD``, rejecting non-midnight datetimes.""" if isinstance(val, bool) or val is None: raise ValueError( f"Visit schedule attribute '{attr_name}' requires a YYYY-MM-DD date, got {val!r}." ) if isinstance(val, datetime): dt_check = val.astimezone(UTC) if val.tzinfo is not None else val if ( dt_check.hour != 0 or dt_check.minute != 0 or dt_check.second != 0 or dt_check.microsecond != 0 ): raise ValueError( f"Visit schedule attribute '{attr_name}' requires a YYYY-MM-DD date or " f"midnight datetime, got non-midnight datetime '{val.isoformat()}'." ) return dt_check.date().isoformat() if isinstance(val, date): return val.isoformat() if isinstance(val, str): stripped = val.strip() if _ISO_DATE_ONLY_REGEX.fullmatch(stripped): date.fromisoformat(stripped) return stripped raise ValueError( f"Visit schedule attribute '{attr_name}' requires a YYYY-MM-DD date string, " f"got '{val}'." ) raise ValueError( f"Visit schedule attribute '{attr_name}' requires a YYYY-MM-DD date, got {val!r}." ) def _compile_utc_timestamp_value( val: Any, *, op: str, attr_name: str, preserve_explicit_offset_str: bool = False, ) -> str: """Compile a canonical UTC audit attribute value to an ISO-8601 UTC timestamp.""" if isinstance(val, bool) or val is None: raise ValueError( f"UTC timestamp attribute '{attr_name}' requires a date or ISO-8601 timestamp, " f"got {val!r}." ) is_end = op in ("<", "<=") if isinstance(val, datetime): return format_iso_datetime(val) if isinstance(val, date): return normalize_utc_timestamp_bound(val.isoformat(), is_end=is_end) if isinstance(val, str): stripped = val.strip() if not stripped: raise ValueError(f"UTC timestamp attribute '{attr_name}' cannot be empty.") if re.fullmatch(r"\d{4}(?:-\d{2})?", stripped): raise ValueError( f"Partial-year or incomplete date '{val}' is not valid for UTC timestamp " f"attribute '{attr_name}'; expected YYYY-MM-DD or ISO-8601 timestamp." ) if ( preserve_explicit_offset_str and "T" in stripped and _ISO_8601_TIMESTAMP_REGEX.fullmatch(stripped) ): parse_iso_datetime(stripped) return stripped return normalize_utc_timestamp_bound(stripped, is_end=is_end) raise ValueError( f"UTC timestamp attribute '{attr_name}' requires a date or ISO-8601 timestamp, got {val!r}." ) def _expand_allowed_attributes( allowed_attributes: Collection[str], ) -> tuple[frozenset[str], tuple[str, ...]]: """Return ``(accepted_keys, sorted_canonical_camel_keys)`` for an allowlist.""" canonical = sorted({_snake_to_camel(attr) for attr in allowed_attributes}) accepted = frozenset( set(allowed_attributes) | set(canonical) | {_camel_to_snake(attr) for attr in canonical} ) return accepted, tuple(canonical)
[docs]def validate_filter_key( key: str, *, model: type[Any] | None = None, allowed_attributes: Collection[str] | None = None, local_attributes: Collection[str] | None = None, ) -> None: """Validate that a filter key is non-empty, operator-free, and allowed. Args: key: The key string to validate. model: Optional Pydantic resource model class to validate attribute names against. allowed_attributes: Optional endpoint filter attribute allowlist. When provided, takes precedence over ``model`` attribute membership while preserving ``snake_case`` and ``camelCase`` forms. local_attributes: Optional client-side filter attributes accepted alongside ``allowed_attributes``. Raises: ValueError: If key is empty, contains whitespace or operator characters, or is not permitted by ``allowed_attributes`` / ``model``. """ if not isinstance(key, str) or not key or not key.strip(): raise ValueError("Filter key must be a non-empty string") if any(c.isspace() for c in key): raise ValueError(f"Filter key '{key}' cannot contain whitespace") if any(c in _OPERATOR_CHARS for c in key): raise ValueError(f"Filter key '{key}' cannot contain operator characters") if allowed_attributes is not None: effective_allowed: Collection[str] = ( set(allowed_attributes) | set(local_attributes) if local_attributes else allowed_attributes ) accepted, canonical = _expand_allowed_attributes(effective_allowed) if key not in accepted: valid_display = ", ".join(canonical) if canonical else "none" if key in ("study_key", "studyKey") and "studyKey" not in canonical: raise ValueError( "'study_key' and 'studyKey' cannot be used in --filter when " f"study_key is scoped to the command. Valid attributes: {valid_display}" ) target_name = model.__name__ if model is not None else "endpoint" raise ValueError( f"Unknown filter attribute '{key}' for {target_name}. " f"Valid attributes: {valid_display}" ) return if model is not None: valid_keys = _get_model_filter_keys(model) if valid_keys and key not in valid_keys: raise ValueError( f"Unknown filter attribute '{key}' for {model.__name__}. " f"Valid attributes: {', '.join(sorted(valid_keys))}" )
_VALID_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_.:-]*$") _CANDIDATE_OPERATORS: tuple[str, ...] = (*ORDERED_FILTER_OPERATORS, "=") def _find_operator(clause: str) -> tuple[int, str] | None: """Locate the first filter operator outside double quotes in a single clause.""" in_quotes = False escape = False length = len(clause) for idx, ch in enumerate(clause): if escape: escape = False continue if ch == "\\" and in_quotes: escape = True continue if ch == '"': in_quotes = not in_quotes continue if not in_quotes: for op in _CANDIDATE_OPERATORS: op_len = len(op) if clause.startswith(op, idx) and idx + op_len <= length: return idx, op return None def _unquote_filter_scalar(raw_value: str, err_ctx: str) -> tuple[str, bool]: """Validate double-quote escaping and return ``(text_value, was_quoted)``.""" if len(raw_value) >= 2 and raw_value.startswith('"') and raw_value.endswith('"'): escape = False for idx, ch in enumerate(raw_value[1:], start=1): if escape: escape = False continue if ch == "\\": escape = True continue if ch == '"' and idx != len(raw_value) - 1: raise ValueError( f"Invalid filter format: '{err_ctx}'. Unexpected quote inside value." ) inner = raw_value[1:-1] unescaped = inner.replace(r"\"", '"').replace("\\\\", "\\") return unescaped, True if '"' in raw_value: raise ValueError(f"Invalid filter format: '{err_ctx}'. Malformed quoted value.") return raw_value, False def _coerce_filter_scalar( raw_value: str, raw_arg: str = "", *, field_kind: str | None = None, field_name: str | None = None, ) -> tuple[str | bool | int | float, bool]: """Coerce quoted, boolean, and numeric string tokens using optional schema guidance.""" err_ctx = raw_arg or raw_value text_value, was_quoted = _unquote_filter_scalar(raw_value, err_ctx) attr_label = field_name or "attribute" if field_kind == "str": return text_value, was_quoted if field_kind == "int": if _ASCII_INT_RE.fullmatch(text_value): return int(text_value), False raise ValueError( f"Invalid filter format: '{err_ctx}'. " f"Invalid integer value '{text_value}' for attribute '{attr_label}'." ) if field_kind == "float": if _ASCII_FLOAT_RE.fullmatch(text_value): return float(text_value), False raise ValueError( f"Invalid filter format: '{err_ctx}'. " f"Invalid numeric value '{text_value}' for attribute '{attr_label}'." ) if field_kind == "bool": lowered_bool = text_value.lower() if lowered_bool == "true": return True, False if lowered_bool == "false": return False, False raise ValueError( f"Invalid filter format: '{err_ctx}'. " f"Invalid boolean value '{text_value}' for attribute '{attr_label}'; " "expected 'true' or 'false'." ) if was_quoted: return text_value, True lowered = text_value.lower() if lowered == "true": return True, False if lowered == "false": return False, False if _UNPADDED_ASCII_INT_RE.fullmatch(text_value): return int(text_value), False return text_value, False def _validate_expression_tokens(expr: str) -> None: """Validate quote balance, connector exclusivity, unquoted whitespace, and non-empty clauses.""" has_semi, has_comma, has_whitespace, in_quotes = _scan_filter_string(expr) if in_quotes: raise ValueError("Filter expression contains unclosed quotation marks") if has_semi and has_comma: raise ValueError("Filter expression cannot combine both ';' (AND) and ',' (OR) connectors") if has_whitespace: raise ValueError( "Filter expression contains whitespace between attribute, operator, and value" ) clauses, _ = _split_filter_clauses(expr.strip()) if any(not c for c in clauses): raise ValueError("Filter expression contains an empty clause") def _parse_single_clause( clause: str, raw_arg: str, *, model: type[Any] | None = None, allowed_attributes: Collection[str] | None = None, local_attributes: Collection[str] | None = None, allow_regex: bool = False, ) -> tuple[str, str, str | bool | int | float, bool]: """Parse ``key<op>value`` into ``(key, op, parsed_value, was_quoted)``.""" if not isinstance(clause, str) or not clause or not clause.strip(): raise ValueError( f"Invalid filter format: '{raw_arg}'. " "Use 'key=value' with non-empty key and value (e.g., 'form_key=DEMO')." ) found = _find_operator(clause) if found is None: raise ValueError( f"Invalid filter format: '{raw_arg}'. " "Use 'key=value' with non-empty key and value (e.g., 'form_key=DEMO')." ) op_idx, matched_op = found raw_key = clause[:op_idx] raw_value = clause[op_idx + len(matched_op) :] if not raw_key or not raw_key.strip() or not raw_value or not raw_value.strip(): raise ValueError( f"Invalid filter format: '{raw_arg}'. " "Key and value cannot be empty; use 'key=value' (e.g., 'form_key=DEMO')." ) try: _validate_expression_tokens(clause) except ValueError as exc: raise ValueError(f"Invalid filter format: '{raw_arg}'. {exc}") from exc allowed_ops = sorted(RECORD_DATA_OPERATORS if allow_regex else ALLOWED_OPERATORS) if raw_value.startswith(("=", "<", ">", "~", "!")): raise ValueError( f"Invalid filter format: '{raw_arg}'. " f"Unsupported comparison operator; allowed operators: {allowed_ops}." ) try: validate_filter_key( raw_key, model=model, allowed_attributes=allowed_attributes, local_attributes=local_attributes, ) except ValueError as exc: raise ValueError(f"Invalid filter format: '{raw_arg}'. {exc}") from exc if not _VALID_KEY_PATTERN.match(raw_key): raise ValueError( f"Invalid filter format: '{raw_arg}'. Invalid filter attribute '{raw_key}'." ) if matched_op != "=": try: validate_filter_operator(matched_op, allow_regex=allow_regex) except ValueError as exc: raise ValueError(f"Invalid filter format: '{raw_arg}'. {exc}") from exc field_kind: str | None = None if model is not None: field_kind = _get_model_field_types(model).get(raw_key) parsed_scalar, was_quoted = _coerce_filter_scalar( raw_value, raw_arg, field_kind=field_kind, field_name=raw_key, ) camel_key = _snake_to_camel(raw_key) effective_op = "==" if matched_op == "=" else matched_op if camel_key in CANONICAL_UTC_ATTRIBUTES: raw_text, _ = _unquote_filter_scalar(raw_value, raw_arg or raw_value) try: parsed_scalar = _compile_utc_timestamp_value( raw_text, op=effective_op, attr_name=raw_key, preserve_explicit_offset_str=False, ) except ValueError as exc: raise ValueError(f"Invalid filter format: '{raw_arg}'. {exc}") from exc was_quoted = False elif _is_visit_model(model) and camel_key in VISIT_SCHEDULE_DATE_ATTRIBUTES: raw_text, _ = _unquote_filter_scalar(raw_value, raw_arg or raw_value) try: parsed_scalar = _compile_visit_schedule_date_value(raw_text, attr_name=raw_key) except ValueError as exc: raise ValueError(f"Invalid filter format: '{raw_arg}'. {exc}") from exc was_quoted = False if raw_key == "status" and model is not None and getattr(model, "__name__", None) == "Query": if matched_op not in _ALLOWED_QUERY_STATUS_OPERATORS: raise ValueError( f"Invalid filter format: '{raw_arg}'. " f"Unsupported operator '{matched_op}' for Query status; " "allowed operators: ['!=', '=', '==']." ) raw_status_token, _ = _unquote_filter_scalar(raw_value, raw_arg or raw_value) try: parsed_scalar = coerce_query_status(raw_status_token).value except ValueError as exc: raise ValueError(f"Invalid filter format: '{raw_arg}'. {exc}") from exc if was_quoted and isinstance(parsed_scalar, str): parsed_scalar = _QuotedFilterStr(parsed_scalar) return raw_key, matched_op, parsed_scalar, was_quoted def _format_clause( key: str, op: str, val: str | bool | int | float, was_quoted: bool, *, model: type[Any] | None = None, ) -> str: """Format a parsed clause as a valid iMednet server filter segment.""" api_op = "==" if op == "=" else op camel_key = _snake_to_camel(key) if was_quoted and isinstance(val, str): escaped = val.replace("\\", "\\\\").replace('"', r"\"") return f'{camel_key}{api_op}"{escaped}"' return ( f"{camel_key}{api_op}" f"{_format_attribute_filter_value(val, camel_key=camel_key, key_label=key, op=api_op, model=model)}" )
[docs]def parse_filter_expression( filter_str: str, *, model: type[Any] | None = None, allowed_attributes: Collection[str] | None = None, local_attributes: Collection[str] | None = None, allow_regex: bool = False, ) -> tuple[str, Any]: """Parse a single filter expression string into ``(key, value_or_operator_tuple)``. Matches two-character comparison operators (``<=``, ``>=``, ``!=``, ``==``, and ``=~`` when ``allow_regex=True``) and single-character inequalities (``<``, ``>``) before single ``=`` equality shorthand per the iMednet Common API specification. Args: filter_str: Raw filter expression string. model: Optional Pydantic model class used for scalar coercion and fallback key checks. allowed_attributes: Optional endpoint filter attribute allowlist. local_attributes: Optional client-side filter attributes accepted alongside ``allowed_attributes``. allow_regex: Whether to permit ``=~`` (Table 7 ``recordDataFilter`` only). Returns: Tuple of ``(key, parsed_value)`` where ``parsed_value`` is ``(operator, scalar)`` for explicit operators or ``scalar`` for ``=`` shorthand. Raises: ValueError: If syntax, operator, or key validation fails. """ if isinstance(filter_str, str) and _split_filter_clauses(filter_str)[1] is not None: raise ValueError( f"Invalid filter format: '{filter_str}'. " "Expected a single 'key=value' filter expression." ) raw_key, matched_op, parsed_scalar, _ = _parse_single_clause( filter_str, filter_str, model=model, allowed_attributes=allowed_attributes, local_attributes=local_attributes, allow_regex=allow_regex, ) if matched_op == "=": return raw_key, parsed_scalar return raw_key, (matched_op, parsed_scalar)
[docs]def parse_filter_expressions( expressions: Sequence[str], *, model: type[Any] | None = None, allowed_attributes: Collection[str] | None = None, local_attributes: Collection[str] | None = None, allow_regex: bool = False, multi_bound_attributes: Collection[str] | None = None, ) -> dict[str, Any]: """Parse multiple filter expressions into a filter dictionary. Supports compound ``;`` (AND) and ``,`` (OR) expressions, quote-aware values, endpoint ``allowed_attributes`` allowlists, and resource ``model`` scalar coercion. Duplicate attributes in ``;`` (AND) clauses are rejected after normalizing ``snake_case`` to ``camelCase`` unless listed in ``multi_bound_attributes`` (which accumulate into ``list[tuple[str, Any]]``). Comma-separated OR expressions return ``{"filter": formatted_or_string}``. """ for arg in expressions: if not isinstance(arg, str) or not arg or not arg.strip(): raise ValueError( f"Invalid filter format: '{arg}'. " "Use 'key=value' with non-empty key and value (e.g., 'form_key=DEMO')." ) try: _validate_expression_tokens(arg) except ValueError as exc: raise ValueError(f"Invalid filter format: '{arg}'. {exc}") from exc combined_raw = ";".join(expressions) try: validate_connector_exclusivity(combined_raw) except ValueError as exc: raise ValueError(f"Invalid filter format: '{combined_raw}'. {exc}") from exc if any(_split_filter_clauses(arg)[1] == "," for arg in expressions): raw_arg = expressions[0] or_clauses, _ = _split_filter_clauses(raw_arg) parsed_or = [ _parse_single_clause( clause, raw_arg, model=model, allowed_attributes=allowed_attributes, local_attributes=local_attributes, allow_regex=allow_regex, ) for clause in or_clauses ] formatted = ",".join(_format_clause(*pc, model=model) for pc in parsed_or) try: _validate_filter_expression(formatted, allow_regex=allow_regex) except ValueError as exc: raise ValueError(f"Invalid filter format: '{raw_arg}'. {exc}") from exc return {"filter": formatted} multi_bound_set = ( frozenset(_snake_to_camel(attr) for attr in multi_bound_attributes) if multi_bound_attributes else frozenset() ) filter_dict: dict[str, Any] = {} canonical_to_key: dict[str, str] = {} seen_and_keys: set[str] = set() for expr in expressions: expr_clauses, _ = _split_filter_clauses(expr) for clause in expr_clauses: key, op, val, _ = _parse_single_clause( clause, expr, model=model, allowed_attributes=allowed_attributes, local_attributes=local_attributes, allow_regex=allow_regex, ) canonical_key = _snake_to_camel(key) if canonical_key in seen_and_keys: if canonical_key not in multi_bound_set: raise ValueError( f"Invalid filter format: '{expr}'. " f"Duplicate filter attribute '{canonical_key}' in AND clause." ) prev_key = canonical_to_key[canonical_key] prev_val = filter_dict.pop(prev_key) next_tuple = ("==", val) if op == "=" else (op, val) if isinstance(prev_val, list): prev_list = list(prev_val) elif isinstance(prev_val, tuple): prev_list = [prev_val] else: prev_list = [("==", prev_val)] prev_list.append(next_tuple) filter_dict[canonical_key] = prev_list canonical_to_key[canonical_key] = canonical_key continue seen_and_keys.add(canonical_key) canonical_to_key[canonical_key] = key filter_dict[key] = val if op == "=" else (op, val) return filter_dict
[docs]def validate_connector_exclusivity(filter_str: str) -> None: """Validate that a filter expression does not combine both ';' and ',' connectors. Connectors inside double quotation marks are ignored. The literal string 'none' (case-insensitive) bypasses validation. Args: filter_str: The filter expression string to validate. Raises: ValueError: If both ';' and ',' connectors appear outside quotation marks, or if quotation marks are unclosed. """ if not isinstance(filter_str, str): raise ValueError(f"Filter expression must be a string, got {type(filter_str).__name__}") stripped = filter_str.strip() if not stripped or stripped.lower() == "none": return has_semi, has_comma, _, in_quotes = _scan_filter_string(filter_str) if in_quotes: raise ValueError("Filter expression contains unclosed quotation marks") if has_semi and has_comma: raise ValueError("Filter expression cannot combine both ';' (AND) and ',' (OR) connectors")
def _validate_filter_expression(filter_str: str, *, allow_regex: bool) -> None: """Validate a filter or recordDataFilter expression.""" if not isinstance(filter_str, str): raise ValueError(f"Filter expression must be a string, got {type(filter_str).__name__}") stripped = filter_str.strip() if not stripped or stripped.lower() == "none": return has_semi, has_comma, has_whitespace, in_quotes = _scan_filter_string(filter_str) if in_quotes: raise ValueError("Filter expression contains unclosed quotation marks") if has_semi and has_comma: raise ValueError("Filter expression cannot combine both ';' (AND) and ',' (OR) connectors") if has_whitespace: raise ValueError( "Filter expression contains whitespace between attribute, operator, and value" ) clauses, connector = _split_filter_clauses(stripped) allowed = RECORD_DATA_OPERATORS if allow_regex else ALLOWED_OPERATORS seen_and_attrs: set[str] = set() for clause in clauses: if not clause: raise ValueError("Filter expression contains an empty clause") parsed = _parse_clause_operator(clause) if parsed is None: raise ValueError(f"Malformed filter clause '{clause}': missing comparison operator") attr, op, _ = parsed if op not in allowed: raise ValueError( f"Invalid filter operator '{op}'. Allowed operators: {sorted(allowed)}" ) if connector == ";": dedup_attr = attr if allow_regex else _snake_to_camel(attr) if dedup_attr in seen_and_attrs: raise ValueError(f"Duplicate filter attribute '{dedup_attr}' in AND clause") seen_and_attrs.add(dedup_attr)
[docs]def validate_filter_syntax(filter_str: str) -> None: """Validate a standard ``filter`` expression for syntax, operators, and uniqueness. Verifies connector exclusivity, ensures no whitespace exists outside of double-quoted strings, restricts operators to Table 2 (excluding ``=~``), and rejects duplicate attributes in ``;`` (AND) clauses. Args: filter_str: The filter expression string to validate. Raises: ValueError: If syntax, operator, or attribute uniqueness rules are violated. """ _validate_filter_expression(filter_str, allow_regex=False)
[docs]def validate_record_filter(filter_str: str) -> None: """Validate a ``recordDataFilter`` expression for syntax, operators, and uniqueness. Allows ``=~`` per Common API Table 7 while enforcing connector exclusivity, quote/whitespace rules, and unique attributes in ``;`` (AND) clauses. Args: filter_str: The recordDataFilter expression string to validate. Raises: ValueError: If syntax, operator, or attribute uniqueness rules are violated. """ _validate_filter_expression(filter_str, allow_regex=True)
def _format_filter_value(val: Any) -> str: """Format a single filter value, escaping if necessary.""" if val is None: raise ValueError("Filter value cannot be None") if isinstance(val, bool): return "true" if val else "false" if isinstance(val, (dict, set, list, tuple)): raise ValueError(f"Invalid filter value type: {type(val).__name__}") if isinstance(val, datetime): return format_iso_datetime(val) if isinstance(val, date): return val.isoformat() if isinstance(val, str): if val == "" or isinstance(val, _QuotedFilterStr): escaped = val.replace("\\", "\\\\").replace('"', r"\"") return f'"{escaped}"' if _ISO_8601_TIMESTAMP_REGEX.match(val): return val if _UNSAFE_CHARS_REGEX.search(val): # Escape backslashes first to prevent escape injection escaped = val.replace("\\", "\\\\").replace('"', r"\"") return f'"{escaped}"' return val return str(val)
[docs]def compile_raw_filter_expression( filter_str: str, *, model: type[Any] | None = None, ) -> str: """Validate and compile a raw ``filter`` string, normalizing connectors and date bounds.""" validate_filter_syntax(filter_str) stripped = filter_str.strip() if not stripped or stripped.lower() == "none": return "" clauses, connector = _split_filter_clauses(stripped) compiled_clauses: list[str] = [] for clause in clauses: parsed = _parse_clause_operator(clause) if parsed is None: raise ValueError(f"Malformed filter clause '{clause}': missing comparison operator") attr, op, raw_rhs = parsed camel_attr = _snake_to_camel(attr) if camel_attr in CANONICAL_UTC_ATTRIBUTES: text_rhs, _ = _unquote_filter_scalar(raw_rhs, clause) compiled_rhs = _compile_utc_timestamp_value(text_rhs, op=op, attr_name=attr) compiled_clauses.append(f"{attr}{op}{compiled_rhs}") elif _is_visit_model(model) and camel_attr in VISIT_SCHEDULE_DATE_ATTRIBUTES: text_rhs, _ = _unquote_filter_scalar(raw_rhs, clause) compiled_rhs = _compile_visit_schedule_date_value(text_rhs, attr_name=attr) compiled_clauses.append(f"{attr}{op}{compiled_rhs}") else: compiled_clauses.append(clause) if connector is None: return compiled_clauses[0] return connector.join(compiled_clauses)
def _format_attribute_filter_value( val: Any, *, camel_key: str, key_label: str, op: str, model: type[Any] | None = None, ) -> str: """Format a filter value according to attribute-specific UTC or Visit date rules.""" if val is None: raise ValueError("Filter value cannot be None") if isinstance(val, (dict, set, list, tuple)): raise ValueError(f"Invalid filter value type: {type(val).__name__}") if isinstance(val, _QuotedFilterStr): return _format_filter_value(val) if camel_key in CANONICAL_UTC_ATTRIBUTES: return _compile_utc_timestamp_value( val, op=op, attr_name=key_label, preserve_explicit_offset_str=(model is None), ) if _is_visit_model(model) and camel_key in VISIT_SCHEDULE_DATE_ATTRIBUTES: return _compile_visit_schedule_date_value(val, attr_name=key_label) return _format_filter_value(val) def _build_filter_part( key: str, value: Any | tuple[str, Any] | list[Any], and_connector: str = ";", or_connector: str = ",", *, model: type[Any] | None = None, ) -> str: """Build a single filter string part from a key and value.""" validate_filter_key(key) camel_key = _snake_to_camel(key) if isinstance(value, tuple): if len(value) != 2: raise ValueError( f"Filter tuple for '{key}' must have exactly 2 elements (operator, value), got {len(value)}" ) op, val = value validate_filter_operator(op) formatted_val = _format_attribute_filter_value( val, camel_key=camel_key, key_label=key, op=op, model=model ) return f"{camel_key}{op}{formatted_val}" if isinstance(value, list): if value and any(isinstance(item, tuple) for item in value): if not all(isinstance(item, tuple) for item in value): raise ValueError( f"Filter list for '{key}' cannot mix operator tuples and scalar values" ) tuple_parts: list[str] = [] for item in value: if len(item) != 2: raise ValueError( f"Filter tuple for '{key}' must have exactly 2 elements (operator, value), got {len(item)}" ) op, val = item validate_filter_operator(op) formatted_val = _format_attribute_filter_value( val, camel_key=camel_key, key_label=key, op=op, model=model ) tuple_parts.append(f"{camel_key}{op}{formatted_val}") if len(tuple_parts) > 1 and and_connector.strip().lower() in (";", "and"): raise ValueError(f"Duplicate filter attribute '{camel_key}' in AND clause") return and_connector.join(tuple_parts) subparts = [ f"{camel_key}==" f"{_format_attribute_filter_value(v, camel_key=camel_key, key_label=key, op='==', model=model)}" for v in value ] return or_connector.join(subparts) formatted_val = _format_attribute_filter_value( value, camel_key=camel_key, key_label=key, op="==", model=model ) return f"{camel_key}=={formatted_val}"
[docs]def build_filter_string( filters: dict[str, Any | tuple[str, Any] | list[Any]], and_connector: str = ";", or_connector: str = ",", *, model: type[Any] | None = None, ) -> str: """Return a filter string constructed according to iMednet rules. Each key in ``filters`` is converted to camelCase. Raw values imply equality, tuples allow explicit operators, lists of ``(operator, value)`` tuples on one key join with ``and_connector``, and lists of scalars generate multiple equality filters joined by ``or_connector``. Conditions across keys are joined by ``and_connector``. Example: >>> from imednet.utils.filters import build_filter_string >>> build_filter_string({'age': ('>', 30), 'status': 'active'}) 'age>30;status==active' >>> build_filter_string({'type': ['A', 'B']}) 'type==A,type==B' """ seen_keys: set[str] = set() check_duplicates = and_connector.strip().lower() in (";", "and") parts: list[str] = [] for key, value in filters.items(): validate_filter_key(key) camel_key = _snake_to_camel(key) if check_duplicates: if camel_key in seen_keys: raise ValueError(f"Duplicate filter attribute '{camel_key}' in AND clause") seen_keys.add(camel_key) parts.append( _build_filter_part( key, value, and_connector=and_connector, or_connector=or_connector, model=model, ) ) non_empty_parts = [part for part in parts if part] result = and_connector.join(non_empty_parts) validate_connector_exclusivity(result) return result
QUERY_STATUS_ATTRIBUTES: frozenset[str] = frozenset({"status"}) _ALLOWED_QUERY_STATUS_OPERATORS: frozenset[str] = frozenset({"==", "=", "!="})
[docs]def coerce_query_status(val: Any, *, param_name: str = "status") -> Any: """Coerce *val* into a validated ``QueryStatus`` enum member.""" from imednet.models.queries import QueryStatus if isinstance(val, QueryStatus): return val if isinstance(val, str) and val.strip(): try: return QueryStatus(val) except (ValueError, KeyError) as exc: valid = ", ".join(s.value for s in QueryStatus) raise ValueError(f"Invalid {param_name} '{val}'. Valid statuses: {valid}") from exc valid = ", ".join(s.value for s in QueryStatus) raise ValueError(f"Invalid {param_name} '{val}'. Valid statuses: {valid}")
[docs]def resolve_query_status(query: Any) -> Any: """Resolve ``QueryStatus`` from explicit model/dict status or ``queryComments``.""" from collections.abc import Mapping from imednet.models.queries import QueryStatus, calculate_legacy_status if isinstance(query, Mapping): raw_status = query.get("status") comments = query.get("query_comments") if comments is None: comments = query.get("queryComments") else: raw_status = getattr(query, "status", None) comments = getattr(query, "query_comments", None) if comments is None: comments = getattr(query, "queryComments", None) if isinstance(raw_status, QueryStatus): return raw_status if isinstance(raw_status, str) and raw_status.strip(): try: return QueryStatus(raw_status) except ValueError: pass return calculate_legacy_status(comments)
def _eval_single_query_status(actual: Any, op: str, target: Any) -> bool: """Evaluate a single ``(op, target)`` status predicate against ``actual``.""" if op in ("==", "="): if isinstance(target, tuple): return actual in target return bool(actual == target) if op in ("!=", "<>"): return bool(actual != target) raise ValueError(f"Unsupported status filter operator: {op!r}")
[docs]def matches_query_status_bounds( item: Any, local_predicates: Sequence[tuple[str, Any]], ) -> bool: """Return True when *item* satisfies all local ``(op, target)`` status predicates.""" if not local_predicates: return True actual = resolve_query_status(item) for op, target in local_predicates: if op == "or": if not any( _eval_single_query_status(actual, sub_op, sub_val) for sub_op, sub_val in target ): return False continue if not _eval_single_query_status(actual, op, target): return False return True
def _validate_status_operator(op: str, *, ctx: str | None = None) -> str: """Validate comparison operator for discrete ``QueryStatus`` predicates.""" if op != "=": validate_filter_operator(op) if op not in _ALLOWED_QUERY_STATUS_OPERATORS: prefix = f"Invalid filter format: '{ctx}'. " if ctx else "" raise ValueError( f"{prefix}Unsupported operator '{op}' for Query status; " "allowed operators: ['!=', '=', '==']." ) return "==" if op == "=" else op def _extract_kwarg_query_status_predicates(raw_val: Any) -> list[tuple[str, Any]]: """Convert a ``status`` keyword argument into local ``(op, target)`` predicates.""" if isinstance(raw_val, tuple): if len(raw_val) != 2: raise ValueError( f"Filter tuple for 'status' must have exactly 2 elements " f"(operator, value), got {len(raw_val)}" ) op, val = raw_val norm_op = _validate_status_operator(op) return [(norm_op, coerce_query_status(val))] if isinstance(raw_val, list): if not raw_val: raise ValueError("Filter list for 'status' cannot be empty") if any(isinstance(item, tuple) for item in raw_val): if not all(isinstance(item, tuple) for item in raw_val): raise ValueError( "Filter list for 'status' cannot mix operator tuples and scalar values" ) predicates: list[tuple[str, Any]] = [] for item in raw_val: if len(item) != 2: raise ValueError( f"Filter tuple for 'status' must have exactly 2 elements " f"(operator, value), got {len(item)}" ) op, val = item norm_op = _validate_status_operator(op) predicates.append((norm_op, coerce_query_status(val))) return predicates coerced_or = tuple(coerce_query_status(item) for item in raw_val) return [("==", coerced_or)] return [("==", coerce_query_status(raw_val))]
[docs]def split_query_status_filters( filters: dict[str, Any] | Any, ) -> tuple[dict[str, Any], list[tuple[str, Any]]]: """Split client-side ``status`` predicates from upstream ``QueriesEndpoint`` filters.""" working = dict(filters) local_predicates: list[tuple[str, Any]] = [] if "status" in working: raw_status_kwarg = working.pop("status") if raw_status_kwarg is not None: local_predicates.extend(_extract_kwarg_query_status_predicates(raw_status_kwarg)) else: raise ValueError("Filter value cannot be None") raw_filter = working.get("filter") has_active_raw_filter = ( isinstance(raw_filter, str) and bool(raw_filter.strip()) and raw_filter.strip().lower() != "none" ) if not has_active_raw_filter or not isinstance(raw_filter, str): return working, local_predicates if "status" not in extract_filter_attributes(raw_filter): validate_filter_syntax(raw_filter) return working, local_predicates has_semi, has_comma, has_ws, in_quotes = _scan_filter_string(raw_filter) if in_quotes: raise ValueError("Filter expression contains unclosed quotation marks") if has_semi and has_comma: raise ValueError("Filter expression cannot combine both ';' (AND) and ',' (OR) connectors") if has_ws: raise ValueError( "Filter expression contains whitespace between attribute, operator, and value" ) clauses, connector = _split_filter_clauses(raw_filter.strip()) if any(not c for c in clauses): raise ValueError("Filter expression contains an empty clause") if connector == ",": or_status_pairs: list[tuple[str, Any]] = [] has_upstream_or = False for clause in clauses: parsed = _parse_clause_operator(clause) if parsed is None: raise ValueError(f"Invalid filter format: '{clause}'. Missing comparison operator.") attr, op, raw_rhs = parsed if _snake_to_camel(attr) == "status": norm_op = _validate_status_operator(op, ctx=clause) unquoted_rhs, _ = _unquote_filter_scalar(raw_rhs, clause) or_status_pairs.append((norm_op, coerce_query_status(unquoted_rhs))) else: if op not in ALLOWED_OPERATORS: raise ValueError( f"Invalid filter operator '{op}'. " f"Allowed operators: {sorted(ALLOWED_OPERATORS)}" ) has_upstream_or = True if has_upstream_or: raise ValueError( "Cannot combine client-side 'status' filter with upstream attributes " "in an OR (',') expression; use ';' (AND) instead." ) working.pop("filter", None) local_predicates.append(("or", tuple(or_status_pairs))) return working, local_predicates upstream_clauses: list[str] = [] seen_upstream_attrs: set[str] = set() for clause in clauses: parsed = _parse_clause_operator(clause) if parsed is None: raise ValueError(f"Malformed filter clause '{clause}': missing comparison operator") attr, op, raw_rhs = parsed camel_attr = _snake_to_camel(attr) if camel_attr == "status": norm_op = _validate_status_operator(op, ctx=clause) unquoted_rhs, _ = _unquote_filter_scalar(raw_rhs, clause) local_predicates.append((norm_op, coerce_query_status(unquoted_rhs))) else: if op not in ALLOWED_OPERATORS: raise ValueError( f"Invalid filter operator '{op}'. " f"Allowed operators: {sorted(ALLOWED_OPERATORS)}" ) if camel_attr in seen_upstream_attrs: raise ValueError(f"Duplicate filter attribute '{camel_attr}' in AND clause") seen_upstream_attrs.add(camel_attr) upstream_clauses.append(clause) if upstream_clauses: working["filter"] = ";".join(upstream_clauses) else: working.pop("filter", None) return working, local_predicates
from ._revision_filters import ( REVISION_DATE_ATTRIBUTES, matches_revision_date_bound, matches_revision_date_bounds, parse_revision_timestamp_utc, split_revision_date_bounds, ) __all__ = [ "ALLOWED_OPERATORS", "CANONICAL_UTC_ATTRIBUTES", "ORDERED_FILTER_OPERATORS", "QUERY_STATUS_ATTRIBUTES", "RECORD_DATA_OPERATORS", "REVISION_DATE_ATTRIBUTES", "VISIT_SCHEDULE_DATE_ATTRIBUTES", "build_filter_string", "coerce_query_status", "compile_raw_filter_expression", "compile_sort_parameter", "derive_model_sort_attributes", "extract_filter_attributes", "matches_query_status_bounds", "matches_revision_date_bound", "matches_revision_date_bounds", "normalize_filter_connectors", "parse_filter_expression", "parse_filter_expressions", "parse_revision_timestamp_utc", "resolve_query_status", "split_query_status_filters", "split_revision_date_bounds", "validate_connector_exclusivity", "validate_filter_key", "validate_filter_operator", "validate_filter_syntax", "validate_record_filter", ]