1use std::assert_matches::assert_matches;
16use std::collections::{HashMap, HashSet};
17
18use fixedbitset::FixedBitSet;
19use itertools::Itertools;
20use risingwave_common::catalog::{
21 ColumnCatalog, ColumnDesc, ConflictBehavior, CreateType, Engine, Field, ICEBERG_SINK_PREFIX,
22 ICEBERG_SOURCE_PREFIX, Schema, StreamJobStatus, TableDesc, TableId, TableVersionId,
23};
24use risingwave_common::hash::{VnodeCount, VnodeCountCompat};
25use risingwave_common::id::{JobId, SourceId};
26use risingwave_common::util::epoch::Epoch;
27use risingwave_common::util::sort_util::ColumnOrder;
28use risingwave_connector::source::cdc::external::ExternalCdcTableType;
29use risingwave_pb::catalog::table::{
30 CdcTableType as PbCdcTableType, PbEngine, PbTableType, PbTableVersion,
31};
32use risingwave_pb::catalog::{
33 PbCreateType, PbStreamJobStatus, PbTable, PbVectorIndexInfo, PbWebhookSourceInfo,
34};
35use risingwave_pb::common::PbColumnOrder;
36use risingwave_pb::plan_common::DefaultColumnDesc;
37use risingwave_pb::plan_common::column_desc::GeneratedOrDefaultColumn;
38use risingwave_sqlparser::ast;
39use risingwave_sqlparser::parser::Parser;
40use thiserror_ext::AsReport as _;
41
42use super::purify::try_purify_table_source_create_sql_ast;
43use super::{ColumnId, DatabaseId, FragmentId, OwnedByUserCatalog, SchemaId};
44use crate::error::{ErrorCode, Result, RwError};
45use crate::expr::ExprImpl;
46use crate::optimizer::property::Cardinality;
47use crate::session::current::notice_to_user;
48use crate::user::UserId;
49
50#[derive(Clone, Debug, PartialEq, Eq, Hash)]
82#[cfg_attr(test, derive(Default))]
83pub struct TableCatalog {
84 pub id: TableId,
85
86 pub schema_id: SchemaId,
87
88 pub database_id: DatabaseId,
89
90 pub associated_source_id: Option<SourceId>, pub name: String,
93
94 pub columns: Vec<ColumnCatalog>,
96
97 pub pk: Vec<ColumnOrder>,
99
100 pub stream_key: Vec<usize>,
104
105 pub table_type: TableType,
108
109 pub distribution_key: Vec<usize>,
111
112 pub append_only: bool,
115
116 pub cardinality: Cardinality,
118
119 pub owner: UserId,
121
122 pub retention_seconds: Option<u32>,
124
125 pub fragment_id: FragmentId,
127
128 pub dml_fragment_id: Option<FragmentId>,
130
131 pub vnode_col_index: Option<usize>,
134
135 pub row_id_index: Option<usize>,
138
139 pub value_indices: Vec<usize>,
141
142 pub definition: String,
144
145 pub conflict_behavior: ConflictBehavior,
149
150 pub version_column_indices: Vec<usize>,
151
152 pub read_prefix_len_hint: usize,
153
154 pub version: Option<TableVersion>,
156
157 pub watermark_columns: FixedBitSet,
159
160 pub dist_key_in_pk: Vec<usize>,
163
164 pub created_at_epoch: Option<Epoch>,
165
166 pub initialized_at_epoch: Option<Epoch>,
167
168 pub create_type: CreateType,
170
171 pub stream_job_status: StreamJobStatus,
174
175 pub description: Option<String>,
177
178 pub created_at_cluster_version: Option<String>,
179
180 pub initialized_at_cluster_version: Option<String>,
181
182 pub cdc_table_id: Option<String>,
183
184 pub vnode_count: VnodeCount,
193
194 pub webhook_info: Option<PbWebhookSourceInfo>,
195
196 pub job_id: Option<JobId>,
197
198 pub engine: Engine,
199
200 pub clean_watermark_index_in_pk: Option<usize>,
201
202 pub clean_watermark_indices: Vec<usize>,
206
207 pub refreshable: bool,
209
210 pub vector_index_info: Option<PbVectorIndexInfo>,
211
212 pub cdc_table_type: Option<ExternalCdcTableType>,
213}
214
215#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
216#[cfg_attr(test, derive(Default))]
217pub enum TableType {
218 #[cfg_attr(test, default)]
220 Table,
221 MaterializedView,
223 Index,
226 VectorIndex,
227 Internal,
229}
230
231impl TableType {
232 fn from_prost(prost: PbTableType) -> Self {
233 match prost {
234 PbTableType::Table => Self::Table,
235 PbTableType::MaterializedView => Self::MaterializedView,
236 PbTableType::Index => Self::Index,
237 PbTableType::Internal => Self::Internal,
238 PbTableType::VectorIndex => Self::VectorIndex,
239 PbTableType::Unspecified => unreachable!(),
240 }
241 }
242
243 pub(crate) fn to_prost(self) -> PbTableType {
244 match self {
245 Self::Table => PbTableType::Table,
246 Self::MaterializedView => PbTableType::MaterializedView,
247 Self::Index => PbTableType::Index,
248 Self::VectorIndex => PbTableType::VectorIndex,
249 Self::Internal => PbTableType::Internal,
250 }
251 }
252}
253
254#[derive(Clone, Debug, PartialEq, Eq, Hash)]
256pub struct TableVersion {
257 pub version_id: TableVersionId,
258 pub next_column_id: ColumnId,
259}
260
261impl TableVersion {
262 #[cfg(test)]
264 pub fn new_initial_for_test(max_column_id: ColumnId) -> Self {
265 use risingwave_common::catalog::INITIAL_TABLE_VERSION_ID;
266
267 Self {
268 version_id: INITIAL_TABLE_VERSION_ID,
269 next_column_id: max_column_id.next(),
270 }
271 }
272
273 pub fn from_prost(prost: PbTableVersion) -> Self {
274 Self {
275 version_id: prost.version,
276 next_column_id: ColumnId::from(prost.next_column_id),
277 }
278 }
279
280 pub fn to_prost(&self) -> PbTableVersion {
281 PbTableVersion {
282 version: self.version_id,
283 next_column_id: self.next_column_id.into(),
284 }
285 }
286}
287
288impl TableCatalog {
289 pub fn create_sql_purified(&self) -> String {
294 self.create_sql_ast_purified()
295 .and_then(|stmt| stmt.try_to_string().map_err(Into::into))
296 .unwrap_or_else(|_| self.create_sql())
297 }
298
299 pub fn create_sql_ast_purified(&self) -> Result<ast::Statement> {
304 if let TableType::Table = self.table_type() {
306 let base = if self.definition.is_empty() {
307 let name = ast::ObjectName(vec![self.name.as_str().into()]);
309 ast::Statement::default_create_table(name)
310 } else {
311 self.create_sql_ast_from_persisted()?
312 };
313
314 match try_purify_table_source_create_sql_ast(
315 base,
316 self.columns(),
317 self.row_id_index,
318 &self.pk_column_ids(),
319 ) {
320 Ok(stmt) => return Ok(stmt),
321 Err(e) => notice_to_user(format!(
322 "error occurred while purifying definition for table \"{}\", \
323 results may be inaccurate: {}",
324 self.name,
325 e.as_report()
326 )),
327 }
328 }
329
330 self.create_sql_ast_from_persisted()
331 }
332}
333
334impl TableCatalog {
335 pub fn id(&self) -> TableId {
337 self.id
338 }
339
340 pub fn with_id(mut self, id: TableId) -> Self {
341 self.id = id;
342 self
343 }
344
345 pub fn conflict_behavior(&self) -> ConflictBehavior {
346 self.conflict_behavior
347 }
348
349 pub fn table_type(&self) -> TableType {
350 self.table_type
351 }
352
353 pub fn engine(&self) -> Engine {
354 self.engine
355 }
356
357 pub fn iceberg_source_name(&self) -> Option<String> {
358 match self.engine {
359 Engine::Iceberg => Some(format!("{}{}", ICEBERG_SOURCE_PREFIX, self.name)),
360 Engine::Hummock => None,
361 }
362 }
363
364 pub fn iceberg_sink_name(&self) -> Option<String> {
365 match self.engine {
366 Engine::Iceberg => Some(format!("{}{}", ICEBERG_SINK_PREFIX, self.name)),
367 Engine::Hummock => None,
368 }
369 }
370
371 pub fn is_user_table(&self) -> bool {
372 self.table_type == TableType::Table
373 }
374
375 pub fn is_internal_table(&self) -> bool {
376 self.table_type == TableType::Internal
377 }
378
379 pub fn is_mview(&self) -> bool {
380 self.table_type == TableType::MaterializedView
381 }
382
383 pub fn is_index(&self) -> bool {
384 self.table_type == TableType::Index
385 }
386
387 #[must_use]
389 pub fn bad_drop_error(&self) -> RwError {
390 let msg = match self.table_type {
391 TableType::MaterializedView => {
392 "Use `DROP MATERIALIZED VIEW` to drop a materialized view."
393 }
394 TableType::Index | TableType::VectorIndex => "Use `DROP INDEX` to drop an index.",
395 TableType::Table => "Use `DROP TABLE` to drop a table.",
396 TableType::Internal => "Internal tables cannot be dropped.",
397 };
398
399 ErrorCode::InvalidInputSyntax(msg.to_owned()).into()
400 }
401
402 #[must_use]
404 pub fn associated_source_id(&self) -> Option<SourceId> {
405 self.associated_source_id
406 }
407
408 pub fn has_associated_source(&self) -> bool {
409 self.associated_source_id.is_some()
410 }
411
412 pub fn columns(&self) -> &[ColumnCatalog] {
414 &self.columns
415 }
416
417 pub fn columns_without_rw_timestamp(&self) -> Vec<ColumnCatalog> {
418 self.columns
419 .iter()
420 .filter(|c| !c.is_rw_timestamp_column())
421 .cloned()
422 .collect()
423 }
424
425 pub fn pk(&self) -> &[ColumnOrder] {
427 self.pk.as_ref()
428 }
429
430 pub fn pk_column_ids(&self) -> Vec<ColumnId> {
432 self.pk
433 .iter()
434 .map(|x| self.columns[x.column_index].column_id())
435 .collect()
436 }
437
438 pub fn pk_column_names(&self) -> Vec<&str> {
440 self.pk
441 .iter()
442 .map(|x| self.columns[x.column_index].name())
443 .collect()
444 }
445
446 pub fn stream_key(&self) -> Vec<usize> {
450 if self
452 .distribution_key
453 .iter()
454 .any(|dist_key| !self.stream_key.contains(dist_key))
455 {
456 let mut new_stream_key = self.distribution_key.clone();
457 let mut seen: HashSet<usize> = self.distribution_key.iter().copied().collect();
458 for &key in &self.stream_key {
459 if seen.insert(key) {
460 new_stream_key.push(key);
461 }
462 }
463 new_stream_key
464 } else {
465 self.stream_key.clone()
466 }
467 }
468
469 pub fn table_desc(&self) -> TableDesc {
474 use risingwave_common::catalog::TableOption;
475
476 let table_options = TableOption::new(self.retention_seconds);
477
478 TableDesc {
479 table_id: self.id,
480 pk: self.pk.clone(),
481 stream_key: self.stream_key(),
482 columns: self.columns.iter().map(|c| c.column_desc.clone()).collect(),
483 distribution_key: self.distribution_key.clone(),
484 append_only: self.append_only,
485 retention_seconds: table_options.retention_seconds,
486 value_indices: self.value_indices.clone(),
487 read_prefix_len_hint: self.read_prefix_len_hint,
488 watermark_columns: self.watermark_columns.clone(),
489 versioned: self.version.is_some(),
490 vnode_col_index: self.vnode_col_index,
491 vnode_count: self.vnode_count(),
492 }
493 }
494
495 pub fn name(&self) -> &str {
497 self.name.as_ref()
498 }
499
500 pub fn distribution_key(&self) -> &[usize] {
501 self.distribution_key.as_ref()
502 }
503
504 pub fn to_internal_table_prost(&self) -> PbTable {
505 self.to_prost()
506 }
507
508 pub fn create_sql(&self) -> String {
512 self.create_sql_ast()
513 .and_then(|stmt| stmt.try_to_string().map_err(Into::into))
514 .unwrap_or_else(|_| self.definition.clone())
515 }
516
517 pub fn create_sql_ast(&self) -> Result<ast::Statement> {
525 if let TableType::Table = self.table_type()
526 && self.definition.is_empty()
527 {
528 self.create_sql_ast_purified()
530 } else {
531 self.create_sql_ast_from_persisted()
533 }
534 }
535
536 fn create_sql_ast_from_persisted(&self) -> Result<ast::Statement> {
537 Ok(Parser::parse_exactly_one(&self.definition)?)
538 }
539
540 pub fn version(&self) -> Option<&TableVersion> {
542 self.version.as_ref()
543 }
544
545 pub fn version_id(&self) -> Option<TableVersionId> {
547 self.version().map(|v| v.version_id)
548 }
549
550 pub fn vnode_count(&self) -> usize {
552 if self.id().is_placeholder() {
553 0
554 } else {
555 self.vnode_count.value()
557 }
558 }
559
560 pub fn to_prost(&self) -> PbTable {
561 PbTable {
562 id: self.id,
563 schema_id: self.schema_id,
564 database_id: self.database_id,
565 name: self.name.clone(),
566 columns: self
568 .columns_without_rw_timestamp()
569 .iter()
570 .map(|c| c.to_protobuf())
571 .collect(),
572 pk: self.pk.iter().map(|o| o.to_protobuf()).collect(),
573 stream_key: self.stream_key().iter().map(|x| *x as _).collect(),
574 optional_associated_source_id: self.associated_source_id.map(Into::into),
575 table_type: self.table_type.to_prost() as i32,
576 distribution_key: self
577 .distribution_key
578 .iter()
579 .map(|k| *k as i32)
580 .collect_vec(),
581 append_only: self.append_only,
582 owner: self.owner,
583 fragment_id: self.fragment_id,
584 dml_fragment_id: self.dml_fragment_id,
585 vnode_col_index: self.vnode_col_index.map(|i| i as _),
586 row_id_index: self.row_id_index.map(|i| i as _),
587 value_indices: self.value_indices.iter().map(|x| *x as _).collect(),
588 definition: self.definition.clone(),
589 read_prefix_len_hint: self.read_prefix_len_hint as u32,
590 version: self.version.as_ref().map(TableVersion::to_prost),
591 watermark_indices: self.watermark_columns.ones().map(|x| x as _).collect_vec(),
592 dist_key_in_pk: self.dist_key_in_pk.iter().map(|x| *x as _).collect(),
593 handle_pk_conflict_behavior: self.conflict_behavior.to_protobuf().into(),
594 version_column_indices: self
595 .version_column_indices
596 .iter()
597 .map(|&idx| idx as u32)
598 .collect(),
599 cardinality: Some(self.cardinality.to_protobuf()),
600 initialized_at_epoch: self.initialized_at_epoch.map(|epoch| epoch.0),
601 created_at_epoch: self.created_at_epoch.map(|epoch| epoch.0),
602 #[expect(deprecated)]
603 cleaned_by_watermark: false,
604 stream_job_status: self.stream_job_status.to_proto().into(),
605 create_type: self.create_type.to_proto().into(),
606 description: self.description.clone(),
607 #[expect(deprecated)]
608 incoming_sinks: vec![],
609 created_at_cluster_version: self.created_at_cluster_version.clone(),
610 initialized_at_cluster_version: self.initialized_at_cluster_version.clone(),
611 retention_seconds: self.retention_seconds,
612 cdc_table_id: self.cdc_table_id.clone(),
613 maybe_vnode_count: self.vnode_count.to_protobuf(),
614 webhook_info: self.webhook_info.clone(),
615 job_id: self.job_id,
616 engine: Some(self.engine.to_protobuf().into()),
617 #[expect(deprecated)]
618 clean_watermark_index_in_pk: self.clean_watermark_index_in_pk.map(|x| x as i32),
619 clean_watermark_indices: self
620 .clean_watermark_indices
621 .iter()
622 .map(|&x| x as u32)
623 .collect(),
624 refreshable: self.refreshable,
625 vector_index_info: self.vector_index_info,
626 cdc_table_type: self
627 .cdc_table_type
628 .clone()
629 .map(|t| PbCdcTableType::from(t) as i32),
630 }
631 }
632
633 pub fn columns_to_insert(&self) -> impl Iterator<Item = &ColumnCatalog> {
635 self.columns
636 .iter()
637 .filter(|c| !c.is_hidden() && !c.is_generated())
638 }
639
640 pub fn generated_column_names(&self) -> impl Iterator<Item = &str> {
641 self.columns
642 .iter()
643 .filter(|c| c.is_generated())
644 .map(|c| c.name())
645 }
646
647 pub fn generated_col_idxes(&self) -> impl Iterator<Item = usize> + '_ {
648 self.columns
649 .iter()
650 .enumerate()
651 .filter(|(_, c)| c.is_generated())
652 .map(|(i, _)| i)
653 }
654
655 pub fn default_column_expr(&self, col_idx: usize) -> ExprImpl {
656 if let Some(GeneratedOrDefaultColumn::DefaultColumn(DefaultColumnDesc { expr, .. })) = self
657 .columns[col_idx]
658 .column_desc
659 .generated_or_default_column
660 .as_ref()
661 {
662 ExprImpl::from_expr_proto(expr.as_ref().unwrap())
663 .expect("expr in default columns corrupted")
664 } else {
665 ExprImpl::literal_null(self.columns[col_idx].data_type().clone())
666 }
667 }
668
669 pub fn default_column_exprs(columns: &[ColumnCatalog]) -> Vec<ExprImpl> {
670 columns
671 .iter()
672 .map(|c| {
673 if let Some(GeneratedOrDefaultColumn::DefaultColumn(DefaultColumnDesc {
674 expr,
675 ..
676 })) = c.column_desc.generated_or_default_column.as_ref()
677 {
678 ExprImpl::from_expr_proto(expr.as_ref().unwrap())
679 .expect("expr in default columns corrupted")
680 } else {
681 ExprImpl::literal_null(c.data_type().clone())
682 }
683 })
684 .collect()
685 }
686
687 pub fn default_columns(&self) -> impl Iterator<Item = (usize, ExprImpl)> + '_ {
688 self.columns.iter().enumerate().filter_map(|(i, c)| {
689 if let Some(GeneratedOrDefaultColumn::DefaultColumn(DefaultColumnDesc {
690 expr, ..
691 })) = c.column_desc.generated_or_default_column.as_ref()
692 {
693 Some((
694 i,
695 ExprImpl::from_expr_proto(expr.as_ref().unwrap())
696 .expect("expr in default columns corrupted"),
697 ))
698 } else {
699 None
700 }
701 })
702 }
703
704 pub fn has_generated_column(&self) -> bool {
705 self.columns.iter().any(|c| c.is_generated())
706 }
707
708 pub fn has_rw_timestamp_column(&self) -> bool {
709 self.columns.iter().any(|c| c.is_rw_timestamp_column())
710 }
711
712 pub fn column_schema(&self) -> Schema {
713 Schema::new(
714 self.columns
715 .iter()
716 .map(|c| Field::from(&c.column_desc))
717 .collect(),
718 )
719 }
720
721 pub fn is_created(&self) -> bool {
722 self.stream_job_status == StreamJobStatus::Created
723 }
724
725 pub fn is_iceberg_engine_table(&self) -> bool {
726 self.engine == Engine::Iceberg
727 }
728
729 pub fn order_column_indices(&self) -> impl Iterator<Item = usize> + '_ {
730 self.pk.iter().map(|col| col.column_index)
731 }
732
733 pub fn get_id_to_op_idx_mapping(&self) -> HashMap<ColumnId, usize> {
734 ColumnDesc::get_id_to_op_idx_mapping(&self.columns, None)
735 }
736
737 pub fn order_column_ids(&self) -> Vec<ColumnId> {
738 self.pk
739 .iter()
740 .map(|col| self.columns[col.column_index].column_desc.column_id)
741 .collect()
742 }
743
744 pub fn arrange_key_orders_protobuf(&self) -> Vec<PbColumnOrder> {
745 self.pk.iter().map(|x| x.to_protobuf()).collect()
747 }
748}
749
750impl From<PbTable> for TableCatalog {
751 fn from(tb: PbTable) -> Self {
752 let id = tb.id;
753 let tb_conflict_behavior = tb.handle_pk_conflict_behavior();
754 let tb_engine = tb
755 .get_engine()
756 .map(|engine| PbEngine::try_from(*engine).expect("Invalid engine"))
757 .unwrap_or(PbEngine::Hummock);
758 let table_type = tb.get_table_type().unwrap();
759 let stream_job_status = tb
760 .get_stream_job_status()
761 .unwrap_or(PbStreamJobStatus::Created);
762 let create_type = tb.get_create_type().unwrap_or(PbCreateType::Foreground);
763 let associated_source_id = tb.optional_associated_source_id.map(Into::into);
764 let name = tb.name.clone();
765
766 let vnode_count = tb.vnode_count_inner();
767 if let VnodeCount::Placeholder = vnode_count {
768 assert_matches!(stream_job_status, PbStreamJobStatus::Creating);
771 }
772
773 let mut col_names = HashSet::new();
774 let mut col_index: HashMap<i32, usize> = HashMap::new();
775
776 let conflict_behavior = ConflictBehavior::from_protobuf(&tb_conflict_behavior);
777 let version_column_indices: Vec<usize> = tb
778 .version_column_indices
779 .iter()
780 .map(|&idx| idx as usize)
781 .collect();
782 let mut columns: Vec<ColumnCatalog> =
783 tb.columns.into_iter().map(ColumnCatalog::from).collect();
784 if columns.iter().all(|c| !c.is_rw_timestamp_column()) {
785 columns.push(ColumnCatalog::rw_timestamp_column());
787 }
788 for (idx, catalog) in columns.clone().into_iter().enumerate() {
789 let col_name = catalog.name();
790 if !col_names.insert(col_name.to_owned()) {
791 panic!("duplicated column name {} in table {} ", col_name, tb.name)
792 }
793
794 let col_id = catalog.column_desc.column_id.get_id();
795 col_index.insert(col_id, idx);
796 }
797
798 let pk = tb.pk.iter().map(ColumnOrder::from_protobuf).collect();
799 let mut watermark_columns = FixedBitSet::with_capacity(columns.len());
800 for idx in &tb.watermark_indices {
801 watermark_columns.insert(*idx as _);
802 }
803 let engine = Engine::from_protobuf(&tb_engine);
804
805 Self {
806 id,
807 schema_id: tb.schema_id,
808 database_id: tb.database_id,
809 associated_source_id,
810 name,
811 pk,
812 columns,
813 table_type: TableType::from_prost(table_type),
814 distribution_key: tb
815 .distribution_key
816 .iter()
817 .map(|k| *k as usize)
818 .collect_vec(),
819 stream_key: tb.stream_key.iter().map(|x| *x as _).collect(),
820 append_only: tb.append_only,
821 owner: tb.owner,
822 fragment_id: tb.fragment_id,
823 dml_fragment_id: tb.dml_fragment_id,
824 vnode_col_index: tb.vnode_col_index.map(|x| x as usize),
825 row_id_index: tb.row_id_index.map(|x| x as usize),
826 value_indices: tb.value_indices.iter().map(|x| *x as _).collect(),
827 definition: tb.definition,
828 conflict_behavior,
829 version_column_indices,
830 read_prefix_len_hint: tb.read_prefix_len_hint as usize,
831 version: tb.version.map(TableVersion::from_prost),
832 watermark_columns,
833 dist_key_in_pk: tb.dist_key_in_pk.iter().map(|x| *x as _).collect(),
834 cardinality: tb
835 .cardinality
836 .map(|c| Cardinality::from_protobuf(&c))
837 .unwrap_or_else(Cardinality::unknown),
838 created_at_epoch: tb.created_at_epoch.map(Epoch::from),
839 initialized_at_epoch: tb.initialized_at_epoch.map(Epoch::from),
840 create_type: CreateType::from_proto(create_type),
841 stream_job_status: StreamJobStatus::from_proto(stream_job_status),
842 description: tb.description,
843 created_at_cluster_version: tb.created_at_cluster_version.clone(),
844 initialized_at_cluster_version: tb.initialized_at_cluster_version.clone(),
845 retention_seconds: tb.retention_seconds,
846 cdc_table_id: tb.cdc_table_id,
847 vnode_count,
848 webhook_info: tb.webhook_info,
849 job_id: tb.job_id,
850 engine,
851 #[expect(deprecated)]
852 clean_watermark_index_in_pk: tb.clean_watermark_index_in_pk.map(|x| x as usize),
853 clean_watermark_indices: tb
854 .clean_watermark_indices
855 .iter()
856 .map(|&x| x as usize)
857 .collect(),
858
859 refreshable: tb.refreshable,
860 vector_index_info: tb.vector_index_info,
861 cdc_table_type: tb
862 .cdc_table_type
863 .and_then(|t| PbCdcTableType::try_from(t).ok())
864 .map(ExternalCdcTableType::from),
865 }
866 }
867}
868
869impl From<&PbTable> for TableCatalog {
870 fn from(tb: &PbTable) -> Self {
871 tb.clone().into()
872 }
873}
874
875impl OwnedByUserCatalog for TableCatalog {
876 fn owner(&self) -> UserId {
877 self.owner
878 }
879}
880
881#[cfg(test)]
882mod tests {
883 use risingwave_common::catalog::{ColumnDesc, ColumnId};
884 use risingwave_common::test_prelude::*;
885 use risingwave_common::types::*;
886 use risingwave_common::util::sort_util::OrderType;
887 use risingwave_pb::catalog::table::PbEngine;
888 use risingwave_pb::plan_common::{
889 AdditionalColumn, ColumnDescVersion, PbColumnCatalog, PbColumnDesc,
890 };
891
892 use super::*;
893
894 #[test]
895 fn test_into_table_catalog() {
896 let table: TableCatalog = PbTable {
897 id: 0.into(),
898 schema_id: 0.into(),
899 database_id: 0.into(),
900 name: "test".to_owned(),
901 table_type: PbTableType::Table as i32,
902 columns: vec![
903 ColumnCatalog::row_id_column().to_protobuf(),
904 PbColumnCatalog {
905 column_desc: Some(PbColumnDesc::new(
906 DataType::from(StructType::new([
907 ("address", DataType::Varchar),
908 ("zipcode", DataType::Varchar),
909 ]))
910 .to_protobuf(),
911 "country",
912 1,
913 )),
914 is_hidden: false,
915 },
916 ],
917 pk: vec![ColumnOrder::new(0, OrderType::ascending()).to_protobuf()],
918 stream_key: vec![0],
919 distribution_key: vec![0],
920 optional_associated_source_id: Some(SourceId::new(233).into()),
921 append_only: false,
922 owner: risingwave_common::catalog::DEFAULT_SUPER_USER_ID,
923 retention_seconds: Some(300),
924 fragment_id: 0.into(),
925 dml_fragment_id: None,
926 initialized_at_epoch: None,
927 value_indices: vec![0],
928 definition: "".into(),
929 read_prefix_len_hint: 0,
930 vnode_col_index: None,
931 row_id_index: None,
932 version: Some(PbTableVersion {
933 version: 0,
934 next_column_id: 2,
935 }),
936 watermark_indices: vec![],
937 handle_pk_conflict_behavior: 3,
938 dist_key_in_pk: vec![0],
939 cardinality: None,
940 created_at_epoch: None,
941 #[expect(deprecated)]
942 cleaned_by_watermark: false,
943 stream_job_status: PbStreamJobStatus::Created.into(),
944 create_type: PbCreateType::Foreground.into(),
945 description: Some("description".to_owned()),
946 #[expect(deprecated)]
947 incoming_sinks: vec![],
948 created_at_cluster_version: None,
949 initialized_at_cluster_version: None,
950 version_column_indices: Vec::new(),
951 cdc_table_id: None,
952 maybe_vnode_count: VnodeCount::set(233).to_protobuf(),
953 webhook_info: None,
954 job_id: None,
955 engine: Some(PbEngine::Hummock as i32),
956 #[expect(deprecated)]
957 clean_watermark_index_in_pk: None,
958 clean_watermark_indices: vec![],
959
960 refreshable: false,
961 vector_index_info: None,
962 cdc_table_type: None,
963 }
964 .into();
965
966 assert_eq!(
967 table,
968 TableCatalog {
969 id: TableId::new(0),
970 schema_id: 0.into(),
971 database_id: 0.into(),
972 associated_source_id: Some(SourceId::new(233)),
973 name: "test".to_owned(),
974 table_type: TableType::Table,
975 columns: vec![
976 ColumnCatalog::row_id_column(),
977 ColumnCatalog {
978 column_desc: ColumnDesc {
979 data_type: StructType::new(vec![
980 ("address", DataType::Varchar),
981 ("zipcode", DataType::Varchar)
982 ],)
983 .into(),
984 column_id: ColumnId::new(1),
985 name: "country".to_owned(),
986 description: None,
987 generated_or_default_column: None,
988 additional_column: AdditionalColumn { column_type: None },
989 version: ColumnDescVersion::LATEST,
990 system_column: None,
991 nullable: true,
992 },
993 is_hidden: false
994 },
995 ColumnCatalog::rw_timestamp_column(),
996 ],
997 stream_key: vec![0],
998 pk: vec![ColumnOrder::new(0, OrderType::ascending())],
999 distribution_key: vec![0],
1000 append_only: false,
1001 owner: risingwave_common::catalog::DEFAULT_SUPER_USER_ID,
1002 retention_seconds: Some(300),
1003 fragment_id: 0.into(),
1004 dml_fragment_id: None,
1005 vnode_col_index: None,
1006 row_id_index: None,
1007 value_indices: vec![0],
1008 definition: "".into(),
1009 conflict_behavior: ConflictBehavior::NoCheck,
1010 read_prefix_len_hint: 0,
1011 version: Some(TableVersion::new_initial_for_test(ColumnId::new(1))),
1012 watermark_columns: FixedBitSet::with_capacity(3),
1013 dist_key_in_pk: vec![0],
1014 cardinality: Cardinality::unknown(),
1015 created_at_epoch: None,
1016 initialized_at_epoch: None,
1017 stream_job_status: StreamJobStatus::Created,
1018 create_type: CreateType::Foreground,
1019 description: Some("description".to_owned()),
1020 created_at_cluster_version: None,
1021 initialized_at_cluster_version: None,
1022 version_column_indices: Vec::new(),
1023 cdc_table_id: None,
1024 vnode_count: VnodeCount::set(233),
1025 webhook_info: None,
1026 job_id: None,
1027 engine: Engine::Hummock,
1028 clean_watermark_index_in_pk: None,
1029 clean_watermark_indices: vec![],
1030
1031 refreshable: false,
1032 vector_index_info: None,
1033 cdc_table_type: None,
1034 }
1035 );
1036 assert_eq!(table, TableCatalog::from(table.to_prost()));
1037 }
1038}