#[cfg(feature = "postgres")]
use std::{any::Any, sync::Arc};
use std::{any::TypeId, marker::PhantomData};
use crate::{
compiler::QueryFilter,
diesel_helpers::{Backend, Predicate},
};
use anyhow::{Result, ensure};
use diesel::{
Expression, QueryResult,
expression::{AppearsOnTable, SelectableExpression, ValidGrouping, is_aggregate::No},
query_builder::{AstPass, QueryFragment, QueryId},
};
pub type CompiledQueryFilter<T> = QueryFilter<Predicate<T>, RankingSignal<T>>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {
Ascending,
Descending,
}
pub struct RankingSignal<T> {
pub name: String,
pub direction: Direction,
pub operation: String,
sql_type: &'static str,
type_id: TypeId,
pub(crate) expression: ErasedExpression,
table: PhantomData<fn() -> T>,
#[cfg(feature = "postgres")]
pub(crate) provenance: Option<Arc<dyn Any + Send + Sync>>,
}
pub(crate) type ErasedExpression = Box<dyn QueryFragment<Backend> + Send>;
impl<T> RankingSignal<T> {
pub fn sql_type(&self) -> &'static str {
self.sql_type
}
pub fn new<E>(
name: impl Into<String>,
expression: E,
direction: Direction,
operation: impl Into<String>,
) -> Self
where
E: diesel::BoxableExpression<T, Backend> + 'static,
E::SqlType: 'static,
{
Self {
name: name.into(),
direction,
operation: operation.into(),
sql_type: std::any::type_name::<E::SqlType>(),
type_id: TypeId::of::<E::SqlType>(),
expression: Box::new(expression),
table: PhantomData,
#[cfg(feature = "postgres")]
provenance: None,
}
}
pub fn into_expression<ST: diesel::expression::TypedExpressionType + 'static>(
self,
) -> Result<RankingExpression<T, ST>> {
ensure!(
self.type_id == TypeId::of::<ST>(),
"signal `{}` has SQL type {}, requested {}",
self.name,
self.sql_type,
std::any::type_name::<ST>()
);
Ok(RankingExpression {
expression: self.expression,
marker: PhantomData,
})
}
pub fn into_ordering(self) -> Ordering<T> {
Ordering {
terms: vec![(self.expression, self.direction)],
table: PhantomData,
}
}
}
pub struct RankingExpression<T, ST> {
expression: ErasedExpression,
marker: PhantomData<fn() -> (T, ST)>,
}
impl<T, ST: diesel::expression::TypedExpressionType> Expression for RankingExpression<T, ST> {
type SqlType = ST;
}
impl<T, ST> AppearsOnTable<T> for RankingExpression<T, ST> where Self: Expression {}
impl<T, ST> SelectableExpression<T> for RankingExpression<T, ST> where Self: Expression {}
impl<T, ST> ValidGrouping<()> for RankingExpression<T, ST> {
type IsAggregate = No;
}
impl<T, ST> QueryId for RankingExpression<T, ST> {
type QueryId = ();
const HAS_STATIC_QUERY_ID: bool = false;
}
impl<T, ST> QueryFragment<Backend> for RankingExpression<T, ST> {
fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, Backend>) -> QueryResult<()> {
self.expression.walk_ast(out)
}
}
pub struct Ordering<T> {
terms: Vec<(ErasedExpression, Direction)>,
table: PhantomData<fn() -> T>,
}
impl<T> Expression for Ordering<T> {
type SqlType = diesel::expression::expression_types::NotSelectable;
}
impl<T> AppearsOnTable<T> for Ordering<T> {}
impl<T> ValidGrouping<()> for Ordering<T> {
type IsAggregate = No;
}
impl<T> QueryId for Ordering<T> {
type QueryId = ();
const HAS_STATIC_QUERY_ID: bool = false;
}
impl<T> QueryFragment<Backend> for Ordering<T> {
fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Backend>) -> QueryResult<()> {
for (i, (expression, direction)) in self.terms.iter().enumerate() {
if i != 0 {
out.push_sql(", ");
}
expression.walk_ast(out.reborrow())?;
out.push_sql(match direction {
Direction::Ascending => " ASC",
Direction::Descending => " DESC",
});
}
Ok(())
}
}
impl<T> CompiledQueryFilter<T> {
pub fn take_signal(&mut self, name: &str) -> Result<RankingSignal<T>> {
let position = self.signal_position(name)?;
Ok(self.signals.remove(position))
}
fn signal_position(&self, name: &str) -> Result<usize> {
let mut matches = self
.signals
.iter()
.enumerate()
.filter(|(_, signal)| signal.name == name);
let (position, _) = matches
.next()
.ok_or_else(|| anyhow::anyhow!("missing signal `{name}`"))?;
ensure!(matches.next().is_none(), "ambiguous signal `{name}`");
Ok(position)
}
pub fn ordering(&mut self, names: &[&str]) -> Result<Ordering<T>> {
ensure!(!names.is_empty(), "ordering requires at least one signal");
for (i, name) in names.iter().enumerate() {
ensure!(
!names[..i].contains(name),
"duplicate ordering signal `{name}`"
);
self.signal_position(name)?;
}
let mut terms = Vec::with_capacity(names.len());
for name in names {
let signal = self.take_signal(name)?;
terms.push((signal.expression, signal.direction));
}
Ok(Ordering {
terms,
table: PhantomData,
})
}
}