1use crate::builder::steps::{Arg, Ret, Step};
8use php_std::ArrayKey;
9
10use crate::builder::core::{Builder, Dialect};
11use crate::builder::types::SpatialDistanceFilter;
12use crate::error::Result;
13use crate::method::Method;
14use crate::query::{Query, is_numeric};
15use crate::value::{Array, Param, Value};
16
17pub trait SqlDialect: Dialect {
20 fn compile_search_expression(b: &mut Builder<Self>, attribute: &str, values: &Array, not: bool) -> Result<String>;
22
23 fn compile_spatial_distance(
25 b: &mut Builder<Self>,
26 method: Method,
27 attribute: &str,
28 values: &Array,
29 ) -> Result<String>;
30
31 fn compile_spatial_predicate(
33 b: &mut Builder<Self>,
34 function: &str,
35 attribute: &str,
36 values: &Array,
37 not: bool,
38 ) -> Result<String>;
39
40 fn compile_spatial_covers_predicate(
42 b: &mut Builder<Self>,
43 attribute: &str,
44 values: &Array,
45 not: bool,
46 ) -> Result<String>;
47
48 fn compile_json_contains_expression(
50 b: &mut Builder<Self>,
51 attribute: &str,
52 values: &Array,
53 not: bool,
54 ) -> Result<String>;
55
56 fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String>;
58
59 fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String>;
61
62 fn compile_conflict_header(b: &mut Builder<Self>) -> Result<String>;
64
65 fn compile_conflict_assignment(wrapped: &str) -> String;
67
68 fn compile_spatial_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
70 sql_compile_spatial_filter(b, method, attribute, query)
71 }
72
73 fn compile_array_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
75 sql_compile_array_filter(b, method, attribute, query)
76 }
77}
78
79pub(crate) fn sql_base_step<D: SqlDialect>(
81 b: &mut Builder<D>,
82 step: Step,
83 arguments: &[Arg<'_>],
84) -> Option<Result<Ret>> {
85 Some(match (step, arguments) {
86 (Step::CompileSearchExpression, [Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)]) => {
87 D::compile_search_expression(b, attribute, values, *not).map(Ret::Str)
88 }
89 (Step::CompileSpatialFilter, [Arg::Method(method), Arg::Str(attribute), Arg::Query(query)]) => {
90 D::compile_spatial_filter(b, *method, attribute, query).map(Ret::Str)
91 }
92 (Step::CompileArrayFilter, [Arg::Method(method), Arg::Str(attribute), Arg::Query(query)]) => {
93 D::compile_array_filter(b, *method, attribute, query).map(Ret::Str)
94 }
95 (Step::CompileJsonContainsExpression, [Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)]) => {
96 D::compile_json_contains_expression(b, attribute, values, *not).map(Ret::Str)
97 }
98 (Step::CompileJsonOverlapsExpression, [Arg::Str(attribute), Arg::Values(values)]) => {
99 D::compile_json_overlaps_expression(b, attribute, values).map(Ret::Str)
100 }
101 (Step::CompileSpatialDistance, [Arg::Method(method), Arg::Str(attribute), Arg::Values(values)]) => {
102 D::compile_spatial_distance(b, *method, attribute, values).map(Ret::Str)
103 }
104 (
105 Step::CompileSpatialPredicate,
106 [Arg::Str(function), Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)],
107 ) => D::compile_spatial_predicate(b, function, attribute, values, *not).map(Ret::Str),
108 (Step::CompileSpatialCoversPredicate, [Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)]) => {
109 D::compile_spatial_covers_predicate(b, attribute, values, *not).map(Ret::Str)
110 }
111 (Step::CompileJsonPathExpression, [Arg::Str(attribute), Arg::Values(values)]) => {
112 D::compile_json_path_expression(b, attribute, values).map(Ret::Str)
113 }
114 (Step::CompileJsonFilter, [Arg::Method(method), Arg::Str(attribute), Arg::Query(query)]) => {
115 sql_compile_json_filter(b, *method, attribute, query).map(Ret::Str)
116 }
117 (Step::CompileConflictHeader, []) => D::compile_conflict_header(b).map(Ret::Str),
118 (Step::CompileConflictAssignment, [Arg::Str(wrapped)]) => Ok(Ret::Str(D::compile_conflict_assignment(wrapped))),
119 (Step::CompileConflictClause, []) => crate::builder::mysql::base_conflict_clause(b).map(Ret::Str),
120 _ => return None,
121 })
122}
123
124pub(crate) fn sql_compile_filter<D: SqlDialect>(b: &mut Builder<D>, query: &Query) -> Result<String> {
127 let method = query.method();
128 let attribute = b.resolve_and_wrap(query.attribute())?;
129 match method {
130 Method::Search => {
131 return b.step_string(
132 Step::CompileSearchExpression,
133 &[Arg::Str(&attribute), Arg::Values(query.values()), Arg::Bool(false)],
134 );
135 }
136 Method::NotSearch => {
137 return b.step_string(
138 Step::CompileSearchExpression,
139 &[Arg::Str(&attribute), Arg::Values(query.values()), Arg::Bool(true)],
140 );
141 }
142 _ => {}
143 }
144 if method.is_spatial() {
145 return b
146 .step_string(Step::CompileSpatialFilter, &[Arg::Method(method), Arg::Str(&attribute), Arg::Query(query)]);
147 }
148 if matches!(query.attribute_type(), "point" | "linestring" | "polygon") {
149 let spatial = match method {
150 Method::Equal => Some(Method::SpatialEquals),
151 Method::NotEqual => Some(Method::NotSpatialEquals),
152 Method::Contains => Some(Method::Covers),
153 Method::NotContains => Some(Method::NotCovers),
154 _ => None,
155 };
156 if let Some(spatial) = spatial {
157 return b.step_string(
158 Step::CompileSpatialFilter,
159 &[Arg::Method(spatial), Arg::Str(&attribute), Arg::Query(query)],
160 );
161 }
162 }
163 if method.is_json() {
164 return b.step_string(Step::CompileJsonFilter, &[Arg::Method(method), Arg::Str(&attribute), Arg::Query(query)]);
165 }
166 if query.on_array()
167 && matches!(method, Method::Contains | Method::ContainsAny | Method::NotContains | Method::ContainsAll)
168 {
169 return b
170 .step_string(Step::CompileArrayFilter, &[Arg::Method(method), Arg::Str(&attribute), Arg::Query(query)]);
171 }
172 b.base_compile_filter(query)
173}
174
175pub(crate) fn sql_compile_array_filter<D: SqlDialect>(
177 b: &mut Builder<D>,
178 method: Method,
179 attribute: &str,
180 query: &Query,
181) -> Result<String> {
182 let wrapped = crate::value::list([Value::Array(query.values().clone())]);
183 match method {
184 Method::Contains | Method::ContainsAny => {
185 b.step_string(Step::CompileJsonOverlapsExpression, &[Arg::Str(attribute), Arg::Values(&wrapped)])
186 }
187 Method::NotContains => Ok(format!(
188 "NOT {}",
189 b.step_string(Step::CompileJsonOverlapsExpression, &[Arg::Str(attribute), Arg::Values(&wrapped)])?
190 )),
191 Method::ContainsAll => b.step_string(
192 Step::CompileJsonContainsExpression,
193 &[Arg::Str(attribute), Arg::Values(&wrapped), Arg::Bool(false)],
194 ),
195 _ => b.base_compile_filter(query),
196 }
197}
198
199pub(crate) fn sql_compile_spatial_filter<D: SqlDialect>(
201 b: &mut Builder<D>,
202 method: Method,
203 attribute: &str,
204 query: &Query,
205) -> Result<String> {
206 let values = query.values();
207 let predicate = |b: &mut Builder<D>, function: &str, not: bool| {
208 b.step_string(
209 Step::CompileSpatialPredicate,
210 &[Arg::Str(function), Arg::Str(attribute), Arg::Values(values), Arg::Bool(not)],
211 )
212 };
213 use Method::*;
214 match method {
215 DistanceLessThan | DistanceGreaterThan | DistanceEqual | DistanceNotEqual => b.step_string(
216 Step::CompileSpatialDistance,
217 &[Arg::Method(method), Arg::Str(attribute), Arg::Values(values)],
218 ),
219 Intersects => predicate(b, "ST_Intersects", false),
220 NotIntersects => predicate(b, "ST_Intersects", true),
221 Crosses => predicate(b, "ST_Crosses", false),
222 NotCrosses => predicate(b, "ST_Crosses", true),
223 Overlaps => predicate(b, "ST_Overlaps", false),
224 NotOverlaps => predicate(b, "ST_Overlaps", true),
225 Touches => predicate(b, "ST_Touches", false),
226 NotTouches => predicate(b, "ST_Touches", true),
227 Covers => b.step_string(
228 Step::CompileSpatialCoversPredicate,
229 &[Arg::Str(attribute), Arg::Values(values), Arg::Bool(false)],
230 ),
231 NotCovers => b.step_string(
232 Step::CompileSpatialCoversPredicate,
233 &[Arg::Str(attribute), Arg::Values(values), Arg::Bool(true)],
234 ),
235 SpatialEquals => predicate(b, "ST_Equals", false),
236 NotSpatialEquals => predicate(b, "ST_Equals", true),
237 _ => b.base_compile_filter(query),
238 }
239}
240
241pub(crate) fn sql_compile_json_filter<D: SqlDialect>(
243 b: &mut Builder<D>,
244 method: Method,
245 attribute: &str,
246 query: &Query,
247) -> Result<String> {
248 let values = query.values();
249 match method {
250 Method::JsonContains => b.step_string(
251 Step::CompileJsonContainsExpression,
252 &[Arg::Str(attribute), Arg::Values(values), Arg::Bool(false)],
253 ),
254 Method::JsonNotContains => b.step_string(
255 Step::CompileJsonContainsExpression,
256 &[Arg::Str(attribute), Arg::Values(values), Arg::Bool(true)],
257 ),
258 Method::JsonOverlaps => {
259 b.step_string(Step::CompileJsonOverlapsExpression, &[Arg::Str(attribute), Arg::Values(values)])
260 }
261 Method::JsonPath => b.step_string(Step::CompileJsonPathExpression, &[Arg::Str(attribute), Arg::Values(values)]),
262 _ => b.base_compile_filter(query),
263 }
264}
265
266fn coordinate(value: Option<&Value>) -> String {
268 php_std::number::to_string(value.map(Value::to_double).unwrap_or(0.0))
269}
270
271fn at(array: &Array, index: i64) -> Option<&Value> {
272 array.get(&ArrayKey::Int(index))
273}
274
275pub fn geometry_to_wkt(geometry: &Array) -> Result<String> {
282 if is_coordinate(geometry) {
283 return Ok(format!("POINT({})", coordinate_wkt(geometry)));
284 }
285 let Some(Value::Array(first)) = at(geometry, 0).filter(|_| geometry.is_list()) else {
286 return Err(invalid("expected an [x, y] point, a list of points or a list of rings"));
287 };
288 if let Some(Value::Array(_)) = at(first, 0) {
289 let rings = geometry.values().map(|ring| Ok(format!("({})", ring_wkt(ring)?))).collect::<Result<Vec<_>>>()?;
290 return Ok(format!("POLYGON({})", rings.join(", ")));
291 }
292 if geometry.len() == 1 {
293 return Ok(format!("POINT({})", point_wkt(at(geometry, 0))?));
294 }
295 Ok(format!("LINESTRING({})", points_wkt(geometry)?))
296}
297
298fn invalid(reason: &str) -> crate::Error {
299 crate::Error::Validation(format!("Invalid geometry: {reason}"))
300}
301
302fn ring_wkt(ring: &Value) -> Result<String> {
304 let ring = match ring {
305 Value::Array(ring) if !ring.is_empty() && ring.is_list() => ring,
306 _ => return Err(invalid("a polygon ring must be a list of points")),
307 };
308 let wkt = points_wkt(ring)?;
309 if ring.len() < 4 {
310 return Err(invalid("a polygon ring must have at least 4 points"));
311 }
312 let xy = |p: Option<&Value>| match p {
313 Some(Value::Array(p)) => (number(at(p, 0)), number(at(p, 1))),
314 _ => (0.0, 0.0),
315 };
316 if xy(at(ring, 0)) != xy(at(ring, ring.len() as i64 - 1)) {
317 return Err(invalid("a polygon ring must be closed, with its first point equal to its last"));
318 }
319 Ok(wkt)
320}
321
322fn points_wkt(points: &Array) -> Result<String> {
324 Ok(points.values().map(|p| point_wkt(Some(p))).collect::<Result<Vec<_>>>()?.join(", "))
325}
326
327pub(crate) fn point_wkt(point: Option<&Value>) -> Result<String> {
330 match point {
331 Some(Value::Array(p)) if is_coordinate(p) => Ok(coordinate_wkt(p)),
332 _ => Err(invalid("every point must be an [x, y] pair of finite numbers")),
333 }
334}
335
336fn coordinate_wkt(point: &Array) -> String {
337 format!("{} {}", coordinate(at(point, 0)), coordinate(at(point, 1)))
338}
339
340fn is_coordinate(value: &Array) -> bool {
342 let finite = |v: Option<&Value>| v.is_some_and(|v| is_numeric(v) && v.to_double().is_finite());
343 value.len() == 2 && value.is_list() && finite(at(value, 0)) && finite(at(value, 1))
344}
345
346fn number(value: Option<&Value>) -> f64 {
347 value.map(Value::to_double).unwrap_or(0.0)
348}
349
350pub(crate) fn predicate_wkt<D: Dialect>(
353 b: &mut Builder<D>,
354 values: &Array,
355 class: &str,
356 file: &'static str,
357 line: u32,
358) -> Result<String> {
359 let geometry = values.get(&ArrayKey::Int(0)).unwrap_or(&Value::Null);
360 let function = format!("{class}::geometryToWkt");
361 b.geometry_to_wkt(Param::method(&function, 1, "geometry", file, line).array(geometry)?)
362}
363
364pub(crate) fn distance_filter(values: &Array, file: &'static str, line: u32) -> Result<SpatialDistanceFilter> {
366 let tuple = values.get(&ArrayKey::Int(0)).unwrap_or(&Value::Null);
367 let param = Param::method("Utopia\\Query\\Builder\\SpatialDistanceFilter::fromTuple", 1, "tuple", file, line);
368 SpatialDistanceFilter::from_tuple(param.array(tuple)?)
369}
370
371pub(crate) fn wkt_of<D: Dialect>(b: &mut Builder<D>, geometry: &Value) -> Result<Value> {
373 Ok(match geometry {
374 Value::Array(a) => crate::value::string(b.geometry_to_wkt(a)?),
375 other => other.clone(),
376 })
377}
378
379pub(crate) fn distance_operator(method: Method) -> &'static str {
381 match method {
382 Method::DistanceGreaterThan => ">",
383 Method::DistanceEqual => "=",
384 Method::DistanceNotEqual => "!=",
385 _ => "<",
386 }
387}