datafusion_sql/unparser/mod.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`Unparser`] for converting `Expr` to SQL text
6
7pub mod ast;
8mod expr;
9mod plan;
10mod rewrite;
11mod utils;
12
13use self::dialect::{DefaultDialect, Dialect};
14use crate::unparser::extension_unparser::UserDefinedLogicalNodeUnparser;
15pub use expr::expr_to_sql;
16pub use plan::plan_to_sql;
17use std::sync::Arc;
18pub mod dialect;
19pub mod extension_unparser;
20
21/// Convert a DataFusion [`Expr`] to [`sqlparser::ast::Expr`]
22///
23/// See [`expr_to_sql`] for background. `Unparser` allows greater control of
24/// the conversion, but with a more complicated API.
25///
26/// To get more human-readable output, see [`Self::with_pretty`]
27///
28/// # Example
29/// ```
30/// use datafusion_expr::{col, lit};
31/// use datafusion_sql::unparser::Unparser;
32/// let expr = col("a").gt(lit(4)); // form an expression `a > 4`
33/// let unparser = Unparser::default();
34/// let sql = unparser.expr_to_sql(&expr).unwrap();// convert to AST
35/// // use the Display impl to convert to SQL text
36/// assert_eq!(sql.to_string(), "(a > 4)");
37/// // now convert to pretty sql
38/// let unparser = unparser.with_pretty(true);
39/// let sql = unparser.expr_to_sql(&expr).unwrap();
40/// assert_eq!(sql.to_string(), "a > 4"); // note lack of parenthesis
41/// ```
42///
43/// [`Expr`]: datafusion_expr::Expr
44pub struct Unparser<'a> {
45 dialect: &'a dyn Dialect,
46 pretty: bool,
47 extension_unparsers: Vec<Arc<dyn UserDefinedLogicalNodeUnparser>>,
48}
49
50impl<'a> Unparser<'a> {
51 pub fn new(dialect: &'a dyn Dialect) -> Self {
52 Self {
53 dialect,
54 pretty: false,
55 extension_unparsers: vec![],
56 }
57 }
58
59 /// Create pretty SQL output, better suited for human consumption
60 ///
61 /// See example on the struct level documentation
62 ///
63 /// # Pretty Output
64 ///
65 /// By default, `Unparser` generates SQL text that will parse back to the
66 /// same parsed [`Expr`], which is useful for creating machine readable
67 /// expressions to send to other systems. However, the resulting expressions are
68 /// not always nice to read for humans.
69 ///
70 /// For example
71 ///
72 /// ```sql
73 /// ((a + 4) > 5)
74 /// ```
75 ///
76 /// This method removes parenthesis using to the precedence rules of
77 /// DataFusion. If the output is reparsed, the resulting [`Expr`] produces
78 /// same value as the original in DataFusion, but with a potentially
79 /// different order of operations.
80 ///
81 /// Note that this setting may create invalid SQL for other SQL query
82 /// engines with different precedence rules
83 ///
84 /// # Example
85 /// ```
86 /// use datafusion_expr::{col, lit};
87 /// use datafusion_sql::unparser::Unparser;
88 /// let expr = col("a").gt(lit(4)).and(col("b").lt(lit(5))); // form an expression `a > 4 AND b < 5`
89 /// let unparser = Unparser::default().with_pretty(true);
90 /// let sql = unparser.expr_to_sql(&expr).unwrap();
91 /// assert_eq!(sql.to_string(), "a > 4 AND b < 5"); // note lack of parenthesis
92 /// ```
93 ///
94 /// [`Expr`]: datafusion_expr::Expr
95 pub fn with_pretty(mut self, pretty: bool) -> Self {
96 self.pretty = pretty;
97 self
98 }
99
100 /// Add a custom unparser for user defined logical nodes
101 ///
102 /// DataFusion allows user to define custom logical nodes. This method allows to add custom child unparsers for these nodes.
103 /// Implementation of [`UserDefinedLogicalNodeUnparser`] can be added to the root unparser to handle custom logical nodes.
104 ///
105 /// The child unparsers are called iteratively.
106 /// There are two methods in [`Unparser`] will be called:
107 /// - `extension_to_statement`: This method is called when the custom logical node is a custom statement.
108 /// If multiple child unparsers return a non-None value, the last unparsing result will be returned.
109 /// - `extension_to_sql`: This method is called when the custom logical node is part of a statement.
110 /// If multiple child unparsers are registered for the same custom logical node, all of them will be called in order.
111 pub fn with_extension_unparsers(
112 mut self,
113 extension_unparsers: Vec<Arc<dyn UserDefinedLogicalNodeUnparser>>,
114 ) -> Self {
115 self.extension_unparsers = extension_unparsers;
116 self
117 }
118}
119
120impl Default for Unparser<'_> {
121 fn default() -> Self {
122 Self {
123 dialect: &DefaultDialect {},
124 pretty: false,
125 extension_unparsers: vec![],
126 }
127 }
128}