Source code for s365b.core.selection
"""Choosing item versions: as they were at a time, matching a search.
Browse and restore use the same filters, so a restore takes exactly what
the person saw.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy import and_, func, or_, select
from s365b.db.models import ItemVersionRow
[docs]
def at_time(at: datetime) -> Any:
"""Versions that were current at ``at``."""
return and_(
ItemVersionRow.valid_from <= at,
or_(ItemVersionRow.valid_to.is_(None), ItemVersionRow.valid_to > at),
)
[docs]
def escape_like(text: str) -> str:
"""Escape LIKE wildcards (percent, underscore) and the backslash escape character."""
return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
[docs]
def matches(q: str) -> Any:
"""Versions whose name or any metadata value contains ``q`` (any case)."""
pattern = f"%{escape_like(q)}%"
kv = func.jsonb_each_text(ItemVersionRow.meta).table_valued("key", "value").alias("kv")
in_meta = select(1).select_from(kv).where(kv.c.value.ilike(pattern, escape="\\")).exists()
return or_(ItemVersionRow.name.ilike(pattern, escape="\\"), in_meta)
[docs]
def in_folder(path: str, *, subfolders: bool) -> Any:
"""Versions in the folder ``path`` (and, if asked, the folders below it)."""
if not subfolders:
return ItemVersionRow.path == path
return or_(
ItemVersionRow.path == path,
ItemVersionRow.path.like(f"{escape_like(path)}/%", escape="\\"),
)