Skip to main content

risingwave_meta/controller/catalog/
create_op.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use risingwave_common::cast::datetime_to_timestamp_millis;
16use risingwave_common::system_param::{OverrideValidate, Validate};
17use risingwave_common::util::epoch::Epoch;
18use risingwave_pb::common::PbObjectType;
19use risingwave_pb::meta::PbObjectDependency;
20
21use super::*;
22
23impl CatalogController {
24    pub(crate) async fn create_object(
25        txn: &DatabaseTransaction,
26        obj_type: ObjectType,
27        owner_id: UserId,
28        belong_to_oid: Option<ObjectId>,
29    ) -> MetaResult<object::Model> {
30        let (database_id, schema_id) = match (obj_type, belong_to_oid) {
31            (ObjectType::Database, None) => (None, None),
32            (ObjectType::Database, Some(_)) => {
33                return Err(MetaError::invalid_parameter(
34                    "database object must not have a parent",
35                ));
36            }
37            (ObjectType::Schema, Some(database_oid)) => {
38                let database = Object::find_by_id(database_oid)
39                    .one(txn)
40                    .await?
41                    .ok_or_else(|| MetaError::catalog_id_not_found("database", database_oid))?;
42                if database.obj_type != ObjectType::Database {
43                    return Err(MetaError::invalid_parameter(
44                        "schema object must belong to a database",
45                    ));
46                }
47                (Some(database_oid.as_database_id()), None)
48            }
49            (ObjectType::Schema, None) => {
50                return Err(MetaError::invalid_parameter(
51                    "schema object must belong to a database",
52                ));
53            }
54            (_, Some(parent_oid)) => {
55                let parent = Object::find_by_id(parent_oid)
56                    .one(txn)
57                    .await?
58                    .ok_or_else(|| MetaError::catalog_id_not_found("parent object", parent_oid))?;
59                if parent.obj_type == ObjectType::Schema {
60                    (parent.database_id, Some(parent.oid.as_schema_id()))
61                } else {
62                    (parent.database_id, parent.schema_id)
63                }
64            }
65            (_, None) => {
66                return Err(MetaError::invalid_parameter(
67                    "non-database object must have a parent",
68                ));
69            }
70        };
71        let active_db = object::ActiveModel {
72            oid: Default::default(),
73            obj_type: Set(obj_type),
74            owner_id: Set(owner_id),
75            schema_id: Set(schema_id),
76            database_id: Set(database_id),
77            belong_to_oid: Set(belong_to_oid),
78            initialized_at: Default::default(),
79            created_at: Default::default(),
80            initialized_at_cluster_version: Set(Some(current_cluster_version())),
81            created_at_cluster_version: Set(Some(current_cluster_version())),
82        };
83        Ok(active_db.insert(txn).await?)
84    }
85
86    pub async fn create_database(
87        &self,
88        db: PbDatabase,
89    ) -> MetaResult<(NotificationVersion, risingwave_meta_model::database::Model)> {
90        // validate first
91        if let Some(ref interval) = db.barrier_interval_ms {
92            OverrideValidate::barrier_interval_ms(interval).map_err(|e| anyhow::anyhow!(e))?;
93        }
94        if let Some(ref frequency) = db.checkpoint_frequency {
95            OverrideValidate::checkpoint_frequency(frequency).map_err(|e| anyhow::anyhow!(e))?;
96        }
97
98        let inner = self.inner.write().await;
99        let owner_id = db.owner as _;
100        let txn = inner.db.begin().await?;
101        ensure_user_id(owner_id, &txn).await?;
102        check_database_name_duplicate(&db.name, &txn).await?;
103
104        let db_obj = Self::create_object(&txn, ObjectType::Database, owner_id, None).await?;
105        let mut db: database::ActiveModel = db.into();
106        db.database_id = Set(db_obj.oid.as_database_id());
107        let db = db.insert(&txn).await?;
108
109        let mut schemas = vec![];
110        for schema_name in iter::once(DEFAULT_SCHEMA_NAME).chain(SYSTEM_SCHEMAS) {
111            let schema_obj =
112                Self::create_object(&txn, ObjectType::Schema, owner_id, Some(db_obj.oid)).await?;
113            let schema = schema::ActiveModel {
114                schema_id: Set(schema_obj.oid.as_schema_id()),
115                name: Set(schema_name.into()),
116            };
117            let schema = schema.insert(&txn).await?;
118            schemas.push(ObjectModel(schema, schema_obj, None).into());
119        }
120        txn.commit().await?;
121
122        let mut notifications = self.frontend_notification_batch();
123        notifications.add(
124            NotificationOperation::Add,
125            NotificationInfo::Database(ObjectModel(db.clone(), db_obj, None).into()),
126        );
127        for schema in schemas {
128            notifications.add(NotificationOperation::Add, NotificationInfo::Schema(schema));
129        }
130        let version = notifications
131            .publish()
132            .await
133            .expect("the database notification batch contains the database");
134
135        Ok((version, db))
136    }
137
138    pub async fn create_schema(&self, schema: PbSchema) -> MetaResult<NotificationVersion> {
139        let inner = self.inner.write().await;
140        let owner_id = schema.owner as _;
141        let txn = inner.db.begin().await?;
142        ensure_user_id(owner_id, &txn).await?;
143        ensure_object_id(ObjectType::Database, schema.database_id, &txn).await?;
144        check_schema_name_duplicate(&schema.name, schema.database_id, &txn).await?;
145
146        let schema_obj = Self::create_object(
147            &txn,
148            ObjectType::Schema,
149            owner_id,
150            Some(schema.database_id.as_object_id()),
151        )
152        .await?;
153        let mut schema: schema::ActiveModel = schema.into();
154        schema.schema_id = Set(schema_obj.oid.as_schema_id());
155        let schema = schema.insert(&txn).await?;
156
157        let updated_user_info =
158            grant_default_privileges_automatically(&txn, schema_obj.oid).await?;
159
160        txn.commit().await?;
161
162        let mut notifications = self.frontend_notification_batch();
163        notifications.add(
164            NotificationOperation::Add,
165            NotificationInfo::Schema(ObjectModel(schema, schema_obj, None).into()),
166        );
167
168        // notify default privileges for schemas
169        Self::add_users_update_notifications(&mut notifications, updated_user_info);
170        let version = notifications
171            .publish()
172            .await
173            .expect("the schema notification batch contains the schema");
174
175        Ok(version)
176    }
177
178    pub async fn create_subscription_catalog(
179        &self,
180        pb_subscription: &mut PbSubscription,
181    ) -> MetaResult<()> {
182        let inner = self.inner.write().await;
183        let txn = inner.db.begin().await?;
184
185        ensure_user_id(pb_subscription.owner as _, &txn).await?;
186        ensure_object_id(ObjectType::Database, pb_subscription.database_id, &txn).await?;
187        ensure_object_id(ObjectType::Schema, pb_subscription.schema_id, &txn).await?;
188        check_subscription_name_duplicate(pb_subscription, &txn).await?;
189
190        let obj = Self::create_object(
191            &txn,
192            ObjectType::Subscription,
193            pb_subscription.owner as _,
194            Some(pb_subscription.schema_id.as_object_id()),
195        )
196        .await?;
197        pb_subscription.id = obj.oid.as_subscription_id();
198        let subscription: subscription::ActiveModel = pb_subscription.clone().into();
199        Subscription::insert(subscription).exec(&txn).await?;
200
201        // record object dependency.
202        ObjectDependency::insert(object_dependency::ActiveModel {
203            oid: Set(pb_subscription.dependent_table_id.into()),
204            used_by: Set(pb_subscription.id.into()),
205            ..Default::default()
206        })
207        .exec(&txn)
208        .await?;
209        txn.commit().await?;
210        Ok(())
211    }
212
213    pub async fn create_cross_db_subscriptions(
214        &self,
215        downstream_job_id: JobId,
216        upstream_table_ids: impl IntoIterator<Item = TableId>,
217    ) -> MetaResult<Vec<CrossDbSubscriptionInfo>> {
218        let inner = self.inner.write().await;
219        let txn = inner.db.begin().await?;
220
221        let downstream_object = Object::find_by_id(downstream_job_id)
222            .one(&txn)
223            .await?
224            .ok_or_else(|| MetaError::catalog_id_not_found("streaming job", downstream_job_id))?;
225        let upstream_table_ids = upstream_table_ids.into_iter().collect::<HashSet<_>>();
226        let mut upstream_objects = Object::find()
227            .filter(
228                object::Column::Oid.is_in(
229                    upstream_table_ids
230                        .iter()
231                        .copied()
232                        .map(TableId::as_object_id),
233                ),
234            )
235            .all(&txn)
236            .await?;
237        if upstream_objects.len() != upstream_table_ids.len() {
238            return Err(MetaError::catalog_id_not_found(
239                "cross-database upstream table",
240                downstream_job_id,
241            ));
242        }
243        upstream_objects.sort_by_key(|object| object.oid);
244
245        let mut subscriptions = Vec::with_capacity(upstream_objects.len());
246        for upstream_object in upstream_objects {
247            if upstream_object.obj_type != ObjectType::Table {
248                return Err(MetaError::invalid_parameter(format!(
249                    "cross-database subscription upstream {} is not a table",
250                    upstream_object.oid
251                )));
252            }
253            let upstream_database_id = upstream_object.database_id.ok_or_else(|| {
254                anyhow!(
255                    "cross-database subscription upstream {} has no database",
256                    upstream_object.oid
257                )
258            })?;
259            let subscription_object = Self::create_object(
260                &txn,
261                ObjectType::Subscription,
262                downstream_object.owner_id,
263                Some(downstream_job_id.as_object_id()),
264            )
265            .await?;
266            let subscription = subscription::Model {
267                subscription_id: subscription_object.oid.as_subscription_id(),
268                name: format!(
269                    "__cross_db_subscription_{}_{}",
270                    downstream_job_id, upstream_object.oid
271                ),
272                retention_seconds: None,
273                definition: String::new(),
274                subscription_state: SubscriptionState::Init as i32,
275                dependent_table_id: upstream_object.oid.as_table_id(),
276                cross_db_downstream_job_id: Some(downstream_job_id),
277            };
278            Subscription::insert(subscription.clone().into_active_model())
279                .exec(&txn)
280                .await?;
281            subscriptions.push(CrossDbSubscriptionInfo {
282                subscription_id: subscription.subscription_id,
283                upstream_table_id: subscription.dependent_table_id,
284                upstream_database_id,
285            });
286        }
287        txn.commit().await?;
288        Ok(subscriptions)
289    }
290
291    pub async fn create_source(
292        &self,
293        mut pb_source: PbSource,
294        iceberg_table_id: Option<TableId>,
295    ) -> MetaResult<(SourceId, NotificationVersion)> {
296        let mut inner = self.inner.write().await;
297        let owner_id = pb_source.owner as _;
298        let txn = inner.db.begin().await?;
299        ensure_user_id(owner_id, &txn).await?;
300        ensure_object_id(ObjectType::Database, pb_source.database_id, &txn).await?;
301        ensure_object_id(ObjectType::Schema, pb_source.schema_id, &txn).await?;
302        check_relation_name_duplicate(
303            &pb_source.name,
304            pb_source.database_id,
305            pb_source.schema_id,
306            &txn,
307        )
308        .await?;
309
310        // handle secret ref
311        let secret_ids = get_referred_secret_ids_from_source(&pb_source)?;
312        let connection_ids = get_referred_connection_ids_from_source(&pb_source);
313        let cdc_source_id = pb_source
314            .info
315            .as_ref()
316            .and_then(|info| info.external_table.as_ref())
317            .map(|table| table.source_id);
318        if let Some(cdc_source_id) = cdc_source_id {
319            ensure_object_id(ObjectType::Source, cdc_source_id, &txn).await?;
320        }
321
322        let source_obj = Self::create_object(
323            &txn,
324            ObjectType::Source,
325            owner_id,
326            iceberg_table_id
327                .map(TableId::as_object_id)
328                .or(Some(pb_source.schema_id.as_object_id())),
329        )
330        .await?;
331        let source_id = source_obj.oid.as_source_id();
332        pb_source.id = source_id;
333        if let Some(external_table) = pb_source
334            .info
335            .as_mut()
336            .and_then(|info| info.external_table.as_mut())
337        {
338            external_table.table_id = source_id.as_cdc_table_id();
339            // The connect properties were only needed to validate the descriptor. Consumers
340            // resolve them from the upstream shared source when they are planned, so persisting
341            // a copy here would only make credentials and secret references stale after
342            // `ALTER SOURCE`.
343            external_table.connect_properties.clear();
344            external_table.secret_refs.clear();
345        }
346        let source: source::ActiveModel = pb_source.clone().into();
347        Source::insert(source).exec(&txn).await?;
348
349        // Add secret, connection, and upstream shared CDC source dependencies.
350        let dep_relation_ids = secret_ids
351            .iter()
352            .copied()
353            .map_into()
354            .chain(connection_ids.iter().copied().map_into())
355            .chain(cdc_source_id.map(|id| id.as_object_id()))
356            .collect_vec();
357        let dependencies = if !dep_relation_ids.is_empty() {
358            ObjectDependency::insert_many(dep_relation_ids.into_iter().map(|id| {
359                object_dependency::ActiveModel {
360                    oid: Set(id),
361                    used_by: Set(source_id.as_object_id()),
362                    ..Default::default()
363                }
364            }))
365            .exec(&txn)
366            .await?;
367            secret_ids
368                .iter()
369                .map(|id| PbObjectDependency {
370                    object_id: source_id.as_object_id(),
371                    referenced_object_id: id.as_object_id(),
372                    referenced_object_type: PbObjectType::Secret as _,
373                })
374                .chain(connection_ids.iter().map(|id| PbObjectDependency {
375                    object_id: source_id.as_object_id(),
376                    referenced_object_id: id.as_object_id(),
377                    referenced_object_type: PbObjectType::Connection as _,
378                }))
379                .chain(cdc_source_id.map(|id| PbObjectDependency {
380                    object_id: source_id.as_object_id(),
381                    referenced_object_id: id.as_object_id(),
382                    referenced_object_type: PbObjectType::Source as _,
383                }))
384                .collect_vec()
385        } else {
386            vec![]
387        };
388
389        let mut job_notifications = vec![];
390        let mut updated_user_info = vec![];
391        // check if it belongs to iceberg table
392        if let Some(table_id) = iceberg_table_id {
393            // 1. finish iceberg table job.
394            let table_notifications = self
395                .finish_streaming_job_inner(&txn, table_id.as_job_id())
396                .await?;
397            job_notifications.push((table_id.as_job_id(), table_notifications));
398
399            // 2. finish iceberg sink job.
400            let sink_id = Sink::find()
401                .select_only()
402                .column(sink::Column::SinkId)
403                .join(JoinType::InnerJoin, sink::Relation::Object.def())
404                .filter(
405                    object::Column::BelongToOid
406                        .eq(table_id)
407                        .and(object::Column::ObjType.eq(ObjectType::Sink)),
408                )
409                .into_tuple::<SinkId>()
410                .one(&txn)
411                .await?
412                .ok_or_else(|| {
413                    MetaError::catalog_id_not_found("iceberg sink for table", table_id)
414                })?;
415            let sink_job_id = sink_id.as_job_id();
416            let sink_notifications = self.finish_streaming_job_inner(&txn, sink_job_id).await?;
417            job_notifications.push((sink_job_id, sink_notifications));
418        } else {
419            updated_user_info = grant_default_privileges_automatically(&txn, source_id).await?;
420        }
421
422        txn.commit().await?;
423
424        let mut notifications = self.frontend_notification_batch();
425        let mut finished_job_ids = Vec::with_capacity(job_notifications.len());
426        for (job_id, (op, objects, user_info, dependencies)) in job_notifications {
427            notifications.add(
428                op,
429                NotificationInfo::ObjectGroup(PbObjectGroup {
430                    objects,
431                    dependencies,
432                }),
433            );
434            Self::add_users_update_notifications(&mut notifications, user_info);
435            finished_job_ids.push(job_id);
436        }
437
438        notifications.add(
439            NotificationOperation::Add,
440            NotificationInfo::ObjectGroup(PbObjectGroup {
441                objects: vec![PbObject {
442                    object_info: Some(PbObjectInfo::Source(pb_source)),
443                }],
444                dependencies,
445            }),
446        );
447
448        // notify default privileges for source
449        Self::add_users_update_notifications(&mut notifications, updated_user_info);
450        let version = notifications
451            .publish()
452            .await
453            .expect("the source notification batch contains the source");
454
455        for job_id in finished_job_ids {
456            inner
457                .creating_table_finish_notifier
458                .values_mut()
459                .for_each(|creating_tables| {
460                    if let Some(txs) = creating_tables.remove(&job_id) {
461                        for tx in txs {
462                            let _ = tx.send(Ok(version));
463                        }
464                    }
465                });
466        }
467
468        Ok((source_id, version))
469    }
470
471    pub async fn create_function(
472        &self,
473        mut pb_function: PbFunction,
474    ) -> MetaResult<NotificationVersion> {
475        let inner = self.inner.write().await;
476        let owner_id = pb_function.owner as _;
477        let txn = inner.db.begin().await?;
478        ensure_user_id(owner_id, &txn).await?;
479        ensure_object_id(ObjectType::Database, pb_function.database_id, &txn).await?;
480        ensure_object_id(ObjectType::Schema, pb_function.schema_id, &txn).await?;
481        check_function_signature_duplicate(&pb_function, &txn).await?;
482
483        let function_obj = Self::create_object(
484            &txn,
485            ObjectType::Function,
486            owner_id,
487            Some(pb_function.schema_id.as_object_id()),
488        )
489        .await?;
490        pb_function.id = function_obj.oid.as_function_id();
491        pb_function.created_at_epoch = Some(
492            Epoch::from_unix_millis(datetime_to_timestamp_millis(function_obj.created_at) as _).0,
493        );
494        pb_function.created_at_cluster_version = function_obj.created_at_cluster_version;
495        let function: function::ActiveModel = pb_function.clone().into();
496        Function::insert(function).exec(&txn).await?;
497
498        let updated_user_info =
499            grant_default_privileges_automatically(&txn, function_obj.oid).await?;
500
501        txn.commit().await?;
502
503        let mut notifications = self.frontend_notification_batch();
504        notifications.add(
505            NotificationOperation::Add,
506            NotificationInfo::Function(pb_function),
507        );
508
509        // notify default privileges for functions
510        Self::add_users_update_notifications(&mut notifications, updated_user_info);
511        let version = notifications
512            .publish()
513            .await
514            .expect("the function notification batch contains the function");
515
516        Ok(version)
517    }
518
519    pub async fn create_connection(
520        &self,
521        mut pb_connection: PbConnection,
522    ) -> MetaResult<NotificationVersion> {
523        let inner = self.inner.write().await;
524        let owner_id = pb_connection.owner as _;
525        let txn = inner.db.begin().await?;
526        ensure_user_id(owner_id, &txn).await?;
527        ensure_object_id(ObjectType::Database, pb_connection.database_id, &txn).await?;
528        ensure_object_id(ObjectType::Schema, pb_connection.schema_id, &txn).await?;
529        check_connection_name_duplicate(&pb_connection, &txn).await?;
530
531        let mut dep_secrets: HashSet<SecretId> = HashSet::new();
532        if let Some(ConnectionInfo::ConnectionParams(params)) = &pb_connection.info {
533            dep_secrets.extend(
534                params
535                    .secret_refs
536                    .values()
537                    .map(|secret_ref| secret_ref.secret_id),
538            );
539        }
540
541        let conn_obj = Self::create_object(
542            &txn,
543            ObjectType::Connection,
544            owner_id,
545            Some(pb_connection.schema_id.as_object_id()),
546        )
547        .await?;
548        pb_connection.id = conn_obj.oid.as_connection_id();
549        let connection: connection::ActiveModel = pb_connection.clone().into();
550        Connection::insert(connection).exec(&txn).await?;
551
552        for secret_id in &dep_secrets {
553            ObjectDependency::insert(object_dependency::ActiveModel {
554                oid: Set(secret_id.as_object_id()),
555                used_by: Set(conn_obj.oid),
556                ..Default::default()
557            })
558            .exec(&txn)
559            .await?;
560        }
561
562        let updated_user_info = grant_default_privileges_automatically(&txn, conn_obj.oid).await?;
563
564        txn.commit().await?;
565
566        {
567            // call meta telemetry here to report the connection creation
568            report_event(
569                PbTelemetryEventStage::Unspecified,
570                "connection_create",
571                pb_connection.get_id().as_raw_id() as i64,
572                {
573                    pb_connection.info.as_ref().and_then(|info| match info {
574                        ConnectionInfo::ConnectionParams(params) => {
575                            Some(params.connection_type().as_str_name().to_owned())
576                        }
577                        _ => None,
578                    })
579                },
580                None,
581                None,
582            );
583        }
584
585        let mut notifications = self.frontend_notification_batch();
586        notifications.add(
587            NotificationOperation::Add,
588            NotificationInfo::ObjectGroup(PbObjectGroup {
589                objects: vec![PbObject {
590                    object_info: Some(PbObjectInfo::Connection(pb_connection)),
591                }],
592                dependencies: dep_secrets
593                    .iter()
594                    .map(|secret_id| PbObjectDependency {
595                        object_id: conn_obj.oid,
596                        referenced_object_id: secret_id.as_object_id(),
597                        referenced_object_type: PbObjectType::Secret as _,
598                    })
599                    .collect(),
600            }),
601        );
602
603        // notify default privileges for connections
604        Self::add_users_update_notifications(&mut notifications, updated_user_info);
605        let version = notifications
606            .publish()
607            .await
608            .expect("the connection notification batch contains the connection");
609
610        Ok(version)
611    }
612
613    pub async fn create_secret(
614        &self,
615        mut pb_secret: PbSecret,
616        secret_plain_payload: Vec<u8>,
617    ) -> MetaResult<NotificationVersion> {
618        let inner = self.inner.write().await;
619        let owner_id = pb_secret.owner as _;
620        let txn = inner.db.begin().await?;
621        ensure_user_id(owner_id, &txn).await?;
622        ensure_object_id(ObjectType::Database, pb_secret.database_id, &txn).await?;
623        ensure_object_id(ObjectType::Schema, pb_secret.schema_id, &txn).await?;
624        check_secret_name_duplicate(&pb_secret, &txn).await?;
625
626        let secret_obj = Self::create_object(
627            &txn,
628            ObjectType::Secret,
629            owner_id,
630            Some(pb_secret.schema_id.as_object_id()),
631        )
632        .await?;
633        pb_secret.id = secret_obj.oid.as_secret_id();
634        let secret: secret::ActiveModel = pb_secret.clone().into();
635        Secret::insert(secret).exec(&txn).await?;
636
637        let updated_user_info =
638            grant_default_privileges_automatically(&txn, secret_obj.oid).await?;
639
640        txn.commit().await?;
641
642        // Notify the compute and frontend node plain secret
643        let mut secret_plain = pb_secret;
644        secret_plain.value.clone_from(&secret_plain_payload);
645
646        LocalSecretManager::global().add_secret(secret_plain.id, secret_plain_payload);
647        self.env
648            .notification_manager()
649            .notify_compute_without_version(Operation::Add, Info::Secret(secret_plain.clone()));
650
651        let mut notifications = self.frontend_notification_batch();
652        notifications.add(
653            NotificationOperation::Add,
654            NotificationInfo::Secret(secret_plain),
655        );
656
657        // notify default privileges for secrets
658        Self::add_users_update_notifications(&mut notifications, updated_user_info);
659        let version = notifications
660            .publish()
661            .await
662            .expect("the secret notification batch contains the secret");
663
664        Ok(version)
665    }
666
667    pub async fn create_view(
668        &self,
669        mut pb_view: PbView,
670        dependencies: HashSet<ObjectId>,
671    ) -> MetaResult<NotificationVersion> {
672        let inner = self.inner.write().await;
673        let owner_id = pb_view.owner as _;
674        let txn = inner.db.begin().await?;
675        ensure_user_id(owner_id, &txn).await?;
676        ensure_object_id(ObjectType::Database, pb_view.database_id, &txn).await?;
677        ensure_object_id(ObjectType::Schema, pb_view.schema_id, &txn).await?;
678        check_relation_name_duplicate(&pb_view.name, pb_view.database_id, pb_view.schema_id, &txn)
679            .await?;
680        ensure_object_id(ObjectType::Schema, pb_view.schema_id, &txn).await?;
681        check_relation_name_duplicate(&pb_view.name, pb_view.database_id, pb_view.schema_id, &txn)
682            .await?;
683
684        let view_obj = Self::create_object(
685            &txn,
686            ObjectType::View,
687            owner_id,
688            Some(pb_view.schema_id.as_object_id()),
689        )
690        .await?;
691        pb_view.id = view_obj.oid.as_view_id();
692        pb_view.created_at_epoch =
693            Some(Epoch::from_unix_millis(datetime_to_timestamp_millis(view_obj.created_at) as _).0);
694        pb_view.created_at_cluster_version = view_obj.created_at_cluster_version;
695
696        let view: view::ActiveModel = pb_view.clone().into();
697        View::insert(view).exec(&txn).await?;
698
699        let dependencies = if !dependencies.is_empty() {
700            ObjectDependency::insert_many(dependencies.into_iter().map(|obj_id| {
701                object_dependency::ActiveModel {
702                    oid: Set(obj_id),
703                    used_by: Set(view_obj.oid),
704                    ..Default::default()
705                }
706            }))
707            .exec(&txn)
708            .await?;
709            list_object_dependencies_by_object_id(&txn, view_obj.oid).await?
710        } else {
711            vec![]
712        };
713
714        let updated_user_info = grant_default_privileges_automatically(&txn, view_obj.oid).await?;
715
716        txn.commit().await?;
717        let mut notifications = self.frontend_notification_batch();
718        notifications.add(
719            NotificationOperation::Add,
720            NotificationInfo::ObjectGroup(PbObjectGroup {
721                objects: vec![PbObject {
722                    object_info: Some(PbObjectInfo::View(pb_view)),
723                }],
724                dependencies,
725            }),
726        );
727
728        // notify default privileges for views
729        Self::add_users_update_notifications(&mut notifications, updated_user_info);
730        let version = notifications
731            .publish()
732            .await
733            .expect("the view notification batch contains the view");
734
735        Ok(version)
736    }
737}