use crate::builder::steps::{Arg, Ret, Step};
use php_std::ArrayKey;
use crate::builder::core::{Builder, Dialect};
use crate::builder::types::SpatialDistanceFilter;
use crate::error::Result;
use crate::method::Method;
use crate::query::{Query, is_numeric};
use crate::value::{Array, Param, Value};
pub trait SqlDialect: Dialect {
fn compile_search_expression(b: &mut Builder<Self>, attribute: &str, values: &Array, not: bool) -> Result<String>;
fn compile_spatial_distance(
b: &mut Builder<Self>,
method: Method,
attribute: &str,
values: &Array,
) -> Result<String>;
fn compile_spatial_predicate(
b: &mut Builder<Self>,
function: &str,
attribute: &str,
values: &Array,
not: bool,
) -> Result<String>;
fn compile_spatial_covers_predicate(
b: &mut Builder<Self>,
attribute: &str,
values: &Array,
not: bool,
) -> Result<String>;
fn compile_json_contains_expression(
b: &mut Builder<Self>,
attribute: &str,
values: &Array,
not: bool,
) -> Result<String>;
fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String>;
fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String>;
fn compile_conflict_header(b: &mut Builder<Self>) -> Result<String>;
fn compile_conflict_assignment(wrapped: &str) -> String;
fn compile_spatial_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
sql_compile_spatial_filter(b, method, attribute, query)
}
fn compile_array_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
sql_compile_array_filter(b, method, attribute, query)
}
}
pub(crate) fn sql_base_step<D: SqlDialect>(
b: &mut Builder<D>,
step: Step,
arguments: &[Arg<'_>],
) -> Option<Result<Ret>> {
Some(match (step, arguments) {
(Step::CompileSearchExpression, [Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)]) => {
D::compile_search_expression(b, attribute, values, *not).map(Ret::Str)
}
(Step::CompileSpatialFilter, [Arg::Method(method), Arg::Str(attribute), Arg::Query(query)]) => {
D::compile_spatial_filter(b, *method, attribute, query).map(Ret::Str)
}
(Step::CompileArrayFilter, [Arg::Method(method), Arg::Str(attribute), Arg::Query(query)]) => {
D::compile_array_filter(b, *method, attribute, query).map(Ret::Str)
}
(Step::CompileJsonContainsExpression, [Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)]) => {
D::compile_json_contains_expression(b, attribute, values, *not).map(Ret::Str)
}
(Step::CompileJsonOverlapsExpression, [Arg::Str(attribute), Arg::Values(values)]) => {
D::compile_json_overlaps_expression(b, attribute, values).map(Ret::Str)
}
(Step::CompileSpatialDistance, [Arg::Method(method), Arg::Str(attribute), Arg::Values(values)]) => {
D::compile_spatial_distance(b, *method, attribute, values).map(Ret::Str)
}
(
Step::CompileSpatialPredicate,
[Arg::Str(function), Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)],
) => D::compile_spatial_predicate(b, function, attribute, values, *not).map(Ret::Str),
(Step::CompileSpatialCoversPredicate, [Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)]) => {
D::compile_spatial_covers_predicate(b, attribute, values, *not).map(Ret::Str)
}
(Step::CompileJsonPathExpression, [Arg::Str(attribute), Arg::Values(values)]) => {
D::compile_json_path_expression(b, attribute, values).map(Ret::Str)
}
(Step::CompileJsonFilter, [Arg::Method(method), Arg::Str(attribute), Arg::Query(query)]) => {
sql_compile_json_filter(b, *method, attribute, query).map(Ret::Str)
}
(Step::CompileConflictHeader, []) => D::compile_conflict_header(b).map(Ret::Str),
(Step::CompileConflictAssignment, [Arg::Str(wrapped)]) => Ok(Ret::Str(D::compile_conflict_assignment(wrapped))),
(Step::CompileConflictClause, []) => crate::builder::mysql::base_conflict_clause(b).map(Ret::Str),
_ => return None,
})
}
pub(crate) fn sql_compile_filter<D: SqlDialect>(b: &mut Builder<D>, query: &Query) -> Result<String> {
let method = query.method();
let attribute = b.resolve_and_wrap(query.attribute())?;
match method {
Method::Search => {
return b.step_string(
Step::CompileSearchExpression,
&[Arg::Str(&attribute), Arg::Values(query.values()), Arg::Bool(false)],
);
}
Method::NotSearch => {
return b.step_string(
Step::CompileSearchExpression,
&[Arg::Str(&attribute), Arg::Values(query.values()), Arg::Bool(true)],
);
}
_ => {}
}
if method.is_spatial() {
return b
.step_string(Step::CompileSpatialFilter, &[Arg::Method(method), Arg::Str(&attribute), Arg::Query(query)]);
}
if matches!(query.attribute_type(), "point" | "linestring" | "polygon") {
let spatial = match method {
Method::Equal => Some(Method::SpatialEquals),
Method::NotEqual => Some(Method::NotSpatialEquals),
Method::Contains => Some(Method::Covers),
Method::NotContains => Some(Method::NotCovers),
_ => None,
};
if let Some(spatial) = spatial {
return b.step_string(
Step::CompileSpatialFilter,
&[Arg::Method(spatial), Arg::Str(&attribute), Arg::Query(query)],
);
}
}
if method.is_json() {
return b.step_string(Step::CompileJsonFilter, &[Arg::Method(method), Arg::Str(&attribute), Arg::Query(query)]);
}
if query.on_array()
&& matches!(method, Method::Contains | Method::ContainsAny | Method::NotContains | Method::ContainsAll)
{
return b
.step_string(Step::CompileArrayFilter, &[Arg::Method(method), Arg::Str(&attribute), Arg::Query(query)]);
}
b.base_compile_filter(query)
}
pub(crate) fn sql_compile_array_filter<D: SqlDialect>(
b: &mut Builder<D>,
method: Method,
attribute: &str,
query: &Query,
) -> Result<String> {
let wrapped = crate::value::list([Value::Array(query.values().clone())]);
match method {
Method::Contains | Method::ContainsAny => {
b.step_string(Step::CompileJsonOverlapsExpression, &[Arg::Str(attribute), Arg::Values(&wrapped)])
}
Method::NotContains => Ok(format!(
"NOT {}",
b.step_string(Step::CompileJsonOverlapsExpression, &[Arg::Str(attribute), Arg::Values(&wrapped)])?
)),
Method::ContainsAll => b.step_string(
Step::CompileJsonContainsExpression,
&[Arg::Str(attribute), Arg::Values(&wrapped), Arg::Bool(false)],
),
_ => b.base_compile_filter(query),
}
}
pub(crate) fn sql_compile_spatial_filter<D: SqlDialect>(
b: &mut Builder<D>,
method: Method,
attribute: &str,
query: &Query,
) -> Result<String> {
let values = query.values();
let predicate = |b: &mut Builder<D>, function: &str, not: bool| {
b.step_string(
Step::CompileSpatialPredicate,
&[Arg::Str(function), Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)],
)
};
use Method::*;
match method {
DistanceLessThan | DistanceGreaterThan | DistanceEqual | DistanceNotEqual => b.step_string(
Step::CompileSpatialDistance,
&[Arg::Method(method), Arg::Str(attribute), Arg::Values(values)],
),
Intersects => predicate(b, "ST_Intersects", false),
NotIntersects => predicate(b, "ST_Intersects", true),
Crosses => predicate(b, "ST_Crosses", false),
NotCrosses => predicate(b, "ST_Crosses", true),
Overlaps => predicate(b, "ST_Overlaps", false),
NotOverlaps => predicate(b, "ST_Overlaps", true),
Touches => predicate(b, "ST_Touches", false),
NotTouches => predicate(b, "ST_Touches", true),
Covers => b.step_string(
Step::CompileSpatialCoversPredicate,
&[Arg::Str(attribute), Arg::Values(values), Arg::Bool(false)],
),
NotCovers => b.step_string(
Step::CompileSpatialCoversPredicate,
&[Arg::Str(attribute), Arg::Values(values), Arg::Bool(true)],
),
SpatialEquals => predicate(b, "ST_Equals", false),
NotSpatialEquals => predicate(b, "ST_Equals", true),
_ => b.base_compile_filter(query),
}
}
pub(crate) fn sql_compile_json_filter<D: SqlDialect>(
b: &mut Builder<D>,
method: Method,
attribute: &str,
query: &Query,
) -> Result<String> {
let values = query.values();
match method {
Method::JsonContains => b.step_string(
Step::CompileJsonContainsExpression,
&[Arg::Str(attribute), Arg::Values(values), Arg::Bool(false)],
),
Method::JsonNotContains => b.step_string(
Step::CompileJsonContainsExpression,
&[Arg::Str(attribute), Arg::Values(values), Arg::Bool(true)],
),
Method::JsonOverlaps => {
b.step_string(Step::CompileJsonOverlapsExpression, &[Arg::Str(attribute), Arg::Values(values)])
}
Method::JsonPath => b.step_string(Step::CompileJsonPathExpression, &[Arg::Str(attribute), Arg::Values(values)]),
_ => b.base_compile_filter(query),
}
}
fn coordinate(value: Option<&Value>) -> String {
php_std::number::to_string(value.map(Value::to_double).unwrap_or(0.0))
}
fn at(array: &Array, index: i64) -> Option<&Value> {
array.get(&ArrayKey::Int(index))
}
pub fn geometry_to_wkt(geometry: &Array) -> Result<String> {
if is_coordinate(geometry) {
return Ok(format!("POINT({})", coordinate_wkt(geometry)));
}
let Some(Value::Array(first)) = at(geometry, 0).filter(|_| geometry.is_list()) else {
return Err(invalid("expected an [x, y] point, a list of points or a list of rings"));
};
if let Some(Value::Array(_)) = at(first, 0) {
let rings = geometry.values().map(|ring| Ok(format!("({})", ring_wkt(ring)?))).collect::<Result<Vec<_>>>()?;
return Ok(format!("POLYGON({})", rings.join(", ")));
}
if geometry.len() == 1 {
return Ok(format!("POINT({})", point_wkt(at(geometry, 0))?));
}
Ok(format!("LINESTRING({})", points_wkt(geometry)?))
}
fn invalid(reason: &str) -> crate::Error {
crate::Error::Validation(format!("Invalid geometry: {reason}"))
}
fn ring_wkt(ring: &Value) -> Result<String> {
let ring = match ring {
Value::Array(ring) if !ring.is_empty() && ring.is_list() => ring,
_ => return Err(invalid("a polygon ring must be a list of points")),
};
let wkt = points_wkt(ring)?;
if ring.len() < 4 {
return Err(invalid("a polygon ring must have at least 4 points"));
}
let xy = |p: Option<&Value>| match p {
Some(Value::Array(p)) => (number(at(p, 0)), number(at(p, 1))),
_ => (0.0, 0.0),
};
if xy(at(ring, 0)) != xy(at(ring, ring.len() as i64 - 1)) {
return Err(invalid("a polygon ring must be closed, with its first point equal to its last"));
}
Ok(wkt)
}
fn points_wkt(points: &Array) -> Result<String> {
Ok(points.values().map(|p| point_wkt(Some(p))).collect::<Result<Vec<_>>>()?.join(", "))
}
pub(crate) fn point_wkt(point: Option<&Value>) -> Result<String> {
match point {
Some(Value::Array(p)) if is_coordinate(p) => Ok(coordinate_wkt(p)),
_ => Err(invalid("every point must be an [x, y] pair of finite numbers")),
}
}
fn coordinate_wkt(point: &Array) -> String {
format!("{} {}", coordinate(at(point, 0)), coordinate(at(point, 1)))
}
fn is_coordinate(value: &Array) -> bool {
let finite = |v: Option<&Value>| v.is_some_and(|v| is_numeric(v) && v.to_double().is_finite());
value.len() == 2 && value.is_list() && finite(at(value, 0)) && finite(at(value, 1))
}
fn number(value: Option<&Value>) -> f64 {
value.map(Value::to_double).unwrap_or(0.0)
}
pub(crate) fn predicate_wkt<D: Dialect>(
b: &mut Builder<D>,
values: &Array,
class: &str,
file: &'static str,
line: u32,
) -> Result<String> {
let geometry = values.get(&ArrayKey::Int(0)).unwrap_or(&Value::Null);
let function = format!("{class}::geometryToWkt");
b.geometry_to_wkt(Param::method(&function, 1, "geometry", file, line).array(geometry)?)
}
pub(crate) fn distance_filter(values: &Array, file: &'static str, line: u32) -> Result<SpatialDistanceFilter> {
let tuple = values.get(&ArrayKey::Int(0)).unwrap_or(&Value::Null);
let param = Param::method("Utopia\\Query\\Builder\\SpatialDistanceFilter::fromTuple", 1, "tuple", file, line);
SpatialDistanceFilter::from_tuple(param.array(tuple)?)
}
pub(crate) fn wkt_of<D: Dialect>(b: &mut Builder<D>, geometry: &Value) -> Result<Value> {
Ok(match geometry {
Value::Array(a) => crate::value::string(b.geometry_to_wkt(a)?),
other => other.clone(),
})
}
pub(crate) fn distance_operator(method: Method) -> &'static str {
match method {
Method::DistanceGreaterThan => ">",
Method::DistanceEqual => "=",
Method::DistanceNotEqual => "!=",
_ => "<",
}
}