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::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
781                    .is_in(drop_table_connector_ctx.to_remove_state_table_ids.clone()),
782            )
783            .into_partial_model()
784            .all(txn)
785            .await?;
786        let to_drop_objects = to_drop_source_objects
787            .into_iter()
788            .chain(to_drop_internal_table_objs)
789            .collect_vec();
790        // Find affect users with privileges on all this objects.
791        let to_update_user_ids: Vec<UserId> = UserPrivilege::find()
792            .select_only()
793            .distinct()
794            .column(user_privilege::Column::UserId)
795            .filter(user_privilege::Column::Oid.is_in(to_drop_objects.iter().map(|obj| obj.oid)))
796            .into_tuple()
797            .all(txn)
798            .await?;
799
800        tracing::debug!(
801            "drop_table_associated_source: to_drop_objects: {:?}",
802            to_drop_objects
803        );
804
805        // delete all in to_drop_objects.
806        let res = Object::delete_many()
807            .filter(object::Column::Oid.is_in(to_drop_objects.iter().map(|obj| obj.oid)))
808            .exec(txn)
809            .await?;
810        if res.rows_affected == 0 {
811            return Err(MetaError::catalog_id_not_found(
812                ObjectType::Source.as_str(),
813                drop_table_connector_ctx.to_remove_source_id,
814            ));
815        }
816        let user_infos = list_user_info_by_ids(to_update_user_ids, txn).await?;
817
818        Ok((user_infos, to_drop_objects))
819    }
820
821    pub async fn alter_database_param(
822        &self,
823        database_id: DatabaseId,
824        param: AlterDatabaseParam,
825    ) -> MetaResult<(NotificationVersion, risingwave_meta_model::database::Model)> {
826        let inner = self.inner.write().await;
827        let txn = inner.db.begin().await?;
828
829        let mut database = database::ActiveModel {
830            database_id: Set(database_id),
831            ..Default::default()
832        };
833        match param {
834            AlterDatabaseParam::BarrierIntervalMs(interval) => {
835                if let Some(ref interval) = interval {
836                    OverrideValidate::barrier_interval_ms(interval)
837                        .map_err(|e| anyhow::anyhow!(e))?;
838                }
839                database.barrier_interval_ms = Set(interval.map(|i| i as i32));
840            }
841            AlterDatabaseParam::CheckpointFrequency(frequency) => {
842                if let Some(ref frequency) = frequency {
843                    OverrideValidate::checkpoint_frequency(frequency)
844                        .map_err(|e| anyhow::anyhow!(e))?;
845                }
846                database.checkpoint_frequency = Set(frequency.map(|f| f as i64));
847            }
848        }
849        let database = database.update(&txn).await?;
850
851        let obj = Object::find_by_id(database_id)
852            .one(&txn)
853            .await?
854            .ok_or_else(|| MetaError::catalog_id_not_found("database", database_id))?;
855
856        txn.commit().await?;
857
858        let version = self
859            .notify_frontend(
860                NotificationOperation::Update,
861                NotificationInfo::Database(ObjectModel(database.clone(), obj, None).into()),
862            )
863            .await;
864        Ok((version, database))
865    }
866
867    pub async fn alter_database_resource_group(
868        &self,
869        database_id: DatabaseId,
870        resource_group: Option<String>,
871    ) -> MetaResult<NotificationVersion> {
872        let inner = self.inner.write().await;
873        let txn = inner.db.begin().await?;
874
875        let database =
876            database::ActiveModel {
877                database_id: Set(database_id),
878                resource_group: Set(
879                    resource_group.unwrap_or_else(|| DEFAULT_RESOURCE_GROUP.to_owned())
880                ),
881                ..Default::default()
882            }
883            .update(&txn)
884            .await?;
885
886        let obj = Object::find_by_id(database_id)
887            .one(&txn)
888            .await?
889            .ok_or_else(|| MetaError::catalog_id_not_found("database", database_id))?;
890
891        txn.commit().await?;
892
893        let version = self
894            .notify_frontend(
895                NotificationOperation::Update,
896                NotificationInfo::Database(ObjectModel(database, obj, None).into()),
897            )
898            .await;
899        Ok(version)
900    }
901
902    pub async fn alter_subscription_retention(
903        &self,
904        subscription_id: SubscriptionId,
905        retention_seconds: u64,
906        definition: String,
907    ) -> MetaResult<(NotificationVersion, PbSubscription)> {
908        let inner = self.inner.write().await;
909        let txn = inner.db.begin().await?;
910
911        let obj = Object::find_by_id(subscription_id)
912            .one(&txn)
913            .await?
914            .ok_or_else(|| MetaError::catalog_id_not_found("subscription", subscription_id))?;
915
916        let active_model = subscription::ActiveModel {
917            subscription_id: Set(subscription_id),
918            retention_seconds: Set(retention_seconds as i64),
919            definition: Set(definition),
920            ..Default::default()
921        };
922        let subscription = active_model.update(&txn).await?;
923
924        txn.commit().await?;
925
926        let pb_subscription: PbSubscription = ObjectModel(subscription, obj, None).into();
927        let subscription_info = PbObjectInfo::Subscription(pb_subscription.clone());
928
929        let version = self
930            .notify_frontend(
931                NotificationOperation::Update,
932                NotificationInfo::ObjectGroup(PbObjectGroup {
933                    objects: vec![PbObject {
934                        object_info: Some(subscription_info),
935                    }],
936                    dependencies: vec![],
937                }),
938            )
939            .await;
940
941        Ok((version, pb_subscription))
942    }
943
944    pub async fn alter_streaming_job_config(
945        &self,
946        job_id: JobId,
947        entries_to_add: HashMap<String, String>,
948        keys_to_remove: Vec<String>,
949    ) -> MetaResult<NotificationVersion> {
950        let updates_cache_refill_policy = entries_to_add
951            .contains_key(STREAMING_CACHE_REFILL_POLICY_CONFIG_PATH)
952            || keys_to_remove
953                .iter()
954                .any(|key| key == STREAMING_CACHE_REFILL_POLICY_CONFIG_PATH);
955
956        let inner = self.inner.write().await;
957        let txn = inner.db.begin().await?;
958
959        let config_override: Option<String> = StreamingJob::find_by_id(job_id)
960            .select_only()
961            .column(streaming_job::Column::ConfigOverride)
962            .into_tuple()
963            .one(&txn)
964            .await?
965            .ok_or_else(|| MetaError::catalog_id_not_found("streaming job", job_id))?;
966        let config_override = config_override.unwrap_or_default();
967
968        let mut table: toml::Table =
969            toml::from_str(&config_override).context("invalid streaming job config")?;
970
971        // The frontend guarantees that there's no duplicated keys in `to_add` and `to_remove`.
972        for (key, value) in entries_to_add {
973            let value: toml::Value = value
974                .parse()
975                .with_context(|| format!("invalid config value for path {key}"))?;
976            table
977                .upsert(&key, value)
978                .with_context(|| format!("failed to set config path {key}"))?;
979        }
980        for key in keys_to_remove {
981            table
982                .delete(&key)
983                .with_context(|| format!("failed to reset config path {key}"))?;
984        }
985
986        let updated_config_override = table.to_string();
987
988        // Validate the config override by trying to merge it to the default config.
989        let merged =
990            merge_streaming_config_section(&StreamingConfig::default(), &updated_config_override)
991                .context("invalid streaming job config override")?;
992
993        // Reject unrecognized entries.
994        // Note: If these unrecognized entries are pre-existing, we also reject them here.
995        // Users are able to fix them by issuing a `RESET` first.
996        if let Some(merged) = &merged {
997            let unrecognized_keys = merged.unrecognized_keys().collect_vec();
998            if !unrecognized_keys.is_empty() {
999                bail_invalid_parameter!("unrecognized configs: {:?}", unrecognized_keys);
1000            }
1001        }
1002
1003        StreamingJob::update(streaming_job::ActiveModel {
1004            job_id: Set(job_id),
1005            config_override: Set(Some(updated_config_override)),
1006            ..Default::default()
1007        })
1008        .exec(&txn)
1009        .await?;
1010
1011        txn.commit().await?;
1012        drop(inner);
1013
1014        if updates_cache_refill_policy {
1015            let policies = self.table_cache_refill_policies_snapshot().await?;
1016            self.env.notification_manager().notify_hummock(
1017                NotificationOperation::Update,
1018                NotificationInfo::TableRefillRuntimeConfig(PbTableRefillRuntimeConfig {
1019                    table_cache_refill_policies: Some(policies),
1020                    ..Default::default()
1021                }),
1022            );
1023        }
1024
1025        Ok(IGNORED_NOTIFICATION_VERSION)
1026    }
1027
1028    pub async fn ensure_refresh_job(&self, table_id: TableId) -> MetaResult<()> {
1029        let inner = self.inner.read().await;
1030        let active = refresh_job::ActiveModel {
1031            table_id: Set(table_id),
1032            last_trigger_time: Set(None),
1033            trigger_interval_secs: Set(None),
1034            current_status: Set(RefreshState::Idle),
1035            last_success_time: Set(None),
1036        };
1037        match RefreshJob::insert(active)
1038            .on_conflict_do_nothing()
1039            .exec(&inner.db)
1040            .await
1041        {
1042            Ok(_) => Ok(()),
1043            Err(sea_orm::DbErr::RecordNotInserted) => {
1044                // This is expected when the refresh job already exists due to ON CONFLICT DO NOTHING
1045                tracing::debug!("refresh job already exists for table_id={}", table_id);
1046                Ok(())
1047            }
1048            Err(e) => {
1049                if should_skip_refresh_job_db_err(&inner.db, table_id, &e).await? {
1050                    tracing::warn!(
1051                        %table_id,
1052                        error = %e.as_report(),
1053                        "skip ensure_refresh_job for stale dropped table"
1054                    );
1055                    Ok(())
1056                } else {
1057                    Err(e.into())
1058                }
1059            }
1060        }
1061    }
1062
1063    /// Moves an idle refresh job to `Refreshing`, recording `trigger_time` as the cycle id.
1064    /// Returns false if the job is not idle.
1065    pub async fn begin_refresh_job(
1066        &self,
1067        table_id: TableId,
1068        trigger_time: DateTime,
1069    ) -> MetaResult<bool> {
1070        self.ensure_refresh_job(table_id).await?;
1071        let inner = self.inner.read().await;
1072        let res = RefreshJob::update_many()
1073            .col_expr(
1074                refresh_job::Column::CurrentStatus,
1075                Expr::value(RefreshState::Refreshing),
1076            )
1077            .col_expr(
1078                refresh_job::Column::LastTriggerTime,
1079                Expr::value(Some(datetime_to_timestamp_millis(trigger_time))),
1080            )
1081            .filter(refresh_job::Column::TableId.eq(table_id))
1082            .filter(refresh_job::Column::CurrentStatus.eq(RefreshState::Idle))
1083            .exec(&inner.db)
1084            .await?;
1085        Ok(res.rows_affected == 1)
1086    }
1087
1088    /// Moves the refresh cycle started at `trigger_time` back to `Idle`. Returns false if the job
1089    /// is no longer in that cycle (already finished, or the table was dropped).
1090    pub async fn finish_refresh_job(
1091        &self,
1092        table_id: TableId,
1093        trigger_time: DateTime,
1094        success: bool,
1095    ) -> MetaResult<bool> {
1096        let inner = self.inner.read().await;
1097        let mut update = RefreshJob::update_many().col_expr(
1098            refresh_job::Column::CurrentStatus,
1099            Expr::value(RefreshState::Idle),
1100        );
1101        if success {
1102            update = update.col_expr(
1103                refresh_job::Column::LastSuccessTime,
1104                Expr::value(Some(chrono::Utc::now().timestamp_millis())),
1105            );
1106        }
1107        let res = update
1108            .filter(refresh_job::Column::TableId.eq(table_id))
1109            .filter(refresh_job::Column::CurrentStatus.ne(RefreshState::Idle))
1110            .filter(
1111                refresh_job::Column::LastTriggerTime
1112                    .eq(Some(datetime_to_timestamp_millis(trigger_time))),
1113            )
1114            .exec(&inner.db)
1115            .await?;
1116        Ok(res.rows_affected == 1)
1117    }
1118
1119    pub async fn update_refresh_job_interval(
1120        &self,
1121        table_id: TableId,
1122        trigger_interval_secs: Option<i64>,
1123    ) -> MetaResult<()> {
1124        self.ensure_refresh_job(table_id).await?;
1125        let inner = self.inner.read().await;
1126        let active = refresh_job::ActiveModel {
1127            table_id: Set(table_id),
1128            trigger_interval_secs: Set(trigger_interval_secs),
1129            ..Default::default()
1130        };
1131        RefreshJob::update(active).exec(&inner.db).await?;
1132        Ok(())
1133    }
1134}
1135
1136async fn should_skip_refresh_job_db_err<C>(
1137    db: &C,
1138    table_id: TableId,
1139    err: &sea_orm::DbErr,
1140) -> MetaResult<bool>
1141where
1142    C: ConnectionTrait,
1143{
1144    if matches!(err, sea_orm::DbErr::RecordNotUpdated) {
1145        return Ok(true);
1146    }
1147
1148    if !matches!(
1149        err.sql_err(),
1150        Some(SqlErr::ForeignKeyConstraintViolation(_))
1151    ) {
1152        return Ok(false);
1153    }
1154
1155    let table_exists = Table::find_by_id(table_id).one(db).await?.is_some();
1156    Ok(!table_exists)
1157}