1use std::fmt;
5use std::sync::Arc;
6
7use crate::error::{Error, Result};
8use crate::method::backed_enum;
9use crate::value::{Array, Value};
10
11pub type Executor = Arc<dyn Fn(&Statement) -> Result<Value> + Send + Sync>;
16
17#[derive(Clone)]
22pub struct Statement {
23 pub query: String,
25 pub bindings: Vec<Value>,
27 pub read_only: bool,
29 pub named_bindings: Option<Array>,
31 executor: Option<Executor>,
32}
33
34impl fmt::Debug for Statement {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 f.debug_struct("Statement")
38 .field("query", &self.query)
39 .field("bindings", &self.bindings)
40 .field("read_only", &self.read_only)
41 .field("named_bindings", &self.named_bindings)
42 .field("executor", &self.executor.is_some())
43 .finish()
44 }
45}
46
47impl PartialEq for Statement {
48 fn eq(&self, other: &Self) -> bool {
50 self.query == other.query
51 && self.bindings == other.bindings
52 && self.read_only == other.read_only
53 && self.named_bindings == other.named_bindings
54 }
55}
56
57impl Statement {
58 pub fn new(query: impl Into<String>, bindings: Vec<Value>) -> Self {
62 Statement { query: query.into(), bindings, read_only: false, named_bindings: None, executor: None }
63 }
64
65 pub fn with_parts(
69 query: impl Into<String>,
70 bindings: Vec<Value>,
71 read_only: bool,
72 executor: Option<Executor>,
73 named_bindings: Option<Array>,
74 ) -> Self {
75 Statement { query: query.into(), bindings, read_only, named_bindings, executor }
76 }
77
78 pub fn execute(&self) -> Result<Value> {
82 match &self.executor {
83 Some(executor) => executor(self),
84 None => Err(Error::NoExecutor("No executor configured on this plan".into())),
85 }
86 }
87
88 pub fn with_executor(&self, executor: Executor) -> Statement {
92 Statement { executor: Some(executor), ..self.clone() }
93 }
94
95 pub fn executor(&self) -> Option<&Executor> {
97 self.executor.as_ref()
98 }
99}
100
101#[derive(Debug, Clone, PartialEq)]
106pub struct Binding {
107 pub value: Value,
109 pub column: Option<String>,
111}
112
113impl Binding {
114 pub fn new(value: Value, column: Option<String>) -> Self {
116 Binding { value, column }
117 }
118}
119
120#[derive(Debug, Clone, PartialEq)]
124pub struct Condition {
125 pub expression: String,
127 pub bindings: Vec<Value>,
129}
130
131impl Condition {
132 pub fn new(expression: impl Into<String>, bindings: Vec<Value>) -> Self {
134 Condition { expression: expression.into(), bindings }
135 }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct ColumnPredicate {
143 pub left: String,
145 pub operator: String,
147 pub right: String,
149}
150
151impl ColumnPredicate {
152 pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
154 ColumnPredicate { left: left.into(), operator: operator.into(), right: right.into() }
155 }
156}
157
158#[derive(Debug, Clone, PartialEq)]
162pub struct CteClause {
163 pub name: String,
165 pub query: String,
167 pub bindings: Vec<Value>,
169 pub recursive: bool,
171 pub columns: Vec<String>,
173}
174
175impl CteClause {
176 pub fn new(
178 name: impl Into<String>,
179 query: impl Into<String>,
180 bindings: Vec<Value>,
181 recursive: bool,
182 columns: Vec<String>,
183 ) -> Self {
184 CteClause { name: name.into(), query: query.into(), bindings, recursive, columns }
185 }
186}
187
188#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct JoinOn {
193 pub left: String,
195 pub operator: String,
197 pub right: String,
199}
200
201impl JoinOn {
202 pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
204 JoinOn { left: left.into(), operator: operator.into(), right: right.into() }
205 }
206}
207
208backed_enum! {
209 pub enum JoinType: "Utopia\\Query\\Builder\\JoinType" {
213 Inner = "JOIN",
215 Left = "LEFT JOIN",
217 Right = "RIGHT JOIN",
219 Cross = "CROSS JOIN",
221 FullOuter = "FULL OUTER JOIN",
223 Natural = "NATURAL JOIN",
225 }
226}
227
228backed_enum! {
229 pub enum LockMode: "Utopia\\Query\\Builder\\LockMode" {
233 ForUpdate = "FOR UPDATE",
235 ForShare = "FOR SHARE",
237 ForUpdateSkipLocked = "FOR UPDATE SKIP LOCKED",
239 ForUpdateNoWait = "FOR UPDATE NOWAIT",
241 ForShareSkipLocked = "FOR SHARE SKIP LOCKED",
243 ForShareNoWait = "FOR SHARE NOWAIT",
245 }
246}
247
248impl LockMode {
249 pub fn to_sql(self) -> &'static str {
253 self.as_str()
254 }
255}
256
257backed_enum! {
258 pub enum UnionType: "Utopia\\Query\\Builder\\UnionType" {
262 Union = "UNION",
264 UnionAll = "UNION ALL",
266 Intersect = "INTERSECT",
268 IntersectAll = "INTERSECT ALL",
270 Except = "EXCEPT",
272 ExceptAll = "EXCEPT ALL",
274 }
275}
276
277#[derive(Debug, Clone, PartialEq)]
281pub struct UnionClause {
282 pub union_type: UnionType,
284 pub query: String,
286 pub bindings: Vec<Value>,
288}
289
290impl UnionClause {
291 pub fn new(union_type: UnionType, query: impl Into<String>, bindings: Vec<Value>) -> Self {
293 UnionClause { union_type, query: query.into(), bindings }
294 }
295}
296
297backed_enum! {
298 pub enum VectorMetric: "Utopia\\Query\\Builder\\VectorMetric" {
302 Cosine = "cosine",
304 Euclidean = "euclidean",
306 Dot = "dot",
308 }
309}
310
311impl VectorMetric {
312 pub fn to_operator(self) -> &'static str {
316 match self {
317 VectorMetric::Cosine => "<=>",
318 VectorMetric::Euclidean => "<->",
319 VectorMetric::Dot => "<#>",
320 }
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq)]
328pub struct WindowFrame {
329 pub frame_type: String,
331 pub start: String,
333 pub end: Option<String>,
335}
336
337impl WindowFrame {
338 pub fn new(frame_type: impl Into<String>, start: impl Into<String>, end: Option<String>) -> Self {
340 WindowFrame { frame_type: frame_type.into(), start: start.into(), end }
341 }
342
343 pub fn to_sql(&self) -> String {
347 match &self.end {
348 None => format!("{} {}", self.frame_type, self.start),
349 Some(end) => format!("{} BETWEEN {} AND {}", self.frame_type, self.start, end),
350 }
351 }
352}
353
354#[derive(Debug, Clone, PartialEq, Eq)]
358pub struct WindowDefinition {
359 pub name: String,
361 pub partition_by: Option<Vec<String>>,
363 pub order_by: Option<Vec<String>>,
365 pub frame: Option<WindowFrame>,
367}
368
369impl WindowDefinition {
370 pub fn new(
372 name: impl Into<String>,
373 partition_by: Option<Vec<String>>,
374 order_by: Option<Vec<String>>,
375 frame: Option<WindowFrame>,
376 ) -> Self {
377 WindowDefinition { name: name.into(), partition_by, order_by, frame }
378 }
379}
380
381#[derive(Debug, Clone, PartialEq, Eq)]
385pub struct WindowSelect {
386 pub function: String,
388 pub alias: String,
390 pub partition_by: Option<Vec<String>>,
392 pub order_by: Option<Vec<String>>,
394 pub window_name: Option<String>,
396 pub frame: Option<WindowFrame>,
398}
399
400impl WindowSelect {
401 pub fn new(
403 function: impl Into<String>,
404 alias: impl Into<String>,
405 partition_by: Option<Vec<String>>,
406 order_by: Option<Vec<String>>,
407 window_name: Option<String>,
408 frame: Option<WindowFrame>,
409 ) -> Self {
410 WindowSelect { function: function.into(), alias: alias.into(), partition_by, order_by, window_name, frame }
411 }
412}
413
414#[derive(Debug, Clone, PartialEq)]
418pub struct MergeClause {
419 pub action: String,
421 pub matched: bool,
423 pub bindings: Vec<Value>,
425}
426
427impl MergeClause {
428 pub fn new(action: impl Into<String>, matched: bool, bindings: Vec<Value>) -> Self {
430 MergeClause { action: action.into(), matched, bindings }
431 }
432}
433
434#[derive(Debug, Clone, PartialEq)]
438pub struct SpatialDistanceFilter {
439 pub geometry: Value,
441 pub distance: f64,
443 pub meters: bool,
445}
446
447impl SpatialDistanceFilter {
448 pub fn new(geometry: Value, distance: f64, meters: bool) -> Self {
450 SpatialDistanceFilter { geometry, distance, meters }
451 }
452
453 pub fn from_tuple(tuple: &Array) -> crate::Result<Self> {
461 let at = |i: i64| tuple.get(&php_std::ArrayKey::Int(i)).filter(|v| !matches!(v, Value::Null));
462 let geometry = match at(0) {
463 Some(g @ (Value::Str(_) | Value::Array(_))) => g.clone(),
464 _ => {
465 return Err(Error::Validation(
466 "Invalid distance query: the geometry must be a WKT string or a coordinate array".into(),
467 ));
468 }
469 };
470 let distance = at(1).filter(|d| crate::query::is_numeric(d)).map(Value::to_double);
471 let Some(distance) = distance.filter(|d| d.is_finite()) else {
472 return Err(Error::Validation("Invalid distance query: the distance must be a finite number".into()));
473 };
474 let Some(meters) = at(2).map_or(Some(false), filter_bool) else {
475 return Err(Error::Validation("Invalid distance query: meters must be a boolean".into()));
476 };
477 Ok(SpatialDistanceFilter { geometry, distance, meters })
478 }
479}
480
481fn filter_bool(value: &Value) -> Option<bool> {
484 use php_std::filter as f;
485 let value = match value {
486 Value::Null => f::Value::Null,
487 Value::Bool(b) => f::Value::Bool(*b),
488 Value::Int(i) => f::Value::Int(*i),
489 Value::Float(x) => f::Value::Float(*x),
490 Value::Str(s) => f::Value::Str(s.as_bytes().to_vec()),
491 _ => return None,
493 };
494 match f::filter_var(&value, f::FILTER_VALIDATE_BOOL, &f::Options::Flags(f::FILTER_NULL_ON_FAILURE)) {
495 Ok(f::Filtered { value: f::Value::Bool(b), .. }) => Some(b),
496 _ => None,
497 }
498}