Coverage for src/scixplorer/solr.py: 99%
129 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""Compile expressions to Solr query strings.
3This module is the only place that knows Solr quoting, escaping and range
4syntax. It is pure: no I/O, and the output depends only on the expression.
5"""
7from __future__ import annotations
9import re
10from collections.abc import Iterable
11from typing import Any, NamedTuple
13from .exceptions import QueryError
14from .expr import (
15 And,
16 Constant,
17 Expr,
18 Func,
19 In,
20 InLibrary,
21 Like,
22 Match,
23 Not,
24 Or,
25 Order,
26 Quantified,
27 Range,
28 Raw,
29 Related,
30 SolrLiteral,
31 Wildcard,
32 parse_pattern,
33)
34from .fields import DateTimeField, Field, NameField, StringField, TextField, VirtualField
36__all__ = ["QUOTED_FIELD_TYPES", "compile", "compile_order", "format_value", "quote"]
38#: Field types whose values are written as double-quoted phrases. Values of all
39#: other field types are written bare. ``SolrLiteral`` values are always bare.
40QUOTED_FIELD_TYPES: tuple[type[Field[Any, Any]], ...] = (
41 TextField,
42 StringField,
43 NameField,
44 VirtualField,
45 DateTimeField,
46)
48#: Match kinds that ADS expands by default, so that ``exact`` must be sent as
49#: ``=field:``. On other kinds ``=`` is unnecessary (and breaks ``=bibcode:``).
50EXPANDED_MATCH_KINDS = frozenset({"text", "name"})
52_LUCENE_SPECIALS = re.compile(r'([+\-&|!(){}\[\]^"~:\\/*?])')
53_WHITESPACE = re.compile(r"\s")
56class _Fragment(NamedTuple):
57 """Compiled text, and whether it is a boolean group needing parentheses when nested."""
59 text: str
60 compound: bool = False
63_EVERYTHING = _Fragment("*:*")
64_NOTHING = _Fragment("*:* AND -*:*", compound=True)
67def compile(expr: Expr) -> str:
68 """Compile a resolved expression to a Solr query string.
70 Raises :class:`~scixplorer.exceptions.QueryError` for unresolved ``Related`` and
71 ``Quantified`` nodes.
72 """
73 return _compile(expr).text
76def compile_order(orders: Iterable[Order]) -> str | None:
77 """Return the Solr ``sort`` parameter for ``orders``, or ``None`` if there are none."""
78 keys = [f"{order.field.solr_name} {'desc' if order.descending else 'asc'}" for order in orders]
79 return ",".join(keys) or None
82def quote(text: str) -> str:
83 """Double-quote ``text``, escaping backslashes and then double quotes."""
84 return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
87def format_value(field: Field[Any, Any], value: Any) -> str:
88 """Format one value of ``field`` for a query: the single place quoting is decided."""
89 if isinstance(value, SolrLiteral):
90 return value.text
91 text = field.to_solr(value)
92 return quote(text) if isinstance(field, QUOTED_FIELD_TYPES) else text
95def _compile(expr: Expr) -> _Fragment:
96 if isinstance(expr, And):
97 return _compile_and(expr.operands)
98 if isinstance(expr, Or):
99 return _compile_or(expr.operands)
100 if isinstance(expr, Not):
101 return _compile_and((expr,))
102 if isinstance(expr, Constant):
103 return _EVERYTHING if expr.value else _NOTHING
104 if isinstance(expr, Match):
105 prefix = "=" if _sends_exact(expr.field, expr.exact) else ""
106 return _Fragment(f"{prefix}{expr.field.solr_name}:{format_value(expr.field, expr.value)}")
107 if isinstance(expr, In):
108 return _compile_in(expr)
109 if isinstance(expr, Like):
110 return _Fragment(f"{expr.field.solr_name}:{_compile_pattern(expr.pattern)}")
111 if isinstance(expr, Range):
112 return _compile_range(expr)
113 if isinstance(expr, Func):
114 return _compile_func(expr)
115 if isinstance(expr, InLibrary):
116 return _Fragment(f"docs(library/{expr.library_id})")
117 if isinstance(expr, Raw):
118 return _Fragment(expr.query, compound=True)
119 if isinstance(expr, Related):
120 raise QueryError(
121 f"Cannot compile an unresolved relation ({expr.relation!r}); "
122 f"the planner must resolve it first"
123 )
124 if isinstance(expr, Quantified): 124 ↛ 129line 124 didn't jump to line 129 because the condition on line 124 was always true
125 raise QueryError(
126 f"Cannot compile an unresolved per-record condition ({expr.collection.label(expr.positions)}."
127 f"{expr.quantifier}(...)); the planner must translate it first"
128 )
129 raise TypeError(f"Cannot compile {expr!r}")
132def _operand(expr: Expr) -> str:
133 """Compile an operand of a boolean group, parenthesising nested groups."""
134 fragment = _compile(expr)
135 return f"({fragment.text})" if fragment.compound else fragment.text
138def _compile_and(operands: tuple[Expr, ...]) -> _Fragment:
139 """Compile a conjunction. ``Not`` operands become ``-clause``.
141 Solr cannot evaluate a purely negative group, so if every operand is a
142 ``Not`` the group is anchored with ``*:*``. A ``Not`` anywhere else is
143 compiled as the one-operand conjunction ``*:* AND -clause``.
144 """
145 if not operands:
146 return _EVERYTHING
147 if len(operands) == 1 and not isinstance(operands[0], Not):
148 return _compile(operands[0])
149 clauses = [
150 "-" + _operand(op.operand) if isinstance(op, Not) else _operand(op) for op in operands
151 ]
152 if all(isinstance(op, Not) for op in operands):
153 clauses.insert(0, _EVERYTHING.text)
154 return _Fragment(" AND ".join(clauses), compound=True)
157def _compile_or(operands: tuple[Expr, ...]) -> _Fragment:
158 if not operands:
159 return _NOTHING
160 if len(operands) == 1:
161 return _compile(operands[0])
162 return _Fragment(" OR ".join(_operand(op) for op in operands), compound=True)
165def _sends_exact(field: Field[Any, Any], exact: bool) -> bool:
166 """Whether an exact match on ``field`` needs the ``=`` prefix."""
167 return exact and field.match_kind in EXPANDED_MATCH_KINDS
170def _compile_in(expr: In) -> _Fragment:
171 if not expr.values:
172 return _NOTHING
173 if len(expr.values) == 1:
174 return _compile(Match(expr.field, expr.values[0], expr.exact))
175 if _sends_exact(expr.field, expr.exact):
176 return _compile_or(tuple(Match(expr.field, value, True) for value in expr.values))
177 values = " OR ".join(format_value(expr.field, value) for value in expr.values)
178 return _Fragment(f"{expr.field.solr_name}:({values})")
181def _compile_range(expr: Range) -> _Fragment:
182 """Compile a range. Solr ranges here are inclusive, so exclusive bounds are lowered.
184 Discrete fields (see ``Field.step``) move the bound to the adjacent value: an
185 integer by one, a month-precision date by a month. Any other exclusive bound
186 becomes an inclusive range that excludes the bound value, compiled as
187 ``And(inclusive range, Not(Match(field, bound)))``.
188 """
189 field = expr.field
190 lo, hi = expr.lo, expr.hi
191 excluded: list[Any] = []
192 if lo is not None and not expr.include_lo:
193 stepped = field.step(lo, 1)
194 if stepped is None:
195 excluded.append(lo)
196 else:
197 lo = stepped
198 if hi is not None and not expr.include_hi:
199 stepped = field.step(hi, -1)
200 if stepped is None:
201 excluded.append(hi)
202 else:
203 hi = stepped
204 if excluded:
205 return _compile_and((Range(field, lo, hi), *(Not(Match(field, v)) for v in excluded)))
206 lo_text = "*" if lo is None else format_value(field, lo)
207 hi_text = "*" if hi is None else format_value(field, hi)
208 return _Fragment(f"{field.solr_name}:[{lo_text} TO {hi_text}]")
211def _compile_func(expr: Func) -> _Fragment:
212 args = expr.args
213 if expr.name == "pos" and len(args) == 3 and args[1] == args[2]:
214 args = args[:2]
215 return _Fragment(f"{expr.name}({', '.join(_func_arg(arg) for arg in args)})")
218def _func_arg(arg: Any) -> str:
219 if isinstance(arg, Expr):
220 return _compile(arg).text
221 if isinstance(arg, Order):
222 return f"{arg.field.solr_name} {'desc' if arg.descending else 'asc'}"
223 return str(arg)
226def _compile_pattern(pattern: str) -> str:
227 """Compile a wildcard pattern.
229 A pattern containing whitespace is written as a quoted phrase (escaping
230 backslashes and double quotes); otherwise as a single term with Lucene
231 special characters backslash-escaped. Literal ``*`` and ``?`` are escaped in
232 both forms; wildcards are kept.
233 """
234 tokens = parse_pattern(pattern)
235 phrase = any(isinstance(t, str) and _WHITESPACE.search(t) for t in tokens)
236 parts = []
237 for token in tokens:
238 if isinstance(token, Wildcard):
239 parts.append(token.value)
240 elif phrase:
241 parts.append(re.sub(r'([\\"*?])', r"\\\1", token))
242 else:
243 parts.append(_LUCENE_SPECIALS.sub(r"\\\1", token))
244 body = "".join(parts)
245 return f'"{body}"' if phrase else body