Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/src/order.rs

//! The output operator: a relation's rows in order, cut by an offset and a limit.
//!
//! [`Order`] holds keys ([`OrderKey`]: a column, rising or falling, where its nulls go, and
//! the flag columns that make it null where one is 0), an offset and a limit.
//! [`Output::ordered`] gives a derived relation's rows through it (a counted relation's as
//! [`Rows`] says, the bag one row per match); [`Order::apply`] orders rows in hand. Rows with
//! equal keys keep the order of their whole row, so the answer is one at any thread count.
//! With no key the rows come as stored and reading stops once the offset and the limit are
//! taken (a counted relation's bag is expanded no further).

use crate::eval::Output;
use crate::rules::{Plan, RelId, Rows};
use crate::{NULL, Result, Type, Value};

/// Where the nulls of an [`OrderKey`] go.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Nulls {
    /// After every value rising, before every value falling (SQL's and GQL's default: a
    /// null as the greatest value).
    #[default]
    Default,
    /// Before every value.
    First,
    /// After every value.
    Last,
}

/// One key of an [`Order`]: column `col`, rising or falling. A value is null when the
/// column's type has nulls and the value is the null code ([`crate::NULL`]), or when one of
/// the `null_when` columns (found flags of an optional part) is 0 there.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct OrderKey {
    /// The column.
    pub col: usize,
    /// Falling.
    pub desc: bool,
    /// Where its nulls go.
    pub nulls: Nulls,
    /// Flag columns: the key is null in a row where one of them is 0.
    pub null_when: Vec<usize>,
}

impl OrderKey {
    /// Column `col` rising.
    pub fn asc(col: usize) -> Self {
        OrderKey {
            col,
            desc: false,
            nulls: Nulls::Default,
            null_when: Vec::new(),
        }
    }

    /// Column `col` falling.
    pub fn desc(col: usize) -> Self {
        OrderKey {
            desc: true,
            ..OrderKey::asc(col)
        }
    }

    /// Its nulls before every value.
    pub fn nulls_first(mut self) -> Self {
        self.nulls = Nulls::First;
        self
    }

    /// Its nulls after every value.
    pub fn nulls_last(mut self) -> Self {
        self.nulls = Nulls::Last;
        self
    }

    /// Null where one of the flag columns `flags` is 0.
    pub fn null_when(mut self, flags: impl IntoIterator<Item = usize>) -> Self {
        self.null_when = flags.into_iter().collect();
        self
    }

    /// Null where `marks` make its column null (their flags).
    pub fn null_by(self, marks: &[NullMark]) -> Self {
        let flags: Vec<usize> = marks
            .iter()
            .filter(|m| m.cols.contains(&self.col))
            .map(|m| m.flag)
            .collect();
        self.null_when(flags)
    }
}

/// The null marks of an optional part (GQL's `OPTIONAL MATCH`): where flag column `flag` is
/// 0 (the part was not found), the columns `cols` are null.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct NullMark {
    /// The flag column: 1 where the part was found, 0 where not.
    pub flag: usize,
    /// The columns null where it was not.
    pub cols: Vec<usize>,
}

/// Rows as returned, with their null cells: a cell is null when `nulls` holds its (row,
/// column). Made by [`Marked::pick`]; joined by [`Marked::append`] (`UNION ALL`) and made
/// distinct by [`Marked::distinct`] (`UNION`), a null kept apart from every value.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Marked {
    /// The rows.
    pub rows: Vec<Vec<Value>>,
    /// The null cells, (row, column) rising.
    pub nulls: Vec<(usize, usize)>,
}

impl Marked {
    /// Each of `rows`' columns `pick` (then, with `keep`, the whole row after them), a picked
    /// cell null where one of `marks` holds its column and its flag is 0.
    pub fn pick(rows: Vec<Vec<Value>>, pick: &[usize], keep: bool, marks: &[NullMark]) -> Marked {
        let mut nulls: Vec<(usize, usize)> = Vec::new();
        let rows = rows
            .into_iter()
            .enumerate()
            .map(|(i, r)| {
                let mut mine: Vec<(usize, usize)> = Vec::new();
                for m in marks {
                    if r[m.flag] == 0 {
                        for (p, c) in pick.iter().enumerate() {
                            if m.cols.contains(c) {
                                mine.push((i, p));
                            }
                        }
                    }
                }
                mine.sort_unstable();
                mine.dedup();
                nulls.extend(mine);
                let mut row: Vec<Value> = pick.iter().map(|&c| r[c]).collect();
                if keep {
                    row.extend_from_slice(&r);
                }
                row
            })
            .collect();
        Marked { rows, nulls }
    }

