|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! Bridges between user-provided Python rule classes and the upstream |
| 19 | +//! [`OptimizerRule`] / [`AnalyzerRule`] traits. |
| 20 | +//! |
| 21 | +//! The Python side defines abstract base classes ``OptimizerRule`` and |
| 22 | +//! ``AnalyzerRule`` with ``name()`` plus, respectively, ``rewrite(plan)`` |
| 23 | +//! and ``analyze(plan)``. Instances are wrapped in |
| 24 | +//! [`PyOptimizerRuleAdapter`] / [`PyAnalyzerRuleAdapter`] before being |
| 25 | +//! handed to [`SessionContext::add_optimizer_rule`] / |
| 26 | +//! [`SessionContext::add_analyzer_rule`]. |
| 27 | +//! |
| 28 | +//! `rewrite` may return ``None`` to signal "no transformation" — the |
| 29 | +//! adapter maps that to [`Transformed::no`]. Any returned |
| 30 | +//! :class:`LogicalPlan` becomes [`Transformed::yes`]. `analyze` is |
| 31 | +//! mandatory-rewrite (must return a plan); returning ``None`` is an |
| 32 | +//! error. |
| 33 | +//! |
| 34 | +//! The upstream ``&dyn OptimizerConfig`` / ``&ConfigOptions`` arguments |
| 35 | +//! are not surfaced to Python in this MVP. Rules that need configuration |
| 36 | +//! access should be implemented in Rust today; Python rules read state |
| 37 | +//! from the plan and from any captured ``SessionContext`` they were |
| 38 | +//! constructed with. |
| 39 | +
|
| 40 | +use std::fmt; |
| 41 | +use std::sync::Arc; |
| 42 | + |
| 43 | +use datafusion::common::config::ConfigOptions; |
| 44 | +use datafusion::common::tree_node::Transformed; |
| 45 | +use datafusion::error::{DataFusionError, Result as DataFusionResult}; |
| 46 | +use datafusion::logical_expr::LogicalPlan; |
| 47 | +use datafusion::optimizer::analyzer::AnalyzerRule; |
| 48 | +use datafusion::optimizer::optimizer::{OptimizerConfig, OptimizerRule}; |
| 49 | +use pyo3::prelude::*; |
| 50 | + |
| 51 | +use crate::errors::to_datafusion_err; |
| 52 | +use crate::sql::logical::PyLogicalPlan; |
| 53 | + |
| 54 | +/// Wraps a Python ``OptimizerRule`` instance so that it can be registered |
| 55 | +/// with the upstream optimizer pipeline. |
| 56 | +pub struct PyOptimizerRuleAdapter { |
| 57 | + rule: Py<PyAny>, |
| 58 | + name: String, |
| 59 | +} |
| 60 | + |
| 61 | +impl PyOptimizerRuleAdapter { |
| 62 | + pub fn new(rule: Bound<'_, PyAny>) -> PyResult<Self> { |
| 63 | + let name = rule.call_method0("name")?.extract::<String>()?; |
| 64 | + Ok(Self { |
| 65 | + rule: rule.unbind(), |
| 66 | + name, |
| 67 | + }) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl fmt::Debug for PyOptimizerRuleAdapter { |
| 72 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 73 | + f.debug_struct("PyOptimizerRuleAdapter") |
| 74 | + .field("name", &self.name) |
| 75 | + .finish() |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl OptimizerRule for PyOptimizerRuleAdapter { |
| 80 | + fn name(&self) -> &str { |
| 81 | + &self.name |
| 82 | + } |
| 83 | + |
| 84 | + fn rewrite( |
| 85 | + &self, |
| 86 | + plan: LogicalPlan, |
| 87 | + _config: &dyn OptimizerConfig, |
| 88 | + ) -> DataFusionResult<Transformed<LogicalPlan>> { |
| 89 | + Python::attach(|py| { |
| 90 | + let py_plan = PyLogicalPlan::from(plan.clone()); |
| 91 | + let result = self |
| 92 | + .rule |
| 93 | + .bind(py) |
| 94 | + .call_method1("rewrite", (py_plan,)) |
| 95 | + .map_err(to_datafusion_err)?; |
| 96 | + if result.is_none() { |
| 97 | + return Ok(Transformed::no(plan)); |
| 98 | + } |
| 99 | + let rewritten: PyLogicalPlan = result.extract().map_err(to_datafusion_err)?; |
| 100 | + Ok(Transformed::yes(LogicalPlan::from(rewritten))) |
| 101 | + }) |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +/// Wraps a Python ``AnalyzerRule`` instance so that it can be registered |
| 106 | +/// with the upstream analyzer pipeline. |
| 107 | +pub struct PyAnalyzerRuleAdapter { |
| 108 | + rule: Py<PyAny>, |
| 109 | + name: String, |
| 110 | +} |
| 111 | + |
| 112 | +impl PyAnalyzerRuleAdapter { |
| 113 | + pub fn new(rule: Bound<'_, PyAny>) -> PyResult<Self> { |
| 114 | + let name = rule.call_method0("name")?.extract::<String>()?; |
| 115 | + Ok(Self { |
| 116 | + rule: rule.unbind(), |
| 117 | + name, |
| 118 | + }) |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +impl fmt::Debug for PyAnalyzerRuleAdapter { |
| 123 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 124 | + f.debug_struct("PyAnalyzerRuleAdapter") |
| 125 | + .field("name", &self.name) |
| 126 | + .finish() |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +impl AnalyzerRule for PyAnalyzerRuleAdapter { |
| 131 | + fn analyze(&self, plan: LogicalPlan, _config: &ConfigOptions) -> DataFusionResult<LogicalPlan> { |
| 132 | + Python::attach(|py| { |
| 133 | + let py_plan = PyLogicalPlan::from(plan); |
| 134 | + let result = self |
| 135 | + .rule |
| 136 | + .bind(py) |
| 137 | + .call_method1("analyze", (py_plan,)) |
| 138 | + .map_err(to_datafusion_err)?; |
| 139 | + if result.is_none() { |
| 140 | + return Err(DataFusionError::Execution(format!( |
| 141 | + "AnalyzerRule {} returned None from analyze(); analyzer rules \ |
| 142 | + must return a LogicalPlan", |
| 143 | + self.name |
| 144 | + ))); |
| 145 | + } |
| 146 | + let rewritten: PyLogicalPlan = result.extract().map_err(to_datafusion_err)?; |
| 147 | + Ok(LogicalPlan::from(rewritten)) |
| 148 | + }) |
| 149 | + } |
| 150 | + |
| 151 | + fn name(&self) -> &str { |
| 152 | + &self.name |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +/// Construct an adapter from a Python ``OptimizerRule`` instance. |
| 157 | +pub(crate) fn build_optimizer_rule( |
| 158 | + rule: Bound<'_, PyAny>, |
| 159 | +) -> PyResult<Arc<dyn OptimizerRule + Send + Sync>> { |
| 160 | + Ok(Arc::new(PyOptimizerRuleAdapter::new(rule)?)) |
| 161 | +} |
| 162 | + |
| 163 | +/// Construct an adapter from a Python ``AnalyzerRule`` instance. |
| 164 | +pub(crate) fn build_analyzer_rule( |
| 165 | + rule: Bound<'_, PyAny>, |
| 166 | +) -> PyResult<Arc<dyn AnalyzerRule + Send + Sync>> { |
| 167 | + Ok(Arc::new(PyAnalyzerRuleAdapter::new(rule)?)) |
| 168 | +} |
0 commit comments