use rudb_catalog::{Catalog, QualifiedName};
use rudb_common::Result;
use rudb_plan::{Node, NodeRef, Plan};
use crate::group::{Aggregate, Distinct};
use crate::join::{CrossProduct, Join};
use crate::operator::Operator;
use crate::setop::SetOp;
use crate::sort::Sort;
use crate::source::{Dummy, Scan, Values};
use crate::stream::{Filter, Limit, Project};
pub fn build<'a>(plan: &'a Plan, catalog: &'a Catalog) -> Result<Box<dyn Operator + 'a>> {
node(plan, catalog, plan.root())
}
fn node<'a>(
plan: &'a Plan,
catalog: &'a Catalog,
reference: NodeRef,
) -> Result<Box<dyn Operator + 'a>> {
Ok(match *plan.node(reference) {
Node::Get { catalog: database, schema, table, index, columns, .. } => {
let name =
QualifiedName::new(plan.string(database), plan.string(schema), plan.string(table));
Box::new(Scan::new(plan, catalog.table(&name)?, index, columns)?)
}
Node::Dummy => Box::new(Dummy::new()),
Node::Values { index, columns, rows } => Box::new(Values::new(plan, index, columns, rows)?),
Node::Filter { input, predicate } => {
Box::new(Filter::new(plan, node(plan, catalog, input)?, predicate))
}
Node::Project { input, index, exprs, names } => {
Box::new(Project::new(plan, node(plan, catalog, input)?, index, exprs, names)?)
}
Node::Aggregate { input, index, groups, aggregates } => {
Box::new(Aggregate::new(plan, node(plan, catalog, input)?, index, groups, aggregates)?)
}
Node::Sort { input, keys } => Box::new(Sort::new(plan, node(plan, catalog, input)?, keys)),
Node::Limit { input, count, offset } => {
Box::new(Limit::new(node(plan, catalog, input)?, count, offset))
}
Node::Distinct { input, on } => {
Box::new(Distinct::new(plan, node(plan, catalog, input)?, on))
}
Node::Join { left, right, kind, conditions } => Box::new(Join::new(
plan,
node(plan, catalog, left)?,
node(plan, catalog, right)?,
kind,
conditions,
)),
Node::CrossProduct { left, right } => {
Box::new(CrossProduct::new(node(plan, catalog, left)?, node(plan, catalog, right)?))
}
Node::SetOp { left, right, kind, all, index } => Box::new(SetOp::new(
node(plan, catalog, left)?,
node(plan, catalog, right)?,
kind,
all,
index,
)),
})
}