Skip to main content

rudb_exec/
expr.rs

1//! Evaluating a bound expression over a chunk.
2//!
3//! One function, recursive, one vector out per call. That is section 8.2's description of tier 0
4//! word for word: "a tree of expression nodes, each evaluating its children into intermediate
5//! vectors and then applying a kernel". The intermediate vectors are the cost and they are the
6//! thing tiers 1 and 2 exist to remove, by fusing a chain of them into one loop and by compiling
7//! that loop respectively. Neither of those can be checked against anything until this exists, so
8//! this exists first and stays.
9//!
10//! What runs in a pipeline is [`Prepared`](crate::Prepared), which does once per pipeline the four
11//! things this does once per chunk. This stays as the reference the prepared form is checked
12//! against, for the reason `spec/engine/04-expressions.md` gives for keeping every slow path that
13//! a fast path replaced: a fast path with nothing to disagree with is a fast path nobody can tell
14//! is wrong. It is also still what the operators that evaluate an expression exactly once use,
15//! since preparing a tree to run it on one chunk is more work than walking it.
16//!
17//! Nothing here decides a type. Every expression in a bound plan carries the type it evaluates to,
18//! the binder put the casts in, and a kernel is told what it returns rather than working it out.
19//! An evaluator that inferred anything would be a second type system that has to agree with the
20//! first one, and the interesting bugs in a database are exactly the places where two such things
21//! disagree.
22
23use rudb_common::{Error, Result, Value};
24use rudb_kernels::{cast, combine, compare, is_true};
25use rudb_plan::{Expr, ExprRef, Plan};
26use rudb_vector::{Chunk, Vector};
27
28use crate::prepared::{comparison, connective, narrow};
29use crate::schema::Schema;
30use crate::written::written;
31
32/// Evaluates one expression over a chunk, producing one vector as long as the chunk.
33///
34/// `schema` describes `chunk`, and it is what a column reference resolves against.
35///
36/// # Errors
37///
38/// If a column reference names a binding the schema does not have, if an aggregate appears outside
39/// an aggregate operator, or anything a kernel reports.
40pub fn evaluate(plan: &Plan, expr: ExprRef, schema: &Schema, chunk: &Chunk) -> Result<Vector> {
41    let ty = plan.expr_type(expr).clone();
42    match *plan.expr(expr) {
43        Expr::Column(binding) => {
44            let position = schema.position_of(binding).ok_or_else(|| {
45                Error::internal(format!(
46                    "column #{}.{} is not in the schema this operator was given",
47                    binding.table, binding.column
48                ))
49            })?;
50            Ok(chunk.column(position)?.clone())
51        }
52        Expr::Constant(reference) => {
53            Ok(Vector::constant(ty, plan.value(reference).clone(), chunk.len()))
54        }
55        Expr::Cast { input, try_cast } => {
56            let inner = evaluate(plan, input, schema, chunk)?;
57            cast(&inner, &ty, try_cast)
58        }
59        Expr::Compare { op, left, right } => {
60            let left = evaluate(plan, left, schema, chunk)?;
61            let right = evaluate(plan, right, schema, chunk)?;
62            compare(comparison(op), &left, &right)
63        }
64        Expr::Conjunction { op, children } => {
65            let children = evaluate_all(plan, plan.expr_list(children), schema, chunk)?;
66            combine(connective(op), &children)
67        }
68        Expr::Function { name, args } => {
69            let args = evaluate_all(plan, plan.expr_list(args), schema, chunk)?;
70            // The renderer runs only if a kernel asks for it, which is only on the row that divides
71            // by zero, so a chunk that computes nothing but answers pays nothing for it.
72            rudb_kernels::call(plan.string(name), &args, &ty, Some(&|| written(plan, expr, schema)))
73        }
74        Expr::Aggregate { name, .. } => Err(Error::internal(format!(
75            "the {} aggregate was evaluated as an ordinary expression",
76            plan.string(name)
77        ))),
78        Expr::Case { arms, otherwise } => {
79            let arms = plan.arm_list(arms).to_vec();
80            let mut answers = vec![Value::Null; chunk.len()];
81            let mut pending: Vec<usize> = (0..chunk.len()).collect();
82            for arm in arms {
83                if pending.is_empty() {
84                    break;
85                }
86                let narrowed = narrow(chunk, &pending)?;
87                let flags = evaluate(plan, arm.when, schema, &narrowed)?;
88                let mut taken = Vec::new();
89                let mut still = Vec::new();
90                // row at a time: 2c (#57) replaces this whole arm with a selection threaded through
91                // the arms and a scatter kernel writing the results back, which is the change that
92                // removes all three of these loops at once.
93                for (at, &row) in pending.iter().enumerate() {
94                    if is_true(&flags.value_at(at)) {
95                        taken.push((at, row));
96                    } else {
97                        still.push(row);
98                    }
99                }
100                if !taken.is_empty() {
101                    let positions: Vec<usize> = taken.iter().map(|&(at, _)| at).collect();
102                    let matched = narrow(&narrowed, &positions)?;
103                    let results = evaluate(plan, arm.then, schema, &matched)?;
104                    // row at a time: the scatter this wants is 2c (#57), same as the loop above.
105                    for (slot, &(_, row)) in taken.iter().enumerate() {
106                        answers[row] = results.value_at(slot);
107                    }
108                }
109                pending = still;
110            }
111            if let Some(otherwise) = otherwise {
112                if !pending.is_empty() {
113                    let narrowed = narrow(chunk, &pending)?;
114                    let results = evaluate(plan, otherwise, schema, &narrowed)?;
115                    // row at a time: the scatter this wants is 2c (#57), same as the two above.
116                    for (slot, &row) in pending.iter().enumerate() {
117                        answers[row] = results.value_at(slot);
118                    }
119                }
120            }
121            Vector::from_values(ty, &answers)
122        }
123    }
124}
125
126/// Evaluates a list of expressions over one chunk.
127///
128/// # Errors
129///
130/// Anything [`evaluate`] reports, on the first expression that reports it.
131pub fn evaluate_all(
132    plan: &Plan,
133    exprs: &[ExprRef],
134    schema: &Schema,
135    chunk: &Chunk,
136) -> Result<Vec<Vector>> {
137    exprs.iter().map(|&expr| evaluate(plan, expr, schema, chunk)).collect()
138}