Skip to main content

risingwave_frontend/catalog/
source_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 risingwave_common::catalog::{ColumnCatalog, ICEBERG_SOURCE_PREFIX, SourceVersionId};
16use risingwave_common::util::epoch::Epoch;
17use risingwave_connector::{WithOptionsSecResolved, WithPropertiesExt};
18use risingwave_pb::catalog::{PbSource, StreamSourceInfo, WatermarkDesc};
19use risingwave_pb::plan_common::SourceIngestMode;
20use risingwave_sqlparser::ast;
21use risingwave_sqlparser::parser::Parser;
22use thiserror_ext::AsReport as _;
23
24use super::purify::try_purify_table_source_create_sql_ast;
25use super::{ColumnId, ConnectionId, DatabaseId, OwnedByUserCatalog, SchemaId, SourceId};
26use crate::catalog::TableId;
27use crate::error::Result;
28use crate::session::current::notice_to_user;
29use crate::user::UserId;
30
31/// This struct `SourceCatalog` is used in frontend.
32/// Compared with `PbSource`, it only maintains information used during optimization.
33#[derive(Clone, Debug, PartialEq, Eq, Hash)]
34pub struct SourceCatalog {
35    pub id: SourceId,
36    pub name: String,
37    pub schema_id: SchemaId,
38    pub database_id: DatabaseId,
39    pub columns: Vec<ColumnCatalog>,
40    pub pk_col_ids: Vec<ColumnId>,
41    pub append_only: bool,
42    pub owner: UserId,
43    pub info: StreamSourceInfo,
44    pub row_id_index: Option<usize>,
45    pub with_properties: WithOptionsSecResolved,
46    pub watermark_descs: Vec<WatermarkDesc>,
47    pub associated_table_id: Option<TableId>,
48    pub definition: String,
49    pub connection_id: Option<ConnectionId>,
50    pub created_at_epoch: Option<Epoch>,
51    pub initialized_at_epoch: Option<Epoch>,
52    pub version: SourceVersionId,
53    pub created_at_cluster_version: Option<String>,
54    pub initialized_at_cluster_version: Option<String>,
55    pub rate_limit: Option<u32>,
56    pub ingest_mode: Option<SourceIngestMode>,
57}
58
59impl SourceCatalog {
60    /// Returns the SQL definition when the source was created.
61    pub fn create_sql(&self) -> String {
62        self.definition.clone()
63    }
64
65    /// Returns the parsed SQL definition when the source was created.
66    ///
67    /// Returns error if it's invalid.
68    pub fn create_sql_ast(&self) -> Result<ast::Statement> {
69        Ok(Parser::parse_exactly_one(&self.definition)?)
70    }
71
72    pub fn to_prost(&self) -> PbSource {
73        let (with_properties, secret_refs) = self.with_properties.clone().into_parts();
74        PbSource {
75            id: self.id,
76            schema_id: self.schema_id,
77            database_id: self.database_id,
78            name: self.name.clone(),
79            row_id_index: self.row_id_index.map(|idx| idx as _),
80            columns: self.columns.iter().map(|c| c.to_protobuf()).collect(),
81            pk_column_ids: self.pk_col_ids.iter().map(Into::into).collect(),
82            with_properties,
83            owner: self.owner,
84            info: Some(self.info.clone()),
85            watermark_descs: self.watermark_descs.clone(),
86            definition: self.definition.clone(),
87            connection_id: self.connection_id,
88            initialized_at_epoch: self.initialized_at_epoch.map(|x| x.0),
89            created_at_epoch: self.created_at_epoch.map(|x| x.0),
90            optional_associated_table_id: self.associated_table_id.map(Into::into),
91            version: self.version,
92            created_at_cluster_version: self.created_at_cluster_version.clone(),
93            initialized_at_cluster_version: self.initialized_at_cluster_version.clone(),
94            secret_refs,
95            rate_limit: self.rate_limit,
96            ingest_mode: self.ingest_mode,
97        }
98    }
99
100    /// Get a reference to the source catalog's version.
101    pub fn version(&self) -> SourceVersionId {
102        self.version
103    }
104
105    pub fn connector_name(&self) -> String {
106        self.with_properties
107            .get_connector()
108            .expect("connector name is missing")
109    }
110
111    pub fn is_iceberg_connector(&self) -> bool {
112        self.with_properties.is_iceberg_connector()
113    }
114
115    /// Whether this source represents an external table exposed by a shared CDC source.
116    pub fn is_cdc_table_source(&self) -> bool {
117        self.info.external_table.is_some()
118    }
119
120    pub fn is_iceberg_update_source(&self) -> bool {
121        self.with_properties.is_iceberg_update_source()
122    }
123
124    /// The single place enforcing Iceberg `streaming_updates` restrictions. Called at the end of
125    /// CREATE SOURCE / CREATE TABLE binding, and again when binding a restored catalog.
126    pub fn validate_iceberg_update_source(&self) -> Result<()> {
127        if !self.is_iceberg_update_source() {
128            return Ok(());
129        }
130        let full_reload = self.ingest_mode.as_ref().is_some_and(|mode| {
131            matches!(
132                mode.ingest_mode,
133                Some(risingwave_pb::plan_common::source_ingest_mode::IngestMode::FullReload(_))
134            )
135        });
136        let unsupported = [
137            (self.info.is_shared(), "shared sources"),
138            (full_reload, "FULL_RELOAD refresh"),
139            (self.rate_limit.is_some(), "source rate limiting"),
140            (
141                self.columns
142                    .iter()
143                    .any(ColumnCatalog::is_connector_additional_column),
144                "INCLUDE columns",
145            ),
146            (!self.watermark_descs.is_empty(), "watermarks"),
147        ];
148        if let Some((_, feature)) = unsupported.iter().find(|(violated, _)| *violated) {
149            return Err(crate::error::ErrorCode::NotSupported(
150                format!("Iceberg streaming_updates does not support {feature}"),
151                "Remove it, or set streaming_updates = 'false'".to_owned(),
152            )
153            .into());
154        }
155
156        let stored_columns = self
157            .columns
158            .iter()
159            .all(|column| !column.is_iceberg_hidden_column() && !column.is_generated());
160        let has_key = !self.pk_col_ids.is_empty()
161            && self
162                .pk_col_ids
163                .iter()
164                .all(|id| self.columns.iter().any(|column| column.column_id() == *id));
165        if !stored_columns || !has_key || self.append_only || self.row_id_index.is_some() {
166            return Err(crate::error::ErrorCode::BindError(
167                "invalid Iceberg update source catalog: requires stored logical columns and a SQL primary key, without generated row IDs".to_owned()
168            ).into());
169        }
170        Ok(())
171    }
172
173    /// If this source is an iceberg source, returns the corresponding iceberg table name.
174    pub fn iceberg_table_name(&self) -> Option<String> {
175        if self.name.starts_with(ICEBERG_SOURCE_PREFIX) {
176            Some(self.name[ICEBERG_SOURCE_PREFIX.len()..].to_string())
177        } else {
178            None
179        }
180    }
181
182    /// Returns the SQL definition when the source was created, purified with best effort.
183    pub fn create_sql_purified(&self) -> String {
184        self.create_sql_ast_purified()
185            .and_then(|stmt| stmt.try_to_string().map_err(Into::into))
186            .unwrap_or_else(|_| self.create_sql())
187    }
188
189    /// Returns the parsed SQL definition when the source was created, purified with best effort.
190    ///
191    /// Returns error if it's invalid.
192    pub fn create_sql_ast_purified(&self) -> Result<ast::Statement> {
193        if self.with_properties.is_cdc_connector() || self.is_iceberg_update_source() {
194            // CDC sources infer their schema. Iceberg update sources may key on the hidden
195            // upstream `_row_id`, which a purified column list cannot express.
196            return self.create_sql_ast();
197        }
198
199        match try_purify_table_source_create_sql_ast(
200            self.create_sql_ast()?,
201            &self.columns,
202            self.row_id_index,
203            &self.pk_col_ids,
204        ) {
205            Ok(stmt) => return Ok(stmt),
206            Err(e) => notice_to_user(format!(
207                "error occurred while purifying definition for source \"{}\", \
208                     results may be inaccurate: {}",
209                self.name,
210                e.as_report()
211            )),
212        }
213
214        self.create_sql_ast()
215    }
216
217    /// Fills the `definition` field with the purified SQL definition.
218    ///
219    /// There's no need to call this method for correctness because we automatically purify the
220    /// SQL definition at the time of querying. However, this helps to maintain more accurate
221    /// `definition` field in the catalog when directly inspected for debugging purposes.
222    pub fn fill_purified_create_sql(&mut self) {
223        self.definition = self.create_sql_purified();
224    }
225}
226
227impl From<&PbSource> for SourceCatalog {
228    fn from(prost: &PbSource) -> Self {
229        let id = prost.id;
230        let name = prost.name.clone();
231        let database_id = prost.database_id;
232        let schema_id = prost.schema_id;
233        let prost_columns = prost.columns.clone();
234        let pk_col_ids = prost
235            .pk_column_ids
236            .clone()
237            .into_iter()
238            .map(Into::into)
239            .collect();
240        let connector_props_with_secrets =
241            WithOptionsSecResolved::new(prost.with_properties.clone(), prost.secret_refs.clone());
242        let columns = prost_columns.into_iter().map(ColumnCatalog::from).collect();
243        let row_id_index = prost.row_id_index.map(|idx| idx as _);
244
245        let append_only = row_id_index.is_some();
246        let owner = prost.owner;
247        let watermark_descs = prost.get_watermark_descs().clone();
248
249        let associated_table_id = prost.optional_associated_table_id.map(Into::into);
250        let version = prost.version;
251
252        let connection_id = prost.connection_id;
253        let rate_limit = prost.rate_limit;
254
255        Self {
256            id,
257            name,
258            schema_id,
259            database_id,
260            columns,
261            pk_col_ids,
262            append_only,
263            owner,
264            info: prost.info.clone().unwrap(),
265            row_id_index,
266            with_properties: connector_props_with_secrets,
267            watermark_descs,
268            associated_table_id,
269            definition: prost.definition.clone(),
270            connection_id,
271            created_at_epoch: prost.created_at_epoch.map(Epoch::from),
272            initialized_at_epoch: prost.initialized_at_epoch.map(Epoch::from),
273            version,
274            created_at_cluster_version: prost.created_at_cluster_version.clone(),
275            initialized_at_cluster_version: prost.initialized_at_cluster_version.clone(),
276            rate_limit,
277            ingest_mode: prost.ingest_mode,
278        }
279    }
280}
281
282impl OwnedByUserCatalog for SourceCatalog {
283    fn owner(&self) -> UserId {
284        self.owner
285    }
286}