use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::{Bound, ControlFlow};
use std::sync::Arc;
use chrono::{Datelike, NaiveDateTime, NaiveTime, Timelike};
use relate_core::{NodeId, Temporal, Value};
use relate_ir::BinaryOp;
use relate_model::canonical_key::f64_exact_i64;
use crate::eval;
use crate::group_key::GroupKey;
use super::DrainState;
use crate::graph::unposted::UnpostedMark;
#[derive(Clone, Debug)]
pub(super) enum Postings {
One(NodeId),
Many(HashSet<NodeId>),
}
impl Postings {
fn insert(&mut self, id: NodeId) {
match self {
Postings::One(existing) if *existing == id => {}
Postings::One(existing) => {
let mut set = HashSet::with_capacity(2);
set.insert(*existing);
set.insert(id);
*self = Postings::Many(set);
}
Postings::Many(set) => {
set.insert(id);
}
}
}
fn remove(&mut self, id: NodeId) -> bool {
let demote = match self {
Postings::One(existing) if *existing == id => return true,
Postings::One(_) => return false,
Postings::Many(set) => {
set.remove(&id);
match set.len() {
0 => return true,
1 => set.iter().copied().next(),
_ => None,
}
}
};
if let Some(only) = demote {
*self = Postings::One(only);
}
false
}
#[cfg(test)]
pub(super) fn contains(&self, id: NodeId) -> bool {
match self {
Postings::One(existing) => *existing == id,
Postings::Many(set) => set.contains(&id),
}
}
fn len(&self) -> usize {
match self {
Postings::One(_) => 1,
Postings::Many(set) => set.len(),
}
}
pub(super) fn copy_ids(&self) -> Vec<NodeId> {
match self {
Postings::One(id) => vec![*id],
Postings::Many(set) => {
let mut ids: Vec<NodeId> = set.iter().copied().collect();
ids.sort_unstable();
ids
}
}
}
pub(super) fn each(&self, mut visit: impl FnMut(NodeId) -> ControlFlow<()>) {
match self {
Postings::One(id) => {
let _ = visit(*id);
}
Postings::Many(set) => {
for id in set {
if visit(*id).is_break() {
break;
}
}
}
}
}
fn extend_into(&self, out: &mut HashSet<NodeId>) {
self.each(|id| {
out.insert(id);
ControlFlow::Continue(())
});
}
}
#[derive(Clone, Debug)]
pub(super) enum RevKeys<T> {
One(T),
Many(Vec<T>),
}
impl<T: PartialEq + Clone> RevKeys<T> {
fn insert(&mut self, key: T) {
match self {
RevKeys::One(existing) if existing == &key => {}
RevKeys::One(existing) => {
let first = existing.clone();
*self = RevKeys::Many(vec![first, key]);
}
RevKeys::Many(keys) => {
if !keys.contains(&key) {
keys.push(key);
}
}
}
}
fn into_vec(self) -> Vec<T> {
match self {
RevKeys::One(key) => vec![key],
RevKeys::Many(keys) => keys,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Extremum {
Min,
Max,
}
#[derive(Debug, Default)]
pub(crate) struct RangeIndex {
pub(super) order: BTreeMap<OrderKey, Postings>,
pub(super) by_node: HashMap<NodeId, RevKeys<OrderKey>>,
eq_only: HashMap<GroupKey, Postings>,
eq_by_node: HashMap<NodeId, RevKeys<GroupKey>>,
pub(super) unbounded: HashSet<NodeId>,
pub(super) unposted: UnpostedMark,
pub(super) dirty: HashSet<NodeId>,
}
impl RangeIndex {
pub(super) fn order_is_complete(&self) -> bool {
self.eq_only.is_empty() && self.unbounded.is_empty() && self.unposted.is_empty()
}
pub(super) fn answers_extremum(&self) -> bool {
let one_variant = match (self.order.first_key_value(), self.order.last_key_value()) {
(Some((lo, _)), Some((hi, _))) => matches!(
(lo, hi),
(OrderKey::Int(_), OrderKey::Int(_)) | (OrderKey::String(_), OrderKey::String(_))
),
(None, None) => true,
(None, Some(_)) | (Some(_), None) => {
debug_assert!(false, "one end of a one-map index cannot exist alone");
false
}
};
self.order_is_complete() && one_variant
}
pub(super) fn step_from(
&self,
from: Option<&OrderKey>,
extremum: Extremum,
) -> Option<(&OrderKey, &Postings)> {
let entry = match (from, extremum) {
(None, Extremum::Max) => self.order.last_key_value(),
(None, Extremum::Min) => self.order.first_key_value(),
(Some(k), Extremum::Max) => self.order.range(..k.clone()).next_back(),
(Some(k), Extremum::Min) => self
.order
.range((Bound::Excluded(k.clone()), Bound::Unbounded))
.next(),
};
entry
}
}
impl DrainState for RangeIndex {
fn dirty_mut(&mut self) -> &mut HashSet<NodeId> {
&mut self.dirty
}
fn insert(&mut self, id: NodeId, value: &Value) {
insert_order(self, value, id);
}
fn remove_node(&mut self, id: NodeId) {
order_remove_node(self, id);
}
fn reconcile_live(&mut self, id: NodeId, live: Option<&Value>) {
let unpostable = live.is_some_and(|v| !Destinations::of(v).reaches_a_map());
self.unposted.restate(id, unpostable);
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(in crate::graph) enum OrderKey {
Bool(bool),
Int(i64),
Float(u64),
String(Arc<str>),
Date(i32),
LocalTime(i64),
Time(i64),
LocalDateTime(i64),
DateTime(i64),
Duration(i64, i64, i128),
}
#[cfg(test)]
impl RevKeys<OrderKey> {
pub(super) fn first(&self) -> Option<&OrderKey> {
match self {
RevKeys::One(key) => Some(key),
RevKeys::Many(keys) => keys.first(),
}
}
}
#[derive(Clone, Debug)]
pub(crate) enum RangeSeek {
Cmp { op: BinaryOp, bound: Value },
Eq(Value),
In(Arc<Vec<Value>>),
}
#[derive(Clone, Debug)]
pub(crate) enum SpatialSeek {
Distance {
origin: Value,
max: f64,
inclusive: bool,
},
BBox {
lo: Value,
hi: Value,
},
}
pub(super) fn ord_f64(f: f64) -> u64 {
let bits = f.to_bits();
if bits & (1u64 << 63) == 0 {
bits | (1u64 << 63)
} else {
!bits
}
}
pub(super) fn time_nanos(t: NaiveTime) -> i64 {
t.num_seconds_from_midnight() as i64 * 1_000_000_000 + t.nanosecond() as i64
}
pub(super) fn dt_nanos(dt: NaiveDateTime) -> Option<i64> {
dt.and_utc().timestamp_nanos_opt()
}
pub(in crate::graph) fn order_key(v: &Value) -> Option<OrderKey> {
match v {
Value::Bool(b) => Some(OrderKey::Bool(*b)),
Value::Int(i) => Some(OrderKey::Int(*i)),
Value::Float(f) if !f.is_nan() => Some(match f64_exact_i64(*f) {
Some(i) => OrderKey::Int(i),
None => OrderKey::Float(ord_f64(*f)),
}),
Value::String(s) => Some(OrderKey::String(Arc::clone(s))),
Value::Temporal(Temporal::Date(d)) => Some(OrderKey::Date(d.num_days_from_ce())),
Value::Temporal(Temporal::LocalTime(t)) => Some(OrderKey::LocalTime(time_nanos(*t))),
Value::Temporal(Temporal::Time { time, offset }) => Some(OrderKey::Time(
time_nanos(*time) - i64::from(*offset) * 1_000_000_000,
)),
Value::Temporal(Temporal::LocalDateTime(dt)) => dt_nanos(*dt).map(OrderKey::LocalDateTime),
Value::Temporal(Temporal::DateTime { utc, .. }) => dt_nanos(*utc).map(OrderKey::DateTime),
Value::Temporal(Temporal::Duration {
months,
days,
nanos,
}) => Some(OrderKey::Duration(*months, *days, *nanos)),
_ => None,
}
}
fn bool_lower() -> OrderKey {
OrderKey::Bool(false)
}
fn int_lower() -> OrderKey {
OrderKey::Int(i64::MIN)
}
fn float_lower() -> OrderKey {
OrderKey::Float(ord_f64(f64::NEG_INFINITY))
}
fn string_lower() -> OrderKey {
OrderKey::String(Arc::from(""))
}
fn date_lower() -> OrderKey {
OrderKey::Date(i32::MIN)
}
fn local_time_lower() -> OrderKey {
OrderKey::LocalTime(i64::MIN)
}
fn time_lower() -> OrderKey {
OrderKey::Time(i64::MIN)
}
fn local_date_time_lower() -> OrderKey {
OrderKey::LocalDateTime(i64::MIN)
}
fn date_time_lower() -> OrderKey {
OrderKey::DateTime(i64::MIN)
}
fn duration_lower() -> OrderKey {
OrderKey::Duration(i64::MIN, i64::MIN, i128::MIN)
}
pub(super) fn variant_lower(k: &OrderKey) -> OrderKey {
match k {
OrderKey::Bool(_) => bool_lower(),
OrderKey::Int(_) => int_lower(),
OrderKey::Float(_) => float_lower(),
OrderKey::String(_) => string_lower(),
OrderKey::Date(_) => date_lower(),
OrderKey::LocalTime(_) => local_time_lower(),
OrderKey::Time(_) => time_lower(),
OrderKey::LocalDateTime(_) => local_date_time_lower(),
OrderKey::DateTime(_) => date_time_lower(),
OrderKey::Duration(_, _, _) => duration_lower(),
}
}
fn successor(k: &OrderKey) -> Option<OrderKey> {
Some(match k {
OrderKey::Bool(_) => int_lower(),
OrderKey::Int(_) => float_lower(),
OrderKey::Float(_) => string_lower(),
OrderKey::String(_) => date_lower(),
OrderKey::Date(_) => local_time_lower(),
OrderKey::LocalTime(_) => time_lower(),
OrderKey::Time(_) => local_date_time_lower(),
OrderKey::LocalDateTime(_) => date_time_lower(),
OrderKey::DateTime(_) => duration_lower(),
OrderKey::Duration(_, _, _) => return None,
})
}
pub(super) fn variant_upper(k: &OrderKey) -> Bound<OrderKey> {
successor(k).map_or(Bound::Unbounded, Bound::Excluded)
}
pub(super) fn prefix_successor(prefix: &str) -> Option<String> {
let mut chars: Vec<char> = prefix.chars().collect();
while let Some(c) = chars.pop() {
if let Some(next) = char::from_u32(u32::from(c).saturating_add(1)) {
chars.push(next);
return Some(chars.into_iter().collect());
}
}
None
}
fn remember<T: PartialEq + Clone>(map: &mut HashMap<NodeId, RevKeys<T>>, id: NodeId, key: T) {
match map.entry(id) {
std::collections::hash_map::Entry::Occupied(mut entry) => entry.get_mut().insert(key),
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(RevKeys::One(key));
}
}
}
trait ForwardPostings {
type Key;
fn unpost(&mut self, key: &Self::Key, id: NodeId);
fn post(&mut self, key: Self::Key, id: NodeId);
}
impl<K: Ord> ForwardPostings for BTreeMap<K, Postings> {
type Key = K;
fn unpost(&mut self, key: &K, id: NodeId) {
let empty = self
.get_mut(key)
.is_some_and(|postings| postings.remove(id));
if empty {
self.remove(key);
}
}
fn post(&mut self, key: K, id: NodeId) {
self.entry(key).or_insert(Postings::One(id)).insert(id);
}
}
impl<K: Eq + std::hash::Hash> ForwardPostings for HashMap<K, Postings> {
type Key = K;
fn unpost(&mut self, key: &K, id: NodeId) {
let empty = self
.get_mut(key)
.is_some_and(|postings| postings.remove(id));
if empty {
self.remove(key);
}
}
fn post(&mut self, key: K, id: NodeId) {
self.entry(key).or_insert(Postings::One(id)).insert(id);
}
}
fn forget<K, M>(reverse: &mut HashMap<NodeId, RevKeys<K>>, forward: &mut M, id: NodeId)
where
K: PartialEq + Clone,
M: ForwardPostings<Key = K>,
{
if let Some(keys) = reverse.remove(&id) {
for key in keys.into_vec() {
forward.unpost(&key, id);
}
}
}
fn post<K, M>(reverse: &mut HashMap<NodeId, RevKeys<K>>, forward: &mut M, id: NodeId, key: K)
where
K: PartialEq + Clone,
M: ForwardPostings<Key = K>,
{
remember(reverse, id, key.clone());
forward.post(key, id);
}
pub(super) fn insert_order(st: &mut RangeIndex, value: &Value, id: NodeId) {
let d = Destinations::of(value);
if let Some(k) = d.order {
post(&mut st.by_node, &mut st.order, id, k);
}
if d.unbounded {
st.unbounded.insert(id);
}
if let Some(gk) = d.eq {
post(&mut st.eq_by_node, &mut st.eq_only, id, gk);
}
}
struct Destinations {
order: Option<OrderKey>,
unbounded: bool,
eq: Option<GroupKey>,
}
impl Destinations {
fn of(value: &Value) -> Self {
let order = order_key(value);
Destinations {
eq: if order.is_none() || order_key_finer_than_equality(value) {
GroupKey::for_property_index(value)
} else {
None
},
unbounded: matches!(value, Value::Temporal(_)) && order.is_none(),
order,
}
}
fn reaches_a_map(&self) -> bool {
self.order.is_some() || self.unbounded || self.eq.is_some()
}
}
pub(super) fn order_remove_node(st: &mut RangeIndex, id: NodeId) {
st.unbounded.remove(&id);
st.unposted.clear(id);
forget(&mut st.by_node, &mut st.order, id);
forget(&mut st.eq_by_node, &mut st.eq_only, id);
}
pub(super) fn equality_ids(st: &RangeIndex, value: &Value) -> HashSet<NodeId> {
let mut out = HashSet::new();
equality_each(st, value, |id| {
out.insert(id);
ControlFlow::Continue(())
});
out
}
pub(super) fn equality_each(
st: &RangeIndex,
value: &Value,
visit: impl FnMut(NodeId) -> ControlFlow<()>,
) {
if let Some(postings) = equality_postings(st, value) {
postings.each(visit);
}
}
pub(super) fn equality_count(st: &RangeIndex, value: &Value) -> usize {
equality_postings(st, value).map(Postings::len).unwrap_or(0)
}
fn order_key_finer_than_equality(value: &Value) -> bool {
matches!(value, Value::Temporal(Temporal::DateTime { .. }))
}
fn equality_postings<'a>(st: &'a RangeIndex, value: &Value) -> Option<&'a Postings> {
if !order_key_finer_than_equality(value) {
if let Some(k) = order_key(value) {
return st.order.get(&k);
}
}
st.eq_only.get(&GroupKey::for_property_index(value)?)
}
pub(super) fn collect_range(
order: &BTreeMap<OrderKey, Postings>,
start: Bound<OrderKey>,
end: Bound<OrderKey>,
out: &mut HashSet<NodeId>,
) {
scan::visit_range(order, start, end, |ids| ids.extend_into(out));
}
pub(super) fn range_ids(
order: &BTreeMap<OrderKey, Postings>,
op: BinaryOp,
bound: &Value,
) -> HashSet<NodeId> {
let mut out = HashSet::new();
scan::visit_range_postings(order, op, bound, |ids| ids.extend_into(&mut out));
out
}
pub(super) fn range_count(
order: &BTreeMap<OrderKey, Postings>,
op: BinaryOp,
bound: &Value,
) -> usize {
let mut count = 0usize;
scan::visit_range_postings(order, op, bound, |ids| {
count = count.saturating_add(ids.len());
});
count
}
pub(super) fn prefix_ids(order: &BTreeMap<OrderKey, Postings>, prefix: &str) -> HashSet<NodeId> {
let mut out = HashSet::new();
let start = OrderKey::String(Arc::from(prefix));
let end = match prefix_successor(prefix) {
Some(s) => Bound::Excluded(OrderKey::String(Arc::from(s))),
None => variant_upper(&start),
};
collect_range(order, Bound::Included(start), end, &mut out);
out
}
pub(super) fn cmp_holds(v: &Value, op: BinaryOp, bound: &Value) -> bool {
let Some(ordering) = eval::ordering_operator(op) else {
return false;
};
matches!(
eval::cmp_bool(v, bound, ordering.equality_allowed, ordering.pred),
Value::Bool(true)
)
}
#[cfg(test)]
mod tests;
mod scan;