1use std::sync::Arc;
16
17use either::Either;
18use itertools::Itertools;
19use pgwire::pg_response::StatementType;
20use risingwave_common::bail_not_implemented;
21use risingwave_common::catalog::{ColumnCatalog, max_column_id};
22use risingwave_connector::WithPropertiesExt;
23use risingwave_pb::catalog::StreamSourceInfo;
24use risingwave_pb::plan_common::{EncodeType, FormatType};
25use risingwave_sqlparser::ast::{
26 CompatibleFormatEncode, CreateSourceStatement, Encode, Format, FormatEncodeOptions, ObjectName,
27 SqlOption, Statement,
28};
29
30use super::create_source::{
31 generate_stream_graph_for_source, schema_has_schema_registry, validate_compatibility,
32};
33use super::util::SourceSchemaCompatExt;
34use super::{HandlerArgs, RwPgResponse};
35use crate::catalog::root_catalog::SchemaPath;
36use crate::catalog::source_catalog::SourceCatalog;
37use crate::error::{ErrorCode, Result};
38use crate::handler::create_source::{CreateSourceType, bind_columns_from_source};
39use crate::session::SessionImpl;
40use crate::utils::resolve_secret_ref_in_with_options;
41use crate::{Binder, WithOptions};
42
43fn format_type_to_format(from: FormatType) -> Option<Format> {
44 Some(match from {
45 FormatType::Unspecified => return None,
46 FormatType::Native => Format::Native,
47 FormatType::Debezium => Format::Debezium,
48 FormatType::DebeziumMongo => Format::DebeziumMongo,
49 FormatType::Maxwell => Format::Maxwell,
50 FormatType::Canal => Format::Canal,
51 FormatType::Upsert => Format::Upsert,
52 FormatType::Plain => Format::Plain,
53 FormatType::None => Format::None,
54 })
55}
56
57fn encode_type_to_encode(from: EncodeType) -> Option<Encode> {
58 Some(match from {
59 EncodeType::Unspecified => return None,
60 EncodeType::Native => Encode::Native,
61 EncodeType::Avro => Encode::Avro,
62 EncodeType::Csv => Encode::Csv,
63 EncodeType::Protobuf => Encode::Protobuf,
64 EncodeType::Json => Encode::Json,
65 EncodeType::Bytes => Encode::Bytes,
66 EncodeType::Template => Encode::Template,
67 EncodeType::Parquet => Encode::Parquet,
68 EncodeType::None => Encode::None,
69 EncodeType::Text => Encode::Text,
70 })
71}
72
73fn columns_minus(columns_a: &[ColumnCatalog], columns_b: &[ColumnCatalog]) -> Vec<ColumnCatalog> {
85 columns_a
86 .iter()
87 .filter(|col_a| {
88 !col_a.is_hidden()
89 && !col_a.is_connector_additional_column()
90 && !col_a.is_generated()
91 && !columns_b.iter().any(|col_b| {
92 col_a.name() == col_b.name() && col_a.data_type() == col_b.data_type()
93 })
94 })
95 .cloned()
96 .collect()
97}
98
99pub fn fetch_source_catalog_with_db_schema_id(
101 session: &SessionImpl,
102 name: &ObjectName,
103) -> Result<Arc<SourceCatalog>> {
104 let db_name = &session.database();
105 let (schema_name, real_source_name) = Binder::resolve_schema_qualified_name(db_name, name)?;
106 let search_path = session.config().search_path();
107 let user_name = &session.user_name();
108
109 let schema_path = SchemaPath::new(schema_name.as_deref(), &search_path, user_name);
110
111 let reader = session.env().catalog_reader().read_guard();
112 let (source, schema_name) =
113 reader.get_source_by_name(db_name, schema_path, &real_source_name)?;
114
115 session.check_privilege_for_drop_alter(schema_name, &**source)?;
116
117 Ok(Arc::clone(source))
118}
119
120pub fn check_format_encode(
123 original_source: &SourceCatalog,
124 new_format_encode: &FormatEncodeOptions,
125) -> Result<()> {
126 let StreamSourceInfo {
127 format, row_encode, ..
128 } = original_source.info;
129 let (Some(old_format), Some(old_row_encode)) = (
130 format_type_to_format(FormatType::try_from(format).unwrap()),
131 encode_type_to_encode(EncodeType::try_from(row_encode).unwrap()),
132 ) else {
133 return Err(ErrorCode::NotSupported(
134 "altering a legacy source which is not created using `FORMAT .. ENCODE ..` Clause"
135 .to_owned(),
136 "try this feature by creating a fresh source".to_owned(),
137 )
138 .into());
139 };
140
141 if new_format_encode.format != old_format || new_format_encode.row_encode != old_row_encode {
142 bail_not_implemented!(
143 "the original definition is FORMAT {:?} ENCODE {:?}, and altering them is not supported yet",
144 &old_format,
145 &old_row_encode,
146 );
147 }
148
149 Ok(())
150}
151
152pub async fn refresh_sr_and_get_columns_diff(
154 original_source: &SourceCatalog,
155 format_encode: &FormatEncodeOptions,
156 session: &Arc<SessionImpl>,
157) -> Result<(StreamSourceInfo, Vec<ColumnCatalog>, Vec<ColumnCatalog>)> {
158 let mut with_properties = original_source.with_properties.clone();
159 validate_compatibility(format_encode, &mut with_properties)?;
160
161 if with_properties.is_cdc_connector() {
162 bail_not_implemented!("altering a cdc source is not supported");
163 }
164
165 let (Some(columns_from_resolve_source), source_info) = bind_columns_from_source(
166 session,
167 format_encode,
168 Either::Right(&with_properties),
169 CreateSourceType::for_replace(original_source),
170 )
171 .await?
172 else {
173 unreachable!("source without schema registry is rejected")
175 };
176
177 let mut added_columns = columns_minus(&columns_from_resolve_source, &original_source.columns);
178 let mut next_col_id = max_column_id(&original_source.columns).next();
180 for col in &mut added_columns {
181 col.column_desc.column_id = next_col_id;
182 next_col_id = next_col_id.next();
183 }
184 let dropped_columns = columns_minus(&original_source.columns, &columns_from_resolve_source);
185 tracing::debug!(
186 ?added_columns,
187 ?dropped_columns,
188 ?columns_from_resolve_source,
189 original_source = ?original_source.columns
190 );
191
192 Ok((source_info, added_columns, dropped_columns))
193}
194
195fn get_format_encode_from_source(source: &SourceCatalog) -> Result<FormatEncodeOptions> {
196 let stmt = source.create_sql_ast()?;
197 let Statement::CreateSource {
198 stmt: CreateSourceStatement { format_encode, .. },
199 } = stmt
200 else {
201 return Err(ErrorCode::InternalError(format!(
202 "source \"{}\" has a non-CREATE SOURCE definition",
203 source.name
204 ))
205 .into());
206 };
207 Ok(format_encode.into_v2_with_warning())
208}
209
210fn reject_associated_table(source: &SourceCatalog) -> Result<()> {
211 if source.associated_table_id.is_some() {
212 return Err(ErrorCode::NotSupported(
213 "alter table with connector using ALTER SOURCE statement".to_owned(),
214 "try to use ALTER TABLE instead".to_owned(),
215 )
216 .into());
217 }
218
219 Ok(())
220}
221
222pub async fn handler_refresh_schema(
223 handler_args: HandlerArgs,
224 name: ObjectName,
225) -> Result<RwPgResponse> {
226 let source = fetch_source_catalog_with_db_schema_id(&handler_args.session, &name)?;
227 reject_associated_table(&source)?;
228 let format_encode = get_format_encode_from_source(&source)?;
229 handle_alter_source_with_sr(handler_args, name, format_encode).await
230}
231
232pub async fn handle_alter_source_with_sr(
233 handler_args: HandlerArgs,
234 name: ObjectName,
235 format_encode: FormatEncodeOptions,
236) -> Result<RwPgResponse> {
237 let session = handler_args.session.clone();
238 let source = fetch_source_catalog_with_db_schema_id(&session, &name)?;
239 let mut source = source.as_ref().clone();
240
241 reject_associated_table(&source)?;
242
243 check_format_encode(&source, &format_encode)?;
244
245 if !schema_has_schema_registry(&format_encode) {
246 return Err(ErrorCode::NotSupported(
247 "altering a source without schema registry".to_owned(),
248 "try `ALTER SOURCE .. ADD COLUMN ...` instead".to_owned(),
249 )
250 .into());
251 }
252
253 let (source_info, added_columns, dropped_columns) =
254 refresh_sr_and_get_columns_diff(&source, &format_encode, &session).await?;
255
256 if !dropped_columns.is_empty() {
257 bail_not_implemented!(
258 "this altering statement will drop columns, which is not supported yet: {}",
259 dropped_columns
260 .iter()
261 .map(|col| format!("({}: {})", col.name(), col.data_type()))
262 .join(", ")
263 );
264 }
265
266 source.info = source_info;
267 source.columns.extend(added_columns);
268 source.definition = alter_definition_format_encode(
269 source.create_sql_ast_purified()?,
270 format_encode.row_options.clone(),
271 )?;
272
273 let (format_encode_options, format_encode_secret_ref) = resolve_secret_ref_in_with_options(
274 WithOptions::try_from(format_encode.row_options())?,
275 session.as_ref(),
276 )?
277 .into_parts();
278 source
279 .info
280 .format_encode_options
281 .extend(format_encode_options);
282
283 source
284 .info
285 .format_encode_secret_refs
286 .extend(format_encode_secret_ref);
287
288 source.version += 1;
290
291 let pb_source = source.to_prost();
292 let catalog_writer = session.catalog_writer()?;
293 if source.info.is_shared() {
294 let graph = generate_stream_graph_for_source(handler_args, source.clone())?;
295 catalog_writer.replace_source(pb_source, graph).await?
296 } else {
297 catalog_writer.alter_source(pb_source).await?;
298 }
299 Ok(RwPgResponse::empty_result(StatementType::ALTER_SOURCE))
300}
301
302pub fn alter_definition_format_encode(
304 mut stmt: Statement,
305 format_encode_options: Vec<SqlOption>,
306) -> Result<String> {
307 match &mut stmt {
308 Statement::CreateSource {
309 stmt: CreateSourceStatement { format_encode, .. },
310 }
311 | Statement::CreateTable {
312 format_encode: Some(format_encode),
313 ..
314 } => {
315 match format_encode {
316 CompatibleFormatEncode::V2(schema) => {
317 schema.row_options = format_encode_options;
318 }
319 CompatibleFormatEncode::RowFormat(_schema) => unreachable!(),
322 }
323 }
324 _ => unreachable!(),
325 }
326
327 Ok(stmt.to_string())
328}
329
330#[cfg(test)]
331pub mod tests {
332 use risingwave_common::catalog::{DEFAULT_DATABASE_NAME, DEFAULT_SCHEMA_NAME};
333 use risingwave_common::types::DataType;
334
335 use crate::catalog::root_catalog::SchemaPath;
336 use crate::test_utils::{LocalFrontend, PROTO_FILE_DATA, create_proto_file};
337
338 #[tokio::test]
339 async fn test_refresh_schema_rejects_associated_table() {
340 let proto_file = create_proto_file(PROTO_FILE_DATA);
341 let sql = format!(
342 r#"CREATE TABLE t
343 WITH (
344 connector = 'kafka',
345 topic = 'test-topic',
346 properties.bootstrap.server = 'localhost:29092'
347 )
348 FORMAT PLAIN ENCODE PROTOBUF (
349 message = '.test.TestRecord',
350 schema.location = 'file://{}'
351 )"#,
352 proto_file.path().to_str().unwrap()
353 );
354 let frontend = LocalFrontend::new(Default::default()).await;
355 frontend.run_sql(sql).await.unwrap();
356
357 let error = frontend
358 .run_sql("ALTER SOURCE t REFRESH SCHEMA")
359 .await
360 .unwrap_err();
361 assert!(error.to_string().contains("try to use ALTER TABLE instead"));
362 }
363
364 #[tokio::test]
365 async fn test_alter_source_with_sr_handler() {
366 let proto_file = create_proto_file(PROTO_FILE_DATA);
367 let sql = format!(
368 r#"CREATE SOURCE src
369 WITH (
370 connector = 'kafka',
371 topic = 'test-topic',
372 properties.bootstrap.server = 'localhost:29092'
373 )
374 FORMAT PLAIN ENCODE PROTOBUF (
375 message = '.test.TestRecord',
376 schema.location = 'file://{}'
377 )"#,
378 proto_file.path().to_str().unwrap()
379 );
380 let frontend = LocalFrontend::new(Default::default()).await;
381 let session = frontend.session_ref();
382 let schema_path = SchemaPath::Name(DEFAULT_SCHEMA_NAME);
383
384 frontend
385 .run_sql_with_session(session.clone(), "SET streaming_use_shared_source TO false;")
386 .await
387 .unwrap();
388 frontend
389 .run_sql_with_session(session.clone(), sql)
390 .await
391 .unwrap();
392
393 let get_source = || {
394 let catalog_reader = session.env().catalog_reader().read_guard();
395 catalog_reader
396 .get_source_by_name(DEFAULT_DATABASE_NAME, schema_path, "src")
397 .unwrap()
398 .0
399 .clone()
400 };
401
402 let source = get_source();
403 expect_test::expect!["CREATE SOURCE src (id INT, country STRUCT<address CHARACTER VARYING, city STRUCT<address CHARACTER VARYING, zipcode CHARACTER VARYING>, zipcode CHARACTER VARYING>, zipcode BIGINT, rate REAL) WITH (connector = 'kafka', topic = 'test-topic', properties.bootstrap.server = 'localhost:29092') FORMAT PLAIN ENCODE PROTOBUF (message = '.test.TestRecord', schema.location = 'file://')"].assert_eq(&source.create_sql_purified().replace(proto_file.path().to_str().unwrap(), ""));
404
405 let sql = format!(
406 r#"ALTER SOURCE src FORMAT UPSERT ENCODE PROTOBUF (
407 message = '.test.TestRecord',
408 schema.location = 'file://{}'
409 )"#,
410 proto_file.path().to_str().unwrap()
411 );
412 assert!(
413 frontend
414 .run_sql(sql)
415 .await
416 .unwrap_err()
417 .to_string()
418 .contains("the original definition is FORMAT Plain ENCODE Protobuf")
419 );
420
421 let sql = format!(
422 r#"ALTER SOURCE src FORMAT PLAIN ENCODE PROTOBUF (
423 message = '.test.TestRecordAlterType',
424 schema.location = 'file://{}'
425 )"#,
426 proto_file.path().to_str().unwrap()
427 );
428 let res_str = frontend.run_sql(sql).await.unwrap_err().to_string();
429 assert!(res_str.contains("id: integer"));
430 assert!(res_str.contains("zipcode: bigint"));
431
432 let sql = format!(
433 r#"ALTER SOURCE src FORMAT PLAIN ENCODE PROTOBUF (
434 message = '.test.TestRecordExt',
435 schema.location = 'file://{}'
436 )"#,
437 proto_file.path().to_str().unwrap()
438 );
439 frontend.run_sql(sql).await.unwrap();
440
441 let altered_source = get_source();
442
443 let name_column = altered_source
444 .columns
445 .iter()
446 .find(|col| col.column_desc.name == "name")
447 .unwrap();
448 assert_eq!(name_column.column_desc.data_type, DataType::Varchar);
449
450 expect_test::expect!["CREATE SOURCE src (id INT, country STRUCT<address CHARACTER VARYING, city STRUCT<address CHARACTER VARYING, zipcode CHARACTER VARYING>, zipcode CHARACTER VARYING>, zipcode BIGINT, rate REAL, name CHARACTER VARYING) WITH (connector = 'kafka', topic = 'test-topic', properties.bootstrap.server = 'localhost:29092') FORMAT PLAIN ENCODE PROTOBUF (message = '.test.TestRecordExt', schema.location = 'file://')"].assert_eq(&altered_source.create_sql_purified().replace(proto_file.path().to_str().unwrap(), ""));
451 }
452}