    /// Whether cell (`r`, `c`) is null.
    pub fn is_null(&self, r: usize, c: usize) -> bool {
        self.nulls.binary_search(&(r, c)).is_ok()
    }

    /// `other`'s rows after these (`UNION ALL`).
    pub fn append(&mut self, other: Marked) {
        let n = self.rows.len();
        self.nulls
            .extend(other.nulls.into_iter().map(|(r, c)| (r + n, c)));
        self.rows.extend(other.rows);
    }

    /// The distinct rows, sorted (`UNION`): two rows are one when every cell is (a null cell,
    /// its value kept, is never one with a value, and sorts after every value) and their `extra` keys are (text a
    /// row carries beside its cells, such as its whole values; none: empty). Gives, for each
    /// row kept, the row it was (the first of its equals).
    pub fn distinct(&mut self, extra: &[Vec<String>]) -> Vec<usize> {
        type Key = (Vec<(bool, Value)>, Vec<String>, usize);
        let rows = std::mem::take(&mut self.rows);
        let mut marked: Vec<Key> = rows
            .into_iter()
            .enumerate()
            .map(|(i, r)| {
                let m = r
                    .into_iter()
                    .enumerate()
                    .map(|(c, v)| (self.is_null(i, c), v))
                    .collect();
                (m, extra.get(i).cloned().unwrap_or_default(), i)
            })
            .collect();
        marked.sort_unstable();
        marked.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);
        self.nulls = Vec::new();
        let mut was = Vec::with_capacity(marked.len());
        for (i, (r, _, at)) in marked.into_iter().enumerate() {
            self.nulls
                .extend(r.iter().enumerate().filter(|x| x.1.0).map(|(c, _)| (i, c)));
            self.rows.push(r.into_iter().map(|x| x.1).collect());
            was.push(at);
        }
        was
    }
}

/// The output operator: keys, an offset (rows skipped) and a limit (rows kept at most).
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Order {
    /// The keys, the first deciding first.
    pub keys: Vec<OrderKey>,
    /// Rows skipped after ordering.
    pub offset: u64,
    /// Rows kept at most after the offset (`None`: all).
    pub limit: Option<u64>,
}

impl Order {
    /// No key, no offset, no limit.
    pub fn new() -> Self {
        Order::default()
    }

    /// Then by `key`.
    pub fn by(mut self, key: OrderKey) -> Self {
        self.keys.push(key);
        self
    }

    /// Skip `n` rows.
    pub fn offset(mut self, n: u64) -> Self {
        self.offset = n;
        self
    }

    /// Keep at most `n` rows.
    pub fn limit(mut self, n: u64) -> Self {
        self.limit = Some(n);
        self
    }

    /// The rows wanted at most from the start: offset plus limit.
    fn take(&self) -> Option<usize> {
        let l = self.limit?;
        Some(usize::try_from(self.offset.saturating_add(l)).unwrap_or(usize::MAX))
    }

    fn skip(&self) -> usize {
        usize::try_from(self.offset).unwrap_or(usize::MAX)
    }

    /// `rows` (columns of `types`) ordered by the keys, then by the whole row; the offset
    /// skipped, the limit kept. With no key the rows keep their order.
    pub fn apply(&self, types: &[Type], rows: Vec<Vec<Value>>) -> Vec<Vec<Value>> {
        self.apply_by(types, rows, None)
    }

