risingwave_simulation/
parse.rs

1// Copyright 2025 RisingWave Labs
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 anyhow::Result;
16use risingwave_common::bail;
17use risingwave_sqlparser::ast::{
18    CreateSinkStatement, Ident, SetVariableValue, SetVariableValueSingle, Statement, Value,
19};
20use risingwave_sqlparser::parser::Parser;
21
22use crate::slt::SqlCmd;
23
24fn ensure_one_item<T>(items: Vec<T>) -> Result<T> {
25    if items.len() != 1 {
26        bail!("expected a single item");
27    }
28
29    Ok(items.into_iter().next().unwrap())
30}
31
32pub fn extract_sql_command(sql: &str) -> Result<crate::slt::SqlCmd> {
33    let statements = Parser::parse_sql(sql)?;
34    let statement = ensure_one_item(statements)?;
35    let cmd = match statement {
36        Statement::CreateView {
37            materialized: true,
38            name,
39            ..
40        } => {
41            let base_name = name.base_name();
42            SqlCmd::CreateMaterializedView { name: base_name }
43        }
44        Statement::CreateTable { query, .. } => SqlCmd::Create {
45            is_create_table_as: query.is_some(),
46        },
47        Statement::CreateSink {
48            stmt: CreateSinkStatement {
49                into_table_name, ..
50            },
51        } => SqlCmd::CreateSink {
52            is_sink_into_table: into_table_name.is_some(),
53        },
54        Statement::SetVariable {
55            variable, value, ..
56        } if variable.real_value() == Ident::new_unchecked("background_ddl").real_value() => {
57            let enable = match value {
58                SetVariableValue::Single(SetVariableValueSingle::Literal(Value::Boolean(e))) => e,
59                _ => bail!("incorrect value for background_ddl"),
60            };
61            SqlCmd::SetBackgroundDdl { enable }
62        }
63        Statement::Drop(_) => SqlCmd::Drop,
64        Statement::Insert { .. } | Statement::Update { .. } | Statement::Delete { .. } => {
65            SqlCmd::Dml
66        }
67        Statement::Flush => SqlCmd::Flush,
68        stmt if stmt.is_create() => SqlCmd::Create {
69            is_create_table_as: false,
70        },
71        _ => SqlCmd::Others,
72    };
73    Ok(cmd)
74}