Skip to main content

utopia_query/builder/
flavor.rs

1//! Builder extensions a library on top of this one compiles with, set on a
2//! builder rather than subclassed: a [`Flavor`] changes how some filters
3//! compile, and a [`Scope`] makes `from()` take a collection id.
4//!
5//! PHP subclasses the builders for these (`Utopia\Database\Builder\MySQL`,
6//! `MariaDB`, `Postgres` and `SQLite` override protected compile methods and
7//! use the `ScopesCollections` trait). Rust builders are generic over their
8//! dialect, so the subclasses' behaviour is opt-in state on the builder,
9//! which [`Builder::reset`] keeps:
10//!
11//! | PHP (`utopia-php/database`) | Rust |
12//! |---|---|
13//! | `Builder\PreparesSearchTerms` | [`Flavor::search_terms`] |
14//! | `Builder\MatchesContainsAllPatterns` | [`Flavor::contains_all_patterns`] |
15//! | `Builder\CompilesAggregates` | [`Flavor::compiles_aggregates`] |
16//! | `Builder\Postgres::compileFilter()` (object paths) | [`Flavor::object_path`] |
17//! | `Builder\Postgres::compileSpatialFilter()` | [`Flavor::indexed_distance`] |
18//! | `Builder\SQLite` | [`Flavor::sqlite`] ([`SqliteFlavor`]) |
19//! | `Builder\CollatesDocumentIds` (`SQLite`, `Postgres`) | [`Flavor::ids`] ([`IdCollation`]) |
20//! | `Builder\CompilesFilters`, `Builder\Filtering` | [`Builder::compile_filters`] |
21//! | `Builder\Scope` | [`Scope`] |
22//! | `Builder\ScopesCollections`, `Builder\Scoping`, `Builder\RefusesJoinedWrites` | [`Builder::scope`], [`Builder::is_scoped`], [`Builder::from_table`] and the checks of `from()`, `into()`, `build()` and the multi-table writes |
23//!
24//! PHP throws from `from()`, `into()` and the multi-table writes when a
25//! scoped builder refuses them; these return the builder here, so the
26//! refusal is kept and returned by the next statement the builder compiles
27//! (`build()`, `insert()`, `update()`, `delete()`, `upsert()`, ...).
28
29use std::sync::Arc;
30
31use php_std::pcre::{StrOrArray, preg_replace};
32
33use crate::builder::core::{Builder, Dialect};
34use crate::builder::steps::{Arg, Step};
35use crate::builder::types::{Condition, Statement};
36use crate::error::{Error, Result};
37use crate::hook::Hook;
38use crate::method::Method;
39use crate::query::Query;
40use crate::value::{self, Array, Value};
41
42/// A check of a path into an object attribute (see [`Flavor::object_path`]).
43pub type ObjectPathCheck = Arc<dyn Fn(&str) -> Result<()> + Send + Sync>;
44
45/// How a builder compiles some filters, as `utopia-php/database`'s builder
46/// subclasses do. The default compiles as this library does.
47#[derive(Clone, Default)]
48pub struct Flavor {
49    /// Prepares full-text search terms as 7.x did: every character other
50    /// than a letter, a number, an underscore or whitespace separates words,
51    /// and a term wrapped in double quotes stays an exact search (MySQL,
52    /// MariaDB, PostgreSQL).
53    ///
54    /// PHP: `Utopia\Database\Builder\PreparesSearchTerms`.
55    pub search_terms: bool,
56    /// `containsAll()` on an attribute that is not an array matches as 7.x
57    /// did: each value is a `LIKE` pattern on the whole value, and a row
58    /// matching any one of them is returned (MySQL, MariaDB, PostgreSQL).
59    ///
60    /// PHP: `Utopia\Database\Builder\MatchesContainsAllPatterns`.
61    pub contains_all_patterns: bool,
62    /// Compiles the aggregates MySQL and MariaDB answer differently from the
63    /// other engines. Each floating aggregate (`sum`, `avg`, the variances
64    /// and, through `SQRT()` of a variance, the deviations) compiles through
65    /// the engine's float range check, `+ 0`, which raises an error for a
66    /// value that is not finite: both send a `DOUBLE` aggregate that
67    /// overflowed as `0` over the text protocol, and turn an infinite or
68    /// undefined variance into `DBL_MAX` or `NULL` under `STDDEV`. Each
69    /// bitwise aggregate is cast to `SIGNED`: both answer `BIT_AND`,
70    /// `BIT_OR` and `BIT_XOR` as `BIGINT UNSIGNED`, and the cast reads the
71    /// same 64 bits as the two's complement integer PostgreSQL answers. An
72    /// unaliased aggregate keeps the name the engine gave it.
73    ///
74    /// PHP: `Utopia\Database\Builder\CompilesAggregates` (8.3.4; until
75    /// then `RaisesFloatOverflow`, without the bitwise cast).
76    pub compiles_aggregates: bool,
77    /// Checks the path of a filter into an object attribute
78    /// (`attribute.key.key`) before it compiles (PostgreSQL); its error is
79    /// the filter's.
80    ///
81    /// PHP: `Utopia\Database\Builder\Postgres::compileFilter()`.
82    pub object_path: Option<ObjectPathCheck>,
83    /// `distanceLessThan()` leads with a predicate the spatial index serves,
84    /// in this SRID (PostgreSQL).
85    ///
86    /// PHP: `Utopia\Database\Builder\Postgres::compileSpatialFilter()`.
87    pub indexed_distance: Option<i64>,
88    /// SQLite's overrides.
89    pub sqlite: Option<SqliteFlavor>,
90    /// Compares document ids in the collation of their unique indexes
91    /// (SQLite, PostgreSQL).
92    ///
93    /// PHP: `Utopia\Database\Builder\CollatesDocumentIds`.
94    pub ids: Option<IdCollation>,
95}
96
97impl std::fmt::Debug for Flavor {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("Flavor")
100            .field("search_terms", &self.search_terms)
101            .field("contains_all_patterns", &self.contains_all_patterns)
102            .field("compiles_aggregates", &self.compiles_aggregates)
103            .field("object_path", &self.object_path.is_some())
104            .field("indexed_distance", &self.indexed_distance)
105            .field("sqlite", &self.sqlite)
106            .field("ids", &self.ids)
107            .finish()
108    }
109}
110
111/// SQLite as `utopia-php/database` compiles it: every `LIKE` declares the
112/// backslash escape, `REGEXP` calls the user function the adapter
113/// registers, and array filters match JSON elements. Its id columns compare
114/// in their collation through [`Flavor::ids`].
115///
116/// PHP: `Utopia\Database\Builder\SQLite`.
117#[derive(Debug, Clone, Default, PartialEq, Eq)]
118pub struct SqliteFlavor;
119
120/// Document ids are unique in the collation of their unique indexes, and an
121/// engine only uses an index for a comparison made in the index's
122/// collation, so equality on an id column (`IN`, `NOT IN`), and an `=`,
123/// `!=` or `<>` of a join's ON on id columns, compares in that collation.
124///
125/// PHP: `Utopia\Database\Builder\CollatesDocumentIds`, with the using
126/// builder's `COLLATION`, `isCollated()` and `collatesJoin()`.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct IdCollation {
129    /// The collation (`NOCASE` on SQLite, `utf8_ci_ai` on PostgreSQL).
130    pub collation: String,
131    /// The columns compared in it, by the last segment of their resolved
132    /// name (`_uid`, and `_document` where its index is collated).
133    pub collated_columns: Vec<String>,
134    /// Whether a join comparison is collated only when both sides are id
135    /// columns (PostgreSQL: a plain column such as a relationship key has an
136    /// index in the default collation, which a collated comparison could not
137    /// use), rather than when either is (SQLite).
138    pub join_both_sides: bool,
139}
140
141/// How a builder's `from()` reads a collection: the table it is stored
142/// under, and the hooks that map its attributes to columns and keep its
143/// statements to a tenant.
144///
145/// PHP: `Utopia\Database\Builder\Scope`.
146pub trait Scope: Send + Sync {
147    /// The name the collection's table is stored under (`table()`).
148    fn table(&self, collection: &str) -> String;
149
150    /// The name a builder that read a collection through this scope joins
151    /// `table` under (`joinTable()`).
152    fn join_table(&self, table: &str) -> String;
153
154    /// The hooks for statements over the collection, stored as `table` and
155    /// named `alias` in them when one is given, and what the builder runs
156    /// before each statement it builds, which `reset()` does not clear
157    /// (`bind()`).
158    fn bind(&self, collection: &str, table: &str, alias: &str) -> Result<ScopeBinding>;
159
160    /// The error a scoped builder refuses a call with (PHP throws
161    /// `Utopia\Database\Exception\Query`); a plain query error by default.
162    fn error(&self, message: String) -> Error {
163        Error::new(message, 0)
164    }
165}
166
167/// What [`Scope::bind`] registers on a builder.
168#[derive(Clone, Default)]
169pub struct ScopeBinding {
170    /// The hooks to add.
171    pub hooks: Vec<Hook>,
172    /// What runs before each statement the builder builds.
173    pub before_each_build: Vec<Arc<dyn Fn() + Send + Sync>>,
174}
175
176impl std::fmt::Debug for ScopeBinding {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        f.debug_struct("ScopeBinding")
179            .field("hooks", &self.hooks.len())
180            .field("before_each_build", &self.before_each_build.len())
181            .finish()
182    }
183}
184
185/// A builder's scope, and the collection it read through it.
186#[derive(Clone)]
187pub(crate) struct ScopeState {
188    scope: Arc<dyn Scope>,
189    bound: Option<(String, String)>,
190    before_each_build: Vec<Arc<dyn Fn() + Send + Sync>>,
191}
192
193impl<D: Dialect> Builder<D> {
194    /// Sets the builder's [`Flavor`].
195    pub fn set_flavor(&mut self, flavor: Flavor) -> &mut Self {
196        self.core.flavor = flavor;
197        self
198    }
199
200    /// The builder's [`Flavor`].
201    pub fn flavor(&self) -> &Flavor {
202        &self.core.flavor
203    }
204
205    /// Reads collections through `scope`: `from()` then takes a collection
206    /// id.
207    ///
208    /// Fails once `from()` has read a collection through a scope.
209    ///
210    /// PHP: `Scoping::scope()`.
211    pub fn scope(&mut self, scope: Arc<dyn Scope>) -> Result<&mut Self> {
212        self.require_unbound("take another scope")?;
213        self.core.scope = Some(ScopeState { scope, bound: None, before_each_build: Vec::new() });
214        Ok(self)
215    }
216
217    /// Whether the builder has a scope.
218    ///
219    /// PHP: `Scoping::isScoped()`.
220    pub fn is_scoped(&self) -> bool {
221        self.core.scope.is_some()
222    }
223
224    /// The collection and alias the builder read through its scope.
225    pub fn bound_collection(&self) -> Option<(&str, &str)> {
226        self.core.scope.as_ref().and_then(|s| s.bound.as_ref()).map(|(c, a)| (c.as_str(), a.as_str()))
227    }
228
229    /// Reads the table stored under the name as it is, kept to no tenant.
230    ///
231    /// Fails once `from()` has read a collection through the scope.
232    ///
233    /// PHP: `Scoping::fromTable()`.
234    pub fn from_table(&mut self, table: impl Into<String>, alias: impl Into<String>) -> Result<&mut Self> {
235        let table = table.into();
236        self.require_unbound(&format!("read table '{table}'"))?;
237        Ok(self.plain_from(table, alias.into()))
238    }
239
240    /// The filters joined by `AND`, each compiled as `build()` compiles the
241    /// filters of its `WHERE`, with their bindings in order. The builder's
242    /// bindings are replaced by theirs.
243    ///
244    /// PHP: `Builder\Filtering::compileFilters()` (`CompilesFilters`).
245    pub fn compile_filters(&mut self, filters: &[Query]) -> Result<Condition> {
246        self.core.bindings.clear();
247        self.core.resolved.clear();
248        let mut expressions = Vec::with_capacity(filters.len());
249        for filter in filters {
250            expressions.push(self.step_string(Step::CompileFilter, &[Arg::Query(filter)])?);
251        }
252        Ok(Condition::new(expressions.join(" AND "), self.binding_values()))
253    }
254
255    pub(crate) fn plain_from(&mut self, table: String, alias: String) -> &mut Self {
256        self.core.table = table;
257        self.core.alias = alias;
258        self.core.from_subquery = None;
259        self.core.tableless = self.core.table.is_empty();
260        self
261    }
262
263    /// `ScopesCollections::from()`: through the scope once it has one.
264    pub(crate) fn scoped_from(&mut self, table: String, alias: String) -> &mut Self {
265        let Some(state) = self.core.scope.clone() else {
266            return self.plain_from(table, alias);
267        };
268        if table.is_empty() {
269            return self.plain_from(table, alias);
270        }
271        if let Some((collection, bound_alias)) = &state.bound {
272            if &table != collection || &alias != bound_alias {
273                let mut message = format!("The builder reads collection '{collection}'");
274                if !bound_alias.is_empty() {
275                    message.push_str(&format!(" as '{bound_alias}'"));
276                }
277                message.push_str(&format!(", not '{table}'"));
278                if !alias.is_empty() {
279                    message.push_str(&format!(" as '{alias}'"));
280                }
281                message.push_str(": start another builder");
282                self.defer(state.scope.error(message));
283                return self;
284            }
285            let stored = state.scope.table(&table);
286            return self.plain_from(stored, alias);
287        }
288        let stored = state.scope.table(&table);
289        self.plain_from(stored.clone(), alias.clone());
290        match state.scope.bind(&table, &stored, &alias) {
291            Ok(binding) => {
292                for hook in binding.hooks {
293                    if let Err(e) = D::add_hook(self, hook) {
294                        self.defer(e);
295                    }
296                }
297                if let Some(state) = self.core.scope.as_mut() {
298                    state.bound = Some((table, alias));
299                    state.before_each_build = binding.before_each_build;
300                }
301            }
302            Err(e) => self.defer(e),
303        }
304        self
305    }
306
307    /// Fails with the scope's error once `from()` has read a collection
308    /// through it (`requireUnbound()`).
309    pub(crate) fn require_unbound(&self, action: &str) -> Result<()> {
310        match &self.core.scope {
311            Some(ScopeState { scope, bound: Some((collection, _)), .. }) => Err(scope.error(format!(
312                "The builder reads collection '{collection}' and cannot {action}: start another builder"
313            ))),
314            _ => Ok(()),
315        }
316    }
317
318    /// [`Builder::require_unbound`] for a call that returns the builder: the
319    /// refusal waits for the next statement.
320    pub(crate) fn defer_unbound(&mut self, action: &str) {
321        if let Err(e) = self.require_unbound(action) {
322            self.defer(e);
323        }
324    }
325
326    fn defer(&mut self, error: Error) {
327        if self.core.deferred.is_none() {
328            self.core.deferred = Some(error);
329        }
330    }
331
332    /// The refusal kept from an earlier call, if any.
333    pub(crate) fn check_deferred(&self) -> Result<()> {
334        match &self.core.deferred {
335            Some(e) => Err(e.clone()),
336            None => Ok(()),
337        }
338    }
339
340    /// `ScopesCollections::build()`: the scope's callbacks, then the joins
341    /// named as the scope joins their tables, for this statement only.
342    pub(crate) fn scoped_build(&mut self) -> Result<Statement> {
343        self.check_deferred()?;
344        let Some(state) = self.core.scope.clone() else {
345            return D::build(self);
346        };
347        if state.bound.is_none() {
348            return D::build(self);
349        }
350        for callback in &state.before_each_build {
351            callback();
352        }
353        let written = self.core.pending.clone();
354        self.core.pending = written
355            .iter()
356            .map(|query| {
357                if !query.method().is_join() {
358                    return query.clone();
359                }
360                let table = state.scope.join_table(query.attribute());
361                if table == query.attribute() {
362                    query.clone()
363                } else {
364                    Query::new(query.method(), table, query.values().clone(), query.alias())
365                }
366            })
367            .collect();
368        let result = D::build(self);
369        self.core.pending = written;
370        result
371    }
372
373    // ----- PreparesSearchTerms ------------------------------------------
374
375    /// The values of a search with the term prepared as
376    /// [`Flavor::search_terms`] says, when it is set.
377    pub(crate) fn flavored_search_values(&self, values: &Array) -> Option<Array> {
378        if !self.core.flavor.search_terms {
379            return None;
380        }
381        let term = match values.get(&php_std::ArrayKey::Int(0)) {
382            Some(Value::Str(s)) => s.as_bytes().to_vec(),
383            _ => Vec::new(),
384        };
385        Some(value::list([Value::Str(prepare_search_term(&term).into())]))
386    }
387
388    // ----- CompilesAggregates --------------------------------------------
389
390    /// An aggregate as [`Flavor::compiles_aggregates`] compiles it, when it
391    /// is set and the aggregate is floating or bitwise.
392    pub(crate) fn flavored_aggregate(&mut self, query: &Query) -> Option<Result<String>> {
393        if !self.core.flavor.compiles_aggregates {
394            return None;
395        }
396        let method = query.method();
397        let variance = match method {
398            Method::Stddev => Some(Method::Variance),
399            Method::StddevPop => Some(Method::VarPop),
400            Method::StddevSamp => Some(Method::VarSamp),
401            _ => None,
402        };
403        let bitwise = matches!(method, Method::BitAnd | Method::BitOr | Method::BitXor);
404        if variance.is_none()
405            && !bitwise
406            && !matches!(method, Method::Sum | Method::Avg | Method::Variance | Method::VarPop | Method::VarSamp)
407        {
408            return None;
409        }
410        Some(self.checked_aggregate(query, variance, bitwise))
411    }
412
413    fn checked_aggregate(&mut self, query: &Query, variance: Option<Method>, bitwise: bool) -> Result<String> {
414        let expression =
415            self.base_compile_aggregate(&Query::new(query.method(), query.attribute(), Array::new(), ""))?;
416        let checked = match variance {
417            Some(variance) => format!(
418                "SQRT({} + 0)",
419                self.base_compile_aggregate(&Query::new(variance, query.attribute(), Array::new(), ""))?
420            ),
421            None if bitwise => format!("CAST({expression} AS SIGNED)"),
422            None => format!("{expression} + 0"),
423        };
424        let alias = if query.alias().is_empty() {
425            crate::quote_literal(&expression, D::WRAP)?
426        } else {
427            self.quote(query.alias())?
428        };
429        Ok(format!("{checked} AS {alias}"))
430    }
431
432    // ----- MatchesContainsAllPatterns -----------------------------------
433
434    /// `containsAll()` as [`Flavor::contains_all_patterns`] says, when it is
435    /// set.
436    pub(crate) fn flavored_contains_all(
437        &mut self,
438        attribute: &str,
439        values: &Array,
440        column: Option<&str>,
441    ) -> Option<String> {
442        if !self.core.flavor.contains_all_patterns {
443            return None;
444        }
445        let like = match self.like_keyword() {
446            Ok(like) => like,
447            Err(error) => {
448                self.core.deferred.get_or_insert(error);
449                return None;
450            }
451        };
452        let mut parts = Vec::with_capacity(values.len());
453        for value in values.values() {
454            self.add_binding(value.clone(), column);
455            parts.push(format!("{attribute} {like} ?"));
456        }
457        Some(format!("({})", parts.join(" OR ")))
458    }
459
460    // ----- Document id collation ----------------------------------------
461
462    /// Whether the column resolves to a collated id column
463    /// (`isCollated()`, through `CollatesDocumentIds::columnName()`).
464    pub(crate) fn is_collated(&mut self, column: &str) -> Result<bool> {
465        let Some(ids) = self.core.flavor.ids.clone() else {
466            return Ok(false);
467        };
468        let resolved = self.resolve_attribute(column)?;
469        let name = match resolved.rfind('.') {
470            Some(i) => &resolved[i + 1..],
471            None => resolved.as_str(),
472        };
473        Ok(ids.collated_columns.iter().any(|c| c == name))
474    }
475
476    /// The attribute in the collation when its column is collated
477    /// (`CollatesDocumentIds::collate()`).
478    pub(crate) fn collate(&mut self, attribute: &str, column: Option<&str>) -> Result<String> {
479        let Some(ids) = self.core.flavor.ids.clone() else {
480            return Ok(attribute.to_owned());
481        };
482        match column {
483            Some(column) if self.is_collated(column)? => Ok(format!("{attribute} COLLATE {}", ids.collation)),
484            _ => Ok(attribute.to_owned()),
485        }
486    }
487
488    /// `CollatesDocumentIds::compileJoin()`: the ON comparisons of a join
489    /// query compared in the collation (see [`Self::collate_comparisons`]).
490    pub(crate) fn collate_join(&mut self, query: &Query, sql: String) -> Result<String> {
491        if self.core.flavor.ids.is_none() {
492            return Ok(sql);
493        }
494        let comparisons = on_comparisons(&query.join_on_queries());
495        self.collate_comparisons(sql, &comparisons)
496    }
497
498    /// `CollatesDocumentIds::collateJoin()`: every `=`, `!=` and `<>`
499    /// comparison the builder collates the sides of (`collatesJoin()`)
500    /// compares in the collation.
501    pub(crate) fn collate_comparisons(
502        &mut self,
503        mut sql: String,
504        comparisons: &[(String, String, String)],
505    ) -> Result<String> {
506        let Some(ids) = self.core.flavor.ids.clone() else {
507            return Ok(sql);
508        };
509        let collate = format!(" COLLATE {}", ids.collation);
510        for (left, operator, right) in comparisons {
511            if !matches!(operator.as_str(), "=" | "!=" | "<>") {
512                continue;
513            }
514            let collates = if ids.join_both_sides {
515                self.is_collated(left)? && self.is_collated(right)?
516            } else {
517                self.is_collated(left)? || self.is_collated(right)?
518            };
519            if !collates {
520                continue;
521            }
522            let comparison = format!(" {operator} {}", self.resolve_and_wrap(right)?);
523            let wrapped_left = self.resolve_and_wrap(left)?;
524            sql = sql.replace(&format!("{wrapped_left}{comparison}"), &format!("{wrapped_left}{collate}{comparison}"));
525        }
526        Ok(sql)
527    }
528
529    // ----- SQLite -------------------------------------------------------
530
531    /// `compileLike()` with SQLite's `ESCAPE '\'`, once: the dialect's own LIKE predicate
532    /// may name it already (utopia-database 10.2.5, `str_ends_with($like, self::ESCAPE)`).
533    pub(crate) fn sqlite_like(
534        &mut self,
535        attribute: &str,
536        values: &Array,
537        prefix: &str,
538        suffix: &str,
539        not: bool,
540        column: Option<&str>,
541    ) -> Result<String> {
542        let like = self.base_compile_like(attribute, values, prefix, suffix, not, column)?;
543        const ESCAPE: &str = " ESCAPE '\\'";
544        Ok(if like.ends_with(ESCAPE) { like } else { like + ESCAPE })
545    }
546
547    /// `SQLite::compileSubstrings()`.
548    pub(crate) fn sqlite_substrings(
549        &mut self,
550        attribute: &str,
551        values: &Array,
552        not: bool,
553        column: Option<&str>,
554    ) -> Result<Vec<String>> {
555        let mut predicates = Vec::with_capacity(values.len());
556        for value in values.values() {
557            predicates.push(self.sqlite_like(attribute, &value::list([value.clone()]), "%", "%", not, column)?);
558        }
559        Ok(predicates)
560    }
561
562    /// `SQLite::compileElementMatches()`.
563    pub(crate) fn sqlite_element_matches(&mut self, attribute: &str, needles: &Value) -> Result<Vec<String>> {
564        let needles: Vec<Value> = match needles {
565            Value::Array(items) => items.values().cloned().collect(),
566            Value::Null => Vec::new(),
567            Value::Object(items) => items.values().cloned().collect(),
568            other => vec![other.clone()],
569        };
570        let mut matches = Vec::with_capacity(needles.len());
571        for needle in &needles {
572            let json = value::json_encode(needle, php_std::json::Flags::THROW_ON_ERROR)
573                .map_err(|e| Error::Validation(format!("Invalid JSON payload: {}", e.message())))?;
574            self.add_binding(value::string(json), None);
575            matches.push(format!(
576                "EXISTS (SELECT 1 FROM json_each({attribute}) WHERE json_each.value = json_extract(?, '$'))"
577            ));
578        }
579        Ok(matches)
580    }
581}
582
583impl Builder<crate::builder::PostgreSqlDialect> {
584    /// `Builder\Postgres::compileSpatialFilter()` for `distanceLessThan()`:
585    /// `ST_DWithin()` on the geometry, or for a distance in meters from a
586    /// point to a point column a degree box around the point, then the exact
587    /// `ST_Distance()` check.
588    pub(crate) fn indexed_distance(&mut self, attribute: &str, query: &Query, srid: i64) -> Result<String> {
589        let tuple = match query.values().get(&php_std::ArrayKey::Int(0)) {
590            Some(Value::Array(tuple)) => tuple.clone(),
591            _ => Array::new(),
592        };
593        let filter = crate::builder::SpatialDistanceFilter::from_tuple(&tuple)?;
594        let wkt = crate::builder::sql::wkt_of(self, &filter.geometry)?;
595        let geometry = format!("ST_GeomFromText(?, {srid})");
596        if !filter.meters {
597            self.add_binding(wkt.clone(), None);
598            self.add_binding(Value::Float(filter.distance), None);
599            self.add_binding(wkt, None);
600            self.add_binding(Value::Float(filter.distance), None);
601            return Ok(format!(
602                "(ST_DWithin({attribute}, {geometry}, ?) AND ST_Distance({attribute}, {geometry}) < ?)"
603            ));
604        }
605        let distance =
606            format!("ST_Distance(({attribute}::geography), ST_SetSRID(ST_GeomFromText(?), {srid})::geography) < ?");
607        let degrees = if query.attribute_type() == "point" {
608            degrees_within_meters(&filter.geometry, filter.distance)
609        } else {
610            None
611        };
612        let Some((longitude, latitude)) = degrees else {
613            self.add_binding(wkt, None);
614            self.add_binding(Value::Float(filter.distance), None);
615            return Ok(distance);
616        };
617        self.add_binding(wkt.clone(), None);
618        self.add_binding(Value::Float(longitude), None);
619        self.add_binding(Value::Float(latitude), None);
620        self.add_binding(wkt, None);
621        self.add_binding(Value::Float(filter.distance), None);
622        Ok(format!("({attribute} && ST_Expand({geometry}, ?, ?) AND {distance})"))
623    }
624}
625
626/// A degree of latitude spans at least this many meters.
627const METERS_PER_LATITUDE_DEGREE: f64 = 110574.0;
628
629/// A degree of longitude at the equator spans at least this many meters.
630const METERS_PER_EQUATORIAL_LONGITUDE_DEGREE: f64 = 111319.0;
631
632/// `Builder\Postgres::degreesWithinMeters()`: the longitude and latitude
633/// degrees that hold every point within `meters` of `point`; `None` for a
634/// line or polygon, a distance that is not finite, and a box reaching a pole
635/// or the antimeridian.
636fn degrees_within_meters(point: &Value, meters: f64) -> Option<(f64, f64)> {
637    let Value::Array(point) = point else {
638        return None;
639    };
640    let at = |i: i64| point.get(&php_std::ArrayKey::Int(i));
641    if !meters.is_finite()
642        || point.len() != 2
643        || !at(0).is_some_and(crate::query::is_numeric)
644        || !at(1).is_some_and(crate::query::is_numeric)
645    {
646        return None;
647    }
648    let longitude = at(0).map(Value::to_double).unwrap_or(0.0);
649    let latitude = at(1).map(Value::to_double).unwrap_or(0.0);
650    let latitude_degrees = meters / METERS_PER_LATITUDE_DEGREE;
651    if latitude.abs() + latitude_degrees >= 90.0 {
652        return None;
653    }
654    let longitude_degrees = meters
655        / (METERS_PER_EQUATORIAL_LONGITUDE_DEGREE
656            * ((latitude.abs() + latitude_degrees) / 180.0 * std::f64::consts::PI).cos());
657    if longitude - longitude_degrees <= -180.0 || longitude + longitude_degrees >= 180.0 {
658        return None;
659    }
660    Some((longitude_degrees, latitude_degrees))
661}
662
663/// `SQLite::onComparisons()`: the `[left, operator, right]` of every `on`
664/// among the queries, through `and` and `or`.
665fn on_comparisons(queries: &[&Query]) -> Vec<(String, String, String)> {
666    let mut comparisons = Vec::new();
667    for query in queries {
668        match query.method() {
669            Method::On => {
670                let at = |i: i64| query.values().get(&php_std::ArrayKey::Int(i)).cloned().unwrap_or(Value::Null);
671                if let (Value::Str(left), Value::Str(operator), Value::Str(right)) = (at(0), at(1), at(2))
672                    && !left.is_empty()
673                    && !right.is_empty()
674                {
675                    comparisons.push((
676                        String::from_utf8_lossy(left.as_bytes()).into_owned(),
677                        String::from_utf8_lossy(operator.as_bytes()).into_owned(),
678                        String::from_utf8_lossy(right.as_bytes()).into_owned(),
679                    ));
680                }
681            }
682            Method::And | Method::Or => {
683                let nested: Vec<&Query> = query.nested().collect();
684                comparisons.extend(on_comparisons(&nested));
685            }
686            _ => {}
687        }
688    }
689    comparisons
690}
691
692/// `PreparesSearchTerms::prepareSearchTerm()`.
693pub(crate) fn prepare_search_term(term: &[u8]) -> Vec<u8> {
694    let words = search_words(term);
695    let exact = term.starts_with(b"\"") && term.ends_with(b"\"");
696    if exact && !words.is_empty() {
697        let mut quoted = Vec::with_capacity(words.len() + 2);
698        quoted.push(b'"');
699        quoted.extend_from_slice(&words);
700        quoted.push(b'"');
701        return quoted;
702    }
703    words
704}
705
706/// `PreparesSearchTerms::searchWords()`: separators to spaces, runs of
707/// whitespace to one space, trimmed (`preg_replace` failing gives `''`).
708fn search_words(term: &[u8]) -> Vec<u8> {
709    let replace = |pattern: &[u8], replacement: &[u8], subject: &[u8]| -> Vec<u8> {
710        match preg_replace(&StrOrArray::Str(pattern), &StrOrArray::Str(replacement), &StrOrArray::Str(subject), -1) {
711            Ok(preg) => match preg.value.result {
712                php_std::pcre::Value::Str(s) => s,
713                _ => Vec::new(),
714            },
715            Err(_) => Vec::new(),
716        }
717    };
718    let words = replace(b"/[^\\p{L}\\p{N}_\\s]/u", b" ", term);
719    let words = replace(b"/\\s+/", b" ", &words);
720    php_std::string::trim(&words, b" \n\r\t\x0b\0").to_vec()
721}