Skip to main content

risingwave_frontend/catalog/
schema_catalog.rs

1// Copyright 2022 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 std::collections::hash_map::Entry::{Occupied, Vacant};
16use std::collections::{HashMap, HashSet};
17use std::sync::Arc;
18
19use itertools::Itertools;
20use risingwave_common::catalog::{
21    FunctionId, IndexId, ObjectId, StreamJobStatus, TableId, is_system_schema,
22};
23use risingwave_common::types::DataType;
24use risingwave_connector::sink::catalog::SinkCatalog;
25pub use risingwave_expr::sig::*;
26use risingwave_pb::catalog::{
27    PbConnection, PbFunction, PbIndex, PbSchema, PbSecret, PbSink, PbSource, PbSubscription,
28    PbTable, PbView,
29};
30use risingwave_pb::user::grant_privilege::Object;
31
32use super::subscription_catalog::SubscriptionCatalog;
33use super::{OwnedByUserCatalog, OwnedGrantObject, SubscriptionId};
34use crate::catalog::connection_catalog::ConnectionCatalog;
35use crate::catalog::function_catalog::FunctionCatalog;
36use crate::catalog::index_catalog::IndexCatalog;
37use crate::catalog::secret_catalog::SecretCatalog;
38use crate::catalog::source_catalog::SourceCatalog;
39use crate::catalog::system_catalog::SystemTableCatalog;
40use crate::catalog::table_catalog::TableCatalog;
41use crate::catalog::view_catalog::ViewCatalog;
42use crate::catalog::{
43    ConnectionId, DatabaseId, RelationKind, SchemaId, SecretId, SinkId, SourceId, ViewId,
44};
45use crate::expr::{Expr, ExprImpl, infer_type_name, infer_type_with_sigmap};
46use crate::user::user_catalog::UserCatalog;
47use crate::user::{UserId, has_access_to_object};
48
49#[derive(Clone, Debug)]
50pub struct SchemaCatalog {
51    id: SchemaId,
52    pub name: String,
53    pub database_id: DatabaseId,
54    /// Contains [all types of "tables"](super::table_catalog::TableType), not only user tables.
55    table_by_name: HashMap<String, Arc<TableCatalog>>,
56    /// Contains [all types of "tables"](super::table_catalog::TableType), not only user tables.
57    table_by_id: HashMap<TableId, Arc<TableCatalog>>,
58    source_by_name: HashMap<String, Arc<SourceCatalog>>,
59    source_by_id: HashMap<SourceId, Arc<SourceCatalog>>,
60    sink_by_name: HashMap<String, Arc<SinkCatalog>>,
61    sink_by_id: HashMap<SinkId, Arc<SinkCatalog>>,
62    /// reverted index of (`sink.target_table` -> `sink_id`s)
63    table_incoming_sinks: HashMap<TableId, HashSet<SinkId>>,
64    subscription_by_name: HashMap<String, Arc<SubscriptionCatalog>>,
65    subscription_by_id: HashMap<SubscriptionId, Arc<SubscriptionCatalog>>,
66    index_by_name: HashMap<String, Arc<IndexCatalog>>,
67    index_by_id: HashMap<IndexId, Arc<IndexCatalog>>,
68    indexes_by_table_id: HashMap<TableId, Vec<Arc<IndexCatalog>>>,
69    view_by_name: HashMap<String, Arc<ViewCatalog>>,
70    view_by_id: HashMap<ViewId, Arc<ViewCatalog>>,
71    function_registry: FunctionRegistry,
72    function_by_name: HashMap<String, HashMap<Vec<DataType>, Arc<FunctionCatalog>>>,
73    function_by_id: HashMap<FunctionId, Arc<FunctionCatalog>>,
74    connection_by_name: HashMap<String, Arc<ConnectionCatalog>>,
75    connection_by_id: HashMap<ConnectionId, Arc<ConnectionCatalog>>,
76    secret_by_name: HashMap<String, Arc<SecretCatalog>>,
77    secret_by_id: HashMap<SecretId, Arc<SecretCatalog>>,
78
79    _secret_source_ref: HashMap<SecretId, Vec<SourceId>>,
80    _secret_sink_ref: HashMap<SecretId, Vec<SinkId>>,
81
82    // This field is currently used only for `show connections`
83    connection_source_ref: HashMap<ConnectionId, Vec<SourceId>>,
84    // This field is currently used only for `show connections`
85    connection_sink_ref: HashMap<ConnectionId, Vec<SinkId>>,
86    // This field only available when schema is "pg_catalog". Meanwhile, others will be empty.
87    system_table_by_name: HashMap<String, Arc<SystemTableCatalog>>,
88    pub owner: UserId,
89}
90
91impl SchemaCatalog {
92    pub fn create_table(&mut self, prost: &PbTable) -> Arc<TableCatalog> {
93        let name = prost.name.clone();
94        let id = prost.id;
95        let table: TableCatalog = prost.into();
96        let table_ref = Arc::new(table);
97
98        self.table_by_name
99            .try_insert(name, table_ref.clone())
100            .unwrap();
101        self.table_by_id.try_insert(id, table_ref.clone()).unwrap();
102        table_ref
103    }
104
105    pub fn create_sys_table(&mut self, sys_table: Arc<SystemTableCatalog>) {
106        self.system_table_by_name
107            .try_insert(sys_table.name.clone(), sys_table)
108            .unwrap();
109    }
110
111    pub fn create_sys_view(&mut self, sys_view: Arc<ViewCatalog>) {
112        self.view_by_name
113            .try_insert(sys_view.name().to_owned(), sys_view.clone())
114            .unwrap();
115        self.view_by_id
116            .try_insert(sys_view.id, sys_view.clone())
117            .unwrap();
118    }
119
120    pub fn update_table(&mut self, prost: &PbTable) -> Arc<TableCatalog> {
121        let name = prost.name.clone();
122        let id = prost.id;
123        let table: TableCatalog = prost.into();
124        let table_ref = Arc::new(table);
125
126        let old_table = self.table_by_id.get(&id).unwrap();
127        // check if the table name gets updated.
128        if old_table.name() != name
129            && let Some(t) = self.table_by_name.get(old_table.name())
130            && t.id == id
131        {
132            self.table_by_name.remove(old_table.name());
133        }
134
135        self.table_by_name.insert(name, table_ref.clone());
136        self.table_by_id.insert(id, table_ref.clone());
137        table_ref
138    }
139
140    pub fn update_index(&mut self, prost: &PbIndex) {
141        let name = prost.name.clone();
142        let id = prost.id;
143        let old_index = self.index_by_id.get(&id).unwrap();
144        let index_table = self.get_created_table_by_id(prost.index_table_id).unwrap();
145        let primary_table = self
146            .get_created_table_by_id(prost.primary_table_id)
147            .unwrap();
148        let index: IndexCatalog = IndexCatalog::build_from(prost, index_table, primary_table);
149        let index_ref = Arc::new(index);
150
151        // check if the index name gets updated.
152        if old_index.name != name
153            && let Some(idx) = self.index_by_name.get(&old_index.name)
154            && idx.id == id
155        {
156            self.index_by_name.remove(&old_index.name);
157        }
158        self.index_by_name.insert(name, index_ref.clone());
159        self.index_by_id.insert(id, index_ref.clone());
160
161        match self.indexes_by_table_id.entry(index_ref.primary_table.id) {
162            Occupied(mut entry) => {
163                let pos = entry
164                    .get()
165                    .iter()
166                    .position(|x| x.id == index_ref.id)
167                    .unwrap();
168                *entry.get_mut().get_mut(pos).unwrap() = index_ref;
169            }
170            Vacant(_entry) => {
171                unreachable!()
172            }
173        };
174    }
175
176    pub fn drop_table(&mut self, id: TableId) {
177        if let Some(table_ref) = self.table_by_id.remove(&id) {
178            self.table_by_name.remove(&table_ref.name).unwrap();
179            self.indexes_by_table_id.remove(&table_ref.id);
180        } else {
181            tracing::warn!(
182                %id,
183                "table not found when dropping, frontend might not be notified yet"
184            );
185        }
186    }
187
188    pub fn create_index(&mut self, prost: &PbIndex) {
189        let name = prost.name.clone();
190        let id = prost.id;
191        let index_table = self.get_table_by_id(prost.index_table_id).unwrap();
192        let primary_table = self
193            .get_created_table_by_id(prost.primary_table_id)
194            .unwrap();
195        let index: IndexCatalog = IndexCatalog::build_from(prost, index_table, primary_table);
196        let index_ref = Arc::new(index);
197
198        self.index_by_name
199            .try_insert(name, index_ref.clone())
200            .unwrap();
201        self.index_by_id.try_insert(id, index_ref.clone()).unwrap();
202        match self.indexes_by_table_id.entry(index_ref.primary_table.id) {
203            Occupied(mut entry) => {
204                entry.get_mut().push(index_ref);
205            }
206            Vacant(entry) => {
207                entry.insert(vec![index_ref]);
208            }
209        };
210    }
211
212    pub fn drop_index(&mut self, id: IndexId) {
213        let Some(index_ref) = self.index_by_id.remove(&id) else {
214            tracing::warn!(
215                %id,
216                "index not found when dropping, frontend might not be notified yet"
217            );
218            return;
219        };
220        self.index_by_name.remove(&index_ref.name).unwrap();
221        match self.indexes_by_table_id.entry(index_ref.primary_table.id) {
222            Occupied(mut entry) => {
223                let pos = entry
224                    .get_mut()
225                    .iter()
226                    .position(|x| x.id == index_ref.id)
227                    .unwrap();
228                entry.get_mut().remove(pos);
229            }
230            Vacant(_entry) => (),
231        };
232    }
233
234    pub fn create_source(&mut self, prost: &PbSource) {
235        let name = prost.name.clone();
236        let id = prost.id;
237        let source = SourceCatalog::from(prost);
238        let source_ref = Arc::new(source);
239
240        if let Some(connection_id) = source_ref.connection_id {
241            self.connection_source_ref
242                .entry(connection_id)
243                .and_modify(|sources| sources.push(source_ref.id))
244                .or_insert(vec![source_ref.id]);
245        }
246
247        self.source_by_name
248            .try_insert(name, source_ref.clone())
249            .unwrap();
250        self.source_by_id.try_insert(id, source_ref).unwrap();
251    }
252
253    pub fn drop_source(&mut self, id: SourceId) {
254        let Some(source_ref) = self.source_by_id.remove(&id) else {
255            tracing::warn!(
256                %id,
257                "source not found when dropping, frontend might not be notified yet"
258            );
259            return;
260        };
261        self.source_by_name.remove(&source_ref.name).unwrap();
262        if let Some(connection_id) = source_ref.connection_id
263            && let Occupied(mut e) = self.connection_source_ref.entry(connection_id)
264        {
265            let source_ids = e.get_mut();
266            source_ids.retain_mut(|sid| *sid != id);
267            if source_ids.is_empty() {
268                e.remove_entry();
269            }
270        }
271    }
272
273    pub fn update_source(&mut self, prost: &PbSource) {
274        let name = prost.name.clone();
275        let id = prost.id;
276        let source = SourceCatalog::from(prost);
277        let source_ref = Arc::new(source);
278
279        let old_source = self.source_by_id.get(&id).unwrap();
280        // check if the source name gets updated.
281        if old_source.name != name
282            && let Some(src) = self.source_by_name.get(&old_source.name)
283            && src.id == id
284        {
285            self.source_by_name.remove(&old_source.name);
286        }
287
288        self.source_by_name.insert(name, source_ref.clone());
289        self.source_by_id.insert(id, source_ref);
290    }
291
292    pub fn create_sink(&mut self, prost: &PbSink) {
293        let name = prost.name.clone();
294        let id = prost.id;
295        let sink = SinkCatalog::from(prost);
296        let sink_ref = Arc::new(sink);
297
298        if let Some(connection_id) = sink_ref.connection_id {
299            self.connection_sink_ref
300                .entry(connection_id)
301                .and_modify(|sinks| sinks.push(id))
302                .or_insert(vec![id]);
303        }
304
305        if let Some(target_table) = sink_ref.target_table {
306            assert!(
307                self.table_incoming_sinks
308                    .entry(target_table)
309                    .or_default()
310                    .insert(sink_ref.id)
311            );
312        }
313
314        self.sink_by_name
315            .try_insert(name, sink_ref.clone())
316            .unwrap();
317        self.sink_by_id.try_insert(id, sink_ref).unwrap();
318    }
319
320    pub fn drop_sink(&mut self, id: SinkId) {
321        if let Some(sink_ref) = self.sink_by_id.remove(&id) {
322            self.sink_by_name.remove(&sink_ref.name).unwrap();
323            if let Some(connection_id) = sink_ref.connection_id
324                && let Occupied(mut e) = self.connection_sink_ref.entry(connection_id)
325            {
326                let sink_ids = e.get_mut();
327                sink_ids.retain_mut(|sid| *sid != id);
328                if sink_ids.is_empty() {
329                    e.remove_entry();
330                }
331            }
332            if let Some(target_table) = sink_ref.target_table {
333                let incoming_sinks = self
334                    .table_incoming_sinks
335                    .get_mut(&target_table)
336                    .expect("should exists");
337                assert!(incoming_sinks.remove(&sink_ref.id));
338                if incoming_sinks.is_empty() {
339                    self.table_incoming_sinks.remove(&target_table);
340                }
341            }
342        } else {
343            tracing::warn!(
344                %id,
345                "sink not found when dropping, frontend might not be notified yet"
346            );
347        }
348    }
349
350    pub fn update_sink(&mut self, prost: &PbSink) {
351        let name = prost.name.clone();
352        let id = prost.id;
353        let sink = SinkCatalog::from(prost);
354        let sink_ref = Arc::new(sink);
355
356        let old_sink = self.sink_by_id.get(&id).unwrap();
357        assert_eq!(sink_ref.target_table, old_sink.target_table);
358        // check if the sink name gets updated.
359        if old_sink.name != name
360            && let Some(s) = self.sink_by_name.get(&old_sink.name)
361            && s.id == id
362        {
363            self.sink_by_name.remove(&old_sink.name);
364        }
365
366        self.sink_by_name.insert(name, sink_ref.clone());
367        self.sink_by_id.insert(id, sink_ref);
368    }
369
370    pub fn table_incoming_sinks(&self, table_id: TableId) -> Option<&HashSet<SinkId>> {
371        self.table_incoming_sinks.get(&table_id)
372    }
373
374    pub fn create_subscription(&mut self, prost: &PbSubscription) {
375        let name = prost.name.clone();
376        let id = prost.id;
377        let subscription_catalog = SubscriptionCatalog::from(prost);
378        let subscription_ref = Arc::new(subscription_catalog);
379
380        self.subscription_by_name
381            .try_insert(name, subscription_ref.clone())
382            .unwrap();
383        self.subscription_by_id
384            .try_insert(id, subscription_ref)
385            .unwrap();
386    }
387
388    pub fn drop_subscription(&mut self, id: SubscriptionId) {
389        let subscription_ref = self.subscription_by_id.remove(&id);
390        if let Some(subscription_ref) = subscription_ref {
391            self.subscription_by_name.remove(&subscription_ref.name);
392        }
393    }
394
395    pub fn update_subscription(&mut self, prost: &PbSubscription) {
396        let name = prost.name.clone();
397        let id = prost.id;
398        let subscription = SubscriptionCatalog::from(prost);
399        let subscription_ref = Arc::new(subscription);
400
401        let old_subscription = self.subscription_by_id.get(&id).unwrap();
402        // check if the subscription name gets updated.
403        if old_subscription.name != name
404            && let Some(s) = self.subscription_by_name.get(&old_subscription.name)
405            && s.id == id
406        {
407            self.subscription_by_name.remove(&old_subscription.name);
408        }
409
410        self.subscription_by_name
411            .insert(name, subscription_ref.clone());
412        self.subscription_by_id.insert(id, subscription_ref);
413    }
414
415    pub fn create_view(&mut self, prost: &PbView) {
416        let name = prost.name.clone();
417        let id = prost.id;
418        let view = ViewCatalog::from(prost);
419        let view_ref = Arc::new(view);
420
421        self.view_by_name
422            .try_insert(name, view_ref.clone())
423            .unwrap();
424        self.view_by_id.try_insert(id, view_ref).unwrap();
425    }
426
427    pub fn drop_view(&mut self, id: ViewId) {
428        let view_ref = self.view_by_id.remove(&id).unwrap();
429        self.view_by_name.remove(&view_ref.name).unwrap();
430    }
431
432    pub fn update_view(&mut self, prost: &PbView) {
433        let name = prost.name.clone();
434        let id = prost.id;
435        let view = ViewCatalog::from(prost);
436        let view_ref = Arc::new(view);
437
438        let old_view = self.view_by_id.get(&id).unwrap();
439        // check if the view name gets updated.
440        if old_view.name != name
441            && let Some(v) = self.view_by_name.get(old_view.name())
442            && v.id == id
443        {
444            self.view_by_name.remove(&old_view.name);
445        }
446
447        self.view_by_name.insert(name, view_ref.clone());
448        self.view_by_id.insert(id, view_ref);
449    }
450
451    pub fn get_func_sign(func: &FunctionCatalog) -> FuncSign {
452        FuncSign {
453            name: FuncName::Udf(func.name.clone()),
454            inputs_type: func
455                .arg_types
456                .iter()
457                .map(|t| t.clone().into())
458                .collect_vec(),
459            variadic: false,
460            ret_type: func.return_type.clone().into(),
461            build: FuncBuilder::Udf,
462            // dummy type infer, will not use this result
463            type_infer: |_| Ok(DataType::Boolean),
464            deprecated: false,
465            is_async: true,
466        }
467    }
468
469    pub fn create_function(&mut self, prost: &PbFunction) {
470        let name = prost.name.clone();
471        let id = prost.id;
472        let function = FunctionCatalog::from(prost);
473        let args = function.arg_types.clone();
474        let function_ref = Arc::new(function);
475
476        self.function_registry
477            .insert(Self::get_func_sign(&function_ref));
478        self.function_by_name
479            .entry(name)
480            .or_default()
481            .try_insert(args, function_ref.clone())
482            .expect("function already exists with same argument types");
483        self.function_by_id
484            .try_insert(id, function_ref)
485            .expect("function id exists");
486    }
487
488    pub fn drop_function(&mut self, id: FunctionId) {
489        let function_ref = self
490            .function_by_id
491            .remove(&id)
492            .expect("function not found by id");
493
494        self.function_registry
495            .remove(Self::get_func_sign(&function_ref))
496            .expect("function not found in registry");
497
498        self.function_by_name
499            .get_mut(&function_ref.name)
500            .expect("function not found by name")
501            .remove(&function_ref.arg_types)
502            .expect("function not found by argument types");
503    }
504
505    pub fn update_function(&mut self, prost: &PbFunction) {
506        let name = prost.name.clone();
507        let id = prost.id;
508        let function = FunctionCatalog::from(prost);
509        let function_ref = Arc::new(function);
510
511        let old_function_by_id = self.function_by_id.get(&id).unwrap();
512        let old_function_by_name = self
513            .function_by_name
514            .get_mut(&old_function_by_id.name)
515            .unwrap();
516        // check if the function name gets updated.
517        if old_function_by_id.name != name
518            && let Some(f) = old_function_by_name.get(&old_function_by_id.arg_types)
519            && f.id == id
520        {
521            old_function_by_name.remove(&old_function_by_id.arg_types);
522            if old_function_by_name.is_empty() {
523                self.function_by_name.remove(&old_function_by_id.name);
524            }
525        }
526
527        self.function_by_name
528            .entry(name)
529            .or_default()
530            .insert(old_function_by_id.arg_types.clone(), function_ref.clone());
531        self.function_by_id.insert(id, function_ref);
532    }
533
534    pub fn create_connection(&mut self, prost: &PbConnection) {
535        let name = prost.name.clone();
536        let id = prost.id;
537        let connection = ConnectionCatalog::from(prost);
538        let connection_ref = Arc::new(connection);
539        self.connection_by_name
540            .try_insert(name, connection_ref.clone())
541            .unwrap();
542        self.connection_by_id
543            .try_insert(id, connection_ref)
544            .unwrap();
545    }
546
547    pub fn update_connection(&mut self, prost: &PbConnection) {
548        let name = prost.name.clone();
549        let id = prost.id;
550        let connection = ConnectionCatalog::from(prost);
551        let connection_ref = Arc::new(connection);
552
553        let old_connection = self.connection_by_id.get(&id).unwrap();
554        // check if the connection name gets updated.
555        if old_connection.name != name
556            && let Some(conn) = self.connection_by_name.get(&old_connection.name)
557            && conn.id == id
558        {
559            self.connection_by_name.remove(&old_connection.name);
560        }
561
562        self.connection_by_name.insert(name, connection_ref.clone());
563        self.connection_by_id.insert(id, connection_ref);
564    }
565
566    pub fn drop_connection(&mut self, connection_id: ConnectionId) {
567        let connection_ref = self
568            .connection_by_id
569            .remove(&connection_id)
570            .expect("connection not found by id");
571        self.connection_by_name
572            .remove(&connection_ref.name)
573            .expect("connection not found by name");
574    }
575
576    pub fn create_secret(&mut self, prost: &PbSecret) {
577        let name = prost.name.clone();
578        let id = prost.id;
579        let secret = SecretCatalog::from(prost);
580        let secret_ref = Arc::new(secret);
581
582        self.secret_by_id
583            .try_insert(id, secret_ref.clone())
584            .unwrap();
585        self.secret_by_name.try_insert(name, secret_ref).unwrap();
586    }
587
588    pub fn update_secret(&mut self, prost: &PbSecret) {
589        let name = prost.name.clone();
590        let id = prost.id;
591        let secret = SecretCatalog::from(prost);
592        let secret_ref = Arc::new(secret);
593
594        let old_secret = self.secret_by_id.get(&id).unwrap();
595        // check if the secret name gets updated.
596        if old_secret.name != name
597            && let Some(s) = self.secret_by_name.get(&old_secret.name)
598            && s.id == id
599        {
600            self.secret_by_name.remove(&old_secret.name);
601        }
602
603        self.secret_by_name.insert(name, secret_ref.clone());
604        self.secret_by_id.insert(id, secret_ref);
605    }
606
607    pub fn drop_secret(&mut self, secret_id: SecretId) {
608        let secret_ref = self
609            .secret_by_id
610            .remove(&secret_id)
611            .expect("secret not found by id");
612        self.secret_by_name
613            .remove(&secret_ref.name)
614            .expect("secret not found by name");
615    }
616
617    pub fn iter_object_ids(&self) -> impl Iterator<Item = ObjectId> + '_ {
618        self.table_by_id
619            .keys()
620            .map(|id| id.as_object_id())
621            .chain(self.source_by_id.keys().map(|id| id.as_object_id()))
622            .chain(self.sink_by_id.keys().map(|id| id.as_object_id()))
623            .chain(self.subscription_by_id.keys().map(|id| id.as_object_id()))
624            .chain(self.index_by_id.keys().map(|id| id.as_object_id()))
625            .chain(self.view_by_id.keys().map(|id| id.as_object_id()))
626            .chain(self.function_by_id.keys().map(|id| id.as_object_id()))
627            .chain(self.connection_by_id.keys().map(|id| id.as_object_id()))
628            .chain(self.secret_by_id.keys().map(|id| id.as_object_id()))
629    }
630
631    pub fn iter_all(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
632        self.table_by_name.values()
633    }
634
635    pub fn iter_user_table(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
636        self.table_by_name.values().filter(|v| v.is_user_table())
637    }
638
639    pub fn iter_user_table_with_acl<'a>(
640        &'a self,
641        user: &'a UserCatalog,
642    ) -> impl Iterator<Item = &'a Arc<TableCatalog>> {
643        self.table_by_name
644            .values()
645            .filter(|v| v.is_user_table() && has_access_to_object(user, v.id, v.owner))
646    }
647
648    pub fn iter_internal_table(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
649        self.table_by_name
650            .values()
651            .filter(|v| v.is_internal_table())
652    }
653
654    pub fn iter_internal_table_with_acl<'a>(
655        &'a self,
656        user: &'a UserCatalog,
657    ) -> impl Iterator<Item = &'a Arc<TableCatalog>> {
658        self.table_by_name
659            .values()
660            .filter(|v| v.is_internal_table() && has_access_to_object(user, v.id, v.owner))
661    }
662
663    /// Iterate all non-internal tables, including user tables, materialized views and indices.
664    pub fn iter_table_mv_indices(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
665        self.table_by_name
666            .values()
667            .filter(|v| !v.is_internal_table())
668    }
669
670    pub fn iter_table_mv_indices_with_acl<'a>(
671        &'a self,
672        user: &'a UserCatalog,
673    ) -> impl Iterator<Item = &'a Arc<TableCatalog>> {
674        self.table_by_name
675            .values()
676            .filter(|v| !v.is_internal_table() && has_access_to_object(user, v.id, v.owner))
677    }
678
679    /// Iterate all materialized views, excluding the indices.
680    pub fn iter_all_mvs(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
681        self.table_by_name.values().filter(|v| v.is_mview())
682    }
683
684    pub fn iter_all_mvs_with_acl<'a>(
685        &'a self,
686        user: &'a UserCatalog,
687    ) -> impl Iterator<Item = &'a Arc<TableCatalog>> {
688        self.table_by_name
689            .values()
690            .filter(|v| v.is_mview() && has_access_to_object(user, v.id, v.owner))
691    }
692
693    /// Iterate created materialized views, excluding the indices.
694    pub fn iter_created_mvs(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
695        self.table_by_name
696            .values()
697            .filter(|v| v.is_mview() && v.is_created())
698    }
699
700    pub fn iter_created_mvs_with_acl<'a>(
701        &'a self,
702        user: &'a UserCatalog,
703    ) -> impl Iterator<Item = &'a Arc<TableCatalog>> {
704        self.table_by_name
705            .values()
706            .filter(|v| v.is_mview() && v.is_created() && has_access_to_object(user, v.id, v.owner))
707    }
708
709    /// Iterate all indices
710    pub fn iter_index(&self) -> impl Iterator<Item = &Arc<IndexCatalog>> {
711        self.index_by_name.values()
712    }
713
714    pub fn iter_index_with_acl<'a>(
715        &'a self,
716        user: &'a UserCatalog,
717    ) -> impl Iterator<Item = &'a Arc<IndexCatalog>> {
718        self.index_by_name
719            .values()
720            .filter(|idx| has_access_to_object(user, idx.id, idx.owner()))
721    }
722
723    /// Iterate all sources
724    pub fn iter_source(&self) -> impl Iterator<Item = &Arc<SourceCatalog>> {
725        self.source_by_name.values()
726    }
727
728    pub fn iter_source_with_acl<'a>(
729        &'a self,
730        user: &'a UserCatalog,
731    ) -> impl Iterator<Item = &'a Arc<SourceCatalog>> {
732        self.source_by_name
733            .values()
734            .filter(|s| has_access_to_object(user, s.id, s.owner))
735    }
736
737    pub fn iter_sink(&self) -> impl Iterator<Item = &Arc<SinkCatalog>> {
738        self.sink_by_name.values()
739    }
740
741    pub fn iter_sink_with_acl<'a>(
742        &'a self,
743        user: &'a UserCatalog,
744    ) -> impl Iterator<Item = &'a Arc<SinkCatalog>> {
745        self.sink_by_name
746            .values()
747            .filter(|s| has_access_to_object(user, s.id, s.owner))
748    }
749
750    pub fn iter_subscription(&self) -> impl Iterator<Item = &Arc<SubscriptionCatalog>> {
751        self.subscription_by_name.values()
752    }
753
754    pub fn iter_subscription_with_acl<'a>(
755        &'a self,
756        user: &'a UserCatalog,
757    ) -> impl Iterator<Item = &'a Arc<SubscriptionCatalog>> {
758        self.subscription_by_name
759            .values()
760            .filter(|s| has_access_to_object(user, s.id, s.owner))
761    }
762
763    pub fn iter_view(&self) -> impl Iterator<Item = &Arc<ViewCatalog>> {
764        self.view_by_name.values()
765    }
766
767    pub fn iter_view_with_acl<'a>(
768        &'a self,
769        user: &'a UserCatalog,
770    ) -> impl Iterator<Item = &'a Arc<ViewCatalog>> {
771        self.view_by_name
772            .values()
773            .filter(|v| v.is_system_view() || has_access_to_object(user, v.id, v.owner))
774    }
775
776    pub fn iter_function(&self) -> impl Iterator<Item = &Arc<FunctionCatalog>> {
777        self.function_by_name.values().flat_map(|v| v.values())
778    }
779
780    pub fn iter_function_with_acl<'a>(
781        &'a self,
782        user: &'a UserCatalog,
783    ) -> impl Iterator<Item = &'a Arc<FunctionCatalog>> {
784        self.function_by_name
785            .values()
786            .flat_map(|v| v.values())
787            .filter(|f| has_access_to_object(user, f.id, f.owner))
788    }
789
790    pub fn iter_connections(&self) -> impl Iterator<Item = &Arc<ConnectionCatalog>> {
791        self.connection_by_name.values()
792    }
793
794    pub fn iter_connections_with_acl<'a>(
795        &'a self,
796        user: &'a UserCatalog,
797    ) -> impl Iterator<Item = &'a Arc<ConnectionCatalog>> {
798        self.connection_by_name
799            .values()
800            .filter(|c| has_access_to_object(user, c.id, c.owner))
801    }
802
803    pub fn iter_secret(&self) -> impl Iterator<Item = &Arc<SecretCatalog>> {
804        self.secret_by_name.values()
805    }
806
807    pub fn iter_secret_with_acl<'a>(
808        &'a self,
809        user: &'a UserCatalog,
810    ) -> impl Iterator<Item = &'a Arc<SecretCatalog>> {
811        self.secret_by_name
812            .values()
813            .filter(|s| has_access_to_object(user, s.id, s.owner))
814    }
815
816    pub fn iter_system_tables(&self) -> impl Iterator<Item = &Arc<SystemTableCatalog>> {
817        self.system_table_by_name.values()
818    }
819
820    pub fn get_table_by_name(
821        &self,
822        table_name: &str,
823        bind_creating_relations: bool,
824    ) -> Option<&Arc<TableCatalog>> {
825        self.table_by_name
826            .get(table_name)
827            .filter(|&table| bind_creating_relations || table.is_created())
828    }
829
830    pub fn get_any_table_by_name(&self, table_name: &str) -> Option<&Arc<TableCatalog>> {
831        self.get_table_by_name(table_name, true)
832    }
833
834    pub fn get_created_table_by_name(&self, table_name: &str) -> Option<&Arc<TableCatalog>> {
835        self.get_table_by_name(table_name, false)
836    }
837
838    pub fn get_table_by_id(&self, table_id: TableId) -> Option<&Arc<TableCatalog>> {
839        self.table_by_id.get(&table_id)
840    }
841
842    pub fn get_created_table_by_id(&self, table_id: TableId) -> Option<&Arc<TableCatalog>> {
843        self.table_by_id
844            .get(&table_id)
845            .filter(|&table| table.stream_job_status == StreamJobStatus::Created)
846    }
847
848    pub fn get_view_by_name(&self, view_name: &str) -> Option<&Arc<ViewCatalog>> {
849        self.view_by_name.get(view_name)
850    }
851
852    pub fn get_view_by_id(&self, view_id: ViewId) -> Option<&Arc<ViewCatalog>> {
853        self.view_by_id.get(&view_id)
854    }
855
856    pub fn get_source_by_name(&self, source_name: &str) -> Option<&Arc<SourceCatalog>> {
857        self.source_by_name.get(source_name)
858    }
859
860    pub fn get_source_by_id(&self, source_id: SourceId) -> Option<&Arc<SourceCatalog>> {
861        self.source_by_id.get(&source_id)
862    }
863
864    pub fn get_sink_by_name(
865        &self,
866        sink_name: &str,
867        bind_creating: bool,
868    ) -> Option<&Arc<SinkCatalog>> {
869        self.sink_by_name
870            .get(sink_name)
871            .filter(|s| bind_creating || s.is_created())
872    }
873
874    pub fn get_any_sink_by_name(&self, sink_name: &str) -> Option<&Arc<SinkCatalog>> {
875        self.get_sink_by_name(sink_name, true)
876    }
877
878    pub fn get_created_sink_by_name(&self, sink_name: &str) -> Option<&Arc<SinkCatalog>> {
879        self.get_sink_by_name(sink_name, false)
880    }
881
882    pub fn get_sink_by_id(&self, sink_id: SinkId) -> Option<&Arc<SinkCatalog>> {
883        self.sink_by_id.get(&sink_id)
884    }
885
886    pub fn get_subscription_by_name(
887        &self,
888        subscription_name: &str,
889    ) -> Option<&Arc<SubscriptionCatalog>> {
890        self.subscription_by_name.get(subscription_name)
891    }
892
893    pub fn get_subscription_by_id(
894        &self,
895        subscription_id: SubscriptionId,
896    ) -> Option<&Arc<SubscriptionCatalog>> {
897        self.subscription_by_id.get(&subscription_id)
898    }
899
900    pub fn get_index_by_name(
901        &self,
902        index_name: &str,
903        bind_creating: bool,
904    ) -> Option<&Arc<IndexCatalog>> {
905        self.index_by_name
906            .get(index_name)
907            .filter(|i| bind_creating || i.is_created())
908    }
909
910    pub fn get_any_index_by_name(&self, index_name: &str) -> Option<&Arc<IndexCatalog>> {
911        self.get_index_by_name(index_name, true)
912    }
913
914    pub fn get_created_index_by_name(&self, index_name: &str) -> Option<&Arc<IndexCatalog>> {
915        self.get_index_by_name(index_name, false)
916    }
917
918    pub fn get_index_by_id(&self, index_id: IndexId) -> Option<&Arc<IndexCatalog>> {
919        self.index_by_id.get(&index_id)
920    }
921
922    pub fn get_indexes_by_table_id(
923        &self,
924        table_id: TableId,
925        include_creating: bool,
926    ) -> Vec<Arc<IndexCatalog>> {
927        self.indexes_by_table_id
928            .get(&table_id)
929            .cloned()
930            .unwrap_or_default()
931            .into_iter()
932            .filter(|i| include_creating || i.is_created())
933            .collect()
934    }
935
936    pub fn get_any_indexes_by_table_id(&self, table_id: TableId) -> Vec<Arc<IndexCatalog>> {
937        self.get_indexes_by_table_id(table_id, true)
938    }
939
940    pub fn get_created_indexes_by_table_id(&self, table_id: TableId) -> Vec<Arc<IndexCatalog>> {
941        self.get_indexes_by_table_id(table_id, false)
942    }
943
944    pub fn get_system_table_by_name(&self, table_name: &str) -> Option<&Arc<SystemTableCatalog>> {
945        self.system_table_by_name.get(table_name)
946    }
947
948    /// Returns what `name` refers to in this schema, including relations still being created.
949    pub fn relation_kind(&self, name: &str) -> Option<RelationKind> {
950        if is_system_schema(&self.name()) {
951            return (self.get_system_table_by_name(name).is_some()
952                || self.get_view_by_name(name).is_some())
953            .then_some(RelationKind::SystemCatalog);
954        }
955        // Tables go first: a table with a connector and an index each own another object of the
956        // same name.
957        if let Some(table) = self.get_any_table_by_name(name) {
958            Some(table.table_type().into())
959        } else if self.get_source_by_name(name).is_some() {
960            Some(RelationKind::Source)
961        } else if self.get_any_sink_by_name(name).is_some() {
962            Some(RelationKind::Sink)
963        } else if self.get_view_by_name(name).is_some() {
964            Some(RelationKind::View)
965        } else if self.get_subscription_by_name(name).is_some() {
966            Some(RelationKind::Subscription)
967        } else {
968            None
969        }
970    }
971
972    pub fn get_table_name_by_id(&self, table_id: TableId) -> Option<String> {
973        self.table_by_id
974            .get(&table_id)
975            .map(|table| table.name.clone())
976    }
977
978    pub fn get_function_by_id(&self, function_id: FunctionId) -> Option<&Arc<FunctionCatalog>> {
979        self.function_by_id.get(&function_id)
980    }
981
982    pub fn get_function_by_name_inputs(
983        &self,
984        name: &str,
985        inputs: &mut [ExprImpl],
986    ) -> Option<&Arc<FunctionCatalog>> {
987        infer_type_with_sigmap(
988            FuncName::Udf(name.to_owned()),
989            inputs,
990            &self.function_registry,
991        )
992        .ok()?;
993        let args = inputs.iter().map(|x| x.return_type()).collect_vec();
994        self.function_by_name.get(name)?.get(&args)
995    }
996
997    pub fn get_function_by_name_args(
998        &self,
999        name: &str,
1000        args: &[DataType],
1001    ) -> Option<&Arc<FunctionCatalog>> {
1002        let args = args.iter().map(|x| Some(x.clone())).collect_vec();
1003        let func = infer_type_name(
1004            &self.function_registry,
1005            FuncName::Udf(name.to_owned()),
1006            &args,
1007        )
1008        .ok()?;
1009
1010        let args = func
1011            .inputs_type
1012            .iter()
1013            .filter_map(|x| {
1014                if let SigDataType::Exact(t) = x {
1015                    Some(t.clone())
1016                } else {
1017                    None
1018                }
1019            })
1020            .collect_vec();
1021
1022        self.function_by_name.get(name)?.get(&args)
1023    }
1024
1025    pub fn get_functions_by_name(&self, name: &str) -> Option<Vec<&Arc<FunctionCatalog>>> {
1026        let functions = self.function_by_name.get(name)?;
1027        if functions.is_empty() {
1028            return None;
1029        }
1030        Some(functions.values().collect())
1031    }
1032
1033    pub fn get_connection_by_id(
1034        &self,
1035        connection_id: ConnectionId,
1036    ) -> Option<&Arc<ConnectionCatalog>> {
1037        self.connection_by_id.get(&connection_id)
1038    }
1039
1040    pub fn get_connection_by_name(&self, connection_name: &str) -> Option<&Arc<ConnectionCatalog>> {
1041        self.connection_by_name.get(connection_name)
1042    }
1043
1044    pub fn get_secret_by_name(&self, secret_name: &str) -> Option<&Arc<SecretCatalog>> {
1045        self.secret_by_name.get(secret_name)
1046    }
1047
1048    pub fn get_secret_by_id(&self, secret_id: SecretId) -> Option<&Arc<SecretCatalog>> {
1049        self.secret_by_id.get(&secret_id)
1050    }
1051
1052    /// get all sources referencing the connection
1053    pub fn get_source_ids_by_connection(
1054        &self,
1055        connection_id: ConnectionId,
1056    ) -> Option<Vec<SourceId>> {
1057        self.connection_source_ref
1058            .get(&connection_id)
1059            .map(|c| c.to_owned())
1060    }
1061
1062    /// get all sinks referencing the connection
1063    pub fn get_sink_ids_by_connection(&self, connection_id: ConnectionId) -> Option<Vec<SinkId>> {
1064        self.connection_sink_ref
1065            .get(&connection_id)
1066            .map(|s| s.to_owned())
1067    }
1068
1069    pub fn get_grant_object_by_oid(&self, oid: ObjectId) -> Option<OwnedGrantObject> {
1070        #[expect(clippy::manual_map)]
1071        if let Some(table) = self.get_created_table_by_id(oid.as_table_id()) {
1072            Some(OwnedGrantObject {
1073                owner: table.owner,
1074                object: Object::TableId(oid.as_table_id()),
1075            })
1076        } else if let Some(index) = self.get_index_by_id(oid.as_index_id()) {
1077            Some(OwnedGrantObject {
1078                owner: index.owner(),
1079                object: Object::TableId(oid.as_table_id()),
1080            })
1081        } else if let Some(source) = self.get_source_by_id(oid.as_source_id()) {
1082            Some(OwnedGrantObject {
1083                owner: source.owner,
1084                object: Object::SourceId(oid.as_source_id()),
1085            })
1086        } else if let Some(sink) = self.get_sink_by_id(oid.as_sink_id()) {
1087            Some(OwnedGrantObject {
1088                owner: sink.owner,
1089                object: Object::SinkId(oid.as_sink_id()),
1090            })
1091        } else if let Some(view) = self.get_view_by_id(oid.as_view_id()) {
1092            Some(OwnedGrantObject {
1093                owner: view.owner,
1094                object: Object::ViewId(oid.as_view_id()),
1095            })
1096        } else if let Some(function) = self.get_function_by_id(oid.as_function_id()) {
1097            Some(OwnedGrantObject {
1098                owner: function.owner(),
1099                object: Object::FunctionId(oid.as_function_id()),
1100            })
1101        } else if let Some(subscription) = self.get_subscription_by_id(oid.as_subscription_id()) {
1102            Some(OwnedGrantObject {
1103                owner: subscription.owner,
1104                object: Object::SubscriptionId(oid.as_subscription_id()),
1105            })
1106        } else if let Some(connection) = self.get_connection_by_id(oid.as_connection_id()) {
1107            Some(OwnedGrantObject {
1108                owner: connection.owner,
1109                object: Object::ConnectionId(oid.as_connection_id()),
1110            })
1111        } else if let Some(secret) = self.get_secret_by_id(oid.as_secret_id()) {
1112            Some(OwnedGrantObject {
1113                owner: secret.owner,
1114                object: Object::SecretId(oid.as_secret_id()),
1115            })
1116        } else {
1117            None
1118        }
1119    }
1120
1121    pub fn contains_object(&self, oid: ObjectId) -> bool {
1122        self.table_by_id.contains_key(&oid.as_table_id())
1123            || self.index_by_id.contains_key(&oid.as_index_id())
1124            || self.source_by_id.contains_key(&oid.as_source_id())
1125            || self.sink_by_id.contains_key(&oid.as_sink_id())
1126            || self.view_by_id.contains_key(&oid.as_view_id())
1127            || self.function_by_id.contains_key(&oid.as_function_id())
1128            || self
1129                .subscription_by_id
1130                .contains_key(&oid.as_subscription_id())
1131            || self.connection_by_id.contains_key(&oid.as_connection_id())
1132    }
1133
1134    pub fn id(&self) -> SchemaId {
1135        self.id
1136    }
1137
1138    pub fn database_id(&self) -> DatabaseId {
1139        self.database_id
1140    }
1141
1142    pub fn name(&self) -> String {
1143        self.name.clone()
1144    }
1145}
1146
1147impl OwnedByUserCatalog for SchemaCatalog {
1148    fn owner(&self) -> UserId {
1149        self.owner
1150    }
1151}
1152
1153impl From<&PbSchema> for SchemaCatalog {
1154    fn from(schema: &PbSchema) -> Self {
1155        Self {
1156            id: schema.id,
1157            owner: schema.owner,
1158            name: schema.name.clone(),
1159            database_id: schema.database_id,
1160            table_by_name: HashMap::new(),
1161            table_by_id: HashMap::new(),
1162            source_by_name: HashMap::new(),
1163            source_by_id: HashMap::new(),
1164            sink_by_name: HashMap::new(),
1165            sink_by_id: HashMap::new(),
1166            table_incoming_sinks: HashMap::new(),
1167            index_by_name: HashMap::new(),
1168            index_by_id: HashMap::new(),
1169            indexes_by_table_id: HashMap::new(),
1170            system_table_by_name: HashMap::new(),
1171            view_by_name: HashMap::new(),
1172            view_by_id: HashMap::new(),
1173            function_registry: FunctionRegistry::default(),
1174            function_by_name: HashMap::new(),
1175            function_by_id: HashMap::new(),
1176            connection_by_name: HashMap::new(),
1177            connection_by_id: HashMap::new(),
1178            secret_by_name: HashMap::new(),
1179            secret_by_id: HashMap::new(),
1180            _secret_source_ref: HashMap::new(),
1181            _secret_sink_ref: HashMap::new(),
1182            connection_source_ref: HashMap::new(),
1183            connection_sink_ref: HashMap::new(),
1184            subscription_by_name: HashMap::new(),
1185            subscription_by_id: HashMap::new(),
1186        }
1187    }
1188}
1189
1190#[cfg(test)]
1191mod tests {
1192    use risingwave_pb::catalog::PbSchema;
1193
1194    use super::SchemaCatalog;
1195
1196    #[test]
1197    fn test_drop_missing_relation_is_idempotent() {
1198        let mut schema = SchemaCatalog::from(&PbSchema::default());
1199        schema.drop_index(1.into());
1200        schema.drop_source(2.into());
1201    }
1202}