use std::sync::Arc;
use php_std::pcre::{StrOrArray, preg_replace};
use crate::builder::core::{Builder, Dialect};
use crate::builder::steps::{Arg, Step};
use crate::builder::types::{Condition, Statement};
use crate::error::{Error, Result};
use crate::hook::Hook;
use crate::method::Method;
use crate::query::Query;
use crate::value::{self, Array, Value};
pub type ObjectPathCheck = Arc<dyn Fn(&str) -> Result<()> + Send + Sync>;
#[derive(Clone, Default)]
pub struct Flavor {
pub search_terms: bool,
pub contains_all_patterns: bool,
pub compiles_aggregates: bool,
pub object_path: Option<ObjectPathCheck>,
pub indexed_distance: Option<i64>,
pub sqlite: Option<SqliteFlavor>,
pub ids: Option<IdCollation>,
}
impl std::fmt::Debug for Flavor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Flavor")
.field("search_terms", &self.search_terms)
.field("contains_all_patterns", &self.contains_all_patterns)
.field("compiles_aggregates", &self.compiles_aggregates)
.field("object_path", &self.object_path.is_some())
.field("indexed_distance", &self.indexed_distance)
.field("sqlite", &self.sqlite)
.field("ids", &self.ids)
.finish()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SqliteFlavor;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdCollation {
pub collation: String,
pub collated_columns: Vec<String>,
pub join_both_sides: bool,
}
pub trait Scope: Send + Sync {
fn table(&self, collection: &str) -> String;
fn join_table(&self, table: &str) -> String;
fn bind(&self, collection: &str, table: &str, alias: &str) -> Result<ScopeBinding>;
fn error(&self, message: String) -> Error {
Error::new(message, 0)
}
}
#[derive(Clone, Default)]
pub struct ScopeBinding {
pub hooks: Vec<Hook>,
pub before_each_build: Vec<Arc<dyn Fn() + Send + Sync>>,
}
impl std::fmt::Debug for ScopeBinding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScopeBinding")
.field("hooks", &self.hooks.len())
.field("before_each_build", &self.before_each_build.len())
.finish()
}
}
#[derive(Clone)]
pub(crate) struct ScopeState {
scope: Arc<dyn Scope>,
bound: Option<(String, String)>,
before_each_build: Vec<Arc<dyn Fn() + Send + Sync>>,
}
impl<D: Dialect> Builder<D> {
pub fn set_flavor(&mut self, flavor: Flavor) -> &mut Self {
self.core.flavor = flavor;
self
}
pub fn flavor(&self) -> &Flavor {
&self.core.flavor
}
pub fn scope(&mut self, scope: Arc<dyn Scope>) -> Result<&mut Self> {
self.require_unbound("take another scope")?;
self.core.scope = Some(ScopeState { scope, bound: None, before_each_build: Vec::new() });
Ok(self)
}
pub fn is_scoped(&self) -> bool {
self.core.scope.is_some()
}
pub fn bound_collection(&self) -> Option<(&str, &str)> {
self.core.scope.as_ref().and_then(|s| s.bound.as_ref()).map(|(c, a)| (c.as_str(), a.as_str()))
}
pub fn from_table(&mut self, table: impl Into<String>, alias: impl Into<String>) -> Result<&mut Self> {
let table = table.into();
self.require_unbound(&format!("read table '{table}'"))?;
Ok(self.plain_from(table, alias.into()))
}
pub fn compile_filters(&mut self, filters: &[Query]) -> Result<Condition> {
self.core.bindings.clear();
self.core.resolved.clear();
let mut expressions = Vec::with_capacity(filters.len());
for filter in filters {
expressions.push(self.step_string(Step::CompileFilter, &[Arg::Query(filter)])?);
}
Ok(Condition::new(expressions.join(" AND "), self.binding_values()))
}
pub(crate) fn plain_from(&mut self, table: String, alias: String) -> &mut Self {
self.core.table = table;
self.core.alias = alias;
self.core.from_subquery = None;
self.core.tableless = self.core.table.is_empty();
self
}
pub(crate) fn scoped_from(&mut self, table: String, alias: String) -> &mut Self {
let Some(state) = self.core.scope.clone() else {
return self.plain_from(table, alias);
};
if table.is_empty() {
return self.plain_from(table, alias);
}
if let Some((collection, bound_alias)) = &state.bound {
if &table != collection || &alias != bound_alias {
let mut message = format!("The builder reads collection '{collection}'");
if !bound_alias.is_empty() {
message.push_str(&format!(" as '{bound_alias}'"));
}
message.push_str(&format!(", not '{table}'"));
if !alias.is_empty() {
message.push_str(&format!(" as '{alias}'"));
}
message.push_str(": start another builder");
self.defer(state.scope.error(message));
return self;
}
let stored = state.scope.table(&table);
return self.plain_from(stored, alias);
}
let stored = state.scope.table(&table);
self.plain_from(stored.clone(), alias.clone());
match state.scope.bind(&table, &stored, &alias) {
Ok(binding) => {
for hook in binding.hooks {
if let Err(e) = D::add_hook(self, hook) {
self.defer(e);
}
}
if let Some(state) = self.core.scope.as_mut() {
state.bound = Some((table, alias));
state.before_each_build = binding.before_each_build;
}
}
Err(e) => self.defer(e),
}
self
}
pub(crate) fn require_unbound(&self, action: &str) -> Result<()> {
match &self.core.scope {
Some(ScopeState { scope, bound: Some((collection, _)), .. }) => Err(scope.error(format!(
"The builder reads collection '{collection}' and cannot {action}: start another builder"
))),
_ => Ok(()),
}
}
pub(crate) fn defer_unbound(&mut self, action: &str) {
if let Err(e) = self.require_unbound(action) {
self.defer(e);
}
}
fn defer(&mut self, error: Error) {
if self.core.deferred.is_none() {
self.core.deferred = Some(error);
}
}
pub(crate) fn check_deferred(&self) -> Result<()> {
match &self.core.deferred {
Some(e) => Err(e.clone()),
None => Ok(()),
}
}
pub(crate) fn scoped_build(&mut self) -> Result<Statement> {
self.check_deferred()?;
let Some(state) = self.core.scope.clone() else {
return D::build(self);
};
if state.bound.is_none() {
return D::build(self);
}
for callback in &state.before_each_build {
callback();
}
let written = self.core.pending.clone();
self.core.pending = written
.iter()
.map(|query| {
if !query.method().is_join() {
return query.clone();
}
let table = state.scope.join_table(query.attribute());
if table == query.attribute() {
query.clone()
} else {
Query::new(query.method(), table, query.values().clone(), query.alias())
}
})
.collect();
let result = D::build(self);
self.core.pending = written;
result
}
pub(crate) fn flavored_search_values(&self, values: &Array) -> Option<Array> {
if !self.core.flavor.search_terms {
return None;
}
let term = match values.get(&php_std::ArrayKey::Int(0)) {
Some(Value::Str(s)) => s.as_bytes().to_vec(),
_ => Vec::new(),
};
Some(value::list([Value::Str(prepare_search_term(&term).into())]))
}
pub(crate) fn flavored_aggregate(&mut self, query: &Query) -> Option<Result<String>> {
if !self.core.flavor.compiles_aggregates {
return None;
}
let method = query.method();
let variance = match method {
Method::Stddev => Some(Method::Variance),
Method::StddevPop => Some(Method::VarPop),
Method::StddevSamp => Some(Method::VarSamp),
_ => None,
};
let bitwise = matches!(method, Method::BitAnd | Method::BitOr | Method::BitXor);
if variance.is_none()
&& !bitwise
&& !matches!(method, Method::Sum | Method::Avg | Method::Variance | Method::VarPop | Method::VarSamp)
{
return None;
}
Some(self.checked_aggregate(query, variance, bitwise))
}
fn checked_aggregate(&mut self, query: &Query, variance: Option<Method>, bitwise: bool) -> Result<String> {
let expression =
self.base_compile_aggregate(&Query::new(query.method(), query.attribute(), Array::new(), ""))?;
let checked = match variance {
Some(variance) => format!(
"SQRT({} + 0)",
self.base_compile_aggregate(&Query::new(variance, query.attribute(), Array::new(), ""))?
),
None if bitwise => format!("CAST({expression} AS SIGNED)"),
None => format!("{expression} + 0"),
};
let alias = if query.alias().is_empty() {
crate::quote_literal(&expression, D::WRAP)?
} else {
self.quote(query.alias())?
};
Ok(format!("{checked} AS {alias}"))
}
pub(crate) fn flavored_contains_all(
&mut self,
attribute: &str,
values: &Array,
column: Option<&str>,
) -> Option<String> {
if !self.core.flavor.contains_all_patterns {
return None;
}
let like = match self.like_keyword() {
Ok(like) => like,
Err(error) => {
self.core.deferred.get_or_insert(error);
return None;
}
};
let mut parts = Vec::with_capacity(values.len());
for value in values.values() {
self.add_binding(value.clone(), column);
parts.push(format!("{attribute} {like} ?"));
}
Some(format!("({})", parts.join(" OR ")))
}
pub(crate) fn is_collated(&mut self, column: &str) -> Result<bool> {
let Some(ids) = self.core.flavor.ids.clone() else {
return Ok(false);
};
let resolved = self.resolve_attribute(column)?;
let name = match resolved.rfind('.') {
Some(i) => &resolved[i + 1..],
None => resolved.as_str(),
};
Ok(ids.collated_columns.iter().any(|c| c == name))
}
pub(crate) fn collate(&mut self, attribute: &str, column: Option<&str>) -> Result<String> {
let Some(ids) = self.core.flavor.ids.clone() else {
return Ok(attribute.to_owned());
};
match column {
Some(column) if self.is_collated(column)? => Ok(format!("{attribute} COLLATE {}", ids.collation)),
_ => Ok(attribute.to_owned()),
}
}
pub(crate) fn collate_join(&mut self, query: &Query, sql: String) -> Result<String> {
if self.core.flavor.ids.is_none() {
return Ok(sql);
}
let comparisons = on_comparisons(&query.join_on_queries());
self.collate_comparisons(sql, &comparisons)
}
pub(crate) fn collate_comparisons(
&mut self,
mut sql: String,
comparisons: &[(String, String, String)],
) -> Result<String> {
let Some(ids) = self.core.flavor.ids.clone() else {
return Ok(sql);
};
let collate = format!(" COLLATE {}", ids.collation);
for (left, operator, right) in comparisons {
if !matches!(operator.as_str(), "=" | "!=" | "<>") {
continue;
}
let collates = if ids.join_both_sides {
self.is_collated(left)? && self.is_collated(right)?
} else {
self.is_collated(left)? || self.is_collated(right)?
};
if !collates {
continue;
}
let comparison = format!(" {operator} {}", self.resolve_and_wrap(right)?);
let wrapped_left = self.resolve_and_wrap(left)?;
sql = sql.replace(&format!("{wrapped_left}{comparison}"), &format!("{wrapped_left}{collate}{comparison}"));
}
Ok(sql)
}
pub(crate) fn sqlite_like(
&mut self,
attribute: &str,
values: &Array,
prefix: &str,
suffix: &str,
not: bool,
column: Option<&str>,
) -> Result<String> {
Ok(self.base_compile_like(attribute, values, prefix, suffix, not, column)? + " ESCAPE '\\'")
}
pub(crate) fn sqlite_substrings(
&mut self,
attribute: &str,
values: &Array,
not: bool,
column: Option<&str>,
) -> Result<Vec<String>> {
let mut predicates = Vec::with_capacity(values.len());
for value in values.values() {
predicates.push(self.sqlite_like(attribute, &value::list([value.clone()]), "%", "%", not, column)?);
}
Ok(predicates)
}
pub(crate) fn sqlite_element_matches(&mut self, attribute: &str, needles: &Value) -> Result<Vec<String>> {
let needles: Vec<Value> = match needles {
Value::Array(items) => items.values().cloned().collect(),
Value::Null => Vec::new(),
Value::Object(items) => items.values().cloned().collect(),
other => vec![other.clone()],
};
let mut matches = Vec::with_capacity(needles.len());
for needle in &needles {
let json = value::json_encode(needle, php_std::json::Flags::THROW_ON_ERROR)
.map_err(|e| Error::Validation(format!("Invalid JSON payload: {}", e.message())))?;
self.add_binding(value::string(json), None);
matches.push(format!(
"EXISTS (SELECT 1 FROM json_each({attribute}) WHERE json_each.value = json_extract(?, '$'))"
));
}
Ok(matches)
}
}
impl Builder<crate::builder::PostgreSqlDialect> {
pub(crate) fn indexed_distance(&mut self, attribute: &str, query: &Query, srid: i64) -> Result<String> {
let tuple = match query.values().get(&php_std::ArrayKey::Int(0)) {
Some(Value::Array(tuple)) => tuple.clone(),
_ => Array::new(),
};
let filter = crate::builder::SpatialDistanceFilter::from_tuple(&tuple)?;
let wkt = crate::builder::sql::wkt_of(self, &filter.geometry)?;
let geometry = format!("ST_GeomFromText(?, {srid})");
if !filter.meters {
self.add_binding(wkt.clone(), None);
self.add_binding(Value::Float(filter.distance), None);
self.add_binding(wkt, None);
self.add_binding(Value::Float(filter.distance), None);
return Ok(format!(
"(ST_DWithin({attribute}, {geometry}, ?) AND ST_Distance({attribute}, {geometry}) < ?)"
));
}
let distance =
format!("ST_Distance(({attribute}::geography), ST_SetSRID(ST_GeomFromText(?), {srid})::geography) < ?");
let degrees = if query.attribute_type() == "point" {
degrees_within_meters(&filter.geometry, filter.distance)
} else {
None
};
let Some((longitude, latitude)) = degrees else {
self.add_binding(wkt, None);
self.add_binding(Value::Float(filter.distance), None);
return Ok(distance);
};
self.add_binding(wkt.clone(), None);
self.add_binding(Value::Float(longitude), None);
self.add_binding(Value::Float(latitude), None);
self.add_binding(wkt, None);
self.add_binding(Value::Float(filter.distance), None);
Ok(format!("({attribute} && ST_Expand({geometry}, ?, ?) AND {distance})"))
}
}
const METERS_PER_LATITUDE_DEGREE: f64 = 110574.0;
const METERS_PER_EQUATORIAL_LONGITUDE_DEGREE: f64 = 111319.0;
fn degrees_within_meters(point: &Value, meters: f64) -> Option<(f64, f64)> {
let Value::Array(point) = point else {
return None;
};
let at = |i: i64| point.get(&php_std::ArrayKey::Int(i));
if !meters.is_finite()
|| point.len() != 2
|| !at(0).is_some_and(crate::query::is_numeric)
|| !at(1).is_some_and(crate::query::is_numeric)
{
return None;
}
let longitude = at(0).map(Value::to_double).unwrap_or(0.0);
let latitude = at(1).map(Value::to_double).unwrap_or(0.0);
let latitude_degrees = meters / METERS_PER_LATITUDE_DEGREE;
if latitude.abs() + latitude_degrees >= 90.0 {
return None;
}
let longitude_degrees = meters
/ (METERS_PER_EQUATORIAL_LONGITUDE_DEGREE
* ((latitude.abs() + latitude_degrees) / 180.0 * std::f64::consts::PI).cos());
if longitude - longitude_degrees <= -180.0 || longitude + longitude_degrees >= 180.0 {
return None;
}
Some((longitude_degrees, latitude_degrees))
}
fn on_comparisons(queries: &[&Query]) -> Vec<(String, String, String)> {
let mut comparisons = Vec::new();
for query in queries {
match query.method() {
Method::On => {
let at = |i: i64| query.values().get(&php_std::ArrayKey::Int(i)).cloned().unwrap_or(Value::Null);
if let (Value::Str(left), Value::Str(operator), Value::Str(right)) = (at(0), at(1), at(2))
&& !left.is_empty()
&& !right.is_empty()
{
comparisons.push((
String::from_utf8_lossy(left.as_bytes()).into_owned(),
String::from_utf8_lossy(operator.as_bytes()).into_owned(),
String::from_utf8_lossy(right.as_bytes()).into_owned(),
));
}
}
Method::And | Method::Or => {
let nested: Vec<&Query> = query.nested().collect();
comparisons.extend(on_comparisons(&nested));
}
_ => {}
}
}
comparisons
}
pub(crate) fn prepare_search_term(term: &[u8]) -> Vec<u8> {
let words = search_words(term);
let exact = term.starts_with(b"\"") && term.ends_with(b"\"");
if exact && !words.is_empty() {
let mut quoted = Vec::with_capacity(words.len() + 2);
quoted.push(b'"');
quoted.extend_from_slice(&words);
quoted.push(b'"');
return quoted;
}
words
}
fn search_words(term: &[u8]) -> Vec<u8> {
let replace = |pattern: &[u8], replacement: &[u8], subject: &[u8]| -> Vec<u8> {
match preg_replace(&StrOrArray::Str(pattern), &StrOrArray::Str(replacement), &StrOrArray::Str(subject), -1) {
Ok(preg) => match preg.value.result {
php_std::pcre::Value::Str(s) => s,
_ => Vec::new(),
},
Err(_) => Vec::new(),
}
};
let words = replace(b"/[^\\p{L}\\p{N}_\\s]/u", b" ", term);
let words = replace(b"/\\s+/", b" ", &words);
php_std::string::trim(&words, b" \n\r\t\x0b\0").to_vec()
}