Skip to main content

risingwave_meta/controller/catalog/
alter_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 anyhow::Context;
16use risingwave_common::cast::datetime_to_timestamp_millis;
17use risingwave_common::catalog::{AlterDatabaseParam, ICEBERG_SINK_PREFIX, ICEBERG_SOURCE_PREFIX};
18use risingwave_common::config::mutate::TomlTableMutateExt as _;
19use risingwave_common::config::{StreamingConfig, merge_streaming_config_section};
20use risingwave_common::id::JobId;
21use risingwave_common::system_param::{OverrideValidate, Validate};
22use risingwave_common::util::worker_util::DEFAULT_RESOURCE_GROUP;
23use risingwave_meta_model::refresh_job::{self, RefreshState};
24use sea_orm::ActiveValue::{NotSet, Set};
25use sea_orm::prelude::DateTime;
26use sea_orm::sea_query::Expr;
27use sea_orm::{ActiveModelTrait, ConnectionTrait, DatabaseTransaction, SqlErr};
28use thiserror_ext::AsReport;
29
30use super::*;
31use crate::controller::utils::load_streaming_jobs_by_ids;
32use crate::error::bail_invalid_parameter;
33
34impl CatalogController {
35    async fn alter_database_name(
36        &self,
37        database_id: DatabaseId,
38        name: &str,
39    ) -> MetaResult<NotificationVersion> {
40        let inner = self.inner.write().await;
41        let txn = inner.db.begin().await?;
42        check_database_name_duplicate(name, &txn).await?;
43
44        let active_model = database::ActiveModel {
45            database_id: Set(database_id),
46            name: Set(name.to_owned()),
47            ..Default::default()
48        };
49        let database = active_model.update(&txn).await?;
50
51        let obj = Object::find_by_id(database_id)
52            .one(&txn)
53            .await?
54            .ok_or_else(|| MetaError::catalog_id_not_found("database", database_id))?;
55
56        txn.commit().await?;
57
58        let version = self
59            .notify_frontend(
60                NotificationOperation::Update,
61                NotificationInfo::Database(ObjectModel(database, obj, None).into()),
62            )
63            .await;
64        Ok(version)
65    }
66
67    async fn alter_schema_name(
68        &self,
69        schema_id: SchemaId,
70        name: &str,
71    ) -> MetaResult<NotificationVersion> {
72        let inner = self.inner.write().await;
73        let txn = inner.db.begin().await?;
74
75        let obj = Object::find_by_id(schema_id)
76            .one(&txn)
77            .await?
78            .ok_or_else(|| MetaError::catalog_id_not_found("schema", schema_id))?;
79        check_schema_name_duplicate(name, obj.database_id.unwrap(), &txn).await?;
80
81        let active_model = schema::ActiveModel {
82            schema_id: Set(schema_id),
83            name: Set(name.to_owned()),
84        };
85        let schema = active_model.update(&txn).await?;
86
87        txn.commit().await?;
88
89        let version = self
90            .notify_frontend(
91                NotificationOperation::Update,
92                NotificationInfo::Schema(ObjectModel(schema, obj, None).into()),
93            )
94            .await;
95        Ok(version)
96    }
97
98    pub async fn alter_name(
99        &self,
100        object_type: ObjectType,
101        object_id: impl Into<ObjectId>,
102        object_name: &str,
103    ) -> MetaResult<NotificationVersion> {
104        let object_id = object_id.into();
105        if object_type == ObjectType::Database {
106            return self
107                .alter_database_name(object_id.as_database_id(), object_name)
108                .await;
109        } else if object_type == ObjectType::Schema {
110            return self
111                .alter_schema_name(object_id.as_schema_id(), object_name)
112                .await;
113        }
114
115        let inner = self.inner.write().await;
116        let txn = inner.db.begin().await?;
117        let obj: PartialObject = Object::find_by_id(object_id)
118            .into_partial_model()
119            .one(&txn)
120            .await?
121            .ok_or_else(|| MetaError::catalog_id_not_found(object_type.as_str(), object_id))?;
122        assert_eq!(obj.obj_type, object_type);
123        check_relation_name_duplicate(
124            object_name,
125            obj.database_id.unwrap(),
126            obj.schema_id.unwrap(),
127            &txn,
128        )
129        .await?;
130
131        // rename relation.
132        let (mut to_update_relations, old_name) =
133            rename_relation(&txn, object_type, object_id, object_name).await?;
134        // rename referring relation name.
135        to_update_relations.extend(
136            rename_relation_refer(&txn, object_type, object_id, object_name, &old_name).await?,
137        );
138
139        txn.commit().await?;
140
141        let version = self
142            .notify_frontend(
143                NotificationOperation::Update,
144                NotificationInfo::ObjectGroup(PbObjectGroup {
145                    objects: to_update_relations,
146                    dependencies: vec![],
147                }),
148            )
149            .await;
150
151        Ok(version)
152    }
153
154    pub async fn alter_swap_rename(
155        &self,
156        object_type: ObjectType,
157        object_id: ObjectId,
158        dst_object_id: ObjectId,
159    ) -> MetaResult<NotificationVersion> {
160        let inner = self.inner.write().await;
161        let txn = inner.db.begin().await?;
162        let dst_name: String = match object_type {
163            ObjectType::Table => Table::find_by_id(dst_object_id.as_table_id())
164                .select_only()
165                .column(table::Column::Name)
166                .into_tuple()
167                .one(&txn)
168                .await?
169                .ok_or_else(|| {
170                    MetaError::catalog_id_not_found(object_type.as_str(), dst_object_id)
171                })?,
172            ObjectType::Source => Source::find_by_id(dst_object_id.as_source_id())
173                .select_only()
174                .column(source::Column::Name)
175                .into_tuple()
176                .one(&txn)
177                .await?
178                .ok_or_else(|| {
179                    MetaError::catalog_id_not_found(object_type.as_str(), dst_object_id)
180                })?,
181            ObjectType::Sink => Sink::find_by_id(dst_object_id.as_sink_id())
182                .select_only()
183                .column(sink::Column::Name)
184                .into_tuple()
185                .one(&txn)
186                .await?
187                .ok_or_else(|| {
188                    MetaError::catalog_id_not_found(object_type.as_str(), dst_object_id)
189                })?,
190            ObjectType::View => View::find_by_id(dst_object_id.as_view_id())
191                .select_only()
192                .column(view::Column::Name)
193                .into_tuple()
194                .one(&txn)
195                .await?
196                .ok_or_else(|| {
197                    MetaError::catalog_id_not_found(object_type.as_str(), dst_object_id)
198                })?,
199            ObjectType::Subscription => {
200                Subscription::find_by_id(dst_object_id.as_subscription_id())
201                    .select_only()
202                    .column(subscription::Column::Name)
203                    .into_tuple()
204                    .one(&txn)
205                    .await?
206                    .ok_or_else(|| {
207                        MetaError::catalog_id_not_found(object_type.as_str(), dst_object_id)
208                    })?
209            }
210            _ => {
211                return Err(MetaError::permission_denied(format!(
212                    "swap rename not supported for object type: {:?}",
213                    object_type
214                )));
215            }
216        };
217
218        // rename relations.
219        let (mut to_update_relations, src_name) =
220            rename_relation(&txn, object_type, object_id, &dst_name).await?;
221        let (to_update_relations2, _) =
222            rename_relation(&txn, object_type, dst_object_id, &src_name).await?;
223        to_update_relations.extend(to_update_relations2);
224        // rename referring relation name.
225        to_update_relations.extend(
226            rename_relation_refer(&txn, object_type, object_id, &dst_name, &src_name).await?,
227        );
228        to_update_relations.extend(
229            rename_relation_refer(&txn, object_type, dst_object_id, &src_name, &dst_name).await?,
230        );
231
232        txn.commit().await?;
233
234        let version = self
235            .notify_frontend(
236                NotificationOperation::Update,
237                NotificationInfo::ObjectGroup(PbObjectGroup {
238                    objects: to_update_relations,
239                    dependencies: vec![],
240                }),
241            )
242            .await;
243
244        Ok(version)
245    }
246
247    pub async fn alter_non_shared_source(
248        &self,
249        pb_source: PbSource,
250    ) -> MetaResult<NotificationVersion> {
251        let source_id: SourceId = pb_source.id;
252        let inner = self.inner.write().await;
253        let txn = inner.db.begin().await?;
254
255        let original_version: i64 = Source::find_by_id(source_id)
256            .select_only()
257            .column(source::Column::Version)
258            .into_tuple()
259            .one(&txn)
260            .await?
261            .ok_or_else(|| MetaError::catalog_id_not_found("source", source_id))?;
262        if original_version + 1 != pb_source.version as i64 {
263            return Err(MetaError::permission_denied(
264                "source version is stale".to_owned(),
265            ));
266        }
267
268        let source: source::ActiveModel = pb_source.clone().into();
269        Source::update(source).exec(&txn).await?;
270        txn.commit().await?;
271
272        let version = self
273            .notify_frontend_relation_info(
274                NotificationOperation::Update,
275                PbObjectInfo::Source(pb_source),
276            )
277            .await;
278        Ok(version)
279    }
280
281    pub async fn alter_owner(
282        &self,
283        object_type: ObjectType,
284        object_id: ObjectId,
285        new_owner: UserId,
286    ) -> MetaResult<NotificationVersion> {
287        let inner = self.inner.write().await;
288        let txn = inner.db.begin().await?;
289        ensure_user_id(new_owner, &txn).await?;
290
291        let obj = Object::find_by_id(object_id)
292            .one(&txn)
293            .await?
294            .ok_or_else(|| MetaError::catalog_id_not_found(object_type.as_str(), object_id))?;
295        if obj.owner_id == new_owner {
296            return Ok(IGNORED_NOTIFICATION_VERSION);
297        }
298        let mut obj = obj.into_active_model();
299        obj.owner_id = Set(new_owner);
300        let obj = obj.update(&txn).await?;
301
302        let mut objects = vec![];
303        match object_type {
304            ObjectType::Database => {
305                let db = Database::find_by_id(object_id.as_database_id())
306                    .one(&txn)
307                    .await?
308                    .ok_or_else(|| MetaError::catalog_id_not_found("database", object_id))?;
309
310                txn.commit().await?;
311
312                let version = self
313                    .notify_frontend(
314                        NotificationOperation::Update,
315                        NotificationInfo::Database(ObjectModel(db, obj, None).into()),
316                    )
317                    .await;
318                return Ok(version);
319            }
320            ObjectType::Schema => {
321                let schema = Schema::find_by_id(object_id.as_schema_id())
322                    .one(&txn)
323                    .await?
324                    .ok_or_else(|| MetaError::catalog_id_not_found("schema", object_id))?;
325
326                txn.commit().await?;
327
328                let version = self
329                    .notify_frontend(
330                        NotificationOperation::Update,
331                        NotificationInfo::Schema(ObjectModel(schema, obj, None).into()),
332                    )
333                    .await;
334                return Ok(version);
335            }
336            ObjectType::Table => {
337                let table = Table::find_by_id(object_id.as_table_id())
338                    .one(&txn)
339                    .await?
340                    .ok_or_else(|| MetaError::catalog_id_not_found("table", object_id))?;
341                let streaming_job = streaming_job::Entity::find_by_id(object_id.as_job_id())
342                    .one(&txn)
343                    .await?;
344
345                // associated source.
346                if let Some(associated_source_id) = table.optional_associated_source_id {
347                    let src_obj = object::ActiveModel {
348                        oid: Set(associated_source_id.as_object_id()),
349                        owner_id: Set(new_owner),
350                        ..Default::default()
351                    }
352                    .update(&txn)
353                    .await?;
354                    let source = Source::find_by_id(associated_source_id)
355                        .one(&txn)
356                        .await?
357                        .ok_or_else(|| {
358                            MetaError::catalog_id_not_found("source", associated_source_id)
359                        })?;
360                    objects.push(PbObjectInfo::Source(
361                        ObjectModel(source, src_obj, None).into(),
362                    ));
363                }
364
365                // associated sink and source for iceberg table.
366                if matches!(table.engine, Some(table::Engine::Iceberg)) {
367                    let iceberg_sink = Sink::find()
368                        .inner_join(Object)
369                        .select_only()
370                        .column(sink::Column::SinkId)
371                        .filter(
372                            object::Column::DatabaseId
373                                .eq(obj.database_id)
374                                .and(object::Column::SchemaId.eq(obj.schema_id))
375                                .and(
376                                    sink::Column::Name
377                                        .eq(format!("{}{}", ICEBERG_SINK_PREFIX, table.name)),
378                                ),
379                        )
380                        .into_tuple::<SinkId>()
381                        .one(&txn)
382                        .await?
383                        .expect("iceberg sink must exist");
384                    let sink_obj = object::ActiveModel {
385                        oid: Set(iceberg_sink.as_object_id()),
386                        owner_id: Set(new_owner),
387                        ..Default::default()
388                    }
389                    .update(&txn)
390                    .await?;
391                    let sink = Sink::find_by_id(iceberg_sink)
392                        .one(&txn)
393                        .await?
394                        .ok_or_else(|| MetaError::catalog_id_not_found("sink", iceberg_sink))?;
395                    objects.push(PbObjectInfo::Sink(
396                        ObjectModel(sink, sink_obj, streaming_job.clone()).into(),
397                    ));
398
399                    let iceberg_source = Source::find()
400                        .inner_join(Object)
401                        .select_only()
402                        .column(source::Column::SourceId)
403                        .filter(
404                            object::Column::DatabaseId
405                                .eq(obj.database_id)
406                                .and(object::Column::SchemaId.eq(obj.schema_id))
407                                .and(
408                                    source::Column::Name
409                                        .eq(format!("{}{}", ICEBERG_SOURCE_PREFIX, table.name)),
410                                ),
411                        )
412                        .into_tuple::<SourceId>()
413                        .one(&txn)
414                        .await?
415                        .expect("iceberg source must exist");
416                    let source_obj = object::ActiveModel {
417                        oid: Set(iceberg_source.as_object_id()),
418                        owner_id: Set(new_owner),
419                        ..Default::default()
420                    }
421                    .update(&txn)
422                    .await?;
423                    let source = Source::find_by_id(iceberg_source)
424                        .one(&txn)
425                        .await?
426                        .ok_or_else(|| MetaError::catalog_id_not_found("source", iceberg_source))?;
427                    objects.push(PbObjectInfo::Source(
428                        ObjectModel(source, source_obj, None).into(),
429                    ));
430                }
431
432                // indexes.
433                let (index_ids, mut table_ids): (Vec<IndexId>, Vec<TableId>) = Index::find()
434                    .select_only()
435                    .columns([index::Column::IndexId, index::Column::IndexTableId])
436                    .filter(index::Column::PrimaryTableId.eq(object_id))
437                    .into_tuple::<(IndexId, TableId)>()
438                    .all(&txn)
439                    .await?
440                    .into_iter()
441                    .unzip();
442                objects.push(PbObjectInfo::Table(
443                    ObjectModel(table, obj, streaming_job).into(),
444                ));
445
446                // internal tables.
447                let internal_tables: Vec<TableId> = Table::find()
448                    .select_only()
449                    .column(table::Column::TableId)
450                    .filter(
451                        table::Column::BelongsToJobId.is_in(
452                            table_ids
453                                .iter()
454                                .cloned()
455                                .chain(std::iter::once(object_id.as_table_id())),
456                        ),
457                    )
458                    .into_tuple()
459                    .all(&txn)
460                    .await?;
461                table_ids.extend(internal_tables);
462
463                if !index_ids.is_empty() || !table_ids.is_empty() {
464                    Object::update_many()
465                        .col_expr(object::Column::OwnerId, SimpleExpr::Value(new_owner.into()))
466                        .filter(
467                            object::Column::Oid.is_in::<ObjectId, _>(
468                                index_ids
469                                    .iter()
470                                    .copied()
471                                    .map_into()
472                                    .chain(table_ids.iter().copied().map_into()),
473                            ),
474                        )
475                        .exec(&txn)
476                        .await?;
477                }
478
479                if !table_ids.is_empty() {
480                    let table_objs = Table::find()
481                        .find_also_related(Object)
482                        .filter(table::Column::TableId.is_in(table_ids))
483                        .all(&txn)
484                        .await?;
485                    let streaming_jobs = load_streaming_jobs_by_ids(
486                        &txn,
487                        table_objs.iter().map(|(table, _)| table.job_id()),
488                    )
489                    .await?;
490                    for (table, table_obj) in table_objs {
491                        let job_id = table.job_id();
492                        let streaming_job = streaming_jobs.get(&job_id).cloned();
493                        objects.push(PbObjectInfo::Table(
494                            ObjectModel(table, table_obj.unwrap(), streaming_job).into(),
495                        ));
496                    }
497                }
498                // FIXME: frontend will update index/primary table from cache, requires apply updates of indexes after tables.
499                if !index_ids.is_empty() {
500                    let index_objs = Index::find()
501                        .find_also_related(Object)
502                        .filter(index::Column::IndexId.is_in(index_ids))
503                        .all(&txn)
504                        .await?;
505                    let streaming_jobs = load_streaming_jobs_by_ids(
506                        &txn,
507                        index_objs
508                            .iter()
509                            .map(|(index, _)| index.index_id.as_job_id()),
510                    )
511                    .await?;
512                    for (index, index_obj) in index_objs {
513                        let streaming_job =
514                            streaming_jobs.get(&index.index_id.as_job_id()).cloned();
515                        objects.push(PbObjectInfo::Index(
516                            ObjectModel(index, index_obj.unwrap(), streaming_job).into(),
517                        ));
518                    }
519                }
520            }
521            ObjectType::Source => {
522                let source = Source::find_by_id(object_id.as_source_id())
523                    .one(&txn)
524                    .await?
525                    .ok_or_else(|| MetaError::catalog_id_not_found("source", object_id))?;
526                let is_shared = source.is_shared();
527                objects.push(PbObjectInfo::Source(ObjectModel(source, obj, None).into()));
528
529                // Note: For non-shared source, we don't update their state tables, which
530                // belongs to the MV.
531                if is_shared {
532                    update_internal_tables(
533                        &txn,
534                        object_id,
535                        object::Column::OwnerId,
536                        new_owner,
537                        &mut objects,
538                    )
539                    .await?;
540                }
541            }
542            ObjectType::Sink => {
543                let (sink, sink_obj) = Sink::find_by_id(object_id.as_sink_id())
544                    .find_also_related(Object)
545                    .one(&txn)
546                    .await?
547                    .ok_or_else(|| MetaError::catalog_id_not_found("sink", object_id))?;
548                let streaming_job = streaming_job::Entity::find_by_id(sink.sink_id.as_job_id())
549                    .one(&txn)
550                    .await?;
551                objects.push(PbObjectInfo::Sink(
552                    ObjectModel(sink, sink_obj.unwrap(), streaming_job).into(),
553                ));
554
555                update_internal_tables(
556                    &txn,
557                    object_id,
558                    object::Column::OwnerId,
559                    new_owner,
560                    &mut objects,
561                )
562                .await?;
563            }
564            ObjectType::Subscription => {
565                let subscription = Subscription::find_by_id(object_id.as_subscription_id())
566                    .one(&txn)
567                    .await?
568                    .ok_or_else(|| MetaError::catalog_id_not_found("subscription", object_id))?;
569                objects.push(PbObjectInfo::Subscription(
570                    ObjectModel(subscription, obj, None).into(),
571                ));
572            }
573            ObjectType::View => {
574                let view = View::find_by_id(object_id.as_view_id())
575                    .one(&txn)
576                    .await?
577                    .ok_or_else(|| MetaError::catalog_id_not_found("view", object_id))?;
578                objects.push(PbObjectInfo::View(ObjectModel(view, obj, None).into()));
579            }
580            ObjectType::Connection => {
581                let connection = Connection::find_by_id(object_id.as_connection_id())
582                    .one(&txn)
583                    .await?
584                    .ok_or_else(|| MetaError::catalog_id_not_found("connection", object_id))?;
585                objects.push(PbObjectInfo::Connection(
586                    ObjectModel(connection, obj, None).into(),
587                ));
588            }
589            ObjectType::Function => {
590                let function = Function::find_by_id(object_id.as_function_id())
591                    .one(&txn)
592                    .await?
593                    .ok_or_else(|| MetaError::catalog_id_not_found("function", object_id))?;
594                objects.push(PbObjectInfo::Function(
595                    ObjectModel(function, obj, None).into(),
596                ));
597            }
598            ObjectType::Secret => {
599                let secret = Secret::find_by_id(object_id.as_secret_id())
600                    .one(&txn)
601                    .await?
602                    .ok_or_else(|| MetaError::catalog_id_not_found("secret", object_id))?;
603                objects.push(PbObjectInfo::Secret(ObjectModel(secret, obj, None).into()));
604            }
605            _ => unreachable!("not supported object type: {:?}", object_type),
606        };
607
608        txn.commit().await?;
609
610        let version = self
611            .notify_frontend(
612                NotificationOperation::Update,
613                NotificationInfo::ObjectGroup(PbObjectGroup {
614                    objects: objects
615                        .into_iter()
616                        .map(|object| PbObject {
617                            object_info: Some(object),
618                        })
619                        .collect(),
620                    dependencies: vec![],
621                }),
622            )
623            .await;
624        Ok(version)
625    }
626
627    pub async fn alter_schema(
628        &self,
629        object_type: ObjectType,
630        object_id: ObjectId,
631        new_schema: SchemaId,
632    ) -> MetaResult<NotificationVersion> {
633        let inner = self.inner.write().await;
634        let txn = inner.db.begin().await?;
635        ensure_object_id(ObjectType::Schema, new_schema, &txn).await?;
636
637        let obj = Object::find_by_id(object_id)
638            .one(&txn)
639            .await?
640            .ok_or_else(|| MetaError::catalog_id_not_found(object_type.as_str(), object_id))?;
641        if obj.obj_type != object_type {
642            return Err(MetaError::catalog_id_not_found(
643                object_type.as_str(),
644                object_id,
645            ));
646        }
647        if object_type == ObjectType::Table {
648            let table_type = Table::find_by_id(object_id.as_table_id())
649                .select_only()
650                .column(table::Column::TableType)
651                .into_tuple::<TableType>()
652                .one(&txn)
653                .await?
654                .ok_or_else(|| MetaError::catalog_id_not_found("table", object_id))?;
655            if table_type == TableType::Internal {
656                return Err(MetaError::catalog_id_not_found("table", object_id));
657            }
658        }
659        if obj.schema_id == Some(new_schema) {
660            return Ok(IGNORED_NOTIFICATION_VERSION);
661        }
662        let database_id = obj
663            .database_id
664            .ok_or_else(|| anyhow!("catalog object {} has no database", object_id))?;
665
666        // Indexes are named schema objects rather than objects belonging to their primary table.
667        // Move them with a table explicitly, while subscriptions remain in their own schemas.
668        let mut objects = vec![obj];
669        if object_type == ObjectType::Table {
670            let index_ids = Index::find()
671                .select_only()
672                .column(index::Column::IndexId)
673                .filter(index::Column::PrimaryTableId.eq(object_id.as_table_id()))
674                .into_tuple::<IndexId>()
675                .all(&txn)
676                .await?;
677            objects.extend(
678                Object::find()
679                    .filter(
680                        object::Column::Oid
681                            .is_in(index_ids.into_iter().map(|id| id.as_object_id())),
682                    )
683                    .all(&txn)
684                    .await?,
685            );
686        }
687
688        let object_ids = objects.iter().map(|object| object.oid).collect_vec();
689        let belonging_objects = get_belong_objects_by_ids(&txn, object_ids.iter().copied()).await?;
690        objects.extend(belonging_objects.iter().cloned());
691        let mut object_models = load_object_models(&txn, &objects).await?;
692
693        prepare_object_models_for_schema_change(&txn, &mut object_models, database_id, new_schema)
694            .await?;
695        Object::update_many()
696            .col_expr(object::Column::SchemaId, new_schema.into())
697            .col_expr(
698                object::Column::BelongToOid,
699                new_schema.as_object_id().into(),
700            )
701            .filter(object::Column::Oid.is_in(object_ids))
702            .exec(&txn)
703            .await?;
704        if !belonging_objects.is_empty() {
705            Object::update_many()
706                .col_expr(object::Column::SchemaId, new_schema.into())
707                .filter(
708                    object::Column::Oid.is_in(belonging_objects.iter().map(|object| object.oid)),
709                )
710                .exec(&txn)
711                .await?;
712        }
713        let notification = NotificationInfo::ObjectGroup(PbObjectGroup {
714            objects: object_models
715                .into_iter()
716                .map(|object_info| PbObject {
717                    object_info: Some(object_info),
718                })
719                .collect(),
720            dependencies: vec![],
721        });
722
723        txn.commit().await?;
724        let version = self
725            .notify_frontend(NotificationOperation::Update, notification)
726            .await;
727        Ok(version)
728    }
729
730    pub async fn alter_secret(
731        &self,
732        pb_secret: PbSecret,
733        secret_plain_payload: Vec<u8>,
734    ) -> MetaResult<NotificationVersion> {
735        let inner = self.inner.write().await;
736        let owner_id = pb_secret.owner as _;
737        let txn = inner.db.begin().await?;
738        ensure_user_id(owner_id, &txn).await?;
739        ensure_object_id(ObjectType::Database, pb_secret.database_id, &txn).await?;
740        ensure_object_id(ObjectType::Schema, pb_secret.schema_id, &txn).await?;
741
742        ensure_object_id(ObjectType::Secret, pb_secret.id, &txn).await?;
743        let secret: secret::ActiveModel = pb_secret.clone().into();
744        Secret::update(secret).exec(&txn).await?;
745
746        txn.commit().await?;
747
748        // Notify the compute and frontend node plain secret
749        let mut secret_plain = pb_secret;
750        secret_plain.value.clone_from(&secret_plain_payload);
751
752        LocalSecretManager::global().update_secret(secret_plain.id, secret_plain_payload);
753        self.env
754            .notification_manager()
755            .notify_compute_without_version(Operation::Update, Info::Secret(secret_plain.clone()));
756
757        let version = self
758            .notify_frontend(
759                NotificationOperation::Update,
760                NotificationInfo::Secret(secret_plain),
761            )
762            .await;
763
764        Ok(version)
765    }
766
767    // drop table associated source is a special case of drop relation, which just remove the source object and associated state table, keeping the streaming job and fragments.
768    pub async fn drop_table_associated_source(
769        txn: &DatabaseTransaction,
770        drop_table_connector_ctx: &DropTableConnectorContext,
771    ) -> MetaResult<(Vec<PbUserInfo>, Vec<PartialObject>)> {
772        let to_drop_source_objects: Vec<PartialObject> = Object::find()
773            .filter(object::Column::Oid.is_in(vec![drop_table_connector_ctx.to_remove_source_id]))
774            .into_partial_model()
775            .all(txn)
776            .await?;
777        let to_drop_internal_table_objs: Vec<PartialObject> = Object::find()
778            .select_only()
779            .filter(
780                object::Column::Oid.is_in(vec![drop_table_connector_ctx.to_remove_state_table_id]),
781            )
782            .into_partial_model()
783            .all(txn)
784            .await?;
785        let to_drop_objects = to_drop_source_objects
786            .into_iter()
787            .chain(to_drop_internal_table_objs)
788            .collect_vec();
789        // Find affect users with privileges on all this objects.
790        let to_update_user_ids: Vec<UserId> = UserPrivilege::find()
791            .select_only()
792            .distinct()
793            .column(user_privilege::Column::UserId)
794            .filter(user_privilege::Column::Oid.is_in(to_drop_objects.iter().map(|obj| obj.oid)))
795            .into_tuple()
796            .all(txn)
797            .await?;
798
799        tracing::debug!(
800            "drop_table_associated_source: to_drop_objects: {:?}",
801            to_drop_objects
802        );
803
804        // delete all in to_drop_objects.
805        let res = Object::delete_many()
806            .filter(object::Column::Oid.is_in(to_drop_objects.iter().map(|obj| obj.oid)))
807            .exec(txn)
808            .await?;
809        if res.rows_affected == 0 {
810            return Err(MetaError::catalog_id_not_found(
811                ObjectType::Source.as_str(),
812                drop_table_connector_ctx.to_remove_source_id,
813            ));
814        }
815        let user_infos = list_user_info_by_ids(to_update_user_ids, txn).await?;
816
817        Ok((user_infos, to_drop_objects))
818    }
819
820    pub async fn alter_database_param(
821        &self,
822        database_id: DatabaseId,
823        param: AlterDatabaseParam,
824    ) -> MetaResult<(NotificationVersion, risingwave_meta_model::database::Model)> {
825        let inner = self.inner.write().await;
826        let txn = inner.db.begin().await?;
827
828        let mut database = database::ActiveModel {
829            database_id: Set(database_id),
830            ..Default::default()
831        };
832        match param {
833            AlterDatabaseParam::BarrierIntervalMs(interval) => {
834                if let Some(ref interval) = interval {
835                    OverrideValidate::barrier_interval_ms(interval)
836                        .map_err(|e| anyhow::anyhow!(e))?;
837                }
838                database.barrier_interval_ms = Set(interval.map(|i| i as i32));
839            }
840            AlterDatabaseParam::CheckpointFrequency(frequency) => {
841                if let Some(ref frequency) = frequency {
842                    OverrideValidate::checkpoint_frequency(frequency)
843                        .map_err(|e| anyhow::anyhow!(e))?;
844                }
845                database.checkpoint_frequency = Set(frequency.map(|f| f as i64));
846            }
847        }
848        let database = database.update(&txn).await?;
849
850        let obj = Object::find_by_id(database_id)
851            .one(&txn)
852            .await?
853            .ok_or_else(|| MetaError::catalog_id_not_found("database", database_id))?;
854
855        txn.commit().await?;
856
857        let version = self
858            .notify_frontend(
859                NotificationOperation::Update,
860                NotificationInfo::Database(ObjectModel(database.clone(), obj, None).into()),
861            )
862            .await;
863        Ok((version, database))
864    }
865
866    pub async fn alter_database_resource_group(
867        &self,
868        database_id: DatabaseId,
869        resource_group: Option<String>,
870    ) -> MetaResult<NotificationVersion> {
871        let inner = self.inner.write().await;
872        let txn = inner.db.begin().await?;
873
874        let database =
875            database::ActiveModel {
876                database_id: Set(database_id),
877                resource_group: Set(
878                    resource_group.unwrap_or_else(|| DEFAULT_RESOURCE_GROUP.to_owned())
879                ),
880                ..Default::default()
881            }
882            .update(&txn)
883            .await?;
884
885        let obj = Object::find_by_id(database_id)
886            .one(&txn)
887            .await?
888            .ok_or_else(|| MetaError::catalog_id_not_found("database", database_id))?;
889
890        txn.commit().await?;
891
892        let version = self
893            .notify_frontend(
894                NotificationOperation::Update,
895                NotificationInfo::Database(ObjectModel(database, obj, None).into()),
896            )
897            .await;
898        Ok(version)
899    }
900
901    pub async fn alter_subscription_retention(
902        &self,
903        subscription_id: SubscriptionId,
904        retention_seconds: u64,
905        definition: String,
906    ) -> MetaResult<(NotificationVersion, PbSubscription)> {
907        let inner = self.inner.write().await;
908        let txn = inner.db.begin().await?;
909
910        let obj = Object::find_by_id(subscription_id)
911            .one(&txn)
912            .await?
913            .ok_or_else(|| MetaError::catalog_id_not_found("subscription", subscription_id))?;
914
915        let active_model = subscription::ActiveModel {
916            subscription_id: Set(subscription_id),
917            retention_seconds: Set(retention_seconds as i64),
918            definition: Set(definition),
919            ..Default::default()
920        };
921        let subscription = active_model.update(&txn).await?;
922
923        txn.commit().await?;
924
925        let pb_subscription: PbSubscription = ObjectModel(subscription, obj, None).into();
926        let subscription_info = PbObjectInfo::Subscription(pb_subscription.clone());
927
928        let version = self
929            .notify_frontend(
930                NotificationOperation::Update,
931                NotificationInfo::ObjectGroup(PbObjectGroup {
932                    objects: vec![PbObject {
933                        object_info: Some(subscription_info),
934                    }],
935                    dependencies: vec![],
936                }),
937            )
938            .await;
939
940        Ok((version, pb_subscription))
941    }
942
943    pub async fn alter_streaming_job_config(
944        &self,
945        job_id: JobId,
946        entries_to_add: HashMap<String, String>,
947        keys_to_remove: Vec<String>,
948    ) -> MetaResult<NotificationVersion> {
949        let updates_cache_refill_policy = entries_to_add
950            .contains_key(STREAMING_CACHE_REFILL_POLICY_CONFIG_PATH)
951            || keys_to_remove
952                .iter()
953                .any(|key| key == STREAMING_CACHE_REFILL_POLICY_CONFIG_PATH);
954
955        let inner = self.inner.write().await;
956        let txn = inner.db.begin().await?;
957
958        let config_override: Option<String> = StreamingJob::find_by_id(job_id)
959            .select_only()
960            .column(streaming_job::Column::ConfigOverride)
961            .into_tuple()
962            .one(&txn)
963            .await?
964            .ok_or_else(|| MetaError::catalog_id_not_found("streaming job", job_id))?;
965        let config_override = config_override.unwrap_or_default();
966
967        let mut table: toml::Table =
968            toml::from_str(&config_override).context("invalid streaming job config")?;
969
970        // The frontend guarantees that there's no duplicated keys in `to_add` and `to_remove`.
971        for (key, value) in entries_to_add {
972            let value: toml::Value = value
973                .parse()
974                .with_context(|| format!("invalid config value for path {key}"))?;
975            table
976                .upsert(&key, value)
977                .with_context(|| format!("failed to set config path {key}"))?;
978        }
979        for key in keys_to_remove {
980            table
981                .delete(&key)
982                .with_context(|| format!("failed to reset config path {key}"))?;
983        }
984
985        let updated_config_override = table.to_string();
986
987        // Validate the config override by trying to merge it to the default config.
988        let merged =
989            merge_streaming_config_section(&StreamingConfig::default(), &updated_config_override)
990                .context("invalid streaming job config override")?;
991
992        // Reject unrecognized entries.
993        // Note: If these unrecognized entries are pre-existing, we also reject them here.
994        // Users are able to fix them by issuing a `RESET` first.
995        if let Some(merged) = &merged {
996            let unrecognized_keys = merged.unrecognized_keys().collect_vec();
997            if !unrecognized_keys.is_empty() {
998                bail_invalid_parameter!("unrecognized configs: {:?}", unrecognized_keys);
999            }
1000        }
1001
1002        StreamingJob::update(streaming_job::ActiveModel {
1003            job_id: Set(job_id),
1004            config_override: Set(Some(updated_config_override)),
1005            ..Default::default()
1006        })
1007        .exec(&txn)
1008        .await?;
1009
1010        txn.commit().await?;
1011        drop(inner);
1012
1013        if updates_cache_refill_policy {
1014            let policies = self.table_cache_refill_policies_snapshot().await?;
1015            self.env
1016                .notification_manager()
1017                .notify_hummock(
1018                    NotificationOperation::Update,
1019                    NotificationInfo::TableRefillRuntimeConfig(PbTableRefillRuntimeConfig {
1020                        table_cache_refill_policies: Some(policies),
1021                        ..Default::default()
1022                    }),
1023                )
1024                .await;
1025        }
1026
1027        Ok(IGNORED_NOTIFICATION_VERSION)
1028    }
1029
1030    pub async fn ensure_refresh_job(&self, table_id: TableId) -> MetaResult<()> {
1031        let inner = self.inner.read().await;
1032        let active = refresh_job::ActiveModel {
1033            table_id: Set(table_id),
1034            last_trigger_time: Set(None),
1035            trigger_interval_secs: Set(None),
1036            current_status: Set(RefreshState::Idle),
1037            last_success_time: Set(None),
1038        };
1039        match RefreshJob::insert(active)
1040            .on_conflict_do_nothing()
1041            .exec(&inner.db)
1042            .await
1043        {
1044            Ok(_) => Ok(()),
1045            Err(sea_orm::DbErr::RecordNotInserted) => {
1046                // This is expected when the refresh job already exists due to ON CONFLICT DO NOTHING
1047                tracing::debug!("refresh job already exists for table_id={}", table_id);
1048                Ok(())
1049            }
1050            Err(e) => {
1051                if should_skip_refresh_job_db_err(&inner.db, table_id, &e).await? {
1052                    tracing::warn!(
1053                        %table_id,
1054                        error = %e.as_report(),
1055                        "skip ensure_refresh_job for stale dropped table"
1056                    );
1057                    Ok(())
1058                } else {
1059                    Err(e.into())
1060                }
1061            }
1062        }
1063    }
1064
1065    pub async fn update_refresh_job_status(
1066        &self,
1067        table_id: TableId,
1068        status: RefreshState,
1069        trigger_time: Option<DateTime>,
1070        is_success: bool,
1071    ) -> MetaResult<()> {
1072        self.ensure_refresh_job(table_id).await?;
1073        let inner = self.inner.read().await;
1074
1075        // expect only update trigger_time when the status changes to Refreshing
1076        assert_eq!(trigger_time.is_some(), status == RefreshState::Refreshing);
1077        let active = refresh_job::ActiveModel {
1078            table_id: Set(table_id),
1079            current_status: Set(status),
1080            last_trigger_time: if trigger_time.is_some() {
1081                Set(trigger_time.map(datetime_to_timestamp_millis))
1082            } else {
1083                NotSet
1084            },
1085            last_success_time: if is_success {
1086                Set(Some(chrono::Utc::now().timestamp_millis()))
1087            } else {
1088                NotSet
1089            },
1090            ..Default::default()
1091        };
1092        match RefreshJob::update(active).exec(&inner.db).await {
1093            Ok(_) => Ok(()),
1094            Err(e) => {
1095                if should_skip_refresh_job_db_err(&inner.db, table_id, &e).await? {
1096                    tracing::warn!(
1097                        %table_id,
1098                        error = %e.as_report(),
1099                        "skip update_refresh_job_status for stale dropped table"
1100                    );
1101                    Ok(())
1102                } else {
1103                    Err(e.into())
1104                }
1105            }
1106        }
1107    }
1108
1109    pub async fn reset_all_refresh_jobs_to_idle(&self) -> MetaResult<()> {
1110        let inner = self.inner.read().await;
1111        RefreshJob::update_many()
1112            .col_expr(
1113                refresh_job::Column::CurrentStatus,
1114                Expr::value(RefreshState::Idle),
1115            )
1116            .exec(&inner.db)
1117            .await?;
1118        Ok(())
1119    }
1120
1121    pub async fn update_refresh_job_interval(
1122        &self,
1123        table_id: TableId,
1124        trigger_interval_secs: Option<i64>,
1125    ) -> MetaResult<()> {
1126        self.ensure_refresh_job(table_id).await?;
1127        let inner = self.inner.read().await;
1128        let active = refresh_job::ActiveModel {
1129            table_id: Set(table_id),
1130            trigger_interval_secs: Set(trigger_interval_secs),
1131            ..Default::default()
1132        };
1133        RefreshJob::update(active).exec(&inner.db).await?;
1134        Ok(())
1135    }
1136}
1137
1138async fn should_skip_refresh_job_db_err<C>(
1139    db: &C,
1140    table_id: TableId,
1141    err: &sea_orm::DbErr,
1142) -> MetaResult<bool>
1143where
1144    C: ConnectionTrait,
1145{
1146    if matches!(err, sea_orm::DbErr::RecordNotUpdated) {
1147        return Ok(true);
1148    }
1149
1150    if !matches!(
1151        err.sql_err(),
1152        Some(SqlErr::ForeignKeyConstraintViolation(_))
1153    ) {
1154        return Ok(false);
1155    }
1156
1157    let table_exists = Table::find_by_id(table_id).one(db).await?.is_some();
1158    Ok(!table_exists)
1159}