sql/statements/
statement.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Display;
16
17use datafusion_sql::parser::Statement as DfStatement;
18use serde::Serialize;
19use sqlparser::ast::Statement as SpStatement;
20use sqlparser_derive::{Visit, VisitMut};
21
22use crate::error::{ConvertToDfStatementSnafu, Error};
23use crate::statements::admin::Admin;
24use crate::statements::alter::{AlterDatabase, AlterTable};
25use crate::statements::copy::Copy;
26use crate::statements::create::{
27    CreateDatabase, CreateExternalTable, CreateFlow, CreateTable, CreateTableLike, CreateView,
28};
29use crate::statements::cursor::{CloseCursor, DeclareCursor, FetchCursor};
30use crate::statements::delete::Delete;
31use crate::statements::describe::DescribeTable;
32use crate::statements::drop::{DropDatabase, DropFlow, DropTable, DropView};
33use crate::statements::explain::Explain;
34use crate::statements::insert::Insert;
35use crate::statements::query::Query;
36use crate::statements::set_variables::SetVariables;
37use crate::statements::show::{
38    ShowColumns, ShowCreateDatabase, ShowCreateFlow, ShowCreateTable, ShowCreateView,
39    ShowDatabases, ShowFlows, ShowIndex, ShowKind, ShowRegion, ShowSearchPath, ShowStatus,
40    ShowTableStatus, ShowTables, ShowVariables, ShowViews,
41};
42use crate::statements::tql::Tql;
43use crate::statements::truncate::TruncateTable;
44
45/// Tokens parsed by `DFParser` are converted into these values.
46#[allow(clippy::large_enum_variant)]
47#[derive(Debug, Clone, PartialEq, Eq, Visit, VisitMut, Serialize)]
48pub enum Statement {
49    // Query
50    Query(Box<Query>),
51    // Insert
52    Insert(Box<Insert>),
53    // Delete
54    Delete(Box<Delete>),
55    /// CREATE TABLE
56    CreateTable(CreateTable),
57    // CREATE EXTERNAL TABLE
58    CreateExternalTable(CreateExternalTable),
59    // CREATE TABLE ... LIKE
60    CreateTableLike(CreateTableLike),
61    // CREATE FLOW
62    CreateFlow(CreateFlow),
63    // CREATE VIEW ... AS
64    CreateView(CreateView),
65    // CREATE TRIGGER
66    #[cfg(feature = "enterprise")]
67    CreateTrigger(crate::statements::create::trigger::CreateTrigger),
68    // DROP TABLE
69    DropTable(DropTable),
70    // DROP DATABASE
71    DropDatabase(DropDatabase),
72    // DROP FLOW
73    DropFlow(DropFlow),
74    // DROP View
75    DropView(DropView),
76    // CREATE DATABASE
77    CreateDatabase(CreateDatabase),
78    /// ALTER TABLE
79    AlterTable(AlterTable),
80    /// ALTER DATABASE
81    AlterDatabase(AlterDatabase),
82    // Databases.
83    ShowDatabases(ShowDatabases),
84    // SHOW TABLES
85    ShowTables(ShowTables),
86    // SHOW TABLE STATUS
87    ShowTableStatus(ShowTableStatus),
88    // SHOW COLUMNS
89    ShowColumns(ShowColumns),
90    // SHOW CHARSET or SHOW CHARACTER SET
91    ShowCharset(ShowKind),
92    // SHOW COLLATION
93    ShowCollation(ShowKind),
94    // SHOW INDEX
95    ShowIndex(ShowIndex),
96    // SHOW REGION
97    ShowRegion(ShowRegion),
98    // SHOW CREATE DATABASE
99    ShowCreateDatabase(ShowCreateDatabase),
100    // SHOW CREATE TABLE
101    ShowCreateTable(ShowCreateTable),
102    // SHOW CREATE FLOW
103    ShowCreateFlow(ShowCreateFlow),
104    /// SHOW FLOWS
105    ShowFlows(ShowFlows),
106    // SHOW TRIGGERS
107    #[cfg(feature = "enterprise")]
108    ShowTriggers(crate::statements::show::trigger::ShowTriggers),
109    // SHOW CREATE VIEW
110    ShowCreateView(ShowCreateView),
111    // SHOW STATUS
112    ShowStatus(ShowStatus),
113    // SHOW SEARCH_PATH
114    ShowSearchPath(ShowSearchPath),
115    // SHOW VIEWS
116    ShowViews(ShowViews),
117    // DESCRIBE TABLE
118    DescribeTable(DescribeTable),
119    // EXPLAIN QUERY
120    Explain(Explain),
121    // COPY
122    Copy(Copy),
123    // Telemetry Query Language
124    Tql(Tql),
125    // TRUNCATE TABLE
126    TruncateTable(TruncateTable),
127    // SET VARIABLES
128    SetVariables(SetVariables),
129    // SHOW VARIABLES
130    ShowVariables(ShowVariables),
131    // USE
132    Use(String),
133    // Admin statement(extension)
134    Admin(Admin),
135    // DECLARE ... CURSOR FOR ...
136    DeclareCursor(DeclareCursor),
137    // FETCH ... FROM ...
138    FetchCursor(FetchCursor),
139    // CLOSE
140    CloseCursor(CloseCursor),
141}
142
143impl Display for Statement {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        match self {
146            Statement::Query(s) => s.inner.fmt(f),
147            Statement::Insert(s) => s.inner.fmt(f),
148            Statement::Delete(s) => s.inner.fmt(f),
149            Statement::CreateTable(s) => s.fmt(f),
150            Statement::CreateExternalTable(s) => s.fmt(f),
151            Statement::CreateTableLike(s) => s.fmt(f),
152            Statement::CreateFlow(s) => s.fmt(f),
153            #[cfg(feature = "enterprise")]
154            Statement::CreateTrigger(s) => s.fmt(f),
155            Statement::DropFlow(s) => s.fmt(f),
156            Statement::DropTable(s) => s.fmt(f),
157            Statement::DropDatabase(s) => s.fmt(f),
158            Statement::DropView(s) => s.fmt(f),
159            Statement::CreateDatabase(s) => s.fmt(f),
160            Statement::AlterTable(s) => s.fmt(f),
161            Statement::AlterDatabase(s) => s.fmt(f),
162            Statement::ShowDatabases(s) => s.fmt(f),
163            Statement::ShowTables(s) => s.fmt(f),
164            Statement::ShowTableStatus(s) => s.fmt(f),
165            Statement::ShowColumns(s) => s.fmt(f),
166            Statement::ShowIndex(s) => s.fmt(f),
167            Statement::ShowRegion(s) => s.fmt(f),
168            Statement::ShowCreateTable(s) => s.fmt(f),
169            Statement::ShowCreateFlow(s) => s.fmt(f),
170            Statement::ShowFlows(s) => s.fmt(f),
171            #[cfg(feature = "enterprise")]
172            Statement::ShowTriggers(s) => s.fmt(f),
173            Statement::ShowCreateDatabase(s) => s.fmt(f),
174            Statement::ShowCreateView(s) => s.fmt(f),
175            Statement::ShowViews(s) => s.fmt(f),
176            Statement::ShowStatus(s) => s.fmt(f),
177            Statement::ShowSearchPath(s) => s.fmt(f),
178            Statement::DescribeTable(s) => s.fmt(f),
179            Statement::Explain(s) => s.fmt(f),
180            Statement::Copy(s) => s.fmt(f),
181            Statement::Tql(s) => s.fmt(f),
182            Statement::TruncateTable(s) => s.fmt(f),
183            Statement::SetVariables(s) => s.fmt(f),
184            Statement::ShowVariables(s) => s.fmt(f),
185            Statement::ShowCharset(kind) => {
186                write!(f, "SHOW CHARSET {kind}")
187            }
188            Statement::ShowCollation(kind) => {
189                write!(f, "SHOW COLLATION {kind}")
190            }
191            Statement::CreateView(s) => s.fmt(f),
192            Statement::Use(s) => s.fmt(f),
193            Statement::Admin(admin) => admin.fmt(f),
194            Statement::DeclareCursor(s) => s.fmt(f),
195            Statement::FetchCursor(s) => s.fmt(f),
196            Statement::CloseCursor(s) => s.fmt(f),
197        }
198    }
199}
200
201/// Comment hints from SQL.
202/// It'll be enabled when using `--comment` in mysql client.
203/// Eg: `SELECT * FROM system.number LIMIT 1; -- { ErrorCode 25 }`
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub struct Hint {
206    pub error_code: Option<u16>,
207    pub comment: String,
208    pub prefix: String,
209}
210
211impl TryFrom<&Statement> for DfStatement {
212    type Error = Error;
213
214    fn try_from(s: &Statement) -> Result<Self, Self::Error> {
215        let s = match s {
216            Statement::Query(query) => SpStatement::Query(Box::new(query.inner.clone())),
217            Statement::Explain(explain) => explain.inner.clone(),
218            Statement::Insert(insert) => insert.inner.clone(),
219            Statement::Delete(delete) => delete.inner.clone(),
220            _ => {
221                return ConvertToDfStatementSnafu {
222                    statement: format!("{s:?}"),
223                }
224                .fail();
225            }
226        };
227        Ok(DfStatement::Statement(Box::new(s.into())))
228    }
229}