use std::sync::Arc;
use crate::arrow::datatypes::{DataType, Field, Schema};
use crate::error::{ExecutionError, Result};
use crate::logicalplan::Expr::Literal;
use crate::logicalplan::ScalarValue;
use crate::logicalplan::{Expr, LogicalPlan};
use crate::table::*;
pub struct TableImpl {
plan: Arc<LogicalPlan>,
}
impl TableImpl {
pub fn new(plan: Arc<LogicalPlan>) -> Self {
Self { plan }
}
}
impl Table for TableImpl {
fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<dyn Table>> {
let mut expr: Vec<Expr> = Vec::with_capacity(columns.len());
for column_name in columns {
let i = self.column_index(column_name)?;
expr.push(Expr::Column(i));
}
self.select(expr)
}
fn select(&self, expr_list: Vec<Expr>) -> Result<Arc<dyn Table>> {
let schema = self.plan.schema();
let mut field: Vec<Field> = Vec::with_capacity(expr_list.len());
for expr in &expr_list {
match expr {
Expr::Column(i) => {
field.push(schema.field(*i).clone());
}
other => {
return Err(ExecutionError::NotImplemented(format!(
"Expr {:?} is not currently supported in this context",
other
)))
}
}
}
Ok(Arc::new(TableImpl::new(Arc::new(
LogicalPlan::Projection {
expr: expr_list.clone(),
input: self.plan.clone(),
schema: Arc::new(Schema::new(field)),
},
))))
}
fn filter(&self, expr: Expr) -> Result<Arc<dyn Table>> {
Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::Selection {
expr,
input: self.plan.clone(),
}))))
}
fn aggregate(
&self,
group_expr: Vec<Expr>,
aggr_expr: Vec<Expr>,
) -> Result<Arc<dyn Table>> {
Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::Aggregate {
input: self.plan.clone(),
group_expr,
aggr_expr,
schema: Arc::new(Schema::new(vec![])),
}))))
}
fn limit(&self, n: usize) -> Result<Arc<dyn Table>> {
Ok(Arc::new(TableImpl::new(Arc::new(LogicalPlan::Limit {
expr: Literal(ScalarValue::UInt32(n as u32)),
input: self.plan.clone(),
schema: self.plan.schema().clone(),
}))))
}
fn col(&self, name: &str) -> Result<Expr> {
Ok(Expr::Column(self.column_index(name)?))
}
fn column_index(&self, name: &str) -> Result<usize> {
let schema = self.plan.schema();
match schema.column_with_name(name) {
Some((i, _)) => Ok(i),
_ => Err(ExecutionError::InvalidColumn(format!(
"No column named '{}'",
name
))),
}
}
fn min(&self, expr: &Expr) -> Result<Expr> {
self.aggregate_expr("MIN", expr)
}
fn max(&self, expr: &Expr) -> Result<Expr> {
self.aggregate_expr("MAX", expr)
}
fn sum(&self, expr: &Expr) -> Result<Expr> {
self.aggregate_expr("SUM", expr)
}
fn avg(&self, expr: &Expr) -> Result<Expr> {
self.aggregate_expr("AVG", expr)
}
fn count(&self, expr: &Expr) -> Result<Expr> {
self.aggregate_expr("COUNT", expr)
}
fn to_logical_plan(&self) -> Arc<LogicalPlan> {
self.plan.clone()
}
}
impl TableImpl {
fn get_data_type(&self, expr: &Expr) -> Result<DataType> {
match expr {
Expr::Column(i) => Ok(self.plan.schema().field(*i).data_type().clone()),
_ => Err(ExecutionError::General(format!(
"Could not determine data type for expr {:?}",
expr
))),
}
}
fn aggregate_expr(&self, name: &str, expr: &Expr) -> Result<Expr> {
let return_type = self.get_data_type(expr)?;
Ok(Expr::AggregateFunction {
name: name.to_string(),
args: vec![expr.clone()],
return_type,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::context::ExecutionContext;
use crate::test;
#[test]
fn column_index() {
let t = test_table();
assert_eq!(0, t.column_index("c1").unwrap());
assert_eq!(1, t.column_index("c2").unwrap());
assert_eq!(12, t.column_index("c13").unwrap());
}
#[test]
fn select_columns() -> Result<()> {
let t = test_table();
let t2 = t.select_columns(vec!["c1", "c2", "c11"])?;
let plan = t2.to_logical_plan();
let sql_plan = create_plan("SELECT c1, c2, c11 FROM aggregate_test_100")?;
assert_same_plan(&plan, &sql_plan);
Ok(())
}
#[test]
fn select_expr() -> Result<()> {
let t = test_table();
let t2 = t.select(vec![t.col("c1")?, t.col("c2")?, t.col("c11")?])?;
let plan = t2.to_logical_plan();
let sql_plan = create_plan("SELECT c1, c2, c11 FROM aggregate_test_100")?;
assert_same_plan(&plan, &sql_plan);
Ok(())
}
#[test]
fn select_invalid_column() -> Result<()> {
let t = test_table();
match t.col("invalid_column_name") {
Ok(_) => panic!(),
Err(e) => assert_eq!(
"InvalidColumn(\"No column named \\\'invalid_column_name\\\'\")",
format!("{:?}", e)
),
}
Ok(())
}
#[test]
fn aggregate() -> Result<()> {
let t = test_table();
let group_expr = vec![t.col("c1")?];
let c12 = t.col("c12")?;
let aggr_expr = vec![
t.min(&c12)?,
t.max(&c12)?,
t.avg(&c12)?,
t.sum(&c12)?,
t.count(&c12)?,
];
let t2 = t.aggregate(group_expr.clone(), aggr_expr.clone())?;
let plan = t2.to_logical_plan();
let sql = "SELECT c1, MIN(c12), MAX(c12), AVG(c12), SUM(c12), COUNT(c12) \
FROM aggregate_test_100 \
GROUP BY c1";
let sql_plan = create_plan(sql)?;
assert_same_plan(&plan, &sql_plan);
Ok(())
}
#[test]
fn limit() -> Result<()> {
let t = test_table();
let t2 = t.select_columns(vec!["c1", "c2", "c11"])?.limit(10)?;
let plan = t2.to_logical_plan();
let sql_plan =
create_plan("SELECT c1, c2, c11 FROM aggregate_test_100 LIMIT 10")?;
assert_same_plan(&plan, &sql_plan);
Ok(())
}
fn assert_same_plan(plan1: &LogicalPlan, plan2: &LogicalPlan) {
assert_eq!(format!("{:?}", plan1), format!("{:?}", plan2));
}
fn create_plan(sql: &str) -> Result<Arc<LogicalPlan>> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx);
ctx.create_logical_plan(sql)
}
fn test_table() -> Arc<dyn Table + 'static> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx);
ctx.table("aggregate_test_100").unwrap()
}
fn register_aggregate_csv(ctx: &mut ExecutionContext) {
let schema = test::aggr_test_schema();
let testdata = test::arrow_testdata_path();
ctx.register_csv(
"aggregate_test_100",
&format!("{}/csv/aggregate_test_100.csv", testdata),
&schema,
true,
);
}
}