1use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use itertools::Itertools;
19use risingwave_common::catalog::{FunctionId, IndexId, StreamJobStatus, TableId};
20use risingwave_common::id::ObjectId;
21use risingwave_common::session_config::{SearchPath, USER_NAME_WILD_CARD};
22use risingwave_common::types::DataType;
23use risingwave_connector::sink::catalog::SinkCatalog;
24use risingwave_pb::catalog::{
25 PbConnection, PbDatabase, PbFunction, PbIndex, PbSchema, PbSecret, PbSink, PbSource,
26 PbSubscription, PbTable, PbView,
27};
28use risingwave_pb::common::PbObjectType;
29use risingwave_pb::hummock::HummockVersionStats;
30use risingwave_pb::meta::ObjectDependency as PbObjectDependency;
31
32use super::function_catalog::FunctionCatalog;
33use super::source_catalog::SourceCatalog;
34use super::subscription_catalog::{SubscriptionCatalog, SubscriptionState};
35use super::view_catalog::ViewCatalog;
36use super::{
37 CatalogError, CatalogResult, ConnectionId, SecretId, SinkId, SourceId, SubscriptionId, ViewId,
38};
39use crate::catalog::connection_catalog::ConnectionCatalog;
40use crate::catalog::database_catalog::DatabaseCatalog;
41use crate::catalog::schema_catalog::SchemaCatalog;
42use crate::catalog::secret_catalog::SecretCatalog;
43use crate::catalog::system_catalog::{
44 SystemTableCatalog, get_sys_tables_in_schema, get_sys_views_in_schema,
45};
46use crate::catalog::table_catalog::TableCatalog;
47use crate::catalog::{DatabaseId, IndexCatalog, RelationKind, SchemaId};
48use crate::expr::{Expr, ExprImpl};
49
50#[derive(Copy, Clone)]
51pub enum SchemaPath<'a> {
52 Name(&'a str),
53 Path(&'a SearchPath, &'a str),
55}
56
57impl<'a> SchemaPath<'a> {
58 pub fn new(
59 schema_name: Option<&'a str>,
60 search_path: &'a SearchPath,
61 user_name: &'a str,
62 ) -> Self {
63 match schema_name {
64 Some(schema_name) => SchemaPath::Name(schema_name),
65 None => SchemaPath::Path(search_path, user_name),
66 }
67 }
68
69 pub fn try_find<T, E>(
71 &self,
72 mut f: impl FnMut(&str) -> Result<Option<T>, E>,
73 ) -> Result<Option<(T, &'a str)>, E> {
74 match self {
75 SchemaPath::Name(schema_name) => Ok(f(schema_name)?.map(|t| (t, *schema_name))),
76 SchemaPath::Path(search_path, user_name) => {
77 for schema_name in search_path.path() {
78 let mut schema_name: &str = schema_name;
79 if schema_name == USER_NAME_WILD_CARD {
80 schema_name = user_name;
81 }
82 if let Ok(Some(res)) = f(schema_name) {
83 return Ok(Some((res, schema_name)));
84 }
85 }
86 Ok(None)
87 }
88 }
89 }
90}
91
92#[derive(Clone, Debug)]
93pub struct ObjectDependency {
94 pub object_id: ObjectId,
95 pub referenced_object_id: ObjectId,
96 pub referenced_object_type: PbObjectType,
97}
98
99impl From<PbObjectDependency> for ObjectDependency {
100 fn from(dependency: PbObjectDependency) -> Self {
101 let referenced_object_type = PbObjectType::try_from(dependency.referenced_object_type)
102 .unwrap_or(PbObjectType::Unspecified);
103 Self {
104 object_id: dependency.object_id,
105 referenced_object_id: dependency.referenced_object_id,
106 referenced_object_type,
107 }
108 }
109}
110
111pub struct Catalog {
123 database_by_name: HashMap<String, DatabaseCatalog>,
124 db_name_by_id: HashMap<DatabaseId, String>,
125 table_by_id: HashMap<TableId, Arc<TableCatalog>>,
127 table_stats: HummockVersionStats,
128 object_dependencies: HashMap<ObjectId, Vec<ObjectDependency>>,
129}
130
131#[expect(clippy::derivable_impls)]
132impl Default for Catalog {
133 fn default() -> Self {
134 Self {
135 database_by_name: HashMap::new(),
136 db_name_by_id: HashMap::new(),
137 table_by_id: HashMap::new(),
138 table_stats: HummockVersionStats::default(),
139 object_dependencies: HashMap::new(),
140 }
141 }
142}
143
144impl Catalog {
145 fn get_database_mut(&mut self, db_id: DatabaseId) -> Option<&mut DatabaseCatalog> {
146 let name = self.db_name_by_id.get(&db_id)?;
147 self.database_by_name.get_mut(name)
148 }
149
150 pub fn clear(&mut self) {
151 self.database_by_name.clear();
152 self.db_name_by_id.clear();
153 self.table_by_id.clear();
154 self.object_dependencies.clear();
155 }
156
157 pub fn create_database(&mut self, db: &PbDatabase) {
158 let name = db.name.clone();
159 let id = db.id;
160
161 self.database_by_name
162 .try_insert(name.clone(), db.into())
163 .unwrap();
164 self.db_name_by_id.try_insert(id, name).unwrap();
165 }
166
167 pub fn create_schema(&mut self, proto: &PbSchema) {
168 let database_id = proto.database_id;
169 let id = proto.id;
170 self.get_database_mut(database_id)
171 .unwrap()
172 .create_schema(proto);
173
174 for sys_table in get_sys_tables_in_schema(proto.name.as_str()) {
175 self.get_database_mut(database_id)
176 .unwrap()
177 .get_schema_mut(id)
178 .unwrap()
179 .create_sys_table(sys_table);
180 }
181 for mut sys_view in get_sys_views_in_schema(proto.name.as_str()) {
182 sys_view.database_id = database_id;
183 sys_view.schema_id = id;
184 self.get_database_mut(database_id)
185 .unwrap()
186 .get_schema_mut(id)
187 .unwrap()
188 .create_sys_view(Arc::new(sys_view));
189 }
190 }
191
192 pub fn create_table(&mut self, proto: &PbTable) {
193 let table = self
194 .get_database_mut(proto.database_id)
195 .unwrap()
196 .get_schema_mut(proto.schema_id)
197 .unwrap()
198 .create_table(proto);
199 self.table_by_id.insert(proto.id, table);
200 }
201
202 pub fn create_index(&mut self, proto: &PbIndex) {
203 self.get_database_mut(proto.database_id)
204 .unwrap()
205 .get_schema_mut(proto.schema_id)
206 .unwrap()
207 .create_index(proto);
208 }
209
210 pub fn create_source(&mut self, proto: &PbSource) {
211 self.get_database_mut(proto.database_id)
212 .unwrap()
213 .get_schema_mut(proto.schema_id)
214 .unwrap()
215 .create_source(proto);
216 }
217
218 pub fn create_sink(&mut self, proto: &PbSink) {
219 self.get_database_mut(proto.database_id)
220 .unwrap()
221 .get_schema_mut(proto.schema_id)
222 .unwrap()
223 .create_sink(proto);
224 }
225
226 pub fn create_subscription(&mut self, proto: &PbSubscription) {
227 self.get_database_mut(proto.database_id)
228 .unwrap()
229 .get_schema_mut(proto.schema_id)
230 .unwrap()
231 .create_subscription(proto);
232 }
233
234 pub fn create_secret(&mut self, proto: &PbSecret) {
235 self.get_database_mut(proto.database_id)
236 .unwrap()
237 .get_schema_mut(proto.schema_id)
238 .unwrap()
239 .create_secret(proto);
240 }
241
242 pub fn create_view(&mut self, proto: &PbView) {
243 self.get_database_mut(proto.database_id)
244 .unwrap()
245 .get_schema_mut(proto.schema_id)
246 .unwrap()
247 .create_view(proto);
248 }
249
250 pub fn create_function(&mut self, proto: &PbFunction) {
251 self.get_database_mut(proto.database_id)
252 .unwrap()
253 .get_schema_mut(proto.schema_id)
254 .unwrap()
255 .create_function(proto);
256 }
257
258 pub fn create_connection(&mut self, proto: &PbConnection) {
259 self.get_database_mut(proto.database_id)
260 .unwrap()
261 .get_schema_mut(proto.schema_id)
262 .unwrap()
263 .create_connection(proto);
264 }
265
266 pub fn drop_connection(
267 &mut self,
268 db_id: DatabaseId,
269 schema_id: SchemaId,
270 connection_id: ConnectionId,
271 ) {
272 self.get_database_mut(db_id)
273 .unwrap()
274 .get_schema_mut(schema_id)
275 .unwrap()
276 .drop_connection(connection_id);
277 }
278
279 pub fn update_connection(&mut self, proto: &PbConnection) {
280 let database = self.get_database_mut(proto.database_id).unwrap();
281 let schema = database.get_schema_mut(proto.schema_id).unwrap();
282 if schema.get_connection_by_id(proto.id).is_some() {
283 schema.update_connection(proto);
284 } else {
285 schema.create_connection(proto);
287 database
288 .iter_schemas_mut()
289 .find(|schema| {
290 schema.id() != proto.schema_id
291 && schema.get_connection_by_id(proto.id).is_some()
292 })
293 .unwrap()
294 .drop_connection(proto.id);
295 }
296 }
297
298 pub fn update_secret(&mut self, proto: &PbSecret) {
299 let database = self.get_database_mut(proto.database_id).unwrap();
300 let schema = database.get_schema_mut(proto.schema_id).unwrap();
301 let secret_id = proto.id;
302 if schema.get_secret_by_id(secret_id).is_some() {
303 schema.update_secret(proto);
304 } else {
305 schema.create_secret(proto);
307 database
308 .iter_schemas_mut()
309 .find(|schema| {
310 schema.id() != proto.schema_id && schema.get_secret_by_id(secret_id).is_some()
311 })
312 .unwrap()
313 .drop_secret(secret_id);
314 }
315 }
316
317 pub fn drop_database(&mut self, db_id: DatabaseId) {
318 let name = self.db_name_by_id.remove(&db_id).unwrap();
319 let database = self.database_by_name.remove(&name).unwrap();
320 let object_ids: HashSet<ObjectId> = database.iter_object_ids().collect();
321 self.remove_object_dependencies_for_objects(&object_ids);
322 database.iter_all_table_ids().for_each(|table| {
323 self.table_by_id.remove(&table);
324 });
325 }
326
327 pub fn drop_schema(&mut self, db_id: DatabaseId, schema_id: SchemaId) {
328 let object_ids = self
329 .get_database_by_id(db_id)
330 .ok()
331 .and_then(|db| db.get_schema_by_id(schema_id))
332 .map(|schema| schema.iter_object_ids().collect::<HashSet<_>>())
333 .unwrap_or_default();
334 self.remove_object_dependencies_for_objects(&object_ids);
335 self.get_database_mut(db_id).unwrap().drop_schema(schema_id);
336 }
337
338 pub fn drop_table(&mut self, db_id: DatabaseId, schema_id: SchemaId, tb_id: TableId) {
339 self.remove_object_dependencies_for_object(tb_id.as_object_id());
340 self.table_by_id.remove(&tb_id);
341 self.get_database_mut(db_id)
342 .unwrap()
343 .get_schema_mut(schema_id)
344 .unwrap()
345 .drop_table(tb_id);
346 }
347
348 pub fn update_table(&mut self, proto: &PbTable) {
349 let database = self.get_database_mut(proto.database_id).unwrap();
350 let schema = database.get_schema_mut(proto.schema_id).unwrap();
351 let table = if schema.get_table_by_id(proto.id).is_some() {
352 schema.update_table(proto)
353 } else {
354 let new_table = schema.create_table(proto);
356 database
357 .iter_schemas_mut()
358 .find(|schema| {
359 schema.id() != proto.schema_id
360 && schema.get_created_table_by_id(proto.id).is_some()
361 })
362 .unwrap()
363 .drop_table(proto.id);
364 new_table
365 };
366
367 self.table_by_id.insert(proto.id, table);
368 }
369
370 pub fn update_database(&mut self, proto: &PbDatabase) {
371 let id = proto.id;
372 let name = proto.name.clone();
373
374 let old_database_name = self.db_name_by_id.get(&id).unwrap().to_owned();
375 if old_database_name != name {
376 let mut database = self.database_by_name.remove(&old_database_name).unwrap();
377 database.name.clone_from(&name);
378 database.owner = proto.owner;
379 database.resource_group.clone_from(&proto.resource_group);
380 database.barrier_interval_ms = proto.barrier_interval_ms;
381 database.checkpoint_frequency = proto.checkpoint_frequency;
382 self.database_by_name.insert(name.clone(), database);
383 self.db_name_by_id.insert(id, name);
384 } else {
385 let database = self.get_database_mut(id).unwrap();
386 database.name = name;
387 database.owner = proto.owner;
388 database.resource_group = proto.resource_group.clone();
389 database.barrier_interval_ms = proto.barrier_interval_ms;
390 database.checkpoint_frequency = proto.checkpoint_frequency;
391 }
392 }
393
394 pub fn update_schema(&mut self, proto: &PbSchema) {
395 self.get_database_mut(proto.database_id)
396 .unwrap()
397 .update_schema(proto);
398 }
399
400 pub fn update_index(&mut self, proto: &PbIndex) {
401 let database = self.get_database_mut(proto.database_id).unwrap();
402 let schema = database.get_schema_mut(proto.schema_id).unwrap();
403 if schema.get_index_by_id(proto.id).is_some() {
404 schema.update_index(proto);
405 } else {
406 schema.create_index(proto);
408 database
409 .iter_schemas_mut()
410 .find(|schema| {
411 schema.id() != proto.schema_id && schema.get_index_by_id(proto.id).is_some()
412 })
413 .unwrap()
414 .drop_index(proto.id);
415 }
416 }
417
418 pub fn drop_source(&mut self, db_id: DatabaseId, schema_id: SchemaId, source_id: SourceId) {
419 self.remove_object_dependencies_for_object(source_id.as_object_id());
420 self.get_database_mut(db_id)
421 .unwrap()
422 .get_schema_mut(schema_id)
423 .unwrap()
424 .drop_source(source_id);
425 }
426
427 pub fn update_source(&mut self, proto: &PbSource) {
428 let database = self.get_database_mut(proto.database_id).unwrap();
429 let schema = database.get_schema_mut(proto.schema_id).unwrap();
430 if schema.get_source_by_id(proto.id).is_some() {
431 schema.update_source(proto);
432 } else {
433 schema.create_source(proto);
435 database
436 .iter_schemas_mut()
437 .find(|schema| {
438 schema.id() != proto.schema_id && schema.get_source_by_id(proto.id).is_some()
439 })
440 .unwrap()
441 .drop_source(proto.id);
442 }
443 }
444
445 pub fn drop_sink(&mut self, db_id: DatabaseId, schema_id: SchemaId, sink_id: SinkId) {
446 self.remove_object_dependencies_for_object(sink_id.as_object_id());
447 self.get_database_mut(db_id)
448 .unwrap()
449 .get_schema_mut(schema_id)
450 .unwrap()
451 .drop_sink(sink_id);
452 }
453
454 pub fn drop_secret(&mut self, db_id: DatabaseId, schema_id: SchemaId, secret_id: SecretId) {
455 self.remove_object_dependencies_for_object(secret_id.as_object_id());
456 self.get_database_mut(db_id)
457 .unwrap()
458 .get_schema_mut(schema_id)
459 .unwrap()
460 .drop_secret(secret_id);
461 }
462
463 pub fn update_sink(&mut self, proto: &PbSink) {
464 let database = self.get_database_mut(proto.database_id).unwrap();
465 let schema = database.get_schema_mut(proto.schema_id).unwrap();
466 if schema.get_sink_by_id(proto.id).is_some() {
467 schema.update_sink(proto);
468 } else {
469 schema.create_sink(proto);
471 database
472 .iter_schemas_mut()
473 .find(|schema| {
474 schema.id() != proto.schema_id && schema.get_sink_by_id(proto.id).is_some()
475 })
476 .unwrap()
477 .drop_sink(proto.id);
478 }
479 }
480
481 pub fn drop_subscription(
482 &mut self,
483 db_id: DatabaseId,
484 schema_id: SchemaId,
485 subscription_id: SubscriptionId,
486 ) {
487 self.remove_object_dependencies_for_object(subscription_id.as_object_id());
488 self.get_database_mut(db_id)
489 .unwrap()
490 .get_schema_mut(schema_id)
491 .unwrap()
492 .drop_subscription(subscription_id);
493 }
494
495 pub fn update_subscription(&mut self, proto: &PbSubscription) {
496 let database = self.get_database_mut(proto.database_id).unwrap();
497 let schema = database.get_schema_mut(proto.schema_id).unwrap();
498 if schema.get_subscription_by_id(proto.id).is_some() {
499 schema.update_subscription(proto);
500 } else {
501 schema.create_subscription(proto);
503 database
504 .iter_schemas_mut()
505 .find(|schema| {
506 schema.id() != proto.schema_id
507 && schema.get_subscription_by_id(proto.id).is_some()
508 })
509 .unwrap()
510 .drop_subscription(proto.id);
511 }
512 }
513
514 pub fn drop_index(&mut self, db_id: DatabaseId, schema_id: SchemaId, index_id: IndexId) {
515 self.remove_object_dependencies_for_object(index_id.as_object_id());
516 self.get_database_mut(db_id)
517 .unwrap()
518 .get_schema_mut(schema_id)
519 .unwrap()
520 .drop_index(index_id);
521 }
522
523 pub fn drop_view(&mut self, db_id: DatabaseId, schema_id: SchemaId, view_id: ViewId) {
524 self.remove_object_dependencies_for_object(view_id.as_object_id());
525 self.get_database_mut(db_id)
526 .unwrap()
527 .get_schema_mut(schema_id)
528 .unwrap()
529 .drop_view(view_id);
530 }
531
532 pub fn update_view(&mut self, proto: &PbView) {
533 let database = self.get_database_mut(proto.database_id).unwrap();
534 let schema = database.get_schema_mut(proto.schema_id).unwrap();
535 if schema.get_view_by_id(proto.id).is_some() {
536 schema.update_view(proto);
537 } else {
538 schema.create_view(proto);
540 database
541 .iter_schemas_mut()
542 .find(|schema| {
543 schema.id() != proto.schema_id && schema.get_view_by_id(proto.id).is_some()
544 })
545 .unwrap()
546 .drop_view(proto.id);
547 }
548 }
549
550 pub fn drop_function(
551 &mut self,
552 db_id: DatabaseId,
553 schema_id: SchemaId,
554 function_id: FunctionId,
555 ) {
556 self.remove_object_dependencies_for_object(function_id.as_object_id());
557 self.get_database_mut(db_id)
558 .unwrap()
559 .get_schema_mut(schema_id)
560 .unwrap()
561 .drop_function(function_id);
562 }
563
564 pub fn update_function(&mut self, proto: &PbFunction) {
565 let database = self.get_database_mut(proto.database_id).unwrap();
566 let schema = database.get_schema_mut(proto.schema_id).unwrap();
567 if schema.get_function_by_id(proto.id).is_some() {
568 schema.update_function(proto);
569 } else {
570 schema.create_function(proto);
572 database
573 .iter_schemas_mut()
574 .find(|schema| {
575 schema.id() != proto.schema_id && schema.get_function_by_id(proto.id).is_some()
576 })
577 .unwrap()
578 .drop_function(proto.id);
579 }
580
581 self.get_database_mut(proto.database_id)
582 .unwrap()
583 .get_schema_mut(proto.schema_id)
584 .unwrap()
585 .update_function(proto);
586 }
587
588 pub fn get_database_by_name(&self, db_name: &str) -> CatalogResult<&DatabaseCatalog> {
589 self.database_by_name
590 .get(db_name)
591 .ok_or_else(|| CatalogError::not_found("database", db_name))
592 }
593
594 pub fn get_database_by_id(&self, db_id: DatabaseId) -> CatalogResult<&DatabaseCatalog> {
595 let db_name = self
596 .db_name_by_id
597 .get(&db_id)
598 .ok_or_else(|| CatalogError::not_found("db_id", db_id.to_string()))?;
599 self.database_by_name
600 .get(db_name)
601 .ok_or_else(|| CatalogError::not_found("database", db_name))
602 }
603
604 pub fn find_schema_secret_by_secret_id(
605 &self,
606 db_name: &str,
607 secret_id: SecretId,
608 ) -> CatalogResult<(String, String)> {
609 let db = self.get_database_by_name(db_name)?;
610 let schema_secret = db
611 .iter_schemas()
612 .find_map(|schema| {
613 schema
614 .get_secret_by_id(secret_id)
615 .map(|secret| (schema.name(), secret.name.clone()))
616 })
617 .ok_or_else(|| CatalogError::not_found("secret", secret_id.to_string()))?;
618 Ok(schema_secret)
619 }
620
621 pub fn get_all_schema_names(&self, db_name: &str) -> CatalogResult<Vec<String>> {
622 Ok(self.get_database_by_name(db_name)?.get_all_schema_names())
623 }
624
625 pub fn iter_schemas(
626 &self,
627 db_name: &str,
628 ) -> CatalogResult<impl Iterator<Item = &SchemaCatalog>> {
629 Ok(self.get_database_by_name(db_name)?.iter_schemas())
630 }
631
632 pub fn get_all_database_names(&self) -> Vec<String> {
633 self.database_by_name.keys().cloned().collect_vec()
634 }
635
636 pub fn iter_databases(&self) -> impl Iterator<Item = &DatabaseCatalog> {
637 self.database_by_name.values()
638 }
639
640 pub fn get_schema_by_name(
641 &self,
642 db_name: &str,
643 schema_name: &str,
644 ) -> CatalogResult<&SchemaCatalog> {
645 self.get_database_by_name(db_name)?
646 .get_schema_by_name(schema_name)
647 .ok_or_else(|| CatalogError::not_found("schema", schema_name))
648 }
649
650 pub fn get_table_name_by_id(&self, table_id: TableId) -> CatalogResult<String> {
651 self.get_any_table_by_id(table_id)
652 .map(|table| table.name.clone())
653 }
654
655 pub fn get_schema_by_id(
656 &self,
657 db_id: DatabaseId,
658 schema_id: SchemaId,
659 ) -> CatalogResult<&SchemaCatalog> {
660 self.get_database_by_id(db_id)?
661 .get_schema_by_id(schema_id)
662 .ok_or_else(|| CatalogError::not_found("schema_id", schema_id.to_string()))
663 }
664
665 pub fn first_valid_schema(
667 &self,
668 db_name: &str,
669 search_path: &SearchPath,
670 user_name: &str,
671 ) -> CatalogResult<&SchemaCatalog> {
672 for path in search_path.real_path() {
673 let mut schema_name: &str = path;
674 if schema_name == USER_NAME_WILD_CARD {
675 schema_name = user_name;
676 }
677
678 if let schema_catalog @ Ok(_) = self.get_schema_by_name(db_name, schema_name) {
679 return schema_catalog;
680 }
681 }
682 Err(CatalogError::not_found(
683 "first valid schema",
684 "no schema has been selected to create in".to_owned(),
685 ))
686 }
687
688 pub fn get_source_by_id<'a>(
689 &self,
690 db_name: &'a str,
691 schema_path: SchemaPath<'a>,
692 source_id: SourceId,
693 ) -> CatalogResult<(&Arc<SourceCatalog>, &'a str)> {
694 schema_path
695 .try_find(|schema_name| -> CatalogResult<_> {
696 Ok(self
697 .get_schema_by_name(db_name, schema_name)?
698 .get_source_by_id(source_id))
699 })?
700 .ok_or_else(|| CatalogError::not_found("source", source_id.to_string()))
701 }
702
703 pub fn get_source_by_id_with_db(
705 &self,
706 db_name: &str,
707 source_id: SourceId,
708 ) -> CatalogResult<&Arc<SourceCatalog>> {
709 for schema in self.get_database_by_name(db_name)?.iter_schemas() {
710 if let Some(source) = schema.get_source_by_id(source_id) {
711 return Ok(source);
712 }
713 }
714 Err(CatalogError::not_found("source", source_id.to_string()))
715 }
716
717 pub fn get_table_by_name<'a>(
718 &self,
719 db_name: &str,
720 schema_path: SchemaPath<'a>,
721 table_name: &str,
722 bind_creating: bool,
723 ) -> CatalogResult<(&Arc<TableCatalog>, &'a str)> {
724 schema_path
725 .try_find(|schema_name| -> CatalogResult<_> {
726 Ok(self
727 .get_schema_by_name(db_name, schema_name)?
728 .get_table_by_name(table_name, bind_creating))
729 })?
730 .ok_or_else(|| CatalogError::not_found("table", table_name))
731 }
732
733 pub fn get_any_table_by_name<'a>(
736 &self,
737 db_name: &str,
738 schema_path: SchemaPath<'a>,
739 table_name: &str,
740 ) -> CatalogResult<(&Arc<TableCatalog>, &'a str)> {
741 self.get_table_by_name(db_name, schema_path, table_name, true)
742 }
743
744 pub fn get_created_table_by_name<'a>(
747 &self,
748 db_name: &str,
749 schema_path: SchemaPath<'a>,
750 table_name: &str,
751 ) -> CatalogResult<(&Arc<TableCatalog>, &'a str)> {
752 self.get_table_by_name(db_name, schema_path, table_name, false)
753 }
754
755 pub fn get_any_table_by_id(&self, table_id: TableId) -> CatalogResult<&Arc<TableCatalog>> {
756 self.table_by_id
757 .get(&table_id)
758 .ok_or_else(|| CatalogError::not_found("table id", table_id.to_string()))
759 }
760
761 pub fn get_created_table_by_id_with_db(
763 &self,
764 db_name: &str,
765 table_id: u32,
766 ) -> CatalogResult<&Arc<TableCatalog>> {
767 let table_id = TableId::from(table_id);
768 for schema in self.get_database_by_name(db_name)?.iter_schemas() {
769 if let Some(table) = schema.get_created_table_by_id(table_id) {
770 return Ok(table);
771 }
772 }
773 Err(CatalogError::not_found("table id", table_id.to_string()))
774 }
775
776 pub fn iter_tables(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
777 self.table_by_id.values()
778 }
779
780 pub fn iter_backfilling_internal_tables(&self) -> impl Iterator<Item = &Arc<TableCatalog>> {
781 self.table_by_id
782 .values()
783 .filter(|t| t.is_internal_table() && !t.is_created())
784 }
785
786 pub fn alter_table_name_by_id(&mut self, table_id: TableId, table_name: &str) {
788 let mut found = false;
789 for database in self.database_by_name.values() {
790 if !found {
791 for schema in database.iter_schemas() {
792 if schema.iter_user_table().any(|t| t.id() == table_id) {
793 found = true;
794 break;
795 }
796 }
797 }
798 }
799
800 if found {
801 let mut table = self.get_any_table_by_id(table_id).unwrap().to_prost();
802 table.name = table_name.to_owned();
803 self.update_table(&table);
804 }
805 }
806
807 #[cfg(test)]
808 pub fn insert_table_id_mapping(&mut self, table_id: TableId, fragment_id: super::FragmentId) {
809 self.table_by_id.insert(
810 table_id,
811 Arc::new(TableCatalog {
812 fragment_id,
813 ..Default::default()
814 }),
815 );
816 }
817
818 pub fn get_sys_table_by_name(
819 &self,
820 db_name: &str,
821 schema_name: &str,
822 table_name: &str,
823 ) -> CatalogResult<&Arc<SystemTableCatalog>> {
824 self.get_schema_by_name(db_name, schema_name)?
825 .get_system_table_by_name(table_name)
826 .ok_or_else(|| CatalogError::not_found("table", table_name))
827 }
828
829 pub fn get_source_by_name<'a>(
830 &self,
831 db_name: &str,
832 schema_path: SchemaPath<'a>,
833 source_name: &str,
834 ) -> CatalogResult<(&Arc<SourceCatalog>, &'a str)> {
835 schema_path
836 .try_find(|schema_name| -> CatalogResult<_> {
837 Ok(self
838 .get_schema_by_name(db_name, schema_name)?
839 .get_source_by_name(source_name))
840 })?
841 .ok_or_else(|| CatalogError::not_found("source", source_name))
842 }
843
844 pub fn get_sink_by_name<'a>(
845 &self,
846 db_name: &str,
847 schema_path: SchemaPath<'a>,
848 sink_name: &str,
849 bind_creating: bool,
850 ) -> CatalogResult<(&Arc<SinkCatalog>, &'a str)> {
851 schema_path
852 .try_find(|schema_name| -> CatalogResult<_> {
853 Ok(self
854 .get_schema_by_name(db_name, schema_name)?
855 .get_sink_by_name(sink_name, bind_creating))
856 })?
857 .ok_or_else(|| CatalogError::not_found("sink", sink_name))
858 }
859
860 pub fn get_any_sink_by_name<'a>(
861 &self,
862 db_name: &str,
863 schema_path: SchemaPath<'a>,
864 sink_name: &str,
865 ) -> CatalogResult<(&Arc<SinkCatalog>, &'a str)> {
866 self.get_sink_by_name(db_name, schema_path, sink_name, true)
867 }
868
869 pub fn get_created_sink_by_name<'a>(
870 &self,
871 db_name: &str,
872 schema_path: SchemaPath<'a>,
873 sink_name: &str,
874 ) -> CatalogResult<(&Arc<SinkCatalog>, &'a str)> {
875 self.get_sink_by_name(db_name, schema_path, sink_name, false)
876 }
877
878 pub fn get_subscription_by_name<'a>(
879 &self,
880 db_name: &str,
881 schema_path: SchemaPath<'a>,
882 subscription_name: &str,
883 ) -> CatalogResult<(&Arc<SubscriptionCatalog>, &'a str)> {
884 schema_path
885 .try_find(|schema_name| -> CatalogResult<_> {
886 Ok(self
887 .get_schema_by_name(db_name, schema_name)?
888 .get_subscription_by_name(subscription_name))
889 })?
890 .ok_or_else(|| CatalogError::not_found("subscription", subscription_name))
891 }
892
893 pub fn get_index_by_name<'a>(
894 &self,
895 db_name: &str,
896 schema_path: SchemaPath<'a>,
897 index_name: &str,
898 ) -> CatalogResult<(&Arc<IndexCatalog>, &'a str)> {
899 schema_path
900 .try_find(|schema_name| -> CatalogResult<_> {
901 Ok(self
902 .get_schema_by_name(db_name, schema_name)?
903 .get_created_index_by_name(index_name))
904 })?
905 .ok_or_else(|| CatalogError::not_found("index", index_name))
906 }
907
908 pub fn get_any_index_by_name<'a>(
909 &self,
910 db_name: &str,
911 schema_path: SchemaPath<'a>,
912 index_name: &str,
913 ) -> CatalogResult<(&Arc<IndexCatalog>, &'a str)> {
914 schema_path
915 .try_find(|schema_name| -> CatalogResult<_> {
916 Ok(self
917 .get_schema_by_name(db_name, schema_name)?
918 .get_any_index_by_name(index_name))
919 })?
920 .ok_or_else(|| CatalogError::not_found("index", index_name))
921 }
922
923 pub fn get_index_by_id(
924 &self,
925 db_name: &str,
926 index_id: u32,
927 ) -> CatalogResult<&Arc<IndexCatalog>> {
928 let index_id = IndexId::from(index_id);
929 for schema in self.get_database_by_name(db_name)?.iter_schemas() {
930 if let Some(index) = schema.get_index_by_id(index_id) {
931 return Ok(index);
932 }
933 }
934 Err(CatalogError::not_found("index", index_id.to_string()))
935 }
936
937 pub fn get_view_by_name<'a>(
938 &self,
939 db_name: &str,
940 schema_path: SchemaPath<'a>,
941 view_name: &str,
942 ) -> CatalogResult<(&Arc<ViewCatalog>, &'a str)> {
943 schema_path
944 .try_find(|schema_name| -> CatalogResult<_> {
945 Ok(self
946 .get_schema_by_name(db_name, schema_name)?
947 .get_view_by_name(view_name))
948 })?
949 .ok_or_else(|| CatalogError::not_found("view", view_name))
950 }
951
952 pub fn relation_kind(
954 &self,
955 db_name: &str,
956 schema_path: SchemaPath<'_>,
957 name: &str,
958 ) -> Option<RelationKind> {
959 let (kind, _) = schema_path
960 .try_find(|schema_name| -> CatalogResult<_> {
961 Ok(self
962 .get_schema_by_name(db_name, schema_name)?
963 .relation_kind(name))
964 })
965 .ok()??;
966 Some(kind)
967 }
968
969 pub fn wrong_kind_for_drop(
972 &self,
973 db_name: &str,
974 schema_path: SchemaPath<'_>,
975 name: &str,
976 expected: RelationKind,
977 ) -> Option<CatalogError> {
978 let kind = self.relation_kind(db_name, schema_path, name)?;
979 (kind != expected).then(|| kind.bad_drop_error())
980 }
981
982 pub fn get_view_by_id(&self, db_name: &str, view_id: u32) -> CatalogResult<Arc<ViewCatalog>> {
983 for schema in self.get_database_by_name(db_name)?.iter_schemas() {
984 if let Some(view) = schema.get_view_by_id(ViewId::from(view_id)) {
985 return Ok(view.clone());
986 }
987 }
988 Err(CatalogError::not_found("view", view_id.to_string()))
989 }
990
991 pub fn get_secret_by_name<'a>(
992 &self,
993 db_name: &str,
994 schema_path: SchemaPath<'a>,
995 secret_name: &str,
996 ) -> CatalogResult<(&Arc<SecretCatalog>, &'a str)> {
997 schema_path
998 .try_find(|schema_name| -> CatalogResult<_> {
999 Ok(self
1000 .get_schema_by_name(db_name, schema_name)?
1001 .get_secret_by_name(secret_name))
1002 })?
1003 .ok_or_else(|| CatalogError::not_found("secret", secret_name))
1004 }
1005
1006 pub fn get_connection_by_id(
1007 &self,
1008 db_name: &str,
1009 connection_id: ConnectionId,
1010 ) -> CatalogResult<&Arc<ConnectionCatalog>> {
1011 for schema in self.get_database_by_name(db_name)?.iter_schemas() {
1012 if let Some(conn) = schema.get_connection_by_id(connection_id) {
1013 return Ok(conn);
1014 }
1015 }
1016 Err(CatalogError::not_found(
1017 "connection",
1018 connection_id.to_string(),
1019 ))
1020 }
1021
1022 pub fn get_connection_by_name<'a>(
1023 &self,
1024 db_name: &str,
1025 schema_path: SchemaPath<'a>,
1026 connection_name: &str,
1027 ) -> CatalogResult<(&Arc<ConnectionCatalog>, &'a str)> {
1028 schema_path
1029 .try_find(|schema_name| -> CatalogResult<_> {
1030 Ok(self
1031 .get_schema_by_name(db_name, schema_name)?
1032 .get_connection_by_name(connection_name))
1033 })?
1034 .ok_or_else(|| CatalogError::not_found("connection", connection_name))
1035 }
1036
1037 pub fn get_function_by_name_inputs<'a>(
1038 &self,
1039 db_name: &str,
1040 schema_path: SchemaPath<'a>,
1041 function_name: &str,
1042 inputs: &mut [ExprImpl],
1043 ) -> CatalogResult<(&Arc<FunctionCatalog>, &'a str)> {
1044 schema_path
1045 .try_find(|schema_name| -> CatalogResult<_> {
1046 Ok(self
1047 .get_schema_by_name(db_name, schema_name)?
1048 .get_function_by_name_inputs(function_name, inputs))
1049 })?
1050 .ok_or_else(|| {
1051 CatalogError::not_found(
1052 "function",
1053 format!(
1054 "{}({})",
1055 function_name,
1056 inputs
1057 .iter()
1058 .map(|a| a.return_type().to_string())
1059 .join(", ")
1060 ),
1061 )
1062 })
1063 }
1064
1065 pub fn get_function_by_name_args<'a>(
1066 &self,
1067 db_name: &str,
1068 schema_path: SchemaPath<'a>,
1069 function_name: &str,
1070 args: &[DataType],
1071 ) -> CatalogResult<(&Arc<FunctionCatalog>, &'a str)> {
1072 schema_path
1073 .try_find(|schema_name| -> CatalogResult<_> {
1074 Ok(self
1075 .get_schema_by_name(db_name, schema_name)?
1076 .get_function_by_name_args(function_name, args))
1077 })?
1078 .ok_or_else(|| {
1079 CatalogError::not_found(
1080 "function",
1081 format!(
1082 "{}({})",
1083 function_name,
1084 args.iter().map(|a| a.to_string()).join(", ")
1085 ),
1086 )
1087 })
1088 }
1089
1090 pub fn get_functions_by_name<'a>(
1092 &self,
1093 db_name: &str,
1094 schema_path: SchemaPath<'a>,
1095 function_name: &str,
1096 ) -> CatalogResult<(Vec<&Arc<FunctionCatalog>>, &'a str)> {
1097 schema_path
1098 .try_find(|schema_name| -> CatalogResult<_> {
1099 Ok(self
1100 .get_schema_by_name(db_name, schema_name)?
1101 .get_functions_by_name(function_name))
1102 })?
1103 .ok_or_else(|| CatalogError::not_found("function", function_name))
1104 }
1105
1106 pub fn check_relation_name_duplicated(
1108 &self,
1109 db_name: &str,
1110 schema_name: &str,
1111 relation_name: &str,
1112 ) -> CatalogResult<()> {
1113 let schema = self.get_schema_by_name(db_name, schema_name)?;
1114
1115 if let Some(table) = schema.get_any_table_by_name(relation_name) {
1116 let is_creating = table.stream_job_status == StreamJobStatus::Creating;
1117 if table.is_index() {
1118 Err(CatalogError::duplicated_under_creation(
1119 "index",
1120 relation_name.to_owned(),
1121 is_creating,
1122 ))
1123 } else if table.is_mview() {
1124 Err(CatalogError::duplicated_under_creation(
1125 "materialized view",
1126 relation_name.to_owned(),
1127 is_creating,
1128 ))
1129 } else {
1130 Err(CatalogError::duplicated_under_creation(
1131 "table",
1132 relation_name.to_owned(),
1133 is_creating,
1134 ))
1135 }
1136 } else if schema.get_source_by_name(relation_name).is_some() {
1137 Err(CatalogError::duplicated("source", relation_name))
1138 } else if let Some(sink) = schema.get_any_sink_by_name(relation_name) {
1139 Err(CatalogError::duplicated_under_creation(
1140 "sink",
1141 relation_name.to_owned(),
1142 !sink.is_created(),
1143 ))
1144 } else if schema.get_view_by_name(relation_name).is_some() {
1145 Err(CatalogError::duplicated("view", relation_name))
1146 } else if let Some(subscription) = schema.get_subscription_by_name(relation_name) {
1147 let is_not_created = subscription.subscription_state != SubscriptionState::Created;
1148 Err(CatalogError::duplicated_under_creation(
1149 "subscription",
1150 relation_name.to_owned(),
1151 is_not_created,
1152 ))
1153 } else {
1154 Ok(())
1155 }
1156 }
1157
1158 pub fn check_function_name_duplicated(
1159 &self,
1160 db_name: &str,
1161 schema_name: &str,
1162 function_name: &str,
1163 arg_types: &[DataType],
1164 ) -> CatalogResult<()> {
1165 let schema = self.get_schema_by_name(db_name, schema_name)?;
1166
1167 if schema
1168 .get_function_by_name_args(function_name, arg_types)
1169 .is_some()
1170 {
1171 let name = format!(
1172 "{function_name}({})",
1173 arg_types.iter().map(|t| t.to_string()).join(",")
1174 );
1175 Err(CatalogError::duplicated("function", name))
1176 } else {
1177 Ok(())
1178 }
1179 }
1180
1181 pub fn check_connection_name_duplicated(
1183 &self,
1184 db_name: &str,
1185 schema_name: &str,
1186 connection_name: &str,
1187 ) -> CatalogResult<()> {
1188 let schema = self.get_schema_by_name(db_name, schema_name)?;
1189
1190 if schema.get_connection_by_name(connection_name).is_some() {
1191 Err(CatalogError::duplicated("connection", connection_name))
1192 } else {
1193 Ok(())
1194 }
1195 }
1196
1197 pub fn check_secret_name_duplicated(
1198 &self,
1199 db_name: &str,
1200 schema_name: &str,
1201 secret_name: &str,
1202 ) -> CatalogResult<()> {
1203 let schema = self.get_schema_by_name(db_name, schema_name)?;
1204
1205 if schema.get_secret_by_name(secret_name).is_some() {
1206 Err(CatalogError::duplicated("secret", secret_name))
1207 } else {
1208 Ok(())
1209 }
1210 }
1211
1212 pub fn table_stats(&self) -> &HummockVersionStats {
1213 &self.table_stats
1214 }
1215
1216 pub fn set_table_stats(&mut self, table_stats: HummockVersionStats) {
1217 self.table_stats = table_stats;
1218 }
1219
1220 pub fn set_object_dependencies(&mut self, dependencies: Vec<PbObjectDependency>) {
1221 self.object_dependencies.clear();
1222 self.insert_object_dependencies(dependencies);
1223 }
1224
1225 pub fn insert_object_dependencies(&mut self, dependencies: Vec<PbObjectDependency>) {
1226 let mut grouped: HashMap<ObjectId, Vec<ObjectDependency>> = HashMap::new();
1227 for dependency in dependencies {
1228 let dependency = ObjectDependency::from(dependency);
1229 grouped
1230 .entry(dependency.object_id)
1231 .or_default()
1232 .push(dependency);
1233 }
1234 for (object_id, deps) in grouped {
1235 self.object_dependencies.insert(object_id, deps);
1236 }
1237 }
1238
1239 pub fn iter_object_dependencies(&self) -> impl Iterator<Item = &ObjectDependency> {
1240 self.object_dependencies
1241 .values()
1242 .flat_map(|deps| deps.iter())
1243 }
1244
1245 fn remove_object_dependencies_for_object(&mut self, object_id: ObjectId) {
1246 let mut object_ids = HashSet::new();
1247 object_ids.insert(object_id);
1248 self.remove_object_dependencies_for_objects(&object_ids);
1249 }
1250
1251 fn remove_object_dependencies_for_objects(&mut self, object_ids: &HashSet<ObjectId>) {
1252 if object_ids.is_empty() {
1253 return;
1254 }
1255 self.object_dependencies.retain(|object_id, deps| {
1256 if object_ids.contains(object_id) {
1257 return false;
1258 }
1259 deps.retain(|dep| !object_ids.contains(&dep.referenced_object_id));
1260 !deps.is_empty()
1261 });
1262 }
1263
1264 pub fn get_all_indexes_related_to_object(
1265 &self,
1266 db_id: DatabaseId,
1267 schema_id: SchemaId,
1268 mv_id: TableId,
1269 ) -> Vec<Arc<IndexCatalog>> {
1270 self.get_database_by_id(db_id)
1271 .unwrap()
1272 .get_schema_by_id(schema_id)
1273 .unwrap()
1274 .get_any_indexes_by_table_id(mv_id)
1275 }
1276
1277 pub fn get_id_by_class_name(
1278 &self,
1279 db_name: &str,
1280 schema_path: SchemaPath<'_>,
1281 class_name: &str,
1282 ) -> CatalogResult<ObjectId> {
1283 schema_path
1284 .try_find(|schema_name| -> CatalogResult<_> {
1285 let schema = self.get_schema_by_name(db_name, schema_name)?;
1286
1287 if let Some(item) = schema.get_system_table_by_name(class_name) {
1288 Ok(Some(item.id().as_object_id()))
1289 } else if let Some(item) = schema.get_any_table_by_name(class_name) {
1290 Ok(Some(item.id().as_object_id()))
1291 } else if let Some(item) = schema.get_any_index_by_name(class_name) {
1292 Ok(Some(item.id.as_object_id()))
1293 } else if let Some(item) = schema.get_source_by_name(class_name) {
1294 Ok(Some(item.id.as_object_id()))
1295 } else if let Some(item) = schema.get_view_by_name(class_name) {
1296 Ok(Some(item.id.as_object_id()))
1297 } else if let Some(item) = schema.get_any_sink_by_name(class_name) {
1298 Ok(Some(item.id.as_object_id()))
1299 } else {
1300 Ok(None)
1301 }
1302 })?
1303 .map(|(id, _)| id)
1304 .ok_or_else(|| CatalogError::not_found("class", class_name))
1305 }
1306}
1307
1308#[cfg(test)]
1309mod tests {
1310 use risingwave_pb::catalog::{
1311 PbCreateType, PbDatabase, PbSchema, PbSink, PbSinkType, PbStreamJobStatus,
1312 };
1313
1314 use super::Catalog;
1315
1316 fn test_sink(id: u32, name: &str, database_id: u32, schema_id: u32) -> PbSink {
1317 PbSink {
1318 id: id.into(),
1319 name: name.to_owned(),
1320 database_id: database_id.into(),
1321 schema_id: schema_id.into(),
1322 sink_type: PbSinkType::AppendOnly.into(),
1323 stream_job_status: PbStreamJobStatus::Creating.into(),
1324 create_type: PbCreateType::Background.into(),
1325 ..Default::default()
1326 }
1327 }
1328
1329 #[test]
1330 fn test_update_sink_set_schema_drops_old_catalog() {
1331 let database_id = 1;
1332 let old_schema_id = 2;
1333 let new_schema_id = 3;
1334 let sink_id = 4;
1335 let mut catalog = Catalog::default();
1336 catalog.create_database(&PbDatabase {
1337 id: database_id.into(),
1338 name: "dev".to_owned(),
1339 ..Default::default()
1340 });
1341 catalog.create_schema(&PbSchema {
1342 id: old_schema_id.into(),
1343 database_id: database_id.into(),
1344 name: "public".to_owned(),
1345 ..Default::default()
1346 });
1347 catalog.create_schema(&PbSchema {
1348 id: new_schema_id.into(),
1349 database_id: database_id.into(),
1350 name: "archive".to_owned(),
1351 ..Default::default()
1352 });
1353 catalog.create_sink(&test_sink(
1354 sink_id,
1355 "replace_kafka_sink",
1356 database_id,
1357 old_schema_id,
1358 ));
1359
1360 catalog.update_sink(&test_sink(
1361 sink_id,
1362 "replace_kafka_sink",
1363 database_id,
1364 new_schema_id,
1365 ));
1366
1367 let old_schema = catalog
1368 .get_schema_by_id(database_id.into(), old_schema_id.into())
1369 .unwrap();
1370 assert!(old_schema.get_sink_by_id(sink_id.into()).is_none());
1371 let new_schema = catalog
1372 .get_schema_by_id(database_id.into(), new_schema_id.into())
1373 .unwrap();
1374 assert!(new_schema.get_sink_by_id(sink_id.into()).is_some());
1375 }
1376}