risingwave_frontend/handler/
drop_mv.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 pgwire::pg_response::{PgResponse, StatementType};
16use risingwave_sqlparser::ast::ObjectName;
17
18use super::RwPgResponse;
19use super::util::{LongRunningNotificationAction, execute_with_long_running_notification};
20use crate::binder::Binder;
21use crate::catalog::root_catalog::SchemaPath;
22use crate::catalog::table_catalog::TableType;
23use crate::catalog::{CatalogError, CatalogErrorInner};
24use crate::error::Result;
25use crate::handler::HandlerArgs;
26
27pub async fn handle_drop_mv(
28    handler_args: HandlerArgs,
29    table_name: ObjectName,
30    if_exists: bool,
31    cascade: bool,
32) -> Result<RwPgResponse> {
33    let session = handler_args.session;
34    let db_name = &session.database();
35    let (schema_name, table_name) = Binder::resolve_schema_qualified_name(db_name, &table_name)?;
36    let search_path = session.config().search_path();
37    let user_name = &session.user_name();
38
39    let schema_path = SchemaPath::new(schema_name.as_deref(), &search_path, user_name);
40
41    let table_id = {
42        let reader = session.env().catalog_reader().read_guard();
43        let (table, schema_name) =
44            match reader.get_any_table_by_name(&session.database(), schema_path, &table_name) {
45                Ok((t, s)) => (t, s),
46                Err(e) => {
47                    return if if_exists {
48                        Ok(RwPgResponse::builder(StatementType::DROP_MATERIALIZED_VIEW)
49                            .notice(format!(
50                                "materialized view \"{}\" does not exist, skipping",
51                                table_name
52                            ))
53                            .into())
54                    } else if let CatalogErrorInner::NotFound {
55                        object_type: "table",
56                        name,
57                    } = e.inner()
58                    {
59                        Err(CatalogError::not_found("materialized view", name).into())
60                    } else {
61                        Err(e.into())
62                    };
63                }
64            };
65
66        session.check_privilege_for_drop_alter(schema_name, &**table)?;
67
68        match table.table_type() {
69            TableType::MaterializedView => {}
70            _ => return Err(table.bad_drop_error()),
71        }
72
73        table.id()
74    };
75
76    let catalog_writer = session.catalog_writer()?;
77
78    execute_with_long_running_notification(
79        catalog_writer.drop_materialized_view(table_id, cascade),
80        &session,
81        "DROP MATERIALIZED VIEW",
82        LongRunningNotificationAction::SuggestRecover,
83    )
84    .await?;
85
86    Ok(PgResponse::empty_result(
87        StatementType::DROP_MATERIALIZED_VIEW,
88    ))
89}
90
91#[cfg(test)]
92mod tests {
93    use risingwave_common::catalog::{DEFAULT_DATABASE_NAME, DEFAULT_SCHEMA_NAME};
94
95    use crate::catalog::root_catalog::SchemaPath;
96    use crate::test_utils::LocalFrontend;
97
98    #[tokio::test]
99    async fn test_drop_mv_handler() {
100        let sql_create_table = "create table t (v1 smallint);";
101        let sql_create_mv = "create materialized view mv as select v1 from t;";
102        let sql_drop_mv = "drop materialized view mv;";
103        let frontend = LocalFrontend::new(Default::default()).await;
104        frontend.run_sql(sql_create_table).await.unwrap();
105        frontend.run_sql(sql_create_mv).await.unwrap();
106        frontend.run_sql(sql_drop_mv).await.unwrap();
107
108        let session = frontend.session_ref();
109        let catalog_reader = session.env().catalog_reader().read_guard();
110        let schema_path = SchemaPath::Name(DEFAULT_SCHEMA_NAME);
111
112        let table =
113            catalog_reader.get_created_table_by_name(DEFAULT_DATABASE_NAME, schema_path, "mv");
114        assert!(table.is_err());
115    }
116}