use crate::column::Column;
use crate::expr::{And, Eq, Expr, Gt, GtEq, IsNull, Like, Lt, LtEq, Not, NotEq, Or};
use crate::query::{All, Query, QueryOutput, Table};
use crate::types::{Boolean, Float, Integer, Text};
use core::cmp::Ordering;
use core::marker::PhantomData;
pub trait Repr<'r> {
type Rust;
}
impl<'r> Repr<'r> for Integer {
type Rust = i64;
}
impl<'r> Repr<'r> for Text {
type Rust = &'r str;
}
impl<'r> Repr<'r> for Boolean {
type Rust = bool;
}
impl<'r> Repr<'r> for Float {
type Rust = f64;
}
pub type Rust<'r, S> = <S as Repr<'r>>::Rust;
pub trait Sortable: for<'x> Repr<'x> {
fn compare<'x>(a: Rust<'x, Self>, b: Rust<'x, Self>) -> Ordering;
}
impl Sortable for Integer {
fn compare<'x>(a: i64, b: i64) -> Ordering {
a.cmp(&b)
}
}
impl Sortable for Text {
fn compare<'x>(a: &'x str, b: &'x str) -> Ordering {
a.cmp(b)
}
}
impl Sortable for Boolean {
fn compare<'x>(a: bool, b: bool) -> Ordering {
a.cmp(&b)
}
}
pub trait Eval<'r, Row>: Expr
where
Self::SqlType: Repr<'r>,
{
fn eval(&'r self, row: &'r Row) -> Rust<'r, Self::SqlType>;
}
impl<'r, Row> Eval<'r, Row> for i32 {
fn eval(&'r self, _row: &'r Row) -> i64 {
i64::from(*self)
}
}
impl<'r, Row> Eval<'r, Row> for i64 {
fn eval(&'r self, _row: &'r Row) -> i64 {
*self
}
}
impl<'r, Row> Eval<'r, Row> for bool {
fn eval(&'r self, _row: &'r Row) -> bool {
*self
}
}
impl<'r, Row> Eval<'r, Row> for f32 {
fn eval(&'r self, _row: &'r Row) -> f64 {
f64::from(*self)
}
}
impl<'r, Row> Eval<'r, Row> for f64 {
fn eval(&'r self, _row: &'r Row) -> f64 {
*self
}
}
impl<'r, Row> Eval<'r, Row> for String {
fn eval(&'r self, _row: &'r Row) -> &'r str {
self.as_str()
}
}
impl<'r, 'a, Row> Eval<'r, Row> for &'a str
where
'a: 'r,
{
fn eval(&'r self, _row: &'r Row) -> &'r str {
self
}
}
macro_rules! eval_compare {
($node:ident, $op:tt) => {
impl<'r, Row, L, R> Eval<'r, Row> for $node<L, R>
where
L: Eval<'r, Row>,
R: Expr<SqlType = L::SqlType> + Eval<'r, Row>,
L::SqlType: Repr<'r>,
Rust<'r, L::SqlType>: PartialOrd,
Self: Expr<SqlType = Boolean>,
{
fn eval(&'r self, row: &'r Row) -> bool {
self.left.eval(row) $op self.right.eval(row)
}
}
};
}
eval_compare!(Eq, ==);
eval_compare!(NotEq, !=);
eval_compare!(Lt, <);
eval_compare!(LtEq, <=);
eval_compare!(Gt, >);
eval_compare!(GtEq, >=);
impl<'r, Row, L, R> Eval<'r, Row> for And<L, R>
where
L: Expr<SqlType = Boolean> + Eval<'r, Row>,
R: Expr<SqlType = Boolean> + Eval<'r, Row>,
{
fn eval(&'r self, row: &'r Row) -> bool {
self.left.eval(row) && self.right.eval(row)
}
}
impl<'r, Row, L, R> Eval<'r, Row> for Or<L, R>
where
L: Expr<SqlType = Boolean> + Eval<'r, Row>,
R: Expr<SqlType = Boolean> + Eval<'r, Row>,
{
fn eval(&'r self, row: &'r Row) -> bool {
self.left.eval(row) || self.right.eval(row)
}
}
impl<'r, Row, E> Eval<'r, Row> for Not<E>
where
E: Expr<SqlType = Boolean> + Eval<'r, Row>,
{
fn eval(&'r self, row: &'r Row) -> bool {
!self.inner.eval(row)
}
}
impl<'r, Row, L, R> Eval<'r, Row> for Like<L, R>
where
L: Expr<SqlType = Text> + Eval<'r, Row>,
R: Expr<SqlType = Text> + Eval<'r, Row>,
{
fn eval(&'r self, row: &'r Row) -> bool {
like_match(self.left.eval(row), self.right.eval(row))
}
}
fn like_match(text: &str, pattern: &str) -> bool {
let (mut ti, mut pi) = (0usize, 0usize);
let (mut star, mut mark) = (None::<usize>, 0usize);
loop {
match (text[ti..].chars().next(), pattern[pi..].chars().next()) {
(None, _) => return pattern[pi..].chars().all(|c| c == '%'),
(Some(_), Some('%')) => {
star = Some(pi);
mark = ti;
pi += 1;
}
(Some(t), Some(p)) if p == '_' || p == t => {
ti += t.len_utf8();
pi += p.len_utf8();
}
(Some(_), _) => match star {
Some(s) => {
pi = s + 1;
mark += text[mark..].chars().next().map_or(1, char::len_utf8);
ti = mark;
}
None => return false,
},
}
}
}
pub trait Entity: Sized {
type Table: Table;
}
#[derive(Debug, Clone, Copy)]
pub struct AlwaysTrue;
impl Expr for AlwaysTrue {
type SqlType = Boolean;
fn write_to(&self, sql: &mut String, _params: &mut Vec<crate::SqlValue>) {
sql.push_str("1 = 1");
}
}
impl<'r, Row> Eval<'r, Row> for AlwaysTrue {
fn eval(&'r self, _row: &'r Row) -> bool {
true
}
}
pub trait Conj<P2> {
type Out;
fn conj(self, rhs: P2) -> Self::Out;
}
impl<P2> Conj<P2> for AlwaysTrue {
type Out = P2;
fn conj(self, rhs: P2) -> P2 {
rhs
}
}
macro_rules! conj_binary {
($($node:ident),* $(,)?) => {$(
impl<L, R, P2> Conj<P2> for $node<L, R>
where
Self: Expr<SqlType = Boolean>,
P2: Expr<SqlType = Boolean>,
{
type Out = And<Self, P2>;
fn conj(self, rhs: P2) -> And<Self, P2> {
crate::column::BoolOps::and(self, rhs)
}
}
)*};
}
conj_binary!(Eq, NotEq, Lt, LtEq, Gt, GtEq, And, Or, Like);
macro_rules! conj_unary {
($($node:ident),* $(,)?) => {$(
impl<E, P2> Conj<P2> for $node<E>
where
Self: Expr<SqlType = Boolean>,
P2: Expr<SqlType = Boolean>,
{
type Out = And<Self, P2>;
fn conj(self, rhs: P2) -> And<Self, P2> {
crate::column::BoolOps::and(self, rhs)
}
}
)*};
}
conj_unary!(Not, IsNull);
#[derive(Debug, Clone, Copy)]
pub struct Unordered;
#[derive(Debug, Clone, Copy)]
pub struct Ordered;
type SqlStep<T> = Box<dyn Fn(Query<T, All<T>>) -> Query<T, All<T>>>;
type RowCmp<Row> = Box<dyn Fn(&Row, &Row) -> Ordering>;
struct OrderPart<Row: Entity> {
render: SqlStep<Row::Table>,
cmp: RowCmp<Row>,
}
pub struct Rows<Row: Entity, P, O> {
pred: P,
filtered: bool,
order: Vec<OrderPart<Row>>,
limit: Option<u64>,
offset: Option<u64>,
_ord: PhantomData<O>,
}
pub fn query<Row: Entity>() -> Rows<Row, AlwaysTrue, Unordered> {
Rows {
pred: AlwaysTrue,
filtered: false,
order: Vec::new(),
limit: None,
offset: None,
_ord: PhantomData,
}
}
impl<Row: Entity, P, O> Rows<Row, P, O> {
pub fn filter<P2>(self, predicate: P2) -> Rows<Row, P::Out, O>
where
P: Conj<P2>,
P2: Expr<SqlType = Boolean>,
{
Rows {
pred: self.pred.conj(predicate),
filtered: true,
order: self.order,
limit: self.limit,
offset: self.offset,
_ord: PhantomData,
}
}
pub fn limit(mut self, n: u64) -> Self {
self.limit = Some(n);
self
}
pub fn offset(mut self, n: u64) -> Self {
self.offset = Some(n);
self
}
fn push_order<C>(mut self, column: C, desc: bool) -> Rows<Row, P, Ordered>
where
C: Column<Table = Row::Table> + Copy + 'static,
C: for<'x> Eval<'x, Row>,
C::SqlType: Sortable,
Row: 'static,
{
self.order.push(OrderPart {
render: if desc {
Box::new(move |q: Query<Row::Table, All<Row::Table>>| q.order_by_desc(column))
} else {
Box::new(move |q: Query<Row::Table, All<Row::Table>>| q.order_by(column))
},
cmp: Box::new(move |a: &Row, b: &Row| {
let ord = <C::SqlType as Sortable>::compare(column.eval(a), column.eval(b));
if desc {
ord.reverse()
} else {
ord
}
}),
});
Rows {
pred: self.pred,
filtered: self.filtered,
order: self.order,
limit: self.limit,
offset: self.offset,
_ord: PhantomData,
}
}
pub fn order_by<C>(self, column: C) -> Rows<Row, P, Ordered>
where
C: Column<Table = Row::Table> + Copy + 'static,
C: for<'x> Eval<'x, Row>,
C::SqlType: Sortable,
Row: 'static,
{
self.push_order(column, false)
}
pub fn order_by_desc<C>(self, column: C) -> Rows<Row, P, Ordered>
where
C: Column<Table = Row::Table> + Copy + 'static,
C: for<'x> Eval<'x, Row>,
C::SqlType: Sortable,
Row: 'static,
{
self.push_order(column, true)
}
pub fn to_sql(&self) -> QueryOutput
where
P: Expr<SqlType = Boolean> + Clone + 'static,
{
let mut q: Query<Row::Table, All<Row::Table>> = Query::new();
if self.filtered {
q = q.filter(self.pred.clone());
}
for part in &self.order {
q = (part.render)(q);
}
if let Some(n) = self.limit {
q = q.limit(n);
}
if let Some(n) = self.offset {
q = q.offset(n);
}
q.to_sql()
}
}
pub trait CallToMemoryFirst {}
impl<Row: Entity, P, O> Rows<Row, P, O> {
pub fn select_many<F>(self, _f: F) -> Self
where
Self: CallToMemoryFirst,
{
unreachable!()
}
}
impl<Row: Entity, P> Rows<Row, P, Unordered> {
pub fn to_memory<'a, I>(self, src: I) -> RowIter<'a, Row, I::IntoIter, P>
where
I: IntoIterator<Item = &'a Row>,
Row: 'a,
P: Expr<SqlType = Boolean> + for<'x> Eval<'x, Row>,
{
RowIter {
inner: src.into_iter(),
pred: self.pred,
skip: self.offset.unwrap_or(0),
left: self.limit,
_row: PhantomData,
}
}
}
pub struct RowIter<'a, Row, I, P> {
inner: I,
pred: P,
skip: u64,
left: Option<u64>,
_row: PhantomData<&'a Row>,
}
impl<'a, Row, I, P> Iterator for RowIter<'a, Row, I, P>
where
I: Iterator<Item = &'a Row>,
Row: 'a,
P: Expr<SqlType = Boolean> + for<'x> Eval<'x, Row>,
{
type Item = &'a Row;
fn next(&mut self) -> Option<&'a Row> {
if self.left == Some(0) {
return None;
}
for row in self.inner.by_ref() {
if !self.pred.eval(row) {
continue;
}
if self.skip > 0 {
self.skip -= 1;
continue;
}
if let Some(n) = self.left.as_mut() {
*n -= 1;
}
return Some(row);
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, hi) = self.inner.size_hint();
let hi = match (hi, self.left) {
(Some(h), Some(l)) => Some(h.min(l as usize)),
(Some(h), None) => Some(h),
(None, Some(l)) => Some(l as usize),
(None, None) => None,
};
(0, hi)
}
}
impl<Row: Entity, P> Rows<Row, P, Ordered> {
pub fn to_memory_sorted<'a, I>(self, src: I) -> SortedRows<'a, Row>
where
I: IntoIterator<Item = &'a Row>,
Row: 'a,
P: Expr<SqlType = Boolean> + for<'x> Eval<'x, Row>,
{
let pred = &self.pred;
let mut kept: Vec<&'a Row> = src.into_iter().filter(|r| pred.eval(r)).collect();
let order = &self.order;
kept.sort_by(|a, b| {
for part in order {
match (part.cmp)(a, b) {
Ordering::Equal => continue,
other => return other,
}
}
Ordering::Equal
});
let start = (self.offset.unwrap_or(0) as usize).min(kept.len());
let end = match self.limit {
Some(n) => (start + n as usize).min(kept.len()),
None => kept.len(),
};
kept.truncate(end);
kept.drain(..start);
SortedRows {
rows: kept.into_iter(),
}
}
}
pub struct SortedRows<'a, Row> {
rows: std::vec::IntoIter<&'a Row>,
}
impl<'a, Row> Iterator for SortedRows<'a, Row> {
type Item = &'a Row;
fn next(&mut self) -> Option<&'a Row> {
self.rows.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.rows.size_hint()
}
}
#[macro_export]
macro_rules! entity {
($row:ty => $table:ident { $($col:ident : $ty:ident = $field:ident),* $(,)? }) => {
impl $crate::rows::Entity for $row {
type Table = $table::Marker;
}
$( $crate::entity!(@col $row, $table::$col, $ty, $field); )*
};
(@col $row:ty, $col:path, Integer, $field:ident) => {
impl<'r> $crate::rows::Eval<'r, $row> for $col {
fn eval(&'r self, row: &'r $row) -> i64 { row.$field as i64 }
}
};
(@col $row:ty, $col:path, Text, $field:ident) => {
impl<'r> $crate::rows::Eval<'r, $row> for $col {
fn eval(&'r self, row: &'r $row) -> &'r str { &row.$field[..] }
}
};
(@col $row:ty, $col:path, Boolean, $field:ident) => {
impl<'r> $crate::rows::Eval<'r, $row> for $col {
fn eval(&'r self, row: &'r $row) -> bool { row.$field }
}
};
(@col $row:ty, $col:path, Float, $field:ident) => {
impl<'r> $crate::rows::Eval<'r, $row> for $col {
fn eval(&'r self, row: &'r $row) -> f64 { row.$field as f64 }
}
};
}