1use 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
42pub type ObjectPathCheck = Arc<dyn Fn(&str) -> Result<()> + Send + Sync>;
44
45#[derive(Clone, Default)]
48pub struct Flavor {
49 pub search_terms: bool,
56 pub contains_all_patterns: bool,
62 pub compiles_aggregates: bool,
77 pub object_path: Option<ObjectPathCheck>,
83 pub indexed_distance: Option<i64>,
88 pub sqlite: Option<SqliteFlavor>,
90 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
118pub struct SqliteFlavor;
119
120#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct IdCollation {
129 pub collation: String,
131 pub collated_columns: Vec<String>,
134 pub join_both_sides: bool,
139}
140
141pub trait Scope: Send + Sync {
147 fn table(&self, collection: &str) -> String;
149
150 fn join_table(&self, table: &str) -> String;
153
154 fn bind(&self, collection: &str, table: &str, alias: &str) -> Result<ScopeBinding>;
159
160 fn error(&self, message: String) -> Error {
163 Error::new(message, 0)
164 }
165}
166
167#[derive(Clone, Default)]
169pub struct ScopeBinding {
170 pub hooks: Vec<Hook>,
172 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#[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 pub fn set_flavor(&mut self, flavor: Flavor) -> &mut Self {
196 self.core.flavor = flavor;
197 self
198 }
199
200 pub fn flavor(&self) -> &Flavor {
202 &self.core.flavor
203 }
204
205 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 pub fn is_scoped(&self) -> bool {
221 self.core.scope.is_some()
222 }
223
224 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
626const METERS_PER_LATITUDE_DEGREE: f64 = 110574.0;
628
629const METERS_PER_EQUATORIAL_LONGITUDE_DEGREE: f64 = 111319.0;
631
632fn 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
663fn 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
692pub(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
706fn 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}