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