Skip to main content

risingwave_connector/source/
manager.rs

1// Copyright 2023 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::fmt::Debug;
16
17use risingwave_common::catalog::{
18    CDC_OFFSET_COLUMN_NAME, CDC_TABLE_NAME_COLUMN_NAME, ColumnDesc, ColumnId,
19    KAFKA_TIMESTAMP_COLUMN_NAME, ROW_ID_COLUMN_ID, ROW_ID_COLUMN_NAME,
20};
21use risingwave_common::types::{DataType, Datum};
22use risingwave_common::util::value_encoding::DatumFromProtoExt;
23use risingwave_pb::plan_common::column_desc::GeneratedOrDefaultColumn;
24use risingwave_pb::plan_common::{AdditionalColumn, ColumnDescVersion};
25
26/// `SourceColumnDesc` is used to describe a column in the Source.
27///
28/// See the implementation of `From<&ColumnDesc>` for the difference between `SourceColumnDesc` and [`ColumnDesc`].
29#[derive(Clone, Debug)]
30pub struct SourceColumnDesc {
31    pub name: String,
32    pub data_type: DataType,
33    pub column_id: ColumnId,
34    /// `additional_column` and `column_type` are orthogonal
35    /// `additional_column` is used to indicate the column is from which part of the message
36    /// `column_type` is used to indicate the type of the column, only used in cdc scenario
37    pub additional_column: AdditionalColumn,
38    // ------
39    // Fields above are the same in `ColumnDesc`.
40    // Fields below are specific to `SourceColumnDesc`.
41    // ------
42    pub column_type: SourceColumnType,
43    /// `is_pk` is used to indicate whether the column is part of the primary key columns.
44    pub is_pk: bool,
45    /// `is_hidden_addition_col` is used to indicate whether the column is a hidden addition column.
46    pub is_hidden_addition_col: bool,
47    /// Default evaluated when the column was created or added, used for missing fields.
48    pub default_value: Datum,
49}
50
51/// `SourceColumnType` is used to indicate the type of a column emitted by the Source.
52/// There are 4 types of columns:
53/// - `Normal`: a visible column
54/// - `RowId`: internal column to uniquely identify a row
55/// - `Meta`: internal column to store source related metadata
56/// - `Offset`: internal column to store upstream offset for a row, used in CDC source
57#[derive(Clone, Debug, PartialEq)]
58pub enum SourceColumnType {
59    Normal,
60
61    // internal columns
62    RowId,
63    Meta,
64    Offset,
65}
66
67impl SourceColumnType {
68    pub fn from_name(name: &str) -> Self {
69        if name.starts_with(KAFKA_TIMESTAMP_COLUMN_NAME)
70            || name.starts_with(CDC_TABLE_NAME_COLUMN_NAME)
71        {
72            Self::Meta
73        } else if name == ROW_ID_COLUMN_NAME {
74            Self::RowId
75        } else if name == CDC_OFFSET_COLUMN_NAME {
76            Self::Offset
77        } else {
78            Self::Normal
79        }
80    }
81}
82
83impl SourceColumnDesc {
84    /// Create a [`SourceColumnDesc`].
85    // TODO(struct): rename to `new`?
86    pub fn simple(name: impl Into<String>, data_type: DataType, column_id: ColumnId) -> Self {
87        let name = name.into();
88        Self {
89            name,
90            data_type,
91            column_id,
92            column_type: SourceColumnType::Normal,
93            is_pk: false,
94            is_hidden_addition_col: false,
95            default_value: None,
96            additional_column: AdditionalColumn { column_type: None },
97        }
98    }
99
100    pub fn hidden_addition_col_from_column_desc(c: &ColumnDesc) -> Self {
101        Self {
102            is_hidden_addition_col: true,
103            ..c.into()
104        }
105    }
106
107    pub fn is_row_id(&self) -> bool {
108        self.column_type == SourceColumnType::RowId
109    }
110
111    pub fn is_meta(&self) -> bool {
112        self.column_type == SourceColumnType::Meta
113    }
114
115    pub fn is_offset(&self) -> bool {
116        self.column_type == SourceColumnType::Offset
117    }
118
119    #[inline]
120    pub fn is_visible(&self) -> bool {
121        !self.is_hidden_addition_col && self.column_type == SourceColumnType::Normal
122    }
123}
124
125impl From<&ColumnDesc> for SourceColumnDesc {
126    fn from(
127        ColumnDesc {
128            data_type,
129            column_id,
130            name,
131            additional_column,
132            generated_or_default_column,
133            // ignored fields below
134            description: _,
135            version: _,
136            system_column: _,
137            nullable: _,
138        }: &ColumnDesc,
139    ) -> Self {
140        if let Some(option) = generated_or_default_column {
141            debug_assert!(
142                matches!(option, GeneratedOrDefaultColumn::DefaultColumn(_)),
143                "source column should not be generated: {:?}",
144                generated_or_default_column.as_ref().unwrap()
145            )
146        }
147
148        let default_value = match generated_or_default_column {
149            Some(GeneratedOrDefaultColumn::DefaultColumn(default)) => {
150                default.snapshot_value.as_ref().and_then(|value| {
151                    Datum::from_protobuf(value, data_type).expect("invalid default value")
152                })
153            }
154            _ => None,
155        };
156
157        let column_type = SourceColumnType::from_name(name);
158        if column_type == SourceColumnType::RowId {
159            debug_assert_eq!(name, ROW_ID_COLUMN_NAME);
160            debug_assert_eq!(*column_id, ROW_ID_COLUMN_ID);
161        }
162
163        Self {
164            name: name.clone(),
165            data_type: data_type.clone(),
166            column_id: *column_id,
167            additional_column: additional_column.clone(),
168            // additional fields below
169            column_type,
170            is_pk: false,
171            is_hidden_addition_col: false,
172            default_value,
173        }
174    }
175}
176
177impl From<&SourceColumnDesc> for ColumnDesc {
178    fn from(
179        SourceColumnDesc {
180            name,
181            data_type,
182            column_id,
183            additional_column,
184            // ignored fields below
185            column_type: _,
186            is_pk: _,
187            is_hidden_addition_col: _,
188            default_value: _,
189        }: &SourceColumnDesc,
190    ) -> Self {
191        ColumnDesc {
192            data_type: data_type.clone(),
193            column_id: *column_id,
194            name: name.clone(),
195            additional_column: additional_column.clone(),
196            // additional fields below
197            generated_or_default_column: None,
198            description: None,
199            version: ColumnDescVersion::LATEST,
200            system_column: None,
201            nullable: true,
202        }
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    fn test_is_visible() {
212        let mut c = SourceColumnDesc::simple("a", DataType::Int32, ColumnId::new(0));
213        assert!(c.is_visible());
214        c.column_type = SourceColumnType::RowId;
215        assert!(!c.is_visible());
216        c.column_type = SourceColumnType::Meta;
217        assert!(!c.is_visible());
218    }
219}