risingwave_frontend/handler/
alter_table_column.rs1use std::collections::HashSet;
16use std::sync::Arc;
17
18use itertools::Itertools;
19use pgwire::pg_response::{PgResponse, StatementType};
20use risingwave_common::catalog::ColumnCatalog;
21use risingwave_common::hash::VnodeCount;
22use risingwave_common::license::Feature;
23use risingwave_common::{bail, bail_not_implemented};
24use risingwave_connector::source::cdc::{CDC_COLUMN_EXCLUDE_LIST, parse_cdc_column_exclude_list};
25use risingwave_pb::ddl_service::TableJobType;
26use risingwave_pb::stream_plan::StreamFragmentGraph;
27use risingwave_sqlparser::ast::{
28 AlterColumnOperation, AlterTableOperation, ColumnOption, ObjectName, SqlOption, Statement,
29};
30
31use super::create_source::SqlColumnStrategy;
32use super::create_table::{ColumnIdGenerator, generate_stream_graph_for_replace_table};
33use super::{HandlerArgs, RwPgResponse};
34use crate::catalog::purify::try_purify_table_source_create_sql_ast;
35use crate::catalog::root_catalog::SchemaPath;
36use crate::catalog::source_catalog::SourceCatalog;
37use crate::catalog::table_catalog::TableType;
38use crate::error::{ErrorCode, Result, RwError};
39use crate::expr::ExprImpl;
40use crate::session::SessionImpl;
41use crate::{Binder, TableCatalog, WithOptions};
42
43fn cdc_excluded_columns(with_options: &[SqlOption]) -> Result<HashSet<String>> {
45 Ok(WithOptions::try_from(with_options)?
46 .get(CDC_COLUMN_EXCLUDE_LIST)
47 .map(|list| parse_cdc_column_exclude_list(list))
48 .unwrap_or_default())
49}
50
51pub async fn get_new_table_definition_for_cdc_table(
53 original_catalog: Arc<TableCatalog>,
54 new_columns: &[ColumnCatalog],
55) -> Result<Statement> {
56 assert_eq!(
57 original_catalog.row_id_index, None,
58 "primary key of cdc table must be user defined"
59 );
60
61 let mut definition = original_catalog.create_sql_ast()?;
63
64 let excluded_columns = {
67 let Statement::CreateTable {
68 columns,
69 constraints,
70 with_options,
71 ..
72 } = &mut definition
73 else {
74 panic!("unexpected statement: {:?}", definition);
75 };
76
77 columns.clear();
78 constraints.clear();
79 cdc_excluded_columns(with_options)?
80 };
81 let new_columns = new_columns
82 .iter()
83 .filter(|c| !excluded_columns.contains(c.name()))
84 .cloned()
85 .collect_vec();
86
87 let new_definition = try_purify_table_source_create_sql_ast(
88 definition,
89 &new_columns,
90 None,
91 &original_catalog.pk_column_names(),
94 )?;
95
96 Ok(new_definition)
97}
98
99pub async fn get_replace_table_plan(
100 session: &Arc<SessionImpl>,
101 table_name: ObjectName,
102 new_definition: Statement,
103 old_catalog: &Arc<TableCatalog>,
104 sql_column_strategy: SqlColumnStrategy,
105) -> Result<(
106 Option<SourceCatalog>,
107 TableCatalog,
108 StreamFragmentGraph,
109 TableJobType,
110)> {
111 let handler_args = HandlerArgs::new(session.clone(), &new_definition, Arc::from(""))?;
113 let col_id_gen = ColumnIdGenerator::new_alter(old_catalog);
114
115 let (graph, table, source, job_type) = Box::pin(generate_stream_graph_for_replace_table(
116 session,
117 table_name,
118 old_catalog,
119 handler_args.clone(),
120 new_definition,
121 col_id_gen,
122 sql_column_strategy,
123 ))
124 .await?;
125
126 let mut table = table;
128 table.vnode_count = VnodeCount::set(old_catalog.vnode_count());
129
130 Ok((source, table, graph, job_type))
131}
132
133pub async fn handle_alter_table_column(
136 handler_args: HandlerArgs,
137 table_name: ObjectName,
138 operation: AlterTableOperation,
139) -> Result<RwPgResponse> {
140 let session = handler_args.session;
141 let (original_catalog, has_incoming_sinks) =
142 fetch_table_catalog_for_alter(session.as_ref(), &table_name)?;
143
144 if original_catalog.is_iceberg_engine_table()
145 && matches!(
146 &operation,
147 AlterTableOperation::AddColumn { .. } | AlterTableOperation::DropColumn { .. }
148 )
149 {
150 Feature::SinkAutoSchemaChange.check_available()?;
151 }
152
153 if original_catalog.webhook_info.is_some() {
154 return Err(RwError::from(ErrorCode::BindError(
155 "Adding/dropping a column of a table with webhook has not been implemented.".to_owned(),
156 )));
157 }
158
159 if let Some(source_id) = original_catalog.associated_source_id() {
162 let reader = session.env().catalog_reader().read_guard();
163 let source = reader.get_source_by_id_with_db(&session.database(), source_id)?;
164 if source.is_iceberg_update_source() {
165 return Err(ErrorCode::NotSupported(
166 "altering columns of an Iceberg table with streaming_updates".to_owned(),
167 "Drop and recreate the table with the new columns".to_owned(),
168 )
169 .into());
170 }
171 }
172
173 let mut definition = original_catalog.create_sql_ast_purified()?;
175 let Statement::CreateTable {
176 columns,
177 with_options,
178 ..
179 } = &mut definition
180 else {
181 panic!("unexpected statement: {:?}", definition);
182 };
183
184 if has_incoming_sinks && matches!(operation, AlterTableOperation::DropColumn { .. }) {
185 Err(ErrorCode::InvalidInputSyntax(
186 "dropping columns in target table of sinks is not supported".to_owned(),
187 ))?;
188 }
189
190 let sql_column_strategy = match operation {
208 AlterTableOperation::AddColumn {
209 column_def: new_column,
210 } => {
211 let new_column_name = new_column.name.real_value();
214 if columns
215 .iter()
216 .any(|c| c.name.real_value() == new_column_name)
217 {
218 Err(ErrorCode::InvalidInputSyntax(format!(
219 "column \"{new_column_name}\" of table \"{table_name}\" already exists"
220 )))?
221 }
222 if cdc_excluded_columns(with_options)?.contains(&new_column_name) {
224 Err(ErrorCode::InvalidInputSyntax(format!(
225 "column \"{new_column_name}\" of table \"{table_name}\" is listed in `{CDC_COLUMN_EXCLUDE_LIST}`"
226 )))?
227 }
228
229 if new_column
230 .options
231 .iter()
232 .any(|x| matches!(x.option, ColumnOption::GeneratedColumns(_)))
233 {
234 Err(ErrorCode::InvalidInputSyntax(
235 "alter table add generated columns is not supported".to_owned(),
236 ))?
237 }
238
239 if new_column
240 .options
241 .iter()
242 .any(|x| matches!(x.option, ColumnOption::NotNull))
243 && !new_column
244 .options
245 .iter()
246 .any(|x| matches!(x.option, ColumnOption::DefaultValue(_)))
247 {
248 Err(ErrorCode::InvalidInputSyntax(
249 "alter table add NOT NULL columns must have default value".to_owned(),
250 ))?;
251 }
252
253 columns.push(new_column);
255
256 SqlColumnStrategy::FollowChecked
257 }
258
259 AlterTableOperation::DropColumn {
260 column_name,
261 if_exists,
262 cascade,
263 } => {
264 if cascade {
265 bail_not_implemented!(issue = 6903, "drop column cascade");
266 }
267
268 for column in original_catalog.columns() {
270 if let Some(expr) = column.generated_expr() {
271 let expr = ExprImpl::from_expr_proto(expr)?;
272 let refs = expr.collect_input_refs(original_catalog.columns().len());
273 for idx in refs.ones() {
274 let refed_column = &original_catalog.columns()[idx];
275 if refed_column.name() == column_name.real_value() {
276 bail!(format!(
277 "failed to drop column \"{}\" because it's referenced by a generated column \"{}\"",
278 column_name,
279 column.name()
280 ))
281 }
282 }
283 }
284 }
285
286 let column_name = column_name.real_value();
288 let removed_column = columns
289 .extract_if(.., |c| c.name.real_value() == column_name)
290 .at_most_one()
291 .ok()
292 .unwrap();
293
294 if removed_column.is_some() {
295 } else if if_exists {
297 return Ok(PgResponse::builder(StatementType::ALTER_TABLE)
298 .notice(format!(
299 "column \"{}\" does not exist, skipping",
300 column_name
301 ))
302 .into());
303 } else {
304 Err(ErrorCode::InvalidInputSyntax(format!(
305 "column \"{}\" of table \"{}\" does not exist",
306 column_name, table_name
307 )))?
308 }
309
310 SqlColumnStrategy::FollowUnchecked
311 }
312
313 AlterTableOperation::AlterColumn { column_name, op } => {
314 let AlterColumnOperation::SetDataType {
315 data_type,
316 using: None,
317 } = op
318 else {
319 bail_not_implemented!(issue = 6903, "{op}");
320 };
321
322 let column_name = column_name.real_value();
324 let column = columns
325 .iter_mut()
326 .find(|c| c.name.real_value() == column_name)
327 .ok_or_else(|| {
328 ErrorCode::InvalidInputSyntax(format!(
329 "column \"{}\" of table \"{}\" does not exist",
330 column_name, table_name
331 ))
332 })?;
333
334 column.data_type = Some(data_type);
335
336 SqlColumnStrategy::FollowChecked
337 }
338
339 _ => unreachable!(),
340 };
341 let (source, table, graph, job_type) = Box::pin(get_replace_table_plan(
342 &session,
343 table_name,
344 definition,
345 &original_catalog,
346 sql_column_strategy,
347 ))
348 .await?;
349
350 let catalog_writer = session.catalog_writer()?;
351
352 catalog_writer
353 .replace_table(
354 source.map(|x| x.to_prost()),
355 table.to_prost(),
356 graph,
357 job_type,
358 )
359 .await?;
360 Ok(PgResponse::empty_result(StatementType::ALTER_TABLE))
361}
362
363pub fn fetch_table_catalog_for_alter(
364 session: &SessionImpl,
365 table_name: &ObjectName,
366) -> Result<(Arc<TableCatalog>, bool)> {
367 let db_name = &session.database();
368 let (schema_name, real_table_name) =
369 Binder::resolve_schema_qualified_name(db_name, table_name)?;
370 let search_path = session.config().search_path();
371 let user_name = &session.user_name();
372
373 let schema_path = SchemaPath::new(schema_name.as_deref(), &search_path, user_name);
374
375 {
376 let reader = session.env().catalog_reader().read_guard();
377 let (table, schema_name) =
378 reader.get_created_table_by_name(db_name, schema_path, &real_table_name)?;
379
380 match table.table_type() {
381 TableType::Table => {}
382
383 _ => Err(ErrorCode::InvalidInputSyntax(format!(
384 "\"{table_name}\" is not a table or cannot be altered"
385 )))?,
386 }
387
388 session.check_privilege_for_drop_alter(schema_name, &**table)?;
389
390 let has_incoming_sinks = reader
391 .get_schema_by_id(table.database_id, table.schema_id)?
392 .table_incoming_sinks(table.id)
393 .map(|sinks| !sinks.is_empty())
394 .unwrap_or(false);
395
396 Ok((table.clone(), has_incoming_sinks))
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use std::collections::HashMap;
403
404 use risingwave_common::catalog::{
405 DEFAULT_DATABASE_NAME, DEFAULT_SCHEMA_NAME, ROW_ID_COLUMN_NAME,
406 };
407 use risingwave_common::types::DataType;
408
409 use crate::catalog::root_catalog::SchemaPath;
410 use crate::test_utils::LocalFrontend;
411
412 #[tokio::test]
413 async fn test_add_column_handler() {
414 let frontend = LocalFrontend::new(Default::default()).await;
415 let session = frontend.session_ref();
416 let schema_path = SchemaPath::Name(DEFAULT_SCHEMA_NAME);
417
418 let sql = "create table t (i int, r real);";
419 frontend.run_sql(sql).await.unwrap();
420
421 let get_table = || {
422 let catalog_reader = session.env().catalog_reader().read_guard();
423 catalog_reader
424 .get_created_table_by_name(DEFAULT_DATABASE_NAME, schema_path, "t")
425 .unwrap()
426 .0
427 .clone()
428 };
429
430 let table = get_table();
431
432 let columns: HashMap<_, _> = table
433 .columns
434 .iter()
435 .map(|col| (col.name(), (col.data_type().clone(), col.column_id())))
436 .collect();
437
438 let sql = "alter table t add column s text;";
440 frontend.run_sql(sql).await.unwrap();
441
442 let altered_table = get_table();
443
444 let altered_columns: HashMap<_, _> = altered_table
445 .columns
446 .iter()
447 .map(|col| (col.name(), (col.data_type().clone(), col.column_id())))
448 .collect();
449
450 assert_eq!(columns.len() + 1, altered_columns.len());
452 assert_eq!(altered_columns["s"].0, DataType::Varchar);
453
454 assert_eq!(columns["i"], altered_columns["i"]);
456 assert_eq!(columns["r"], altered_columns["r"]);
457 assert_eq!(
458 columns[ROW_ID_COLUMN_NAME],
459 altered_columns[ROW_ID_COLUMN_NAME]
460 );
461
462 assert_eq!(
464 table.version.as_ref().unwrap().version_id + 1,
465 altered_table.version.as_ref().unwrap().version_id
466 );
467 assert_eq!(
468 table.version.as_ref().unwrap().next_column_id.next(),
469 altered_table.version.as_ref().unwrap().next_column_id
470 );
471 }
472}