use super::{IRResult, NodeId};
use super::operators::*;
use std::collections::HashMap;
use std::sync::Arc;
use crate::types::Position3D;
#[derive(Debug, Clone)]
pub struct LogicalPlan {
pub root: Arc<dyn LogicalOperator>,
pub metadata: PlanMetadata,
pub output_schema: Schema,
pub estimated_cost: ExecutionCost,
}
#[derive(Debug, Clone)]
pub struct PhysicalPlan {
pub root: Arc<dyn PhysicalOperator>,
pub metadata: PlanMetadata,
pub resource_requirements: ResourceRequirements,
pub parallelization: ParallelizationStrategy,
pub memory_strategy: MemoryStrategy,
}
#[derive(Debug, Clone)]
pub struct PlanMetadata {
pub plan_id: String,
pub created_at: chrono::DateTime<chrono::Utc>,
pub version: u32,
pub optimizer_version: String,
pub original_query: Option<String>,
pub statistics: PlanStatistics,
}
#[derive(Debug, Clone, Default)]
pub struct PlanStatistics {
pub estimated_rows: usize,
pub estimated_bytes: usize,
pub estimated_execution_time_ms: u64,
pub complexity_score: f64,
pub optimization_passes: u32,
}
pub trait LogicalOperator: std::fmt::Debug + Send + Sync {
fn output_schema(&self) -> &Schema;
fn children(&self) -> Vec<Arc<dyn LogicalOperator>>;
fn with_children(&self, children: Vec<Arc<dyn LogicalOperator>>) -> Arc<dyn LogicalOperator>;
fn estimated_cost(&self) -> ExecutionCost;
fn estimated_cardinality(&self) -> usize;
fn to_physical(&self, context: &PhysicalPlanContext) -> IRResult<Arc<dyn PhysicalOperator>>;
fn name(&self) -> &'static str;
fn properties(&self) -> OperatorProperties;
}
#[derive(Debug, Clone)]
pub struct LogicalScan {
pub node_id: NodeId,
pub collection_name: String,
pub schema: Schema,
pub predicate: Option<Predicate>,
pub limit: Option<usize>,
pub statistics: TableStatistics,
}
#[derive(Debug, Clone)]
pub struct LogicalFilter {
pub node_id: NodeId,
pub predicate: Predicate,
pub input: Arc<dyn LogicalOperator>,
}
#[derive(Debug, Clone)]
pub struct LogicalProject {
pub node_id: NodeId,
pub columns: Vec<ColumnExpression>,
pub input: Arc<dyn LogicalOperator>,
pub output_schema: Schema,
}
#[derive(Debug, Clone)]
pub struct LogicalJoin {
pub node_id: NodeId,
pub join_type: JoinType,
pub left: Arc<dyn LogicalOperator>,
pub right: Arc<dyn LogicalOperator>,
pub condition: JoinCondition,
pub output_schema: Schema,
}
#[derive(Debug, Clone)]
pub struct LogicalAggregate {
pub node_id: NodeId,
pub group_by: Vec<String>,
pub aggregates: Vec<AggregateFunction>,
pub having: Option<Predicate>,
pub input: Arc<dyn LogicalOperator>,
pub output_schema: Schema,
}
#[derive(Debug, Clone)]
pub struct LogicalSort {
pub node_id: NodeId,
pub sort_keys: Vec<SortKey>,
pub limit: Option<usize>,
pub offset: Option<usize>,
pub input: Arc<dyn LogicalOperator>,
}
pub trait PhysicalOperator: std::fmt::Debug + Send + Sync {
fn execute(&self, input: OperatorInput) -> IRResult<OperatorOutput>;
fn output_schema(&self) -> &Schema;
fn children(&self) -> Vec<Arc<dyn PhysicalOperator>>;
fn properties(&self) -> OperatorProperties;
fn memory_requirement(&self) -> MemoryRequirement;
fn supports_streaming(&self) -> bool;
fn name(&self) -> &'static str;
}
#[derive(Debug, Clone)]
pub enum PhysicalScan {
Sequential {
node_id: NodeId,
collection_name: String,
predicate: Option<Predicate>,
schema: Schema,
},
Index {
node_id: NodeId,
collection_name: String,
index_name: String,
index_condition: IndexCondition,
predicate: Option<Predicate>,
schema: Schema,
},
HyperbolicSpatial {
node_id: NodeId,
collection_name: String,
center: Position3D,
radius: f64,
predicate: Option<Predicate>,
schema: Schema,
},
VectorSimilarity {
node_id: NodeId,
collection_name: String,
query_vector: Vec<f64>,
similarity_function: SimilarityFunction,
k: Option<usize>,
threshold: Option<f64>,
schema: Schema,
},
}
#[derive(Debug, Clone)]
pub enum PhysicalJoin {
NestedLoop {
node_id: NodeId,
left: Arc<dyn PhysicalOperator>,
right: Arc<dyn PhysicalOperator>,
condition: JoinCondition,
join_type: JoinType,
},
Hash {
node_id: NodeId,
build: Arc<dyn PhysicalOperator>, probe: Arc<dyn PhysicalOperator>, build_keys: Vec<String>,
probe_keys: Vec<String>,
join_type: JoinType,
},
SortMerge {
node_id: NodeId,
left: Arc<dyn PhysicalOperator>,
right: Arc<dyn PhysicalOperator>,
left_keys: Vec<String>,
right_keys: Vec<String>,
join_type: JoinType,
},
HyperbolicProximity {
node_id: NodeId,
left: Arc<dyn PhysicalOperator>,
right: Arc<dyn PhysicalOperator>,
left_position_column: String,
right_position_column: String,
max_distance: f64,
},
}
#[derive(Debug, Clone)]
pub enum PhysicalAggregate {
Hash {
node_id: NodeId,
input: Arc<dyn PhysicalOperator>,
group_by: Vec<String>,
aggregates: Vec<AggregateFunction>,
having: Option<Predicate>,
},
Sort {
node_id: NodeId,
input: Arc<dyn PhysicalOperator>,
group_by: Vec<String>,
aggregates: Vec<AggregateFunction>,
having: Option<Predicate>,
},
Streaming {
node_id: NodeId,
input: Arc<dyn PhysicalOperator>,
group_by: Vec<String>,
aggregates: Vec<AggregateFunction>,
having: Option<Predicate>,
},
}
#[allow(dead_code)]
pub struct QueryOptimizer {
rules: Vec<Box<dyn OptimizationRule>>,
cost_model: Box<dyn CostModel>,
statistics: Box<dyn StatisticsProvider>,
config: OptimizerConfig,
}
pub trait OptimizationRule: Send + Sync {
fn name(&self) -> &'static str;
fn matches(&self, plan: &LogicalPlan) -> bool;
fn apply(&self, plan: LogicalPlan) -> IRResult<Vec<LogicalPlan>>;
fn priority(&self) -> i32;
}
pub trait CostModel: Send + Sync {
fn cost_logical(&self, operator: &dyn LogicalOperator) -> ExecutionCost;
fn cost_physical(&self, operator: &dyn PhysicalOperator) -> ExecutionCost;
fn compare_plans(&self, plan1: &LogicalPlan, plan2: &LogicalPlan) -> bool;
}
pub trait StatisticsProvider: Send + Sync {
fn get_table_stats(&self, table_name: &str) -> Option<TableStatistics>;
fn get_column_stats(&self, table_name: &str, column_name: &str) -> Option<ColumnStatistics>;
fn get_index_stats(&self, table_name: &str, index_name: &str) -> Option<IndexStatistics>;
fn update_stats(&mut self, table_name: &str, stats: TableStatistics);
}
#[derive(Debug, Clone)]
pub struct OptimizerConfig {
pub max_passes: u32,
pub time_limit_ms: u64,
pub memory_limit_mb: usize,
pub enable_cbo: bool,
pub enable_hyperbolic_opts: bool,
pub parallelism_factor: usize,
}
#[derive(Debug, Clone)]
pub struct ResourceRequirements {
pub min_cpu_cores: usize,
pub optimal_cpu_cores: usize,
pub memory: MemoryRequirement,
pub disk_io: DiskIORequirement,
pub network: NetworkRequirement,
}
#[derive(Debug, Clone)]
pub enum ParallelizationStrategy {
None,
Operator(usize), Pipeline,
Data(usize), Hybrid {
operator_threads: usize,
data_partitions: usize,
pipeline_stages: usize,
},
}
#[derive(Debug, Clone)]
pub enum MemoryStrategy {
InMemory,
Spill {
spill_threshold: usize,
spill_directory: String,
},
Streaming {
buffer_size: usize,
},
Adaptive,
}
pub struct PhysicalPlanContext {
pub resources: AvailableResources,
pub preferences: ExecutionPreferences,
pub statistics: Box<dyn StatisticsProvider>,
}
#[derive(Debug, Clone)]
pub struct AvailableResources {
pub cpu_cores: usize,
pub memory_bytes: usize,
pub disk_space_bytes: usize,
pub network_bandwidth_mbps: f64,
}
#[derive(Debug, Clone)]
pub struct ExecutionPreferences {
pub prefer_speed: bool,
pub prefer_memory_efficiency: bool,
pub max_parallelism: Option<usize>,
pub spill_allowed: bool,
}
#[derive(Debug, Clone)]
pub struct OperatorProperties {
pub preserves_order: bool,
pub is_deterministic: bool,
pub supports_streaming: bool,
pub memory_intensive: bool,
pub cpu_intensive: bool,
pub io_intensive: bool,
}
#[derive(Debug, Clone)]
pub struct TableStatistics {
pub row_count: usize,
pub byte_size: usize,
pub column_count: usize,
pub last_updated: chrono::DateTime<chrono::Utc>,
pub column_stats: HashMap<String, ColumnStatistics>,
}
#[derive(Debug, Clone)]
pub struct ColumnStatistics {
pub distinct_count: usize,
pub null_count: usize,
pub min_value: Option<Value>,
pub max_value: Option<Value>,
pub histogram: Option<Histogram>,
pub data_type: DataType,
}
#[derive(Debug, Clone)]
pub struct IndexStatistics {
pub index_type: IndexType,
pub key_count: usize,
pub leaf_pages: usize,
pub index_size_bytes: usize,
pub selectivity: f64,
pub last_updated: chrono::DateTime<chrono::Utc>,
}
#[derive(Debug, Clone)]
pub struct Histogram {
pub buckets: Vec<HistogramBucket>,
pub total_count: usize,
}
#[derive(Debug, Clone)]
pub struct HistogramBucket {
pub lower_bound: Value,
pub upper_bound: Value,
pub count: usize,
pub distinct_count: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub enum IndexType {
BTree,
Hash,
HyperbolicSpatial,
VectorIndex,
FullText,
Composite,
}
#[derive(Debug, Clone)]
pub enum IndexCondition {
Equality(Vec<Value>),
Range(Option<Value>, Option<Value>), Prefix(Vec<Value>),
HyperbolicRange(Position3D, f64), VectorSimilarity(Vec<f64>, f64, SimilarityFunction), }
#[derive(Debug, Clone)]
pub struct DiskIORequirement {
pub sequential_reads: usize,
pub random_reads: usize,
pub writes: usize,
pub temp_space_bytes: usize,
}
#[derive(Debug, Clone)]
pub struct NetworkRequirement {
pub bandwidth_mbps: f64,
pub latency_tolerance_ms: u64,
pub connections: usize,
}
impl QueryOptimizer {
pub fn new(
cost_model: Box<dyn CostModel>,
statistics: Box<dyn StatisticsProvider>,
config: OptimizerConfig,
) -> Self {
Self {
rules: Vec::new(),
cost_model,
statistics,
config,
}
}
pub fn optimize(&mut self, _plan: LogicalPlan) -> IRResult<LogicalPlan> {
todo!("Optimize logical plan")
}
pub fn generate_physical_plan(&self, _logical_plan: &LogicalPlan, _context: &PhysicalPlanContext) -> IRResult<PhysicalPlan> {
todo!("Generate physical plan")
}
pub fn add_rule(&mut self, rule: Box<dyn OptimizationRule>) {
self.rules.push(rule);
self.rules.sort_by(|a, b| b.priority().cmp(&a.priority()));
}
}