use std::fmt;
use std::sync::Arc;
use crate::error::{Error, Result};
use crate::method::backed_enum;
use crate::value::{Array, Value};
pub type Executor = Arc<dyn Fn(&Statement) -> Result<Value> + Send + Sync>;
#[derive(Clone)]
pub struct Statement {
pub query: String,
pub bindings: Vec<Value>,
pub read_only: bool,
pub named_bindings: Option<Array>,
executor: Option<Executor>,
}
impl fmt::Debug for Statement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Statement")
.field("query", &self.query)
.field("bindings", &self.bindings)
.field("read_only", &self.read_only)
.field("named_bindings", &self.named_bindings)
.field("executor", &self.executor.is_some())
.finish()
}
}
impl PartialEq for Statement {
fn eq(&self, other: &Self) -> bool {
self.query == other.query
&& self.bindings == other.bindings
&& self.read_only == other.read_only
&& self.named_bindings == other.named_bindings
}
}
impl Statement {
pub fn new(query: impl Into<String>, bindings: Vec<Value>) -> Self {
Statement { query: query.into(), bindings, read_only: false, named_bindings: None, executor: None }
}
pub fn with_parts(
query: impl Into<String>,
bindings: Vec<Value>,
read_only: bool,
executor: Option<Executor>,
named_bindings: Option<Array>,
) -> Self {
Statement { query: query.into(), bindings, read_only, named_bindings, executor }
}
pub fn execute(&self) -> Result<Value> {
match &self.executor {
Some(executor) => executor(self),
None => Err(Error::NoExecutor("No executor configured on this plan".into())),
}
}
pub fn with_executor(&self, executor: Executor) -> Statement {
Statement { executor: Some(executor), ..self.clone() }
}
pub fn executor(&self) -> Option<&Executor> {
self.executor.as_ref()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Binding {
pub value: Value,
pub column: Option<String>,
}
impl Binding {
pub fn new(value: Value, column: Option<String>) -> Self {
Binding { value, column }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Condition {
pub expression: String,
pub bindings: Vec<Value>,
}
impl Condition {
pub fn new(expression: impl Into<String>, bindings: Vec<Value>) -> Self {
Condition { expression: expression.into(), bindings }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnPredicate {
pub left: String,
pub operator: String,
pub right: String,
}
impl ColumnPredicate {
pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
ColumnPredicate { left: left.into(), operator: operator.into(), right: right.into() }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CteClause {
pub name: String,
pub query: String,
pub bindings: Vec<Value>,
pub recursive: bool,
pub columns: Vec<String>,
}
impl CteClause {
pub fn new(
name: impl Into<String>,
query: impl Into<String>,
bindings: Vec<Value>,
recursive: bool,
columns: Vec<String>,
) -> Self {
CteClause { name: name.into(), query: query.into(), bindings, recursive, columns }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JoinOn {
pub left: String,
pub operator: String,
pub right: String,
}
impl JoinOn {
pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
JoinOn { left: left.into(), operator: operator.into(), right: right.into() }
}
}
backed_enum! {
pub enum JoinType: "Utopia\\Query\\Builder\\JoinType" {
Inner = "JOIN",
Left = "LEFT JOIN",
Right = "RIGHT JOIN",
Cross = "CROSS JOIN",
FullOuter = "FULL OUTER JOIN",
Natural = "NATURAL JOIN",
}
}
backed_enum! {
pub enum LockMode: "Utopia\\Query\\Builder\\LockMode" {
ForUpdate = "FOR UPDATE",
ForShare = "FOR SHARE",
ForUpdateSkipLocked = "FOR UPDATE SKIP LOCKED",
ForUpdateNoWait = "FOR UPDATE NOWAIT",
ForShareSkipLocked = "FOR SHARE SKIP LOCKED",
ForShareNoWait = "FOR SHARE NOWAIT",
}
}
impl LockMode {
pub fn to_sql(self) -> &'static str {
self.as_str()
}
}
backed_enum! {
pub enum UnionType: "Utopia\\Query\\Builder\\UnionType" {
Union = "UNION",
UnionAll = "UNION ALL",
Intersect = "INTERSECT",
IntersectAll = "INTERSECT ALL",
Except = "EXCEPT",
ExceptAll = "EXCEPT ALL",
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct UnionClause {
pub union_type: UnionType,
pub query: String,
pub bindings: Vec<Value>,
}
impl UnionClause {
pub fn new(union_type: UnionType, query: impl Into<String>, bindings: Vec<Value>) -> Self {
UnionClause { union_type, query: query.into(), bindings }
}
}
backed_enum! {
pub enum VectorMetric: "Utopia\\Query\\Builder\\VectorMetric" {
Cosine = "cosine",
Euclidean = "euclidean",
Dot = "dot",
}
}
impl VectorMetric {
pub fn to_operator(self) -> &'static str {
match self {
VectorMetric::Cosine => "<=>",
VectorMetric::Euclidean => "<->",
VectorMetric::Dot => "<#>",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowFrame {
pub frame_type: String,
pub start: String,
pub end: Option<String>,
}
impl WindowFrame {
pub fn new(frame_type: impl Into<String>, start: impl Into<String>, end: Option<String>) -> Self {
WindowFrame { frame_type: frame_type.into(), start: start.into(), end }
}
pub fn to_sql(&self) -> String {
match &self.end {
None => format!("{} {}", self.frame_type, self.start),
Some(end) => format!("{} BETWEEN {} AND {}", self.frame_type, self.start, end),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowDefinition {
pub name: String,
pub partition_by: Option<Vec<String>>,
pub order_by: Option<Vec<String>>,
pub frame: Option<WindowFrame>,
}
impl WindowDefinition {
pub fn new(
name: impl Into<String>,
partition_by: Option<Vec<String>>,
order_by: Option<Vec<String>>,
frame: Option<WindowFrame>,
) -> Self {
WindowDefinition { name: name.into(), partition_by, order_by, frame }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowSelect {
pub function: String,
pub alias: String,
pub partition_by: Option<Vec<String>>,
pub order_by: Option<Vec<String>>,
pub window_name: Option<String>,
pub frame: Option<WindowFrame>,
}
impl WindowSelect {
pub fn new(
function: impl Into<String>,
alias: impl Into<String>,
partition_by: Option<Vec<String>>,
order_by: Option<Vec<String>>,
window_name: Option<String>,
frame: Option<WindowFrame>,
) -> Self {
WindowSelect { function: function.into(), alias: alias.into(), partition_by, order_by, window_name, frame }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MergeClause {
pub action: String,
pub matched: bool,
pub bindings: Vec<Value>,
}
impl MergeClause {
pub fn new(action: impl Into<String>, matched: bool, bindings: Vec<Value>) -> Self {
MergeClause { action: action.into(), matched, bindings }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SpatialDistanceFilter {
pub geometry: Value,
pub distance: f64,
pub meters: bool,
}
impl SpatialDistanceFilter {
pub fn new(geometry: Value, distance: f64, meters: bool) -> Self {
SpatialDistanceFilter { geometry, distance, meters }
}
pub fn from_tuple(tuple: &Array) -> crate::Result<Self> {
let at = |i: i64| tuple.get(&php_std::ArrayKey::Int(i)).filter(|v| !matches!(v, Value::Null));
let geometry = match at(0) {
Some(g @ (Value::Str(_) | Value::Array(_))) => g.clone(),
_ => {
return Err(Error::Validation(
"Invalid distance query: the geometry must be a WKT string or a coordinate array".into(),
));
}
};
let distance = at(1).filter(|d| crate::query::is_numeric(d)).map(Value::to_double);
let Some(distance) = distance.filter(|d| d.is_finite()) else {
return Err(Error::Validation("Invalid distance query: the distance must be a finite number".into()));
};
let Some(meters) = at(2).map_or(Some(false), filter_bool) else {
return Err(Error::Validation("Invalid distance query: meters must be a boolean".into()));
};
Ok(SpatialDistanceFilter { geometry, distance, meters })
}
}
fn filter_bool(value: &Value) -> Option<bool> {
use php_std::filter as f;
let value = match value {
Value::Null => f::Value::Null,
Value::Bool(b) => f::Value::Bool(*b),
Value::Int(i) => f::Value::Int(*i),
Value::Float(x) => f::Value::Float(*x),
Value::Str(s) => f::Value::Str(s.as_bytes().to_vec()),
_ => return None,
};
match f::filter_var(&value, f::FILTER_VALIDATE_BOOL, &f::Options::Flags(f::FILTER_NULL_ON_FAILURE)) {
Ok(f::Filtered { value: f::Value::Bool(b), .. }) => Some(b),
_ => None,
}
}