Skip to main content

risingwave_frontend/handler/
alter_table_column.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::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
43/// Columns listed in `column.exclude.list` in the `WITH` options of a CDC table definition.
44fn 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
51/// Used in auto schema change process
52pub 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    // Retrieve the original table definition.
62    let mut definition = original_catalog.create_sql_ast()?;
63
64    // Clear the original columns field, so that we'll follow `new_columns` to generate a
65    // purified definition.
66    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        // The IDs of `new_columns` may not be consistently maintained at this point.
92        // So we use the column names to identify the primary key columns.
93        &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    // Create handler args as if we're creating a new table with the altered definition.
112    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    // Set some fields ourselves so that the meta service does not need to maintain them.
127    let mut table = table;
128    table.vnode_count = VnodeCount::set(old_catalog.vnode_count());
129
130    Ok((source, table, graph, job_type))
131}
132
133/// Handle `ALTER TABLE [ADD|DROP] COLUMN` statements. The `operation` must be either `AddColumn` or
134/// `DropColumn`.
135pub 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    // An Iceberg update source persists its column projection when it first runs and fails if
160    // the columns change afterwards.
161    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    // Retrieve the original table definition and parse it to AST.
174    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    // The `sql_column_strategy` will be `FollowChecked` if the operation is `AddColumn`, and
191    // `FollowUnchecked` if the operation is `DropColumn`.
192    //
193    // Consider the following example:
194    // - There was a column `foo` and a generated column `gen` that references `foo`.
195    // - The external schema is updated to remove `foo`.
196    // - The user tries to drop `foo` from the table.
197    //
198    // Dropping `foo` directly will fail because `gen` references `foo`. However, dropping `gen`
199    // first will also be rejected because `foo` does not exist any more. Also, executing
200    // `REFRESH SCHEMA` will not help because it keeps the generated column. The user gets stuck.
201    //
202    // `FollowUnchecked` workarounds this issue. There are also some alternatives:
203    // - Allow dropping multiple columns at once.
204    // - Check against the persisted schema, instead of resolving again.
205    //
206    // Applied only to tables with schema registry.
207    let sql_column_strategy = match operation {
208        AlterTableOperation::AddColumn {
209            column_def: new_column,
210        } => {
211            // Duplicated names can actually be checked by `StreamMaterialize`. We do here for
212            // better error reporting.
213            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            // Otherwise the next upstream schema change would silently drop it again.
223            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            // Add the new column to the table definition if it is not created by `create table (*)` syntax.
254            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            // Check if the column to drop is referenced by any generated columns.
269            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            // Locate the column by name and remove it.
287            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                // PASS
296            } 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            // Locate the column by name and update its data type.
323            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        // Alter the table.
439        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        // Check the new column.
451        assert_eq!(columns.len() + 1, altered_columns.len());
452        assert_eq!(altered_columns["s"].0, DataType::Varchar);
453
454        // Check the old columns and IDs are not changed.
455        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        // Check the version is updated.
463        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}