    /// [`Order::apply`], a string key's ids first put in their strings' byte order by
    /// `rank` (an id's place among all of a run's strings), when given.
    fn apply_by(
        &self,
        types: &[Type],
        rows: Vec<Vec<Value>>,
        rank: Option<&[u32]>,
    ) -> Vec<Vec<Value>> {
        let skip = self.skip();
        let take = self
            .limit
            .map_or(usize::MAX, |l| usize::try_from(l).unwrap_or(usize::MAX));
        if self.keys.is_empty() {
            return rows.into_iter().skip(skip).take(take).collect();
        }
        // each row with its sort key in front: per key (placed null mark, flag mark, value),
        // a falling key's marks and value inverted; then the row
        let nullable = |c: usize| types.get(c).is_some_and(|t| t.nullable());
        let mut keyed: Vec<(Vec<Value>, Vec<Value>)> = rows
            .into_iter()
            .map(|r| {
                let mut k = Vec::with_capacity(self.keys.len() * 3);
                for key in &self.keys {
                    let v = match rank {
                        Some(rank)
                            if types.get(key.col) == Some(&Type::Str) && r[key.col] != NULL =>
                        {
                            Value::from(rank[r[key.col] as usize])
                        }
                        _ => r[key.col],
                    };
                    let flagged = key.null_when.iter().any(|&f| r[f] == 0);
                    let null = flagged || (nullable(key.col) && v == NULL);
                    let last = match key.nulls {
                        Nulls::Default => !key.desc,
                        Nulls::Last => true,
                        Nulls::First => false,
                    };
                    k.push((null == last) as Value);
                    let inv = |x: Value| if key.desc { !x } else { x };
                    k.push(inv(flagged as Value));
                    k.push(inv(v));
                }
                (k, r)
            })
            .collect();
        let cut = self.take().unwrap_or(usize::MAX);
        if cut < keyed.len() {
            // only the first `cut` rows are wanted: those found, then sorted
            if cut == 0 {
                return Vec::new();
            }
            keyed.select_nth_unstable(cut - 1);
            keyed.truncate(cut);
        }
        keyed.sort_unstable();
        keyed
            .into_iter()
            .skip(skip)
            .take(take)
            .map(|x| x.1)
            .collect()
    }
}

impl Output {
    /// The rows of derived relation `rel` through `order` ([`Order::apply`]): a counted
    /// relation's rows without the count, as `rows` says (the bag: each its count's
    /// times). With no key, reading stops once the offset and the limit are taken. `p` is
    /// the plan that ran.
    pub fn ordered(
        &self,
        p: &Plan,
        rel: RelId,
        rows: Rows,
        order: &Order,
    ) -> Result<Vec<Vec<Value>>> {
        let mut types = p.types(rel);
        let Some(f) = self.get(rel) else {
            return Ok(Vec::new());
        };
        let counted = p.is_counted(rel);
        if counted {
            types.pop();
        }
        if order.keys.is_empty() {
            let take = order.take().unwrap_or(usize::MAX);
            let mut out: Vec<Vec<Value>> = Vec::new();
            for mut r in f.rows() {
                if out.len() >= take {
                    break;
                }
                if !counted {
                    out.push(r);
                    continue;
                }
                let n = r.pop().expect("a count column");
                let times = if rows == Rows::Bag { n } else { 1 };
                for _ in 0..times {
                    if out.len() >= take {
                        break;
                    }
                    out.push(r.clone());
                }
            }
            return Ok(order.apply(&types, out));
        }
        let all = self.rows_as(p, rel, if counted { rows } else { Rows::Distinct }, None)?;
        // strings rules made have ids out of the byte order: a string key goes by its rank
        let rank = self
            .dict()
            .filter(|d| d.len() > d.sorted_len())
            .filter(|_| {
                order
                    .keys
                    .iter()
                    .any(|k| types.get(k.col) == Some(&Type::Str))
            })
            .map(|d| {
                let mut ids: Vec<u32> = (0..d.len() as u32).collect();
                ids.sort_unstable_by(|&a, &b| d.cmp_ids(Value::from(a), Value::from(b)));
                let mut rank = vec![0u32; ids.len()];
                for (r, &id) in ids.iter().enumerate() {
                    rank[id as usize] = r as u32;
                }
                rank
            });
        Ok(order.apply_by(&types, all, rank.as_deref()))
    }
}