Skip to main content

risingwave_meta/controller/catalog/
drop_op.rs

1// Copyright 2024 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 risingwave_common::catalog::ICEBERG_SINK_PREFIX;
16use risingwave_pb::catalog::subscription::PbSubscriptionState;
17use risingwave_pb::telemetry::PbTelemetryDatabaseObject;
18use sea_orm::{ColumnTrait, DatabaseTransaction, EntityTrait, ModelTrait, QueryFilter};
19
20use super::*;
21impl CatalogController {
22    // Drop all kinds of objects including databases,
23    // schemas, relations, connections, functions, etc.
24    pub async fn drop_object(
25        &self,
26        object_type: ObjectType,
27        object_id: impl Into<ObjectId>,
28        drop_mode: DropMode,
29    ) -> MetaResult<(ReleaseContext, NotificationVersion)> {
30        let object_id = object_id.into();
31        let mut inner = self.inner.write().await;
32        let txn = inner.db.begin().await?;
33
34        let obj: PartialObject = Object::find_by_id(object_id)
35            .into_partial_model()
36            .one(&txn)
37            .await?
38            .ok_or_else(|| MetaError::catalog_id_not_found(object_type.as_str(), object_id))?;
39        assert_eq!(obj.obj_type, object_type);
40        let database_id = if object_type == ObjectType::Database {
41            object_id.as_database_id()
42        } else {
43            obj.database_id
44                .ok_or_else(|| anyhow!("dropped object should have database_id"))?
45        };
46
47        // Check the cross-db dependency info to see if the subscription can be dropped.
48        if obj.obj_type == ObjectType::Subscription {
49            validate_subscription_deletion(&txn, object_id.as_subscription_id()).await?;
50        }
51
52        let mut removed_objects = match drop_mode {
53            DropMode::Cascade => {
54                get_referring_objects_cascade(object_id, object_type, &txn).await?
55            }
56            DropMode::Restrict => match object_type {
57                ObjectType::Database => unreachable!("database always be dropped in cascade mode"),
58                ObjectType::Schema => {
59                    ensure_schema_empty(object_id.as_schema_id(), &txn).await?;
60                    Default::default()
61                }
62                ObjectType::Table => {
63                    let objects = validate_restrict_drop_and_collect_owned_objects(
64                        object_type,
65                        object_id,
66                        &txn,
67                    )
68                    .await?;
69                    for obj in objects.iter().filter(|object| {
70                        object.obj_type == ObjectType::Source || object.obj_type == ObjectType::Sink
71                    }) {
72                        report_drop_object(obj.obj_type, obj.oid, &txn).await;
73                    }
74                    assert!(
75                        objects.iter().all(|obj| obj.obj_type == ObjectType::Index
76                            || obj.obj_type == ObjectType::Sink),
77                        "only index and iceberg sink could be dropped in restrict mode"
78                    );
79                    for obj in &objects {
80                        validate_restrict_drop_and_collect_owned_objects(
81                            obj.obj_type,
82                            obj.oid,
83                            &txn,
84                        )
85                        .await?;
86                    }
87                    objects
88                }
89                object_type @ (ObjectType::Source | ObjectType::Sink) => {
90                    validate_restrict_drop_and_collect_owned_objects(object_type, object_id, &txn)
91                        .await?;
92                    report_drop_object(object_type, object_id, &txn).await;
93                    vec![]
94                }
95
96                ObjectType::View
97                | ObjectType::Index
98                | ObjectType::Function
99                | ObjectType::Connection
100                | ObjectType::Subscription
101                | ObjectType::Secret => {
102                    validate_restrict_drop_and_collect_owned_objects(object_type, object_id, &txn)
103                        .await?;
104                    vec![]
105                }
106            },
107        };
108
109        removed_objects.push(obj);
110        let mut removed_object_ids: HashSet<_> =
111            removed_objects.iter().map(|obj| obj.oid).collect();
112
113        for obj in &removed_objects {
114            if obj.obj_type == ObjectType::Sink {
115                let sink = Sink::find_by_id(obj.oid.as_sink_id())
116                    .one(&txn)
117                    .await?
118                    .ok_or_else(|| MetaError::catalog_id_not_found("sink", obj.oid))?;
119
120                if let Some(target_table) = sink.target_table
121                    && !removed_object_ids.contains(&target_table.as_object_id())
122                    && !has_table_been_migrated(&txn, target_table).await?
123                {
124                    return Err(anyhow::anyhow!(
125                        "Dropping sink into table is not allowed for unmigrated table {}. Please migrate it first.",
126                        target_table
127                    ).into());
128                }
129            }
130
131            // A table owns its source, and deleting the source also deletes the table row through
132            // a foreign key.
133            if obj.obj_type == ObjectType::Source
134                && let Some(source) = Source::find_by_id(obj.oid.as_source_id()).one(&txn).await?
135                && let Some(table_id) = source.optional_associated_table_id
136                && !removed_object_ids.contains(&table_id.as_object_id())
137            {
138                return Err(MetaError::permission_denied(format!(
139                    "cannot drop source \"{}\": it belongs to table {table_id}, use DROP TABLE instead",
140                    source.name
141                )));
142            }
143        }
144
145        // Load all objects that belong to the dropped objects before deletion. Cascaded rows are
146        // still needed for notifications and resource cleanup.
147        let root_objects = Object::find()
148            .filter(object::Column::Oid.is_in(removed_object_ids.iter().copied()))
149            .all(&txn)
150            .await?;
151        let belonging_objects =
152            get_belong_objects_by_ids(&txn, removed_objects.iter().map(|obj| obj.oid)).await?;
153        removed_object_ids.extend(belonging_objects.iter().map(|obj| obj.oid));
154        let mut objects_to_remove = root_objects.clone();
155        objects_to_remove.extend(belonging_objects.iter().cloned());
156        let removed_catalog_models = load_object_models(&txn, &objects_to_remove).await?;
157        let removed_cross_db_subscriptions =
158            resolve_cross_db_subscriptions(&txn, &removed_catalog_models).await?;
159        removed_objects.extend(belonging_objects.into_iter().map(|obj| PartialObject {
160            oid: obj.oid,
161            obj_type: obj.obj_type,
162            schema_id: obj.schema_id,
163            database_id: obj.database_id,
164        }));
165
166        let removed_table_ids = removed_objects
167            .iter()
168            .filter(|obj| obj.obj_type == ObjectType::Table || obj.obj_type == ObjectType::Index)
169            .map(|obj| obj.oid.as_table_id());
170
171        let removed_iceberg_table_sinks: Vec<PbSink> = removed_catalog_models
172            .iter()
173            .filter_map(|object_info| match object_info {
174                PbObjectInfo::Sink(sink) if sink.name.starts_with(ICEBERG_SINK_PREFIX) => {
175                    Some(sink.clone())
176                }
177                _ => None,
178            })
179            .collect();
180
181        // Iceberg sinks can be user-created with arbitrary
182        // names, so unlike the iceberg-table cleanup above, identify them by
183        // inspecting properties rather than by name prefix.
184        let mut removed_iceberg_sink_ids: Vec<SinkId> = Vec::new();
185        for object_info in &removed_catalog_models {
186            if let PbObjectInfo::Sink(sink) = object_info
187                && crate::manager::iceberg_compaction::is_iceberg_sink(&sink.properties)
188            {
189                removed_iceberg_sink_ids.push(sink.id);
190            }
191        }
192
193        let removed_streaming_job_ids: Vec<JobId> = StreamingJob::find()
194            .select_only()
195            .column(streaming_job::Column::JobId)
196            .filter(streaming_job::Column::JobId.is_in(removed_object_ids))
197            .into_tuple()
198            .all(&txn)
199            .await?;
200
201        // Check if there are any streaming jobs that are creating.
202        if !removed_streaming_job_ids.is_empty() {
203            let creating = StreamingJob::find()
204                .filter(
205                    streaming_job::Column::JobStatus
206                        .ne(JobStatus::Created)
207                        .and(streaming_job::Column::JobId.is_in(removed_streaming_job_ids.clone())),
208                )
209                .count(&txn)
210                .await?;
211            if creating != 0 {
212                if creating == 1 && object_type == ObjectType::Sink {
213                    info!("dropping creating sink job, it will be cancelled");
214                } else {
215                    return Err(MetaError::permission_denied(format!(
216                        "cannot drop {creating} streaming job(s) that are still being created; please cancel them first"
217                    )));
218                }
219            }
220        }
221
222        let removed_state_table_ids: HashSet<_> = removed_table_ids.clone().collect();
223
224        let removed_source_ids: HashSet<_> = removed_objects
225            .iter()
226            .filter(|obj| obj.obj_type == ObjectType::Source)
227            .map(|obj| obj.oid.as_source_id())
228            .collect();
229
230        let removed_secret_ids = removed_objects
231            .iter()
232            .filter(|obj| obj.obj_type == ObjectType::Secret)
233            .map(|obj| obj.oid.as_secret_id())
234            .collect();
235
236        let removed_objects: HashMap<_, _> = removed_objects
237            .into_iter()
238            .map(|obj| (obj.oid, obj))
239            .collect();
240
241        // TODO: Support drop cascade for cross-database query.
242        for obj in removed_objects.values() {
243            if let Some(obj_database_id) = obj.database_id
244                && obj_database_id != database_id
245            {
246                return Err(MetaError::permission_denied(format!(
247                    "Referenced by other objects in database {obj_database_id}, please drop them manually"
248                )));
249            }
250        }
251
252        let (removed_source_fragments, removed_sink_fragments, removed_fragments) =
253            get_fragments_for_jobs(&txn, removed_streaming_job_ids.clone()).await?;
254
255        let sink_target_fragments = fetch_target_fragments(&txn, removed_sink_fragments).await?;
256        let mut removed_sink_fragment_by_targets = HashMap::new();
257        for (sink_fragment, target_fragments) in sink_target_fragments {
258            assert!(
259                target_fragments.len() <= 1,
260                "sink should have at most one downstream fragment"
261            );
262            if let Some(target_fragment) = target_fragments.first()
263                && !removed_fragments.contains(target_fragment)
264            {
265                removed_sink_fragment_by_targets
266                    .entry(*target_fragment)
267                    .or_insert_with(Vec::new)
268                    .push(sink_fragment);
269            }
270        }
271
272        // Find affect users with privileges on all this objects.
273        let updated_user_ids: Vec<UserId> = UserPrivilege::find()
274            .select_only()
275            .distinct()
276            .column(user_privilege::Column::UserId)
277            .filter(user_privilege::Column::Oid.is_in(removed_objects.keys().cloned()))
278            .into_tuple()
279            .all(&txn)
280            .await?;
281        let dropped_tables = removed_catalog_models
282            .into_iter()
283            .filter_map(|object_info| match object_info {
284                PbObjectInfo::Table(table) if removed_state_table_ids.contains(&table.id) => {
285                    Some(table)
286                }
287                _ => None,
288            });
289        // Delete the explicitly selected objects. The self foreign key cascades to every object
290        // that belongs to them.
291        let res = Object::delete_many()
292            .filter(object::Column::Oid.is_in(root_objects.iter().map(|obj| obj.oid)))
293            .exec(&txn)
294            .await?;
295        if res.rows_affected == 0 {
296            return Err(MetaError::catalog_id_not_found(
297                object_type.as_str(),
298                object_id,
299            ));
300        }
301        let user_infos = list_user_info_by_ids(updated_user_ids, &txn).await?;
302
303        txn.commit().await?;
304
305        // notify about them.
306        let mut notifications = self.frontend_notification_batch();
307        Self::add_users_update_notifications(&mut notifications, user_infos);
308        inner
309            .dropped_tables
310            .extend(dropped_tables.map(|t| (t.id, t)));
311
312        match object_type {
313            ObjectType::Database => {
314                // TODO: Notify objects in other databases when the cross-database query is supported.
315                notifications.add(
316                    NotificationOperation::Delete,
317                    NotificationInfo::Database(PbDatabase {
318                        id: database_id,
319                        ..Default::default()
320                    }),
321                );
322            }
323            ObjectType::Schema => {
324                let (schema_obj, mut to_notify_objs): (Vec<_>, Vec<_>) = removed_objects
325                    .into_values()
326                    .partition(|obj| obj.obj_type == ObjectType::Schema && obj.oid == object_id);
327                let schema_obj = Itertools::exactly_one(schema_obj.into_iter())
328                    .expect("schema object not found");
329                to_notify_objs.push(schema_obj);
330
331                let relation_group = build_object_group_for_delete(to_notify_objs);
332                notifications.add(NotificationOperation::Delete, relation_group);
333            }
334            _ => {
335                // Hummock observers and compactor observers are notified once the corresponding barrier is completed.
336                // They only need RelationInfo::Table.
337                let relation_group =
338                    build_object_group_for_delete(removed_objects.into_values().collect());
339                notifications.add(NotificationOperation::Delete, relation_group);
340            }
341        }
342        let version = notifications
343            .publish()
344            .await
345            .expect("the drop notification batch contains the dropped object");
346
347        Ok((
348            ReleaseContext {
349                database_id,
350                removed_streaming_job_ids,
351                removed_state_table_ids: removed_state_table_ids.into_iter().collect(),
352                removed_source_ids: removed_source_ids.into_iter().collect(),
353                removed_secret_ids,
354                removed_source_fragments,
355                removed_fragments,
356                removed_sink_fragment_by_targets,
357                removed_iceberg_table_sinks,
358                removed_iceberg_sink_ids,
359                removed_cross_db_subscriptions,
360            },
361            version,
362        ))
363    }
364
365    pub async fn try_abort_creating_subscription(
366        &self,
367        subscription_id: SubscriptionId,
368    ) -> MetaResult<()> {
369        let inner = self.inner.write().await;
370        let txn = inner.db.begin().await?;
371
372        let subscription = Subscription::find_by_id(subscription_id).one(&txn).await?;
373        let Some(subscription) = subscription else {
374            tracing::warn!(
375                %subscription_id,
376                "subscription not found when aborting creation, might be cleaned by recovery"
377            );
378            return Ok(());
379        };
380
381        if subscription.subscription_state == PbSubscriptionState::Created as i32 {
382            tracing::warn!(
383                %subscription_id,
384                "subscription is already created when aborting creation"
385            );
386            return Ok(());
387        }
388
389        subscription.delete(&txn).await?;
390        txn.commit().await?;
391        Ok(())
392    }
393}
394
395async fn report_drop_object(
396    object_type: ObjectType,
397    object_id: ObjectId,
398    txn: &DatabaseTransaction,
399) {
400    let connector_name = {
401        match object_type {
402            ObjectType::Sink => Sink::find_by_id(object_id.as_sink_id())
403                .select_only()
404                .column(sink::Column::Properties)
405                .into_tuple::<Property>()
406                .one(txn)
407                .await
408                .ok()
409                .flatten()
410                .and_then(|properties| properties.inner_ref().get("connector").cloned()),
411            ObjectType::Source => Source::find_by_id(object_id.as_source_id())
412                .select_only()
413                .column(source::Column::WithProperties)
414                .into_tuple::<Property>()
415                .one(txn)
416                .await
417                .ok()
418                .flatten()
419                .and_then(|properties| properties.inner_ref().get("connector").cloned()),
420            _ => unreachable!(),
421        }
422    };
423    if let Some(connector_name) = connector_name {
424        report_event(
425            PbTelemetryEventStage::DropStreamJob,
426            "source",
427            object_id.as_raw_id() as _,
428            Some(connector_name),
429            Some(match object_type {
430                ObjectType::Source => PbTelemetryDatabaseObject::Source,
431                ObjectType::Sink => PbTelemetryDatabaseObject::Sink,
432                _ => unreachable!(),
433            }),
434            None,
435        );
436    }
437}