Skip to main content

datafusion_expr/logical_plan/
statement.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
5use arrow::datatypes::FieldRef;
6use datafusion_common::metadata::format_type_and_metadata;
7use datafusion_common::{DFSchema, DFSchemaRef};
8use itertools::Itertools as _;
9use std::fmt::{self, Display};
10use std::sync::Arc;
11
12use crate::{Expr, LogicalPlan, expr_vec_fmt};
13
14/// Various types of Statements.
15///
16/// # Transactions:
17///
18/// While DataFusion does not offer support transactions, it provides
19/// [`LogicalPlan`] support to assist building database systems
20/// using DataFusion
21#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
22pub enum Statement {
23    // Begin a transaction
24    TransactionStart(TransactionStart),
25    // Commit or rollback a transaction
26    TransactionEnd(TransactionEnd),
27    /// Set a Variable
28    SetVariable(SetVariable),
29    /// Reset a Variable
30    ResetVariable(ResetVariable),
31    /// Prepare a statement and find any bind parameters
32    /// (e.g. `?`). This is used to implement SQL-prepared statements.
33    Prepare(Prepare),
34    /// Execute a prepared statement. This is used to implement SQL 'EXECUTE'.
35    Execute(Execute),
36    /// Deallocate a prepared statement.
37    /// This is used to implement SQL 'DEALLOCATE'.
38    Deallocate(Deallocate),
39}
40
41impl Statement {
42    /// Get a reference to the logical plan's schema
43    pub fn schema(&self) -> &DFSchemaRef {
44        // Statements have an unchanging empty schema.
45        DFSchema::empty_ref()
46    }
47
48    /// Return a descriptive string describing the type of this
49    /// [`Statement`]
50    pub fn name(&self) -> &str {
51        match self {
52            Statement::TransactionStart(_) => "TransactionStart",
53            Statement::TransactionEnd(_) => "TransactionEnd",
54            Statement::SetVariable(_) => "SetVariable",
55            Statement::ResetVariable(_) => "ResetVariable",
56            Statement::Prepare(_) => "Prepare",
57            Statement::Execute(_) => "Execute",
58            Statement::Deallocate(_) => "Deallocate",
59        }
60    }
61
62    /// Returns input LogicalPlans in the current `Statement`.
63    pub(super) fn inputs(&self) -> Vec<&LogicalPlan> {
64        match self {
65            Statement::Prepare(Prepare { input, .. }) => vec![input.as_ref()],
66            _ => vec![],
67        }
68    }
69
70    /// Return a `format`able structure with the a human readable
71    /// description of this LogicalPlan node per node, not including
72    /// children.
73    ///
74    /// See [crate::LogicalPlan::display] for an example
75    pub fn display(&self) -> impl Display + '_ {
76        struct Wrapper<'a>(&'a Statement);
77        impl Display for Wrapper<'_> {
78            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79                match self.0 {
80                    Statement::TransactionStart(TransactionStart {
81                        access_mode,
82                        isolation_level,
83                    }) => {
84                        write!(f, "TransactionStart: {access_mode:?} {isolation_level:?}")
85                    }
86                    Statement::TransactionEnd(TransactionEnd { conclusion, chain }) => {
87                        write!(f, "TransactionEnd: {conclusion:?} chain:={chain}")
88                    }
89                    Statement::SetVariable(SetVariable { variable, value }) => {
90                        write!(f, "SetVariable: set {variable:?} to {value:?}")
91                    }
92                    Statement::ResetVariable(ResetVariable { variable }) => {
93                        write!(f, "ResetVariable: reset {variable:?}")
94                    }
95                    Statement::Prepare(Prepare { name, fields, .. }) => {
96                        write!(
97                            f,
98                            "Prepare: {name:?} [{}]",
99                            fields
100                                .iter()
101                                .map(|f| format_type_and_metadata(
102                                    f.data_type(),
103                                    Some(f.metadata())
104                                ))
105                                .join(", ")
106                        )
107                    }
108                    Statement::Execute(Execute { name, parameters }) => {
109                        write!(
110                            f,
111                            "Execute: {} params=[{}]",
112                            name,
113                            expr_vec_fmt!(parameters)
114                        )
115                    }
116                    Statement::Deallocate(Deallocate { name }) => {
117                        write!(f, "Deallocate: {name}")
118                    }
119                }
120            }
121        }
122        Wrapper(self)
123    }
124}
125
126/// Indicates if a transaction was committed or aborted
127#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
128pub enum TransactionConclusion {
129    Commit,
130    Rollback,
131}
132
133/// Indicates if this transaction is allowed to write
134#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
135pub enum TransactionAccessMode {
136    ReadOnly,
137    ReadWrite,
138}
139
140/// Indicates ANSI transaction isolation level
141#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
142pub enum TransactionIsolationLevel {
143    ReadUncommitted,
144    ReadCommitted,
145    RepeatableRead,
146    Serializable,
147    Snapshot,
148}
149
150/// Indicator that the following statements should be committed or rolled back atomically
151#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
152pub struct TransactionStart {
153    /// indicates if transaction is allowed to write
154    pub access_mode: TransactionAccessMode,
155    // indicates ANSI isolation level
156    pub isolation_level: TransactionIsolationLevel,
157}
158
159/// Indicator that any current transaction should be terminated
160#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
161pub struct TransactionEnd {
162    /// whether the transaction committed or aborted
163    pub conclusion: TransactionConclusion,
164    /// if specified a new transaction is immediately started with same characteristics
165    pub chain: bool,
166}
167
168/// Set a Variable's value -- value in
169/// [`ConfigOptions`](datafusion_common::config::ConfigOptions)
170#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
171pub struct SetVariable {
172    /// The variable name
173    pub variable: String,
174    /// The value to set
175    pub value: String,
176}
177
178/// Reset a configuration variable to its default
179#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
180pub struct ResetVariable {
181    /// The variable name
182    pub variable: String,
183}
184/// Prepare a statement but do not execute it. Prepare statements can have 0 or more
185/// `Expr::Placeholder` expressions that are filled in during execution
186#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
187pub struct Prepare {
188    /// The name of the statement
189    pub name: String,
190    /// Data types of the parameters ([`Expr::Placeholder`])
191    pub fields: Vec<FieldRef>,
192    /// The logical plan of the statements
193    pub input: Arc<LogicalPlan>,
194}
195
196/// Execute a prepared statement.
197#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
198pub struct Execute {
199    /// The name of the prepared statement to execute
200    pub name: String,
201    /// The execute parameters
202    pub parameters: Vec<Expr>,
203}
204
205/// Deallocate a prepared statement.
206#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
207pub struct Deallocate {
208    /// The name of the prepared statement to deallocate
209    pub name: String,
210}