use std::any::Any;
use std::borrow::Cow;
use std::sync::Arc;
use arrow::datatypes::SchemaRef;
use async_trait::async_trait;
use datafusion_common::error::Result;
use datafusion_expr::{Expr, LogicalPlan, TableProviderFilterPushDown, TableType};
use datafusion_physical_plan::ExecutionPlan;
use datafusion_physical_plan::work_table::WorkTableExec;
use crate::{ScanArgs, ScanResult, Session, TableProvider};
#[derive(Debug)]
pub struct CteWorkTable {
name: String,
table_schema: SchemaRef,
}
impl CteWorkTable {
pub fn new(name: &str, table_schema: SchemaRef) -> Self {
Self {
name: name.to_owned(),
table_schema,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn schema(&self) -> SchemaRef {
Arc::clone(&self.table_schema)
}
}
#[async_trait]
impl TableProvider for CteWorkTable {
fn as_any(&self) -> &dyn Any {
self
}
fn get_logical_plan(&'_ self) -> Option<Cow<'_, LogicalPlan>> {
None
}
fn schema(&self) -> SchemaRef {
Arc::clone(&self.table_schema)
}
fn table_type(&self) -> TableType {
TableType::Temporary
}
async fn scan(
&self,
state: &dyn Session,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
let options = ScanArgs::default()
.with_projection(projection.map(|p| p.as_slice()))
.with_filters(Some(filters))
.with_limit(limit);
Ok(self.scan_with_args(state, options).await?.into_inner())
}
async fn scan_with_args<'a>(
&self,
_state: &dyn Session,
args: ScanArgs<'a>,
) -> Result<ScanResult> {
Ok(ScanResult::new(Arc::new(WorkTableExec::new(
self.name.clone(),
Arc::clone(&self.table_schema),
args.projection().map(|p| p.to_vec()),
)?)))
}
fn supports_filters_pushdown(
&self,
filters: &[&Expr],
) -> Result<Vec<TableProviderFilterPushDown>> {
Ok(vec![
TableProviderFilterPushDown::Unsupported;
filters.len()
])
}
}