use std::cmp::Ordering;
use crate::{Value, ident};
pub trait RowView {
fn col(&self, column: &str) -> Option<Value>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Quant {
Any,
All,
None,
Empty,
CountGe(usize),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Pred {
Always,
Eq(&'static str, Value),
Ne(&'static str, Value),
Lt(&'static str, Value),
Le(&'static str, Value),
Gt(&'static str, Value),
Ge(&'static str, Value),
Contains(&'static str, String),
ContainsCi(&'static str, String),
StartsWith(&'static str, String),
StartsWithCi(&'static str, String),
Between(&'static str, Value, Value),
In(&'static str, Vec<Value>),
NotIn(&'static str, Vec<Value>),
IdIn(Vec<u64>),
Related {
owner: &'static str,
field: &'static str,
target: &'static str,
quant: Quant,
inner: Box<Pred>,
},
And(Box<Pred>, Box<Pred>),
Or(Box<Pred>, Box<Pred>),
Not(Box<Pred>),
Raw(String, Vec<Value>),
Matches {
columns: &'static [&'static str],
query: String,
},
Within {
lat: &'static str,
lon: &'static str,
min_lat: f64,
max_lat: f64,
min_lon: f64,
max_lon: f64,
},
}
impl Pred {
pub fn columns(&self, out: &mut Vec<&'static str>) {
let push = |c: &'static str, out: &mut Vec<&'static str>| {
if !out.contains(&c) {
out.push(c);
}
};
match self {
Pred::Always | Pred::Raw(..) => {}
Pred::Eq(c, _)
| Pred::Ne(c, _)
| Pred::Lt(c, _)
| Pred::Le(c, _)
| Pred::Gt(c, _)
| Pred::Ge(c, _)
| Pred::Contains(c, _)
| Pred::ContainsCi(c, _)
| Pred::StartsWith(c, _)
| Pred::StartsWithCi(c, _)
| Pred::In(c, _)
| Pred::NotIn(c, _)
| Pred::Between(c, _, _) => push(c, out),
Pred::IdIn(_) => {}
Pred::Related { .. } => {}
Pred::And(a, b) | Pred::Or(a, b) => {
a.columns(out);
b.columns(out);
}
Pred::Not(a) => a.columns(out),
Pred::Matches { columns, .. } => {
for c in *columns {
push(c, out);
}
}
Pred::Within { lat, lon, .. } => {
push(lat, out);
push(lon, out);
}
}
}
fn related_deps(&self, out: &mut Vec<RelatedDep>) {
match self {
Pred::Related {
owner,
field,
target,
inner,
..
} => {
let mut columns = Vec::new();
inner.columns(&mut columns);
out.push(RelatedDep {
owner,
field,
target_table: target,
columns,
});
inner.related_deps(out);
}
Pred::And(a, b) | Pred::Or(a, b) => {
a.related_deps(out);
b.related_deps(out);
}
Pred::Not(a) => a.related_deps(out),
_ => {}
}
}
pub fn contains_raw(&self) -> bool {
match self {
Pred::Raw(..) => true,
Pred::And(a, b) | Pred::Or(a, b) => a.contains_raw() || b.contains_raw(),
Pred::Not(a) => a.contains_raw(),
_ => false,
}
}
pub(crate) fn contains_fold(&self) -> bool {
match self {
Pred::ContainsCi(..) | Pred::StartsWithCi(..) => true,
Pred::And(a, b) | Pred::Or(a, b) => a.contains_fold() || b.contains_fold(),
Pred::Not(a) => a.contains_fold(),
Pred::Related { inner, .. } => inner.contains_fold(),
_ => false,
}
}
pub(crate) fn contains_related(&self) -> bool {
match self {
Pred::Related { .. } => true,
Pred::And(a, b) | Pred::Or(a, b) => a.contains_related() || b.contains_related(),
Pred::Not(a) => a.contains_related(),
_ => false,
}
}
pub fn eval(&self, key: u64, row: &dyn RowView) -> bool {
self.eval3(key, row) == Some(true)
}
pub fn eval3(&self, key: u64, row: &dyn RowView) -> Option<bool> {
match self {
Pred::Always => Some(true),
Pred::Raw(..) | Pred::Matches { .. } => Some(true),
Pred::Related { .. } => Some(true),
Pred::Eq(c, Value::Null) => Some(matches!(row.col(c), Some(Value::Null) | None)),
Pred::Ne(c, Value::Null) => Some(!matches!(row.col(c), Some(Value::Null) | None)),
Pred::Eq(c, v) => defined(row.col(c)).map(|a| a == *v),
Pred::Ne(c, v) => defined(row.col(c)).map(|a| a != *v),
Pred::Lt(c, v) => defined(row.col(c)).map(|a| compare_values(&a, v) == Ordering::Less),
Pred::Le(c, v) => {
defined(row.col(c)).map(|a| compare_values(&a, v) != Ordering::Greater)
}
Pred::Gt(c, v) => {
defined(row.col(c)).map(|a| compare_values(&a, v) == Ordering::Greater)
}
Pred::Ge(c, v) => defined(row.col(c)).map(|a| compare_values(&a, v) != Ordering::Less),
Pred::Between(c, lo, hi) => defined(row.col(c)).map(|a| {
compare_values(&a, lo) != Ordering::Less
&& compare_values(&a, hi) != Ordering::Greater
}),
Pred::Contains(c, needle) => text(row.col(c)).map(|t| t.contains(needle.as_str())),
Pred::ContainsCi(c, needle) => {
text(row.col(c)).map(|t| t.to_lowercase().contains(&needle.to_lowercase()))
}
Pred::StartsWith(c, prefix) => text(row.col(c)).map(|t| t.starts_with(prefix.as_str())),
Pred::StartsWithCi(c, prefix) => {
text(row.col(c)).map(|t| t.to_lowercase().starts_with(&prefix.to_lowercase()))
}
Pred::In(c, set) => defined(row.col(c)).map(|a| in_set(set, &a)),
Pred::NotIn(c, set) => defined(row.col(c)).map(|a| !in_set(set, &a)),
Pred::IdIn(ids) => Some(ids.binary_search(&key).is_ok()),
Pred::And(a, b) => match (a.eval3(key, row), b.eval3(key, row)) {
(Some(false), _) | (_, Some(false)) => Some(false),
(Some(true), Some(true)) => Some(true),
_ => None,
},
Pred::Or(a, b) => match (a.eval3(key, row), b.eval3(key, row)) {
(Some(true), _) | (_, Some(true)) => Some(true),
(Some(false), Some(false)) => Some(false),
_ => None,
},
Pred::Not(a) => a.eval3(key, row).map(|v| !v),
Pred::Within {
lat,
lon,
min_lat,
max_lat,
min_lon,
max_lon,
} => {
let in_range = |c: &str, lo: f64, hi: f64| match defined(row.col(c)) {
Some(Value::Real(v)) => Some(v >= lo && v <= hi),
Some(Value::Int(v)) => Some((v as f64) >= lo && (v as f64) <= hi),
Some(_) => Some(false),
None => None,
};
match (
in_range(lat, *min_lat, *max_lat),
in_range(lon, *min_lon, *max_lon),
) {
(Some(false), _) | (_, Some(false)) => Some(false),
(Some(true), Some(true)) => Some(true),
_ => None,
}
}
}
}
}
impl std::ops::BitAnd for Pred {
type Output = Pred;
fn bitand(self, rhs: Pred) -> Pred {
Pred::And(Box::new(self), Box::new(rhs))
}
}
impl std::ops::BitOr for Pred {
type Output = Pred;
fn bitor(self, rhs: Pred) -> Pred {
Pred::Or(Box::new(self), Box::new(rhs))
}
}
impl std::ops::Not for Pred {
type Output = Pred;
fn not(self) -> Pred {
Pred::Not(Box::new(self))
}
}
#[derive(Clone, Debug)]
pub(crate) enum RelSql {
Children {
target_key: String,
fk_col: String,
owner_key: String,
},
Referent { target_key: String, fk_col: String },
Join {
join_table: String,
owner_col: String,
target_col: String,
owner_key: String,
target_key: String,
},
Linked {
local_col: String,
remote_col: String,
target_key: String,
},
}
pub(crate) trait SqlIndex {
fn relation(&self, owner: &str, field: &str) -> Option<RelSql>;
fn key_of(&self, table: &str) -> Option<String>;
fn table_sql(&self, table: &str) -> String;
fn fts_of(&self, table: &str) -> Option<FtsSql>;
fn fts_key_of(&self, _table: &str) -> &str {
"rowid"
}
fn geo_of(&self, table: &str, lat: &str, lon: &str) -> Option<String>;
fn unicode_fold(&self) -> bool;
}
#[derive(Clone, Debug)]
pub(crate) struct FtsSql {
pub from: String,
pub match_col: String,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum CompileErr {
NeedsFold,
FoldInsideRelation,
Unwired(&'static str, &'static str),
NoFts,
}
impl CompileErr {
pub(crate) fn message(&self) -> String {
match self {
CompileErr::NeedsFold | CompileErr::FoldInsideRelation => {
"case-insensitive predicate needs the driver's day_fold function".into()
}
CompileErr::Unwired(owner, field) => {
format!("`{owner}.{field}` is not a wired relation of this container")
}
CompileErr::NoFts => "matches()/rank() needs a #[model(fts(…))] declaration".into(),
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct SqlQuery {
pub sql: String,
pub params: Vec<Value>,
}
pub(crate) fn compile_fetch(
table: &str,
fetch: &Fetch,
idx: &dyn SqlIndex,
) -> Result<SqlQuery, CompileErr> {
let key = ident(&idx.key_of(table).ok_or(CompileErr::Unwired("", ""))?);
let t = idx.table_sql(table);
let mut params = Vec::new();
let mut aliases = 0usize;
let by_rank = fetch.sort.iter().any(|s| s.by_rank);
let (from, rank_pred);
if by_rank {
let fts = idx.fts_of(table).ok_or(CompileErr::NoFts)?;
let Some(q) = find_match_query(&fetch.pred) else {
return Err(CompileErr::NoFts);
};
params.push(Value::Text(q));
let fts_key = idx.fts_key_of(table);
from = format!(
"{t} JOIN {} AS day_rank ON day_rank.{fts_key} = {t}.{key} AND day_rank.{} MATCH ?",
fts.from, fts.match_col
);
rank_pred = true;
} else {
from = t.clone();
rank_pred = false;
}
let ctx = SqlCtx {
idx,
skip_matches: rank_pred,
};
let where_clause = pred_sql(
&fetch.pred,
table,
&t,
&key,
&ctx,
&mut params,
&mut aliases,
)?;
let mut sql = format!("SELECT {t}.{key} FROM {from}");
if where_clause != "1" {
sql.push_str(&format!(" WHERE {where_clause}"));
}
let mut orders: Vec<String> = Vec::new();
for s in &fetch.sort {
if s.by_rank {
orders.push("day_rank.rank".into());
} else {
orders.push(format!(
"{t}.{} {}",
ident(s.column),
if s.ascending { "ASC" } else { "DESC" }
));
}
}
orders.push(format!("{t}.{key} ASC"));
sql.push_str(&format!(" ORDER BY {}", orders.join(", ")));
if let Some(n) = fetch.limit {
sql.push_str(&format!(" LIMIT {n}"));
}
Ok(SqlQuery { sql, params })
}
pub(crate) fn compile_count(
table: &str,
fetch: &Fetch,
idx: &dyn SqlIndex,
) -> Result<SqlQuery, CompileErr> {
let key = ident(&idx.key_of(table).ok_or(CompileErr::Unwired("", ""))?);
let t = idx.table_sql(table);
let mut params = Vec::new();
let mut aliases = 0usize;
let ctx = SqlCtx {
idx,
skip_matches: false,
};
let where_clause = pred_sql(
&fetch.pred,
table,
&t,
&key,
&ctx,
&mut params,
&mut aliases,
)?;
let mut sql = format!("SELECT COUNT(*) FROM {t}");
if where_clause != "1" {
sql.push_str(&format!(" WHERE {where_clause}"));
}
Ok(SqlQuery { sql, params })
}
pub(crate) fn compile_fallback(
table: &str,
fetch: &Fetch,
idx: &dyn SqlIndex,
) -> Result<(SqlQuery, Vec<&'static str>), CompileErr> {
if fetch.pred.contains_related() && fetch.pred.contains_fold() {
return Err(CompileErr::FoldInsideRelation);
}
let key = ident(&idx.key_of(table).ok_or(CompileErr::Unwired("", ""))?);
let t = idx.table_sql(table);
let mut params = Vec::new();
let mut aliases = 0usize;
let ctx = SqlCtx {
idx,
skip_matches: false,
};
let mut conjuncts = Vec::new();
split_and(&fetch.pred, &mut conjuncts);
let mut clauses = Vec::new();
for c in conjuncts {
if !c.contains_fold() {
clauses.push(pred_sql(
c,
table,
&t,
&key,
&ctx,
&mut params,
&mut aliases,
)?);
}
}
let mut deps = Vec::new();
fetch.pred.columns(&mut deps);
for s in &fetch.sort {
if !s.by_rank && !deps.contains(&s.column) {
deps.push(s.column);
}
}
let cols = if deps.is_empty() {
format!("{t}.{key}")
} else {
format!(
"{t}.{key}, {}",
deps.iter()
.map(|c| format!("{t}.{}", ident(c)))
.collect::<Vec<_>>()
.join(", ")
)
};
let mut sql = format!("SELECT {cols} FROM {t}");
let clauses: Vec<String> = clauses.into_iter().filter(|c| c != "1").collect();
if !clauses.is_empty() {
sql.push_str(&format!(" WHERE {}", clauses.join(" AND ")));
}
let mut orders: Vec<String> = fetch
.sort
.iter()
.filter(|s| !s.by_rank)
.map(|s| {
format!(
"{t}.{} {}",
ident(s.column),
if s.ascending { "ASC" } else { "DESC" }
)
})
.collect();
orders.push(format!("{t}.{key} ASC"));
sql.push_str(&format!(" ORDER BY {}", orders.join(", ")));
Ok((SqlQuery { sql, params }, deps))
}
fn split_and<'p>(pred: &'p Pred, out: &mut Vec<&'p Pred>) {
match pred {
Pred::And(a, b) => {
split_and(a, out);
split_and(b, out);
}
p => out.push(p),
}
}
struct SqlCtx<'a> {
idx: &'a dyn SqlIndex,
skip_matches: bool,
}
fn pred_sql(
pred: &Pred,
table: &str,
alias: &str,
key: &str,
ctx: &SqlCtx<'_>,
params: &mut Vec<Value>,
aliases: &mut usize,
) -> Result<String, CompileErr> {
let col = |c: &str| format!("{alias}.{}", ident(c));
Ok(match pred {
Pred::Always => "1".into(),
Pred::Eq(c, Value::Null) => format!("{} IS NULL", col(c)),
Pred::Ne(c, Value::Null) => format!("{} IS NOT NULL", col(c)),
Pred::Eq(c, v) => {
params.push(v.clone());
format!("{} = ?", col(c))
}
Pred::Ne(c, v) => {
params.push(v.clone());
format!("{} <> ?", col(c))
}
Pred::Lt(c, v) => {
params.push(v.clone());
format!("{} < ?", col(c))
}
Pred::Le(c, v) => {
params.push(v.clone());
format!("{} <= ?", col(c))
}
Pred::Gt(c, v) => {
params.push(v.clone());
format!("{} > ?", col(c))
}
Pred::Ge(c, v) => {
params.push(v.clone());
format!("{} >= ?", col(c))
}
Pred::Contains(c, s) => {
params.push(Value::Text(s.clone()));
format!("instr({}, ?) > 0", col(c))
}
Pred::ContainsCi(c, s) => {
if !ctx.idx.unicode_fold() {
return Err(CompileErr::NeedsFold);
}
params.push(Value::Text(s.to_lowercase()));
format!("instr(day_fold({}), ?) > 0", col(c))
}
Pred::StartsWith(c, prefix) => {
params.push(Value::Int(prefix.chars().count() as i64));
params.push(Value::Text(prefix.clone()));
format!("substr({}, 1, ?) = ?", col(c))
}
Pred::StartsWithCi(c, prefix) => {
if !ctx.idx.unicode_fold() {
return Err(CompileErr::NeedsFold);
}
let folded = prefix.to_lowercase();
params.push(Value::Int(folded.chars().count() as i64));
params.push(Value::Text(folded));
format!("substr(day_fold({}), 1, ?) = ?", col(c))
}
Pred::In(c, set) | Pred::NotIn(c, set) => {
if set.is_empty() {
return Ok(if matches!(pred, Pred::In(..)) {
"0".into()
} else {
format!("{} IS NOT NULL", col(c))
});
}
let negate = if matches!(pred, Pred::NotIn(..)) {
"NOT "
} else {
""
};
let marks = vec!["?"; set.len()].join(", ");
params.extend(set.iter().cloned());
format!("{} {negate}IN ({marks})", col(c))
}
Pred::IdIn(ids) => {
if ids.is_empty() {
return Ok("0".into());
}
for id in ids {
params.push(crate::key_param(*id));
}
let marks = vec!["?"; ids.len()].join(", ");
format!("{alias}.{key} IN ({marks})")
}
Pred::Between(c, lo, hi) => {
params.push(lo.clone());
params.push(hi.clone());
format!("{} BETWEEN ? AND ?", col(c))
}
Pred::And(a, b) => format!(
"({} AND {})",
pred_sql(a, table, alias, key, ctx, params, aliases)?,
pred_sql(b, table, alias, key, ctx, params, aliases)?
),
Pred::Or(a, b) => format!(
"({} OR {})",
pred_sql(a, table, alias, key, ctx, params, aliases)?,
pred_sql(b, table, alias, key, ctx, params, aliases)?
),
Pred::Not(a) => format!(
"NOT ({})",
pred_sql(a, table, alias, key, ctx, params, aliases)?
),
Pred::Raw(sql, args) => {
params.extend(args.iter().cloned());
format!("({sql})")
}
Pred::Matches { query, .. } => {
if ctx.skip_matches {
"1".into()
} else {
let fts = ctx.idx.fts_of(table).ok_or(CompileErr::NoFts)?;
params.push(Value::Text(query.clone()));
let fts_key = ctx.idx.fts_key_of(table);
format!(
"{alias}.{key} IN (SELECT {fts_key} FROM {} WHERE {} MATCH ?)",
fts.from, fts.match_col
)
}
}
Pred::Within {
lat,
lon,
min_lat,
max_lat,
min_lon,
max_lon,
} => {
let exact = {
params.push(Value::Real(*min_lat));
params.push(Value::Real(*max_lat));
params.push(Value::Real(*min_lon));
params.push(Value::Real(*max_lon));
format!(
"({} BETWEEN ? AND ? AND {} BETWEEN ? AND ?)",
col(lat),
col(lon)
)
};
match ctx.idx.geo_of(table, lat, lon) {
Some(geo) => {
params.push(Value::Real(*min_lat));
params.push(Value::Real(*max_lat));
params.push(Value::Real(*min_lon));
params.push(Value::Real(*max_lon));
format!(
"({alias}.{key} IN (SELECT {key} FROM {geo} WHERE \
max_lat >= ? AND min_lat <= ? AND max_lon >= ? AND min_lon <= ?) \
AND {exact})"
)
}
None => exact,
}
}
Pred::Related {
owner,
field,
target,
quant,
inner,
} => {
let rel = ctx
.idx
.relation(owner, field)
.ok_or(CompileErr::Unwired(owner, field))?;
let r = format!("day_r{}", *aliases);
*aliases += 1;
let target_sql = ctx.idx.table_sql(target);
let (from, tie, inner_alias, inner_key) = match &rel {
RelSql::Children {
target_key,
fk_col,
owner_key,
} => (
format!("{target_sql} AS {r}"),
format!("{r}.{} = {}", ident(fk_col), col(owner_key)),
r.clone(),
ident(target_key),
),
RelSql::Referent { target_key, fk_col } => (
format!("{target_sql} AS {r}"),
format!("{r}.{} = {}", ident(target_key), col(fk_col)),
r.clone(),
ident(target_key),
),
RelSql::Linked {
local_col,
remote_col,
target_key,
} => (
format!("{target_sql} AS {r}"),
format!("{r}.{} = {}", ident(remote_col), col(local_col)),
r.clone(),
ident(target_key),
),
RelSql::Join {
join_table,
owner_col,
target_col,
owner_key,
target_key,
} => {
let j = format!("day_j{}", *aliases);
*aliases += 1;
(
format!(
"{} AS {j} JOIN {target_sql} AS {r} ON {r}.{} = {j}.{}",
ctx.idx.table_sql(join_table),
ident(target_key),
ident(target_col)
),
format!("{j}.{} = {}", ident(owner_col), col(owner_key)),
r.clone(),
ident(target_key),
)
}
};
match quant {
Quant::Empty => format!("NOT EXISTS (SELECT 1 FROM {from} WHERE {tie})"),
Quant::CountGe(n) => {
params.push(Value::Int(*n as i64));
format!("(SELECT COUNT(*) FROM {from} WHERE {tie}) >= ?")
}
Quant::Any | Quant::None | Quant::All => {
let inner_sql = pred_sql(
inner,
target,
&inner_alias,
&inner_key,
ctx,
params,
aliases,
)?;
match quant {
Quant::Any => {
format!("EXISTS (SELECT 1 FROM {from} WHERE {tie} AND ({inner_sql}))")
}
Quant::None => format!(
"NOT EXISTS (SELECT 1 FROM {from} WHERE {tie} AND ({inner_sql}))"
),
Quant::All => format!(
"NOT EXISTS (SELECT 1 FROM {from} WHERE {tie} AND ({inner_sql}) IS NOT TRUE)"
),
_ => unreachable!(),
}
}
}
}
})
}
fn defined(v: Option<Value>) -> Option<Value> {
match v {
Some(Value::Null) | None => None,
Some(v) => Some(v),
}
}
fn text(v: Option<Value>) -> Option<String> {
match defined(v) {
Some(Value::Text(t)) => Some(t),
_ => None,
}
}
fn in_set(set: &[Value], v: &Value) -> bool {
let start = set.partition_point(|x| compare_values(x, v) == Ordering::Less);
set[start..]
.iter()
.take_while(|x| compare_values(x, v) == Ordering::Equal)
.any(|x| x == v)
}
pub fn compare_values(a: &Value, b: &Value) -> Ordering {
fn class(v: &Value) -> u8 {
match v {
Value::Null => 0,
Value::Int(_) | Value::Real(_) => 1,
Value::Text(_) => 2,
Value::Blob(_) => 3,
}
}
match (a, b) {
(Value::Int(x), Value::Int(y)) => x.cmp(y),
(Value::Real(x), Value::Real(y)) => x.total_cmp(y),
(Value::Int(x), Value::Real(y)) => (*x as f64).total_cmp(y),
(Value::Real(x), Value::Int(y)) => x.total_cmp(&(*y as f64)),
(Value::Text(x), Value::Text(y)) => x.cmp(y),
(Value::Blob(x), Value::Blob(y)) => x.cmp(y),
_ => class(a).cmp(&class(b)),
}
}
pub struct Col<V: 'static> {
pub column: &'static str,
pub field: &'static str,
pub owner: &'static str,
encode: fn(&V) -> Value,
}
impl<V> Clone for Col<V> {
fn clone(&self) -> Self {
*self
}
}
impl<V> Copy for Col<V> {}
pub struct RelationCol<P: 'static, T: 'static> {
field: &'static str,
owner: &'static str,
target: &'static str,
_p: std::marker::PhantomData<fn() -> (P, T)>,
}
impl<P, T> Clone for RelationCol<P, T> {
fn clone(&self) -> Self {
*self
}
}
impl<P, T> Copy for RelationCol<P, T> {}
impl<P, T> RelationCol<P, T> {
pub const fn new(field: &'static str, owner: &'static str, target: &'static str) -> Self {
RelationCol {
field,
owner,
target,
_p: std::marker::PhantomData,
}
}
fn build(self, quant: Quant, inner: Pred) -> Pred {
Pred::Related {
owner: self.owner,
field: self.field,
target: self.target,
quant,
inner: Box::new(inner),
}
}
pub fn any(self, inner: Pred) -> Pred {
self.build(Quant::Any, inner)
}
pub fn none(self, inner: Pred) -> Pred {
self.build(Quant::None, inner)
}
pub fn all(self, inner: Pred) -> Pred {
self.build(Quant::All, inner)
}
pub fn is_empty(self) -> Pred {
self.build(Quant::Empty, Pred::Always)
}
pub fn count_ge(self, n: usize) -> Pred {
self.build(Quant::CountGe(n), Pred::Always)
}
}
pub fn encode_column<T: crate::ColumnValue>(v: &T) -> Value {
v.to_sqlite_value()
}
impl<V> Col<V> {
pub const fn new(
column: &'static str,
field: &'static str,
owner: &'static str,
encode: fn(&V) -> Value,
) -> Col<V> {
Col {
column,
field,
owner,
encode,
}
}
fn enc(&self, v: &V) -> Value {
(self.encode)(v)
}
pub fn eq(self, v: impl std::borrow::Borrow<V>) -> Pred {
Pred::Eq(self.column, self.enc(v.borrow()))
}
pub fn ne(self, v: impl std::borrow::Borrow<V>) -> Pred {
Pred::Ne(self.column, self.enc(v.borrow()))
}
pub fn lt(self, v: impl std::borrow::Borrow<V>) -> Pred {
Pred::Lt(self.column, self.enc(v.borrow()))
}
pub fn le(self, v: impl std::borrow::Borrow<V>) -> Pred {
Pred::Le(self.column, self.enc(v.borrow()))
}
pub fn gt(self, v: impl std::borrow::Borrow<V>) -> Pred {
Pred::Gt(self.column, self.enc(v.borrow()))
}
pub fn ge(self, v: impl std::borrow::Borrow<V>) -> Pred {
Pred::Ge(self.column, self.enc(v.borrow()))
}
pub fn is_in(self, values: impl IntoIterator<Item = impl std::borrow::Borrow<V>>) -> Pred {
Pred::In(self.column, self.encode_set(values))
}
pub fn not_in(self, values: impl IntoIterator<Item = impl std::borrow::Borrow<V>>) -> Pred {
Pred::NotIn(self.column, self.encode_set(values))
}
fn encode_set(
self,
values: impl IntoIterator<Item = impl std::borrow::Borrow<V>>,
) -> Vec<Value> {
let mut set: Vec<Value> = values.into_iter().map(|v| self.enc(v.borrow())).collect();
set.sort_by(compare_values);
set.dedup();
set
}
pub fn is_null(self) -> Pred {
Pred::Eq(self.column, Value::Null)
}
pub fn is_not_null(self) -> Pred {
Pred::Ne(self.column, Value::Null)
}
pub fn between(self, lo: impl std::borrow::Borrow<V>, hi: impl std::borrow::Borrow<V>) -> Pred {
Pred::Between(self.column, self.enc(lo.borrow()), self.enc(hi.borrow()))
}
pub fn asc(self) -> Sort {
Sort::asc(self.column)
}
pub fn desc(self) -> Sort {
Sort::desc(self.column)
}
}
#[derive(Clone, Copy)]
pub struct FtsRef {
pub columns: &'static [&'static str],
}
impl FtsRef {
pub fn search(self, text: &str) -> Pred {
let terms = text
.split_whitespace()
.map(|term| format!("\"{}\"", term.replace('"', "\"\"")))
.collect::<Vec<_>>();
if terms.is_empty() {
Pred::Always
} else {
self.matches(terms.join(" AND "))
}
}
pub fn matches(self, query: impl Into<String>) -> Pred {
Pred::Matches {
columns: self.columns,
query: query.into(),
}
}
}
#[derive(Clone, Copy)]
pub struct GeoRef {
pub lat: &'static str,
pub lon: &'static str,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GeoRect {
pub min_lat: f64,
pub max_lat: f64,
pub min_lon: f64,
pub max_lon: f64,
}
impl GeoRef {
pub fn within(self, r: GeoRect) -> Pred {
Pred::Within {
lat: self.lat,
lon: self.lon,
min_lat: r.min_lat,
max_lat: r.max_lat,
min_lon: r.min_lon,
max_lon: r.max_lon,
}
}
}
pub fn rank() -> Sort {
Sort {
column: "",
ascending: true,
by_rank: true,
}
}
impl Col<String> {
pub fn contains(self, needle: impl Into<String>) -> Pred {
Pred::Contains(self.column, needle.into())
}
pub fn starts_with(self, prefix: impl Into<String>) -> Pred {
Pred::StartsWith(self.column, prefix.into())
}
pub fn starts_with_ci(self, prefix: impl Into<String>) -> Pred {
Pred::StartsWithCi(self.column, prefix.into())
}
pub fn contains_ci(self, needle: impl Into<String>) -> Pred {
Pred::ContainsCi(self.column, needle.into())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Sort {
pub column: &'static str,
pub ascending: bool,
pub by_rank: bool,
}
impl Sort {
pub fn asc(column: &'static str) -> Sort {
Sort {
column,
ascending: true,
by_rank: false,
}
}
pub fn desc(column: &'static str) -> Sort {
Sort {
column,
ascending: false,
by_rank: false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Fetch {
pub pred: Pred,
pub sort: Vec<Sort>,
pub limit: Option<usize>,
}
impl Default for Fetch {
fn default() -> Fetch {
Fetch {
pred: Pred::Always,
sort: Vec::new(),
limit: None,
}
}
}
impl Fetch {
pub fn new() -> Fetch {
Fetch::default()
}
pub fn filter(mut self, p: Pred) -> Fetch {
self.pred = match self.pred {
Pred::Always => p,
prior => prior & p,
};
self
}
pub fn sort(mut self, s: Sort) -> Fetch {
self.sort.push(s);
self
}
pub fn limit(mut self, n: usize) -> Fetch {
self.limit = Some(n);
self
}
pub fn dependencies(&self) -> Deps {
let mut local = Vec::new();
self.pred.columns(&mut local);
for s in &self.sort {
if !s.by_rank && !local.contains(&s.column) {
local.push(s.column);
}
}
let mut related = Vec::new();
self.pred.related_deps(&mut related);
Deps { local, related }
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Delta {
Insert(usize, u64),
Remove(usize, u64),
Move(usize, usize, u64),
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Deps {
pub local: Vec<&'static str>,
pub related: Vec<RelatedDep>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RelatedDep {
pub owner: &'static str,
pub field: &'static str,
pub target_table: &'static str,
pub columns: Vec<&'static str>,
}
impl Deps {
pub fn touches_local(&self, column: &str) -> bool {
self.local.contains(&column)
}
pub fn touches_related(&self, table: &str, column: &str) -> bool {
self.related
.iter()
.any(|r| r.target_table == table && r.columns.contains(&column))
}
pub fn related_tables(&self) -> Vec<&'static str> {
let mut out: Vec<&'static str> = Vec::new();
for r in &self.related {
if !out.contains(&r.target_table) {
out.push(r.target_table);
}
}
out
}
}
#[derive(Clone, PartialEq, Debug)]
pub enum SetChange {
Same,
Deltas(Vec<Delta>),
Reload,
}
pub struct ResultSet {
ids: Vec<u64>,
fetch: Fetch,
deps: Deps,
}
impl ResultSet {
pub fn new(fetch: Fetch) -> ResultSet {
ResultSet {
ids: Vec::new(),
deps: fetch.dependencies(),
fetch,
}
}
pub fn ids(&self) -> &[u64] {
&self.ids
}
pub fn fetch(&self) -> &Fetch {
&self.fetch
}
pub fn deps(&self) -> &Deps {
&self.deps
}
pub fn reset(&mut self, ids: Vec<u64>) {
self.ids = ids;
}
pub fn adopt(&mut self, new: Vec<u64>) -> SetChange {
if self.ids == new {
return SetChange::Same;
}
let old = std::mem::replace(&mut self.ids, new);
let new = &self.ids;
let new_set: std::collections::HashSet<u64> = new.iter().copied().collect();
let old_set: std::collections::HashSet<u64> = old.iter().copied().collect();
let retained_old: Vec<u64> = old
.iter()
.copied()
.filter(|k| new_set.contains(k))
.collect();
let retained_new: Vec<u64> = new
.iter()
.copied()
.filter(|k| old_set.contains(k))
.collect();
let mut deltas: Vec<Delta> = Vec::new();
for (i, k) in old.iter().enumerate().rev() {
if !new_set.contains(k) {
deltas.push(Delta::Remove(i, *k));
}
}
let mut scratch = retained_old.clone();
if retained_old != retained_new {
let mismatch = retained_old
.iter()
.copied()
.zip(retained_new.iter().copied())
.find(|(a, b)| a != b);
let mut moved = false;
if let Some((a, b)) = mismatch {
for k in [a, b] {
let from = scratch.iter().position(|x| *x == k);
let to = retained_new.iter().position(|x| *x == k);
if let (Some(from), Some(to)) = (from, to) {
let mut trial = scratch.clone();
let key = trial.remove(from);
trial.insert(to, key);
if trial == retained_new {
deltas.push(Delta::Move(from, to, k));
scratch = trial;
moved = true;
break;
}
}
}
}
if !moved {
return SetChange::Reload;
}
}
for (i, k) in new.iter().enumerate() {
if !old_set.contains(k) {
deltas.push(Delta::Insert(i, *k));
if i <= scratch.len() {
scratch.insert(i, *k);
} else {
return SetChange::Reload;
}
}
}
if scratch == *new {
SetChange::Deltas(deltas)
} else {
SetChange::Reload
}
}
}
pub(crate) fn find_match_query(pred: &Pred) -> Option<String> {
match pred {
Pred::Matches { query, .. } => Some(query.clone()),
Pred::And(a, b) | Pred::Or(a, b) => find_match_query(a).or_else(|| find_match_query(b)),
Pred::Not(a) => find_match_query(a),
_ => None,
}
}