use crate::{
query::{output::QueryOutput, runtime::QueryRuntimeView, CteScope},
OwnedPhysicalRow,
};
use uqa_sql::{
expr::EngineHook,
plan::{CommandPlan, QueryPlan},
routines::RoutineResolution,
SQLError, SQLParam, ScalarExpr,
};
pub trait CteBodyExecutor<S: Clone>: Sync {
fn read_control(&self) -> Result<uqa_storage::read_control::StorageReadControl, SQLError>;
fn retained_query(
&self,
query: &QueryPlan,
params: &[SQLParam],
ctes: &CteScope<S>,
) -> Result<Option<Box<dyn crate::PhysicalOperator>>, SQLError>;
fn execute_query(
&self,
query: &QueryPlan,
params: &[SQLParam],
ctes: &mut CteScope<S>,
) -> Result<QueryOutput, SQLError>;
fn execute_lateral_query(
&self,
query: &QueryPlan,
outer: &OwnedPhysicalRow,
params: &[SQLParam],
ctes: &CteScope<S>,
) -> Result<QueryOutput, SQLError>;
fn execute_command(
&self,
command: &CommandPlan,
params: &[SQLParam],
ctes: &CteScope<S>,
) -> Result<crate::mutation::output::MutationOutput, SQLError>;
fn fire_after_triggers(
&self,
queue: &crate::mutation::triggers::queue::AfterTriggerQueue,
) -> Result<(), SQLError>;
}
pub trait QueryOutputRewriter: Sync {
fn optimize_retained_query(
&self,
query: uqa_sql::plan::MutableQueryPlan,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<uqa_sql::plan::OwnedQueryPlan, SQLError>;
fn prune_owned_query_outputs(
&self,
query: uqa_sql::plan::MutableQueryPlan,
aliases: &[String],
projection: &uqa_sql::plan::source_projection::SourceProjection,
schema: &crate::RowSchema,
visible_ctes: &dyn Fn(&str) -> bool,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<uqa_sql::plan::MutableQueryPlan, SQLError>;
fn push_output_filter(
&self,
query: &QueryPlan,
qualifier: &str,
filter: &ScalarExpr,
output_columns: Option<&[String]>,
) -> Result<Option<uqa_sql::plan::OwnedQueryPlan>, SQLError>;
fn push_derived_output_filter(
&self,
query: &QueryPlan,
qualifier: &str,
filter: &ScalarExpr,
output_columns: Option<&[String]>,
) -> Result<Option<uqa_sql::plan::OwnedQueryPlan>, SQLError> {
self.push_output_filter(query, qualifier, filter, output_columns)
}
}
#[derive(Clone)]
pub struct CteExecutionContext<'a, S: Clone> {
pub queries: &'a dyn CteBodyExecutor<S>,
pub rewrites: &'a dyn QueryOutputRewriter,
pub routines: &'a dyn RoutineResolution,
pub functions: &'a (dyn EngineHook + Sync),
pub runtime: QueryRuntimeView<'a>,
}
impl<S: Clone> Copy for CteExecutionContext<'_, S> {}
impl<S: Clone> CteExecutionContext<'_, S> {
pub fn production_resources(
&self,
) -> Result<uqa_core::memory::OwnedProductionControl, SQLError> {
let retained = self.queries.read_control()?;
Ok(uqa_core::memory::ProductionControl::new(
retained.memory(),
retained.cancellation(),
self.runtime.cancellation,
)
.capture())
}
}