datafusion_python/unparser/
mod.rs1mod dialect;
19
20use std::sync::Arc;
21
22use datafusion::sql::unparser::Unparser;
23use datafusion::sql::unparser::dialect::Dialect;
24use dialect::PyDialect;
25use pyo3::exceptions::PyValueError;
26use pyo3::prelude::*;
27
28use crate::sql::logical::PyLogicalPlan;
29
30#[pyclass(
31 from_py_object,
32 frozen,
33 name = "Unparser",
34 module = "datafusion.unparser",
35 subclass
36)]
37#[derive(Clone)]
38pub struct PyUnparser {
39 dialect: Arc<dyn Dialect>,
40 pretty: bool,
41}
42
43#[pymethods]
44impl PyUnparser {
45 #[new]
46 pub fn new(dialect: PyDialect) -> Self {
47 Self {
48 dialect: dialect.dialect.clone(),
49 pretty: false,
50 }
51 }
52
53 pub fn plan_to_sql(&self, plan: &PyLogicalPlan) -> PyResult<String> {
54 let mut unparser = Unparser::new(self.dialect.as_ref());
55 unparser = unparser.with_pretty(self.pretty);
56 let sql = unparser
57 .plan_to_sql(&plan.plan())
58 .map_err(|e| PyValueError::new_err(e.to_string()))?;
59 Ok(sql.to_string())
60 }
61
62 pub fn with_pretty(&self, pretty: bool) -> Self {
63 Self {
64 dialect: self.dialect.clone(),
65 pretty,
66 }
67 }
68}
69
70pub(crate) fn init_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
71 m.add_class::<PyUnparser>()?;
72 m.add_class::<PyDialect>()?;
73 Ok(())
74}