use std::marker::PhantomData;
use std::sync::Arc;
use crate::filter::{ArrayFilterOp, CmpOp, Filter, FilterNode, JsonFilterOp, SpatialOp, Subquery};
use crate::join::JoinOn;
use crate::json::{JsonColumn, JsonPath, JsonPathSegment, JsonSet};
use crate::order::OrderBy;
use crate::spatial::{Point, Polygon};
use crate::value::{Encodable, Ordered, Value};
pub struct Column<M, T> {
pub table: &'static str,
pub column: &'static str,
_marker: PhantomData<fn() -> (M, T)>,
}
impl<M, T> std::fmt::Debug for Column<M, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Column")
.field("table", &self.table)
.field("column", &self.column)
.finish()
}
}
impl<M, T> Copy for Column<M, T> {}
impl<M, T> Clone for Column<M, T> {
fn clone(&self) -> Self {
*self
}
}
impl<M, T> PartialEq for Column<M, T> {
fn eq(&self, other: &Self) -> bool {
self.table == other.table && self.column == other.column
}
}
impl<M, T> Eq for Column<M, T> {}
impl<M, T> Column<M, T> {
#[must_use]
pub const fn new(table: &'static str, column: &'static str) -> Self {
Self {
table,
column,
_marker: PhantomData,
}
}
pub fn on<J>(self, other: Column<J, T>) -> JoinOn {
JoinOn::new(self, other)
}
#[must_use]
pub const fn aliased(self, table: &'static str) -> Self {
Self {
table,
column: self.column,
_marker: PhantomData,
}
}
pub fn in_subquery<Q: Into<Subquery<T>>>(self, subquery: Q) -> Filter<M> {
let subquery = subquery.into().compiled;
Filter::new(FilterNode::InSubquery {
table: self.table,
column: self.column,
subquery,
negated: false,
})
}
pub fn not_in_subquery<Q: Into<Subquery<T>>>(self, subquery: Q) -> Filter<M> {
let subquery = subquery.into().compiled;
Filter::new(FilterNode::InSubquery {
table: self.table,
column: self.column,
subquery,
negated: true,
})
}
#[must_use]
pub fn correlated_to<J>(self, other: Column<J, T>) -> Filter<M> {
Filter::new(FilterNode::ColumnCmp {
left_table: self.table,
left_col: self.column,
op: CmpOp::Eq,
right_table: other.table,
right_col: other.column,
})
}
}
impl<M, T: Encodable> Column<M, T> {
pub fn eq<V: Into<T>>(self, value: V) -> Filter<M> {
let value = value.into().to_value();
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Eq,
value,
})
}
pub fn ne<V: Into<T>>(self, value: V) -> Filter<M> {
let value = value.into().to_value();
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Ne,
value,
})
}
pub fn in_<V: Into<T>>(self, values: Vec<V>) -> Filter<M> {
Filter::new(FilterNode::In {
table: self.table,
column: self.column,
values: values.into_iter().map(|v| v.into().to_value()).collect(),
negated: false,
})
}
pub fn in_set(self, values: impl IntoIterator<Item = impl Into<T>>) -> Filter<M> {
Filter::new(FilterNode::In {
table: self.table,
column: self.column,
values: values.into_iter().map(|v| v.into().to_value()).collect(),
negated: false,
})
}
pub fn not_in_set(self, values: impl IntoIterator<Item = impl Into<T>>) -> Filter<M> {
Filter::new(FilterNode::In {
table: self.table,
column: self.column,
values: values.into_iter().map(|v| v.into().to_value()).collect(),
negated: true,
})
}
pub fn asc(self) -> OrderBy<M> {
OrderBy::new(self.table, self.column, false)
}
pub fn desc(self) -> OrderBy<M> {
OrderBy::new(self.table, self.column, true)
}
}
impl<M, T: Ordered> Column<M, T> {
pub fn gt<V: Into<T>>(self, value: V) -> Filter<M> {
let value = value.into().to_value();
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Gt,
value,
})
}
pub fn gte<V: Into<T>>(self, value: V) -> Filter<M> {
let value = value.into().to_value();
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Gte,
value,
})
}
pub fn lt<V: Into<T>>(self, value: V) -> Filter<M> {
let value = value.into().to_value();
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Lt,
value,
})
}
pub fn lte<V: Into<T>>(self, value: V) -> Filter<M> {
let value = value.into().to_value();
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Lte,
value,
})
}
pub fn between<Lo: Into<T>, Hi: Into<T>>(self, lo: Lo, hi: Hi) -> Filter<M> {
Filter::new(FilterNode::Between {
table: self.table,
column: self.column,
lo: lo.into().to_value(),
hi: hi.into().to_value(),
})
}
}
impl<M> Column<M, String> {
pub fn contains(self, pattern: &str) -> Filter<M> {
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Like,
value: Value::Str(format!("%{pattern}%").into()),
})
}
pub fn starts_with(self, prefix: &str) -> Filter<M> {
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Like,
value: Value::Str(format!("{prefix}%").into()),
})
}
pub fn ends_with(self, suffix: &str) -> Filter<M> {
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Like,
value: Value::Str(format!("%{suffix}").into()),
})
}
pub fn ilike(self, pattern: &str) -> Filter<M> {
Filter::new(FilterNode::Cmp {
table: self.table,
column: self.column,
op: CmpOp::Ilike,
value: Value::Str(format!("%{pattern}%").into()),
})
}
pub fn matches(self, query: impl Into<String>) -> Filter<M> {
Filter::new(FilterNode::FullTextMatch {
table: self.table,
column: self.column,
query: query.into(),
})
}
}
impl<M> Column<M, Option<String>> {
pub fn matches(self, query: impl Into<String>) -> Filter<M> {
Filter::new(FilterNode::FullTextMatch {
table: self.table,
column: self.column,
query: query.into(),
})
}
}
impl<M> Column<M, Point> {
pub fn within_radius(self, point: &Point, distance_meters: f64) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::WithinRadius,
geometry: point.to_wkt(),
distance: Some(distance_meters),
})
}
pub fn distance_asc(self, point: &Point) -> OrderBy<M> {
OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), false)
}
pub fn distance_desc(self, point: &Point) -> OrderBy<M> {
OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), true)
}
pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Intersects,
geometry: polygon.to_wkt(),
distance: None,
})
}
pub fn within_polygon(self, polygon: &Polygon) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Within,
geometry: polygon.to_wkt(),
distance: None,
})
}
}
impl<M> Column<M, Option<Point>> {
pub fn within_radius(self, point: &Point, distance_meters: f64) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::WithinRadius,
geometry: point.to_wkt(),
distance: Some(distance_meters),
})
}
pub fn distance_asc(self, point: &Point) -> OrderBy<M> {
OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), false)
}
pub fn distance_desc(self, point: &Point) -> OrderBy<M> {
OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), true)
}
pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Intersects,
geometry: polygon.to_wkt(),
distance: None,
})
}
}
impl<M> Column<M, Polygon> {
pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Intersects,
geometry: polygon.to_wkt(),
distance: None,
})
}
pub fn contains_point(self, point: &Point) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Contains,
geometry: point.to_wkt(),
distance: None,
})
}
pub fn contains(self, polygon: &Polygon) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Contains,
geometry: polygon.to_wkt(),
distance: None,
})
}
}
impl<M> Column<M, Option<Polygon>> {
pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Intersects,
geometry: polygon.to_wkt(),
distance: None,
})
}
pub fn contains(self, polygon: &Polygon) -> Filter<M> {
Filter::new(FilterNode::Spatial {
table: self.table,
column: self.column,
op: SpatialOp::Contains,
geometry: polygon.to_wkt(),
distance: None,
})
}
}
impl<M, T> Column<M, Option<T>> {
pub fn is_null(self) -> Filter<M> {
Filter::new(FilterNode::Null {
table: self.table,
column: self.column,
negated: false,
})
}
pub fn is_not_null(self) -> Filter<M> {
Filter::new(FilterNode::Null {
table: self.table,
column: self.column,
negated: true,
})
}
}
impl<M> Column<M, serde_json::Value> {
#[must_use]
pub fn get(self, key: &'static str) -> JsonColumn<M, serde_json::Value> {
JsonColumn {
table: self.table,
column: self.column,
path: JsonPath(vec![JsonPathSegment::Key(key)]),
text: false,
_marker: PhantomData,
}
}
#[must_use]
pub fn get_text(self, key: &'static str) -> JsonColumn<M, String> {
JsonColumn {
table: self.table,
column: self.column,
path: JsonPath(vec![JsonPathSegment::Key(key)]),
text: true,
_marker: PhantomData,
}
}
#[must_use]
pub fn at(self, index: usize) -> JsonColumn<M, serde_json::Value> {
JsonColumn {
table: self.table,
column: self.column,
path: JsonPath(vec![JsonPathSegment::Index(index)]),
text: false,
_marker: PhantomData,
}
}
pub fn contains(self, value: serde_json::Value) -> Filter<M> {
Filter::new(FilterNode::Json {
table: self.table,
column: self.column,
path: JsonPath::default(),
text: false,
op: JsonFilterOp::Contains,
value: value.to_value(),
})
}
pub fn has_key(self, key: impl Into<String>) -> Filter<M> {
Filter::new(FilterNode::Json {
table: self.table,
column: self.column,
path: JsonPath::default(),
text: false,
op: JsonFilterOp::HasKey,
value: Value::Str(Arc::from(key.into())),
})
}
#[must_use]
pub fn json_set(self, key: &'static str, value: serde_json::Value) -> JsonSet {
JsonSet {
column: self.column,
path: JsonPath(vec![JsonPathSegment::Key(key)]),
value: value.to_value(),
}
}
#[must_use]
pub fn jsonb_set(self, key: &'static str, value: serde_json::Value) -> JsonSet {
self.json_set(key, value)
}
}
impl<M, T: Encodable> Column<M, Vec<T>> {
pub fn has<V: Into<T>>(self, value: V) -> Filter<M> {
Filter::new(FilterNode::Array {
table: self.table,
column: self.column,
op: ArrayFilterOp::Has,
values: vec![value.into().to_value()],
})
}
pub fn contains<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
Filter::new(FilterNode::Array {
table: self.table,
column: self.column,
op: ArrayFilterOp::Contains,
values: values.into_iter().map(|v| v.into().to_value()).collect(),
})
}
pub fn has_every<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
self.contains(values)
}
pub fn contained_by<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
Filter::new(FilterNode::Array {
table: self.table,
column: self.column,
op: ArrayFilterOp::ContainedBy,
values: values.into_iter().map(|v| v.into().to_value()).collect(),
})
}
pub fn overlaps<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
Filter::new(FilterNode::Array {
table: self.table,
column: self.column,
op: ArrayFilterOp::Overlaps,
values: values.into_iter().map(|v| v.into().to_value()).collect(),
})
}
pub fn has_some<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
self.overlaps(values)
}
pub fn is_empty(self) -> Filter<M> {
Filter::new(FilterNode::Array {
table: self.table,
column: self.column,
op: ArrayFilterOp::IsEmpty,
values: Vec::new(),
})
}
pub fn is_not_empty(self) -> Filter<M> {
Filter::new(FilterNode::Array {
table: self.table,
column: self.column,
op: ArrayFilterOp::IsNotEmpty,
values: Vec::new(),
})
}
}
pub trait Projection<M> {
type Output;
fn projection(&self) -> Vec<&'static str>;
}
impl<M, T> Projection<M> for Column<M, T> {
type Output = (T,);
fn projection(&self) -> Vec<&'static str> {
vec![self.column]
}
}
macro_rules! impl_projection_tuples {
($($n:tt $T:ident),+) => {
impl<M, $($T),+> Projection<M> for ($(Column<M, $T>,)+) {
type Output = ($($T,)+);
#[allow(clippy::vec_init_then_push)]
fn projection(&self) -> Vec<&'static str> {
let mut cols = Vec::new();
$(
cols.push(self.$n.column);
)+
cols
}
}
};
}
impl_projection_tuples! { 0 T0 }
impl_projection_tuples! { 0 T0, 1 T1 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4, 5 T5 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4, 5 T5, 6 T6 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4, 5 T5, 6 T6, 7 T7 }