Skip to main content

risingwave_frontend/handler/
create_table.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 std::collections::{BTreeMap, HashMap, HashSet};
16use std::rc::Rc;
17use std::sync::Arc;
18
19use anyhow::Context;
20use clap::ValueEnum;
21use either::Either;
22use fixedbitset::FixedBitSet;
23use iceberg::spec::FormatVersion;
24use itertools::Itertools;
25use percent_encoding::percent_decode_str;
26use pgwire::pg_response::{PgResponse, StatementType};
27use prost::Message as _;
28use risingwave_common::acl::AclMode;
29use risingwave_common::catalog::{
30    CdcKeyComparison, CdcTableDesc, ColumnCatalog, ColumnDesc, ConflictBehavior,
31    DEFAULT_SCHEMA_NAME, Engine, ICEBERG_SINK_PREFIX, ICEBERG_SOURCE_PREFIX,
32    RISINGWAVE_ICEBERG_ROW_ID, ROW_ID_COLUMN_NAME, TableId,
33};
34use risingwave_common::config::MetaBackend;
35use risingwave_common::global_jvm::Jvm;
36use risingwave_common::session_config::sink_decouple::SinkDecouple;
37use risingwave_common::types::DataType;
38use risingwave_common::util::sort_util::{ColumnOrder, OrderType};
39use risingwave_common::util::value_encoding::DatumToProtoExt;
40use risingwave_common::{bail, bail_not_implemented};
41use risingwave_connector::source::cdc::external::ExternalCdcTableType;
42use risingwave_connector::source::cdc::{
43    CDC_COLUMN_EXCLUDE_LIST, CdcSourceExternalTableIdentifier, build_cdc_table_id,
44    parse_cdc_column_exclude_list,
45};
46use risingwave_connector::{
47    AUTO_SCHEMA_CHANGE_KEY, WithOptionsSecResolved, WithPropertiesExt, dispatch_cdc_source_type,
48};
49use risingwave_pb::catalog::connection::Info as ConnectionInfo;
50use risingwave_pb::catalog::connection_params::ConnectionType;
51use risingwave_pb::catalog::{PbSource, PbWebhookSourceInfo, WatermarkDesc};
52use risingwave_pb::ddl_service::{PbTableJobType, TableJobType};
53use risingwave_pb::plan_common::column_desc::GeneratedOrDefaultColumn;
54use risingwave_pb::plan_common::{
55    AdditionalColumn, ColumnDescVersion, DefaultColumnDesc, GeneratedColumnDesc,
56};
57use risingwave_pb::secret::PbSecretRef;
58use risingwave_pb::secret::secret_ref::PbRefAsType;
59use risingwave_pb::stream_plan::StreamFragmentGraph;
60use risingwave_sqlparser::ast::{
61    CdcTableInfo, ColumnDef, ColumnOption, CompatibleFormatEncode, ConnectionRefValue, CreateSink,
62    CreateSinkStatement, CreateSourceStatement, DataType as AstDataType, ExplainOptions, Format,
63    FormatEncodeOptions, Ident, ObjectName, OnConflict, SecretRefAsType, SourceWatermark,
64    Statement, TableConstraint, WebhookSourceInfo, WithProperties,
65};
66use risingwave_sqlparser::parser::IncludeOption;
67use thiserror_ext::AsReport;
68
69use super::RwPgResponse;
70use super::create_source::{CreateSourceType, SqlColumnStrategy, bind_columns_from_source};
71use crate::binder::{Clause, SecureCompareContext, WEBHOOK_PAYLOAD_FIELD_NAME, bind_data_type};
72use crate::catalog::root_catalog::SchemaPath;
73use crate::catalog::source_catalog::SourceCatalog;
74use crate::catalog::table_catalog::TableVersion;
75use crate::catalog::{ColumnId, DatabaseId, SchemaId, SourceId, check_column_name_not_reserved};
76use crate::error::{ErrorCode, Result, RwError, bail_bind_error};
77use crate::expr::{Expr, ExprImpl, ExprRewriter};
78use crate::handler::HandlerArgs;
79use crate::handler::cdc::{
80    bind_cdc_pk_comparisons_externally, bind_cdc_table_schema, bind_cdc_table_schema_externally,
81    derive_connect_properties_for_cdc_table, not_null_check_for_cdc_table,
82    reject_pk_filtered_by_debezium_column_filter, sanity_check_for_table_on_cdc_source,
83};
84use crate::handler::create_source::{
85    bind_connector_props, bind_create_source_or_table_with_connector, bind_source_watermark,
86    handle_addition_columns,
87};
88use crate::handler::privilege::ObjectCheckItem;
89use crate::handler::util::{
90    LongRunningNotificationAction, SourceSchemaCompatExt, execute_with_long_running_notification,
91};
92use crate::optimizer::plan_node::generic::{SourceNodeKind, build_cdc_scan_options_with_options};
93use crate::optimizer::plan_node::{
94    LogicalCdcScan, LogicalPlanRef, LogicalSource, StreamPlanRef as PlanRef,
95    ensure_sync_log_store_fragment_root,
96};
97use crate::optimizer::property::{Order, RequiredDist};
98use crate::optimizer::{OptimizerContext, OptimizerContextRef, PlanRoot};
99use crate::session::SessionImpl;
100use crate::session::current::notice_to_user;
101use crate::stream_fragmenter::{GraphJobType, build_graph};
102use crate::utils::OverwriteOptions;
103use crate::{Binder, Explain, TableCatalog, WithOptions};
104
105mod col_id_gen;
106pub use col_id_gen::*;
107use risingwave_connector::sink::SinkParam;
108use risingwave_connector::sink::iceberg::{
109    ENABLE_COMPACTION, ENABLE_MANIFEST_REWRITE, IcebergConfig, IcebergSink,
110    is_iceberg_engine_option, parse_partition_by_exprs, validate_order_key_columns,
111};
112use risingwave_pb::ddl_service::create_iceberg_table_request::{PbSinkJobInfo, PbTableJobInfo};
113
114use crate::handler::create_sink::{SinkPlanContext, gen_sink_plan};
115
116fn ensure_column_options_supported(c: &ColumnDef) -> Result<()> {
117    for option_def in &c.options {
118        match option_def.option {
119            ColumnOption::GeneratedColumns(_) => {}
120            ColumnOption::DefaultValue(_) => {}
121            ColumnOption::DefaultValueInternal { .. } => {}
122            ColumnOption::Unique { is_primary: true } => {}
123            ColumnOption::Null => {}
124            ColumnOption::NotNull => {}
125            _ => bail_not_implemented!("column constraints \"{}\"", option_def),
126        }
127    }
128    Ok(())
129}
130
131/// Binds the column schemas declared in CREATE statement into `ColumnDesc`.
132/// If a column is marked as `primary key`, its `ColumnId` is also returned.
133/// This primary key is not combined with table constraints yet.
134pub fn bind_sql_columns(
135    column_defs: &[ColumnDef],
136    is_for_drop_table_connector: bool,
137) -> Result<Vec<ColumnCatalog>> {
138    let mut columns = Vec::with_capacity(column_defs.len());
139
140    for column in column_defs {
141        ensure_column_options_supported(column)?;
142        // Destruct to make sure all fields are properly handled rather than ignored.
143        // Do NOT use `..` to ignore fields you do not want to deal with.
144        // Reject them with a clear NotImplemented error.
145        let ColumnDef {
146            name,
147            data_type,
148            collation,
149            options,
150            ..
151        } = column;
152
153        let data_type = data_type
154            .clone()
155            .ok_or_else(|| ErrorCode::InvalidInputSyntax("data type is not specified".into()))?;
156        if let Some(collation) = collation {
157            // PostgreSQL will limit the datatypes that collate can work on.
158            // https://www.postgresql.org/docs/16/collation.html#COLLATION-CONCEPTS
159            //   > The built-in collatable data types are `text`, `varchar`, and `char`.
160            //
161            // But we don't support real collation, we simply ignore it here.
162            if !["C", "POSIX"].contains(&collation.real_value().as_str()) {
163                bail_not_implemented!(
164                    "Collate collation other than `C` or `POSIX` is not implemented"
165                );
166            }
167
168            match data_type {
169                AstDataType::Text | AstDataType::Varchar | AstDataType::Char(_) => {}
170                _ => {
171                    return Err(ErrorCode::NotSupported(
172                        format!("{} is not a collatable data type", data_type),
173                        "The only built-in collatable data types are `varchar`, please check your type".into(),
174                    ).into());
175                }
176            }
177        }
178
179        if !is_for_drop_table_connector {
180            // additional column name may have prefix _rw
181            // When converting dropping the connector from table, the additional columns are converted to normal columns and keep the original name.
182            // Under this case, we loosen the check for _rw prefix.
183            check_column_name_not_reserved(&name.real_value())?;
184        }
185
186        let nullable: bool = !options
187            .iter()
188            .any(|def| matches!(def.option, ColumnOption::NotNull));
189
190        columns.push(ColumnCatalog {
191            column_desc: ColumnDesc {
192                data_type: bind_data_type(&data_type)?,
193                column_id: ColumnId::placeholder(),
194                name: name.real_value(),
195                generated_or_default_column: None,
196                description: None,
197                additional_column: AdditionalColumn { column_type: None },
198                version: ColumnDescVersion::LATEST,
199                system_column: None,
200                nullable,
201            },
202            is_hidden: false,
203        });
204    }
205
206    Ok(columns)
207}
208
209fn check_generated_column_constraints(
210    column_name: &String,
211    column_id: ColumnId,
212    expr: &ExprImpl,
213    column_catalogs: &[ColumnCatalog],
214    generated_column_names: &[String],
215    pk_column_ids: &[ColumnId],
216) -> Result<()> {
217    let input_refs = expr.collect_input_refs(column_catalogs.len());
218    for idx in input_refs.ones() {
219        let referred_generated_column = &column_catalogs[idx].column_desc.name;
220        if generated_column_names
221            .iter()
222            .any(|c| c == referred_generated_column)
223        {
224            return Err(ErrorCode::BindError(format!(
225                "A generated column cannot reference another generated column. \
226                Generated column \"{}\" references generated column \"{}\"",
227                column_name, referred_generated_column
228            ))
229            .into());
230        }
231    }
232
233    if pk_column_ids.contains(&column_id) && expr.is_impure() {
234        return Err(ErrorCode::BindError(format!(
235            "Generated columns with impure expressions should not be part of the primary key. \
236            Here column \"{}\" is defined as part of the primary key.",
237            column_name
238        ))
239        .into());
240    }
241
242    Ok(())
243}
244
245/// Binds constraints that can be only specified in column definitions,
246/// currently generated columns and default columns.
247pub fn bind_sql_column_constraints(
248    session: &SessionImpl,
249    table_name: String,
250    column_catalogs: &mut [ColumnCatalog],
251    columns: &[ColumnDef],
252    pk_column_ids: &[ColumnId],
253) -> Result<()> {
254    let generated_column_names = {
255        let mut names = vec![];
256        for column in columns {
257            for option_def in &column.options {
258                if let ColumnOption::GeneratedColumns(_) = option_def.option {
259                    names.push(column.name.real_value());
260                    break;
261                }
262            }
263        }
264        names
265    };
266
267    let mut binder = Binder::new_for_ddl(session);
268    binder.bind_columns_to_context(table_name, column_catalogs)?;
269
270    for column in columns {
271        let Some(idx) = column_catalogs
272            .iter()
273            .position(|c| c.name() == column.name.real_value())
274        else {
275            // It's possible that we don't follow the user defined columns in SQL but take the
276            // ones resolved from the source, thus missing some columns. Simply ignore them.
277            continue;
278        };
279
280        for option_def in &column.options {
281            match &option_def.option {
282                ColumnOption::GeneratedColumns(expr) => {
283                    binder.set_clause(Some(Clause::GeneratedColumn));
284
285                    let expr_impl = binder.bind_expr(expr).with_context(|| {
286                        format!(
287                            "failed to bind the expression in generated column \"{}\"",
288                            column.name.real_value()
289                        )
290                    })?;
291
292                    check_generated_column_constraints(
293                        &column.name.real_value(),
294                        column_catalogs[idx].column_id(),
295                        &expr_impl,
296                        column_catalogs,
297                        &generated_column_names,
298                        pk_column_ids,
299                    )?;
300
301                    column_catalogs[idx].column_desc.generated_or_default_column = Some(
302                        GeneratedOrDefaultColumn::GeneratedColumn(GeneratedColumnDesc {
303                            expr: Some(expr_impl.to_expr_proto()),
304                        }),
305                    );
306                    binder.set_clause(None);
307                }
308                ColumnOption::DefaultValue(expr) => {
309                    let expr_impl = binder
310                        .bind_expr(expr)?
311                        .cast_assign(column_catalogs[idx].data_type())?;
312
313                    // Rewrite expressions to evaluate a snapshot value, used for missing values in the case of
314                    // schema change.
315                    //
316                    // TODO: Currently we don't support impure expressions other than `now()` (like `random()`),
317                    // so the rewritten expression should almost always be pure and we directly call `fold_const`
318                    // here. Actually we do not require purity of the expression here since we're only to get a
319                    // snapshot value.
320                    let rewritten_expr_impl = session
321                        .pinned_snapshot()
322                        .inline_now_proc_time()
323                        .rewrite_expr(expr_impl.clone());
324
325                    if let Some(snapshot_value) = rewritten_expr_impl.try_fold_const() {
326                        let snapshot_value = snapshot_value?;
327
328                        column_catalogs[idx].column_desc.generated_or_default_column =
329                            Some(GeneratedOrDefaultColumn::DefaultColumn(DefaultColumnDesc {
330                                snapshot_value: Some(snapshot_value.to_protobuf()),
331                                expr: Some(expr_impl.to_expr_proto()),
332                                // persist the original expression
333                            }));
334                    } else {
335                        return Err(ErrorCode::BindError(format!(
336                            "Default expression used in column `{}` cannot be evaluated. \
337                            Use generated columns instead if you mean to reference other columns.",
338                            column.name
339                        ))
340                        .into());
341                    }
342                }
343                ColumnOption::DefaultValueInternal { persisted, expr: _ } => {
344                    // When a `DEFAULT INTERNAL` is used internally for schema change, the persisted value
345                    // should already be set during purifcation. So if we encounter an empty value here, it
346                    // means the user has specified it explicitly in the SQL statement, typically by
347                    // directly copying the result of `SHOW CREATE TABLE` and executing it.
348                    if persisted.is_empty() {
349                        bail_bind_error!(
350                            "DEFAULT INTERNAL is only used for internal purposes, \
351                             please specify a concrete default value"
352                        );
353                    }
354
355                    let desc = DefaultColumnDesc::decode(&**persisted)
356                        .expect("failed to decode persisted `DefaultColumnDesc`");
357
358                    column_catalogs[idx].column_desc.generated_or_default_column =
359                        Some(GeneratedOrDefaultColumn::DefaultColumn(desc));
360                }
361                _ => {}
362            }
363        }
364    }
365    Ok(())
366}
367
368/// Currently we only support Primary key table constraint, so just return pk names if it exists
369pub fn bind_table_constraints(table_constraints: &[TableConstraint]) -> Result<Vec<String>> {
370    let mut pk_column_names = vec![];
371
372    for constraint in table_constraints {
373        match constraint {
374            TableConstraint::Unique {
375                name: _,
376                columns,
377                is_primary: true,
378            } => {
379                if !pk_column_names.is_empty() {
380                    return Err(multiple_pk_definition_err());
381                }
382                pk_column_names = columns.iter().map(|c| c.real_value()).collect_vec();
383            }
384            _ => bail_not_implemented!("table constraint \"{}\"", constraint),
385        }
386    }
387    Ok(pk_column_names)
388}
389
390pub fn bind_sql_pk_names(
391    columns_defs: &[ColumnDef],
392    pk_names_from_table_constraints: Vec<String>,
393) -> Result<Vec<String>> {
394    let mut pk_column_names = pk_names_from_table_constraints;
395
396    for column in columns_defs {
397        for option_def in &column.options {
398            if let ColumnOption::Unique { is_primary: true } = option_def.option {
399                if !pk_column_names.is_empty() {
400                    return Err(multiple_pk_definition_err());
401                }
402                pk_column_names.push(column.name.real_value());
403            };
404        }
405    }
406
407    Ok(pk_column_names)
408}
409
410fn multiple_pk_definition_err() -> RwError {
411    ErrorCode::BindError("multiple primary keys are not allowed".into()).into()
412}
413
414/// Binds primary keys defined in SQL.
415///
416/// It returns the columns together with `pk_column_ids`, and an optional row id column index if
417/// added.
418pub fn bind_pk_and_row_id_on_relation(
419    mut columns: Vec<ColumnCatalog>,
420    pk_names: Vec<String>,
421    must_need_pk: bool,
422) -> Result<(Vec<ColumnCatalog>, Vec<ColumnId>, Option<usize>)> {
423    for c in &columns {
424        assert!(c.column_id() != ColumnId::placeholder());
425    }
426
427    // Mapping from column name to column id.
428    let name_to_id = columns
429        .iter()
430        .map(|c| (c.name(), c.column_id()))
431        .collect::<HashMap<_, _>>();
432
433    let mut pk_column_ids: Vec<_> = pk_names
434        .iter()
435        .map(|name| {
436            name_to_id.get(name.as_str()).copied().ok_or_else(|| {
437                ErrorCode::BindError(format!("column \"{name}\" named in key does not exist"))
438            })
439        })
440        .try_collect()?;
441
442    // Add `_row_id` column if `pk_column_ids` is empty and must_need_pk
443    let need_row_id = pk_column_ids.is_empty() && must_need_pk;
444
445    let row_id_index = need_row_id.then(|| {
446        let column = ColumnCatalog::row_id_column();
447        let index = columns.len();
448        pk_column_ids = vec![column.column_id()];
449        columns.push(column);
450        index
451    });
452
453    if let Some(col) = columns.iter().map(|c| c.name()).duplicates().next() {
454        Err(ErrorCode::InvalidInputSyntax(format!(
455            "column \"{col}\" specified more than once"
456        )))?;
457    }
458
459    Ok((columns, pk_column_ids, row_id_index))
460}
461
462/// `gen_create_table_plan_with_source` generates the plan for creating a table with an external
463/// stream source.
464#[allow(clippy::too_many_arguments)]
465pub(crate) async fn gen_create_table_plan_with_source(
466    mut handler_args: HandlerArgs,
467    explain_options: ExplainOptions,
468    table_name: ObjectName,
469    column_defs: Vec<ColumnDef>,
470    wildcard_idx: Option<usize>,
471    constraints: Vec<TableConstraint>,
472    format_encode: FormatEncodeOptions,
473    source_watermarks: Vec<SourceWatermark>,
474    mut col_id_gen: ColumnIdGenerator,
475    include_column_options: IncludeOption,
476    props: CreateTableProps,
477    sql_column_strategy: SqlColumnStrategy,
478) -> Result<(PlanRef, Option<SourceCatalog>, TableCatalog)> {
479    if props.append_only
480        && format_encode.format != Format::Plain
481        && format_encode.format != Format::Native
482    {
483        return Err(ErrorCode::BindError(format!(
484            "Append only table does not support format {}.",
485            format_encode.format
486        ))
487        .into());
488    }
489
490    let session = &handler_args.session;
491    let (with_properties, ingest_mode) =
492        bind_connector_props(&handler_args, &format_encode, false)?;
493    if with_properties.is_shareable_cdc_connector() {
494        generated_columns_check_for_cdc_table(&column_defs)?;
495        not_null_check_for_cdc_table(&wildcard_idx, &column_defs)?;
496    } else if column_defs.iter().any(|col| {
497        col.options
498            .iter()
499            .any(|def| matches!(def.option, ColumnOption::NotNull))
500    }) {
501        // if non-cdc source
502        notice_to_user(
503            "The table contains columns with NOT NULL constraints. Any rows from upstream violating the constraints will be ignored silently.",
504        );
505    }
506
507    let db_name: &str = &session.database();
508    let (schema_name, _) = Binder::resolve_schema_qualified_name(db_name, &table_name)?;
509    // Check the CREATE privilege before `bind_columns_from_source`, which may fetch from
510    // user-supplied URLs (schema registry, schema file).
511    session.get_database_and_schema_id_for_create(schema_name.clone())?;
512
513    // TODO: omit this step if `sql_column_strategy` is `Follow`.
514    let (columns_from_resolve_source, source_info) = bind_columns_from_source(
515        session,
516        &format_encode,
517        Either::Left(&with_properties),
518        CreateSourceType::Table,
519    )
520    .await?;
521
522    let overwrite_options = OverwriteOptions::new(&mut handler_args)?;
523    let rate_limit = overwrite_options.source_rate_limit;
524    let source = bind_create_source_or_table_with_connector(
525        handler_args.clone(),
526        table_name,
527        format_encode,
528        with_properties,
529        column_defs,
530        constraints,
531        wildcard_idx,
532        source_watermarks,
533        columns_from_resolve_source,
534        source_info,
535        include_column_options,
536        &mut col_id_gen,
537        CreateSourceType::Table,
538        rate_limit,
539        sql_column_strategy,
540        ingest_mode,
541    )
542    .await?;
543
544    let context = OptimizerContext::new(handler_args, explain_options)?;
545
546    let (plan, table) = gen_table_plan_with_source(
547        context.into(),
548        schema_name,
549        source.clone(),
550        col_id_gen.into_version(),
551        props,
552    )?;
553
554    Ok((plan, Some(source), table))
555}
556
557/// `gen_create_table_plan` generates the plan for creating a table without an external stream
558/// source.
559#[allow(clippy::too_many_arguments)]
560pub(crate) fn gen_create_table_plan(
561    context: OptimizerContext,
562    table_name: ObjectName,
563    column_defs: Vec<ColumnDef>,
564    constraints: Vec<TableConstraint>,
565    mut col_id_gen: ColumnIdGenerator,
566    source_watermarks: Vec<SourceWatermark>,
567    props: CreateTableProps,
568    is_for_replace_plan: bool,
569) -> Result<(PlanRef, TableCatalog)> {
570    let mut columns = bind_sql_columns(&column_defs, is_for_replace_plan)?;
571    for c in &mut columns {
572        col_id_gen.generate(c)?;
573    }
574
575    let (_, secret_refs, connection_refs) = context.with_options().clone().into_parts();
576    if !secret_refs.is_empty() || !connection_refs.is_empty() {
577        return Err(crate::error::ErrorCode::InvalidParameterValue("Secret reference and Connection reference are not allowed in options when creating table without external source".to_owned()).into());
578    }
579
580    gen_create_table_plan_without_source(
581        context,
582        table_name,
583        columns,
584        column_defs,
585        constraints,
586        source_watermarks,
587        col_id_gen.into_version(),
588        props,
589    )
590}
591
592#[allow(clippy::too_many_arguments)]
593pub(crate) fn gen_create_table_plan_without_source(
594    context: OptimizerContext,
595    table_name: ObjectName,
596    columns: Vec<ColumnCatalog>,
597    column_defs: Vec<ColumnDef>,
598    constraints: Vec<TableConstraint>,
599    source_watermarks: Vec<SourceWatermark>,
600    version: TableVersion,
601    props: CreateTableProps,
602) -> Result<(PlanRef, TableCatalog)> {
603    // XXX: Why not bind outside?
604    let pk_names = bind_sql_pk_names(&column_defs, bind_table_constraints(&constraints)?)?;
605    let (mut columns, pk_column_ids, row_id_index) =
606        bind_pk_and_row_id_on_relation(columns, pk_names, true)?;
607
608    let watermark_descs = bind_source_watermark(
609        context.session_ctx(),
610        table_name.real_value(),
611        source_watermarks,
612        &columns,
613    )?;
614
615    bind_sql_column_constraints(
616        context.session_ctx(),
617        table_name.real_value(),
618        &mut columns,
619        &column_defs,
620        &pk_column_ids,
621    )?;
622    let session = context.session_ctx().clone();
623
624    let db_name = &session.database();
625    let (schema_name, table_name) = Binder::resolve_schema_qualified_name(db_name, &table_name)?;
626
627    let info = CreateTableInfo {
628        columns,
629        pk_column_ids,
630        row_id_index,
631        watermark_descs,
632        source_catalog: None,
633        version,
634    };
635
636    gen_table_plan_inner(context.into(), schema_name, table_name, info, props)
637}
638
639fn gen_table_plan_with_source(
640    context: OptimizerContextRef,
641    schema_name: Option<String>,
642    source_catalog: SourceCatalog,
643    version: TableVersion,
644    props: CreateTableProps,
645) -> Result<(PlanRef, TableCatalog)> {
646    let table_name = source_catalog.name.clone();
647
648    let info = CreateTableInfo {
649        columns: source_catalog.columns.clone(),
650        pk_column_ids: source_catalog.pk_col_ids.clone(),
651        row_id_index: source_catalog.row_id_index,
652        watermark_descs: source_catalog.watermark_descs.clone(),
653        source_catalog: Some(source_catalog),
654        version,
655    };
656
657    gen_table_plan_inner(context, schema_name, table_name, info, props)
658}
659
660/// On-conflict behavior either from user input or existing table catalog.
661#[derive(Clone, Copy)]
662pub enum EitherOnConflict {
663    Ast(Option<OnConflict>),
664    Resolved(ConflictBehavior),
665}
666
667impl From<Option<OnConflict>> for EitherOnConflict {
668    fn from(v: Option<OnConflict>) -> Self {
669        Self::Ast(v)
670    }
671}
672
673impl From<ConflictBehavior> for EitherOnConflict {
674    fn from(v: ConflictBehavior) -> Self {
675        Self::Resolved(v)
676    }
677}
678
679impl EitherOnConflict {
680    /// Resolves the conflict behavior based on the given information.
681    pub fn to_behavior(self, append_only: bool, row_id_as_pk: bool) -> Result<ConflictBehavior> {
682        let conflict_behavior = match self {
683            EitherOnConflict::Ast(on_conflict) => {
684                if append_only {
685                    if row_id_as_pk {
686                        // Primary key will be generated, no conflict check needed.
687                        ConflictBehavior::NoCheck
688                    } else {
689                        // User defined PK on append-only table, enforce `DO NOTHING`.
690                        if let Some(on_conflict) = on_conflict
691                            && on_conflict != OnConflict::Nothing
692                        {
693                            return Err(ErrorCode::InvalidInputSyntax(
694                                "When PRIMARY KEY constraint applied to an APPEND ONLY table, \
695                                     the ON CONFLICT behavior must be DO NOTHING."
696                                    .to_owned(),
697                            )
698                            .into());
699                        }
700                        ConflictBehavior::IgnoreConflict
701                    }
702                } else {
703                    // Default to `UPDATE FULL` for non-append-only tables.
704                    match on_conflict.unwrap_or(OnConflict::UpdateFull) {
705                        OnConflict::UpdateFull => ConflictBehavior::Overwrite,
706                        OnConflict::Nothing => ConflictBehavior::IgnoreConflict,
707                        OnConflict::UpdateIfNotNull => ConflictBehavior::DoUpdateIfNotNull,
708                    }
709                }
710            }
711            EitherOnConflict::Resolved(b) => b,
712        };
713
714        Ok(conflict_behavior)
715    }
716}
717
718/// Arguments of the functions that generate a table plan, part 1.
719///
720/// Compared to [`CreateTableProps`], this struct contains fields that need some work of binding
721/// or resolving based on the user input.
722pub struct CreateTableInfo {
723    pub columns: Vec<ColumnCatalog>,
724    pub pk_column_ids: Vec<ColumnId>,
725    pub row_id_index: Option<usize>,
726    pub watermark_descs: Vec<WatermarkDesc>,
727    pub source_catalog: Option<SourceCatalog>,
728    pub version: TableVersion,
729}
730
731/// Arguments of the functions that generate a table plan, part 2.
732///
733/// Compared to [`CreateTableInfo`], this struct contains fields that can be (relatively) simply
734/// obtained from the input or the context.
735pub struct CreateTableProps {
736    pub definition: String,
737    pub append_only: bool,
738    pub on_conflict: EitherOnConflict,
739    pub with_version_columns: Vec<String>,
740    pub webhook_info: Option<PbWebhookSourceInfo>,
741    pub engine: Engine,
742}
743
744#[allow(clippy::too_many_arguments)]
745fn gen_table_plan_inner(
746    context: OptimizerContextRef,
747    schema_name: Option<String>,
748    table_name: String,
749    info: CreateTableInfo,
750    props: CreateTableProps,
751) -> Result<(PlanRef, TableCatalog)> {
752    let CreateTableInfo {
753        ref columns,
754        row_id_index,
755        ref watermark_descs,
756        ref source_catalog,
757        ..
758    } = info;
759    let CreateTableProps { append_only, .. } = props;
760
761    let (database_id, schema_id) = context
762        .session_ctx()
763        .get_database_and_schema_id_for_create(schema_name)?;
764
765    let session = context.session_ctx().clone();
766    let retention_seconds = context.with_options().retention_seconds();
767
768    let source_node: LogicalPlanRef = LogicalSource::new(
769        source_catalog.clone().map(Rc::new),
770        columns.clone(),
771        row_id_index,
772        SourceNodeKind::CreateTable,
773        context.clone(),
774        None,
775    )?
776    .into();
777
778    let required_cols = FixedBitSet::with_capacity(columns.len());
779    let plan_root = PlanRoot::new_with_logical_plan(
780        source_node,
781        RequiredDist::Any,
782        Order::any(),
783        required_cols,
784        vec![],
785    );
786
787    let has_non_ttl_watermark = watermark_descs.iter().any(|d| !d.with_ttl);
788
789    if !append_only && has_non_ttl_watermark {
790        return Err(ErrorCode::NotSupported(
791            "Defining watermarks on table requires the table to be append only.".to_owned(),
792            "Use the key words `APPEND ONLY`".to_owned(),
793        )
794        .into());
795    }
796
797    if !append_only && retention_seconds.is_some() {
798        if session
799            .config()
800            .unsafe_enable_storage_retention_for_non_append_only_tables()
801        {
802            tracing::warn!(
803                "Storage retention is enabled for non-append-only table {}. This may lead to stream inconsistency.",
804                table_name
805            );
806            const NOTICE: &str = "Storage retention is enabled for non-append-only table. \
807                                  This may lead to stream inconsistency and unrecoverable \
808                                  node failure if there is any row INSERT/UPDATE/DELETE operation \
809                                  corresponding to the TTLed primary keys";
810            session.notice_to_user(NOTICE);
811        } else {
812            return Err(ErrorCode::NotSupported(
813                "Defining retention seconds on table requires the table to be append only."
814                    .to_owned(),
815                "Use the key words `APPEND ONLY`".to_owned(),
816            )
817            .into());
818        }
819    }
820
821    let materialize =
822        plan_root.gen_table_plan(context, table_name, database_id, schema_id, info, props)?;
823
824    let mut table = materialize.table().clone();
825    table.owner = session.user_id();
826
827    Ok((
828        ensure_sync_log_store_fragment_root(materialize.into()),
829        table,
830    ))
831}
832
833/// Generate stream plan for cdc table based on shared source.
834/// In replace workflow, the `table_id` is the id of the table to be replaced
835/// in create table workflow, the `table_id` is a placeholder will be filled in the Meta
836#[allow(clippy::too_many_arguments)]
837pub(crate) fn gen_create_table_plan_for_cdc_table(
838    context: OptimizerContextRef,
839    source: Arc<SourceCatalog>,
840    external_table_name: String,
841    column_defs: Vec<ColumnDef>,
842    source_watermarks: Vec<SourceWatermark>,
843    mut columns: Vec<ColumnCatalog>,
844    pk_names: Vec<String>,
845    pk_comparisons: Vec<CdcKeyComparison>,
846    cdc_with_options: WithOptionsSecResolved,
847    mut col_id_gen: ColumnIdGenerator,
848    on_conflict: Option<OnConflict>,
849    with_version_columns: Vec<String>,
850    include_column_options: IncludeOption,
851    table_name: ObjectName,
852    resolved_table_name: String, // table name without schema prefix
853    database_id: DatabaseId,
854    schema_id: SchemaId,
855    table_id: TableId,
856    engine: Engine,
857) -> Result<(PlanRef, TableCatalog)> {
858    let session = context.session_ctx().clone();
859
860    // append additional columns to the end
861    handle_addition_columns(
862        None,
863        &cdc_with_options,
864        include_column_options,
865        &mut columns,
866        true,
867    )?;
868
869    for c in &mut columns {
870        col_id_gen.generate(c)?;
871    }
872
873    let (mut columns, pk_column_ids, _row_id_index) =
874        bind_pk_and_row_id_on_relation(columns, pk_names, true)?;
875
876    let watermark_descs = bind_source_watermark(
877        context.session_ctx(),
878        table_name.real_value(),
879        source_watermarks,
880        &columns,
881    )?;
882
883    // NOTES: In auto schema change, default value is not provided in column definition.
884    bind_sql_column_constraints(
885        context.session_ctx(),
886        table_name.real_value(),
887        &mut columns,
888        &column_defs,
889        &pk_column_ids,
890    )?;
891
892    let definition = context.normalized_sql().to_owned();
893
894    let pk_column_indices = {
895        let mut id_to_idx = HashMap::new();
896        columns.iter().enumerate().for_each(|(idx, c)| {
897            id_to_idx.insert(c.column_id(), idx);
898        });
899        // pk column id must exist in table columns.
900        pk_column_ids
901            .iter()
902            .map(|c| id_to_idx.get(c).copied().unwrap())
903            .collect_vec()
904    };
905    let table_pk = pk_column_indices
906        .iter()
907        .map(|idx| ColumnOrder::new(*idx, OrderType::ascending()))
908        .collect();
909
910    let (options, secret_refs) = cdc_with_options.into_parts();
911
912    let non_generated_column_descs = columns
913        .iter()
914        .filter(|&c| !c.is_generated())
915        .map(|c| c.column_desc.clone())
916        .collect_vec();
917    let non_generated_column_num = non_generated_column_descs.len();
918    let cdc_table_type = ExternalCdcTableType::from_properties(&options);
919    let canonical_name = dispatch_cdc_source_type!(
920        options.cdc_source_type(),
921        T,
922        T::canonical_name(&options),
923        unreachable!("CDC table without a CDC connector")
924    );
925    let cdc_table_desc = CdcTableDesc {
926        table_id,
927        source_id: source.id, // id of cdc source streaming job
928        external_table_name: external_table_name.clone(),
929        pk: table_pk,
930        pk_comparisons,
931        columns: non_generated_column_descs,
932        stream_key: pk_column_indices,
933        connect_properties: options,
934        secret_refs,
935    };
936
937    tracing::debug!(?cdc_table_desc, "create cdc table");
938    let options = build_cdc_scan_options_with_options(
939        context.with_options(),
940        cdc_table_desc.connect_properties.cdc_source_type(),
941    )?;
942
943    let logical_scan = LogicalCdcScan::create(
944        external_table_name,
945        Rc::new(cdc_table_desc),
946        context.clone(),
947        options,
948    );
949
950    let scan_node: LogicalPlanRef = logical_scan.into();
951    let required_cols = FixedBitSet::with_capacity(non_generated_column_num);
952    let plan_root = PlanRoot::new_with_logical_plan(
953        scan_node,
954        RequiredDist::Any,
955        Order::any(),
956        required_cols,
957        vec![],
958    );
959
960    let cdc_table_id = build_cdc_table_id(source.id, &canonical_name);
961    let materialize = plan_root.gen_table_plan(
962        context,
963        resolved_table_name,
964        database_id,
965        schema_id,
966        CreateTableInfo {
967            columns,
968            pk_column_ids,
969            row_id_index: None,
970            watermark_descs,
971            source_catalog: Some((*source).clone()),
972            version: col_id_gen.into_version(),
973        },
974        CreateTableProps {
975            definition,
976            append_only: false,
977            on_conflict: on_conflict.into(),
978            with_version_columns,
979            webhook_info: None,
980            engine,
981        },
982    )?;
983
984    let mut table = materialize.table().clone();
985    table.owner = session.user_id();
986    table.cdc_table_id = Some(cdc_table_id);
987    table.cdc_table_type = Some(cdc_table_type);
988    Ok((
989        ensure_sync_log_store_fragment_root(materialize.into()),
990        table,
991    ))
992}
993
994fn derive_with_options_for_cdc_table(
995    source_with_properties: &WithOptionsSecResolved,
996    table_with_options: &WithOptions,
997    external_table_name: String,
998) -> Result<(WithOptionsSecResolved, String)> {
999    let (mut properties, external_table_name) =
1000        derive_connect_properties_for_cdc_table(source_with_properties, external_table_name)?;
1001    if let Some(value) = table_with_options.get("bypass_pk_order_validation") {
1002        value
1003            .to_ascii_lowercase()
1004            .parse::<bool>()
1005            .map_err(|_| anyhow::anyhow!("bypass_pk_order_validation must be true or false"))?;
1006        properties.insert("bypass_pk_order_validation".into(), value.clone());
1007    }
1008    Ok((properties, external_table_name))
1009}
1010
1011#[allow(clippy::too_many_arguments)]
1012pub(super) async fn handle_create_table_plan(
1013    handler_args: HandlerArgs,
1014    explain_options: ExplainOptions,
1015    format_encode: Option<FormatEncodeOptions>,
1016    cdc_table_info: Option<CdcTableInfo>,
1017    table_name: &ObjectName,
1018    column_defs: Vec<ColumnDef>,
1019    wildcard_idx: Option<usize>,
1020    constraints: Vec<TableConstraint>,
1021    source_watermarks: Vec<SourceWatermark>,
1022    append_only: bool,
1023    on_conflict: Option<OnConflict>,
1024    with_version_columns: Vec<String>,
1025    include_column_options: IncludeOption,
1026    webhook_info: Option<WebhookSourceInfo>,
1027    engine: Engine,
1028) -> Result<(
1029    PlanRef,
1030    Option<SourceCatalog>,
1031    TableCatalog,
1032    TableJobType,
1033    Option<SourceId>,
1034)> {
1035    let col_id_gen = ColumnIdGenerator::new_initial();
1036    let format_encode = check_create_table_with_source(
1037        &handler_args.with_options,
1038        format_encode,
1039        &include_column_options,
1040        &cdc_table_info,
1041    )?;
1042    let webhook_info = webhook_info
1043        .map(|info| bind_webhook_info(&handler_args.session, &column_defs, info))
1044        .transpose()?;
1045
1046    let props = CreateTableProps {
1047        definition: handler_args.normalized_sql.clone(),
1048        append_only,
1049        on_conflict: on_conflict.into(),
1050        with_version_columns: with_version_columns.clone(),
1051        webhook_info,
1052        engine,
1053    };
1054
1055    let ((plan, source, table), job_type, shared_shource_id) = match (
1056        format_encode,
1057        cdc_table_info.as_ref(),
1058    ) {
1059        (Some(format_encode), None) => (
1060            gen_create_table_plan_with_source(
1061                handler_args,
1062                explain_options,
1063                table_name.clone(),
1064                column_defs,
1065                wildcard_idx,
1066                constraints,
1067                format_encode,
1068                source_watermarks,
1069                col_id_gen,
1070                include_column_options,
1071                props,
1072                SqlColumnStrategy::FollowChecked,
1073            )
1074            .await?,
1075            TableJobType::General,
1076            None,
1077        ),
1078        (None, None) => {
1079            let context = OptimizerContext::new(handler_args, explain_options)?;
1080            let (plan, table) = gen_create_table_plan(
1081                context,
1082                table_name.clone(),
1083                column_defs,
1084                constraints,
1085                col_id_gen,
1086                source_watermarks,
1087                props,
1088                false,
1089            )?;
1090
1091            ((plan, None, table), TableJobType::General, None)
1092        }
1093
1094        (None, Some(cdc_table)) => {
1095            sanity_check_for_table_on_cdc_source(
1096                append_only,
1097                &column_defs,
1098                &wildcard_idx,
1099                &constraints,
1100                &source_watermarks,
1101            )?;
1102
1103            generated_columns_check_for_cdc_table(&column_defs)?;
1104            not_null_check_for_cdc_table(&wildcard_idx, &column_defs)?;
1105
1106            let session = &handler_args.session;
1107            let db_name = &session.database();
1108            let user_name = &session.user_name();
1109            let search_path = session.config().search_path();
1110            let (schema_name, resolved_table_name) =
1111                Binder::resolve_schema_qualified_name(db_name, table_name)?;
1112            let (database_id, schema_id) =
1113                session.get_database_and_schema_id_for_create(schema_name.clone())?;
1114
1115            // cdc table cannot be append-only
1116            let (source_schema, source_name) =
1117                Binder::resolve_schema_qualified_name(db_name, &cdc_table.source_name)?;
1118
1119            let source = {
1120                let catalog_reader = session.env().catalog_reader().read_guard();
1121                let schema_path =
1122                    SchemaPath::new(source_schema.as_deref(), &search_path, user_name);
1123
1124                let (source, _) = catalog_reader.get_source_by_name(
1125                    db_name,
1126                    schema_path,
1127                    source_name.as_str(),
1128                )?;
1129                source.clone()
1130            };
1131            check_cdc_source_select_privilege(session, &source)?;
1132            let (cdc_with_options, external_table_name) = derive_with_options_for_cdc_table(
1133                &source.with_properties,
1134                &handler_args.with_options,
1135                cdc_table.external_table_name.clone(),
1136            )?;
1137
1138            let excluded_columns = match handler_args.with_options.get(CDC_COLUMN_EXCLUDE_LIST) {
1139                Some(list) => {
1140                    let columns = parse_cdc_column_exclude_list(list);
1141                    if columns.is_empty() {
1142                        return Err(ErrorCode::InvalidInputSyntax(format!(
1143                            "`{CDC_COLUMN_EXCLUDE_LIST}` must list at least one column"
1144                        ))
1145                        .into());
1146                    }
1147                    if wildcard_idx.is_none() {
1148                        return Err(ErrorCode::InvalidInputSyntax(format!(
1149                            "`{CDC_COLUMN_EXCLUDE_LIST}` requires the `(*)` wildcard in the column list"
1150                        ))
1151                        .into());
1152                    }
1153                    columns
1154                }
1155                None => HashSet::new(),
1156            };
1157
1158            let (columns, pk_names, pk_comparisons) = match wildcard_idx {
1159                Some(_) => {
1160                    bind_cdc_table_schema_externally(cdc_with_options.clone(), &excluded_columns)
1161                        .await?
1162                }
1163                None => {
1164                    for column_def in &column_defs {
1165                        for option_def in &column_def.options {
1166                            if let ColumnOption::DefaultValue(_)
1167                            | ColumnOption::DefaultValueInternal { .. } = option_def.option
1168                            {
1169                                return Err(ErrorCode::NotSupported(
1170                                            "Default value for columns defined on the table created from a CDC source".into(),
1171                                            "Remove the default value expression in the column definitions".into(),
1172                                        )
1173                                            .into());
1174                            }
1175                        }
1176                    }
1177
1178                    let (columns, pk_names) =
1179                        bind_cdc_table_schema(&column_defs, &constraints, false)?;
1180                    let pk_comparisons = Box::pin(bind_cdc_pk_comparisons_externally(
1181                        cdc_with_options.clone(),
1182                        &pk_names,
1183                    ))
1184                    .await?;
1185
1186                    (columns, pk_names, pk_comparisons)
1187                }
1188            };
1189
1190            // CDC-table branch only: if Debezium column filters remove a PK column from the
1191            // change-event value, RisingWave reads NULL for that PK from the payload and silently
1192            // corrupts downstream (UPDATE turns into a fresh INSERT, DELETE no-ops). Plain
1193            // (non-CDC) tables don't hit this check.
1194            reject_pk_filtered_by_debezium_column_filter(&pk_names, &cdc_with_options)?;
1195
1196            let context: OptimizerContextRef =
1197                OptimizerContext::new(handler_args, explain_options)?.into();
1198            let shared_source_id = source.id;
1199            let (plan, table) = gen_create_table_plan_for_cdc_table(
1200                context,
1201                source,
1202                external_table_name,
1203                column_defs,
1204                source_watermarks,
1205                columns,
1206                pk_names,
1207                pk_comparisons,
1208                cdc_with_options,
1209                col_id_gen,
1210                on_conflict,
1211                with_version_columns,
1212                include_column_options,
1213                table_name.clone(),
1214                resolved_table_name,
1215                database_id,
1216                schema_id,
1217                TableId::placeholder(),
1218                engine,
1219            )?;
1220
1221            (
1222                (plan, None, table),
1223                TableJobType::SharedCdcSource,
1224                Some(shared_source_id),
1225            )
1226        }
1227        (Some(_), Some(_)) => {
1228            return Err(ErrorCode::NotSupported(
1229                "Data format and encoding format doesn't apply to table created from a CDC source"
1230                    .into(),
1231                "Remove the FORMAT and ENCODE specification".into(),
1232            )
1233            .into());
1234        }
1235    };
1236    Ok((plan, source, table, job_type, shared_shource_id))
1237}
1238
1239// For both table from cdc source and table with cdc connector
1240fn generated_columns_check_for_cdc_table(columns: &Vec<ColumnDef>) -> Result<()> {
1241    let mut found_generated_column = false;
1242    for column in columns {
1243        let mut is_generated = false;
1244
1245        for option_def in &column.options {
1246            if let ColumnOption::GeneratedColumns(_) = option_def.option {
1247                is_generated = true;
1248                break;
1249            }
1250        }
1251
1252        if is_generated {
1253            found_generated_column = true;
1254        } else if found_generated_column {
1255            return Err(ErrorCode::NotSupported(
1256                "Non-generated column found after a generated column.".into(),
1257                "Ensure that all generated columns appear at the end of the cdc table definition."
1258                    .into(),
1259            )
1260            .into());
1261        }
1262    }
1263    Ok(())
1264}
1265
1266#[allow(clippy::too_many_arguments)]
1267pub async fn handle_create_table(
1268    handler_args: HandlerArgs,
1269    table_name: ObjectName,
1270    column_defs: Vec<ColumnDef>,
1271    wildcard_idx: Option<usize>,
1272    constraints: Vec<TableConstraint>,
1273    if_not_exists: bool,
1274    format_encode: Option<FormatEncodeOptions>,
1275    source_watermarks: Vec<SourceWatermark>,
1276    append_only: bool,
1277    on_conflict: Option<OnConflict>,
1278    with_version_columns: Vec<String>,
1279    cdc_table_info: Option<CdcTableInfo>,
1280    include_column_options: IncludeOption,
1281    webhook_info: Option<WebhookSourceInfo>,
1282    ast_engine: risingwave_sqlparser::ast::Engine,
1283) -> Result<RwPgResponse> {
1284    let session = handler_args.session.clone();
1285
1286    if append_only {
1287        session.notice_to_user("APPEND ONLY TABLE is currently an experimental feature.");
1288    }
1289
1290    session.check_cluster_limits().await?;
1291
1292    let engine = match ast_engine {
1293        risingwave_sqlparser::ast::Engine::Hummock => Engine::Hummock,
1294        risingwave_sqlparser::ast::Engine::Iceberg => Engine::Iceberg,
1295    };
1296
1297    if let Either::Right(resp) = session.check_relation_name_duplicated(
1298        table_name.clone(),
1299        StatementType::CREATE_TABLE,
1300        if_not_exists,
1301    )? {
1302        return Ok(resp);
1303    }
1304
1305    let (graph, source, hummock_table, job_type, shared_source_id) = {
1306        let (plan, source, table, job_type, shared_source_id) = Box::pin(handle_create_table_plan(
1307            handler_args.clone(),
1308            ExplainOptions::default(),
1309            format_encode,
1310            cdc_table_info,
1311            &table_name,
1312            column_defs.clone(),
1313            wildcard_idx,
1314            constraints.clone(),
1315            source_watermarks,
1316            append_only,
1317            on_conflict,
1318            with_version_columns,
1319            include_column_options,
1320            webhook_info,
1321            engine,
1322        ))
1323        .await?;
1324        tracing::trace!("table_plan: {:?}", plan.explain_to_string());
1325
1326        let graph = build_graph(plan, Some(GraphJobType::Table))?;
1327
1328        (graph, source, table, job_type, shared_source_id)
1329    };
1330
1331    tracing::trace!(
1332        "name={}, graph=\n{}",
1333        table_name,
1334        serde_json::to_string_pretty(&graph).unwrap()
1335    );
1336
1337    let dependencies = shared_source_id
1338        .map(|id| HashSet::from([id.as_object_id()]))
1339        .unwrap_or_default();
1340
1341    // Handle engine
1342    match engine {
1343        Engine::Hummock => {
1344            let catalog_writer = session.catalog_writer()?;
1345            let action = match job_type {
1346                TableJobType::SharedCdcSource => LongRunningNotificationAction::MonitorBackfillJob,
1347                _ => LongRunningNotificationAction::DiagnoseBarrierLatency,
1348            };
1349            execute_with_long_running_notification(
1350                catalog_writer.create_table(
1351                    source.map(|s| s.to_prost()),
1352                    hummock_table.to_prost(),
1353                    graph,
1354                    job_type,
1355                    if_not_exists,
1356                    dependencies,
1357                ),
1358                &session,
1359                "CREATE TABLE",
1360                action,
1361            )
1362            .await?;
1363        }
1364        Engine::Iceberg => {
1365            let hummock_table_name = hummock_table.name.clone();
1366            session.create_staging_table(hummock_table.clone());
1367            let res = Box::pin(create_iceberg_engine_table(
1368                session.clone(),
1369                handler_args,
1370                source.map(|s| s.to_prost()),
1371                hummock_table,
1372                graph,
1373                table_name,
1374                job_type,
1375                if_not_exists,
1376            ))
1377            .await;
1378            session.drop_staging_table(&hummock_table_name);
1379            res?
1380        }
1381    }
1382
1383    Ok(PgResponse::empty_result(StatementType::CREATE_TABLE))
1384}
1385
1386fn build_iceberg_engine_sink_options(
1387    mut sink_options: BTreeMap<String, String>,
1388    user_options: &WithOptions,
1389    table: &TableCatalog,
1390    primary_key: &[String],
1391) -> Result<BTreeMap<String, String>> {
1392    sink_options.extend(
1393        user_options
1394            .iter()
1395            .filter(|(key, _)| is_iceberg_engine_option(key))
1396            .map(|(key, value)| (key.clone(), value.clone())),
1397    );
1398
1399    sink_options
1400        .entry(ENABLE_COMPACTION.to_owned())
1401        .or_insert_with(|| "true".to_owned());
1402    sink_options.insert(
1403        "type".to_owned(),
1404        if table.append_only {
1405            "append-only"
1406        } else {
1407            "upsert"
1408        }
1409        .to_owned(),
1410    );
1411
1412    // Supply the table primary key while parsing the typed config. In PK-index mode the
1413    // planner derives it from the upstream stream key, so it is removed again below.
1414    if !table.append_only {
1415        sink_options.insert("primary_key".to_owned(), primary_key.join(","));
1416    }
1417
1418    sink_options.insert("create_table_if_not_exists".to_owned(), "true".to_owned());
1419    sink_options.insert("is_exactly_once".to_owned(), "true".to_owned());
1420
1421    let config = IcebergConfig::from_btreemap(sink_options.clone())?;
1422
1423    // Both merge-on-read and copy-on-write initialize an equality-delete writer for upserts.
1424    // Reject unsupported key types before creating the remote Iceberg table.
1425    if !table.append_only && !config.enable_pk_index {
1426        for pk in table.pk() {
1427            let column = &table.columns()[pk.column_index];
1428            let data_type = column.data_type();
1429            if data_type.is_composite()
1430                || matches!(data_type, DataType::Float32 | DataType::Float64)
1431            {
1432                return Err(ErrorCode::NotSupported(
1433                    format!(
1434                        "Iceberg engine table primary key column \"{}\" has unsupported type {} for equality deletes",
1435                        column.name(), data_type
1436                    ),
1437                    "Use non-floating-point scalar primary key columns.".to_owned(),
1438                )
1439                .into());
1440            }
1441        }
1442    }
1443
1444    // Engine tables own their Iceberg maintenance policy, so enable manifest rewrites by default
1445    // whenever the table format supports them. Keep V3 disabled until rewrites preserve row lineage.
1446    if config.table_format_version() < FormatVersion::V3 {
1447        sink_options
1448            .entry(ENABLE_MANIFEST_REWRITE.to_owned())
1449            .or_insert_with(|| "true".to_owned());
1450    }
1451
1452    if let Some(partition_by) = &config.partition_by {
1453        let mut partition_columns = vec![];
1454        for (column, _) in parse_partition_by_exprs(partition_by.clone())? {
1455            table
1456                .columns()
1457                .iter()
1458                .find(|col| col.name().eq_ignore_ascii_case(&column))
1459                .ok_or_else(|| {
1460                    ErrorCode::InvalidInputSyntax(format!(
1461                        "Partition source column does not exist in schema: {}",
1462                        column
1463                    ))
1464                })?;
1465
1466            partition_columns.push(column);
1467        }
1468
1469        ensure_partition_columns_are_prefix_of_primary_key(&partition_columns, primary_key)
1470            .map_err(|_| {
1471                ErrorCode::InvalidInputSyntax(
1472                    "The partition columns should be the prefix of the primary key".to_owned(),
1473                )
1474            })?;
1475    }
1476
1477    if let Some(order_key) = &config.order_key {
1478        validate_order_key_columns(order_key, table.columns().iter().map(|col| col.name()))
1479            .map_err(|err| ErrorCode::InvalidInputSyntax(err.to_report_string()))?;
1480    }
1481
1482    if config.enable_pk_index {
1483        sink_options.remove("primary_key");
1484    } else {
1485        sink_options.insert(AUTO_SCHEMA_CHANGE_KEY.to_owned(), "true".to_owned());
1486    }
1487
1488    Ok(sink_options)
1489}
1490
1491/// Iceberg table engine is composed of hummock table, iceberg sink and iceberg source.
1492///
1493/// 1. fetch iceberg engine options from the meta node. Or use iceberg engine connection provided by users.
1494/// 2. create a hummock table
1495/// 3. create an iceberg sink
1496/// 4. create an iceberg source
1497///
1498/// See <https://github.com/risingwavelabs/risingwave/issues/21586> for an architecture diagram.
1499#[allow(clippy::too_many_arguments)]
1500pub async fn create_iceberg_engine_table(
1501    session: Arc<SessionImpl>,
1502    handler_args: HandlerArgs,
1503    mut source: Option<PbSource>,
1504    table: TableCatalog,
1505    graph: StreamFragmentGraph,
1506    table_name: ObjectName,
1507    job_type: PbTableJobType,
1508    if_not_exists: bool,
1509) -> Result<()> {
1510    let rw_db_name = session
1511        .env()
1512        .catalog_reader()
1513        .read_guard()
1514        .get_database_by_id(table.database_id)?
1515        .name()
1516        .to_owned();
1517    let rw_schema_name = session
1518        .env()
1519        .catalog_reader()
1520        .read_guard()
1521        .get_schema_by_id(table.database_id, table.schema_id)?
1522        .name()
1523        .clone();
1524    let iceberg_catalog_name = rw_db_name.clone();
1525    let iceberg_database_name = rw_schema_name.clone();
1526    let iceberg_table_name = table_name.0.last().unwrap().real_value();
1527
1528    let iceberg_engine_connection: String = session.config().iceberg_engine_connection();
1529    let sink_decouple = session.config().sink_decouple();
1530    if matches!(sink_decouple, SinkDecouple::Disable) {
1531        bail!(
1532            "Iceberg engine table only supports with sink decouple, try `set sink_decouple = true` to resolve it"
1533        );
1534    }
1535
1536    let mut connection_ref = BTreeMap::new();
1537    let with_common = if iceberg_engine_connection.is_empty() {
1538        bail!("to use iceberg engine table, the variable `iceberg_engine_connection` must be set.");
1539    } else {
1540        let parts: Vec<&str> = iceberg_engine_connection.split('.').collect();
1541        assert_eq!(parts.len(), 2);
1542        let connection_catalog =
1543            session.get_connection_by_name(Some(parts[0].to_owned()), parts[1])?;
1544        if let ConnectionInfo::ConnectionParams(params) = &connection_catalog.info {
1545            if params.connection_type == ConnectionType::Iceberg as i32 {
1546                // With iceberg engine connection:
1547                connection_ref.insert(
1548                    "connection".to_owned(),
1549                    ConnectionRefValue {
1550                        connection_name: ObjectName::from(vec![
1551                            Ident::from(parts[0]),
1552                            Ident::from(parts[1]),
1553                        ]),
1554                    },
1555                );
1556
1557                let mut with_common = BTreeMap::new();
1558                with_common.insert("connector".to_owned(), "iceberg".to_owned());
1559                with_common.insert("database.name".to_owned(), iceberg_database_name);
1560                with_common.insert("table.name".to_owned(), iceberg_table_name);
1561
1562                let hosted_catalog = params
1563                    .properties
1564                    .get("hosted_catalog")
1565                    .map(|s| s.eq_ignore_ascii_case("true"))
1566                    .unwrap_or(false);
1567                if hosted_catalog {
1568                    let meta_client = session.env().meta_client();
1569                    let meta_store_endpoint = meta_client.get_meta_store_endpoint().await?;
1570
1571                    let meta_store_endpoint =
1572                        url::Url::parse(&meta_store_endpoint).map_err(|_| {
1573                            ErrorCode::InternalError(
1574                                "failed to parse the meta store endpoint".to_owned(),
1575                            )
1576                        })?;
1577                    let meta_store_backend = meta_store_endpoint.scheme().to_owned();
1578                    let meta_store_user = meta_store_endpoint.username().to_owned();
1579                    let meta_store_password = match meta_store_endpoint.password() {
1580                        Some(password) => percent_decode_str(password)
1581                            .decode_utf8()
1582                            .map_err(|_| {
1583                                ErrorCode::InternalError(
1584                                    "failed to parse password from meta store endpoint".to_owned(),
1585                                )
1586                            })?
1587                            .into_owned(),
1588                        None => "".to_owned(),
1589                    };
1590                    let meta_store_host = meta_store_endpoint
1591                        .host_str()
1592                        .ok_or_else(|| {
1593                            ErrorCode::InternalError(
1594                                "failed to parse host from meta store endpoint".to_owned(),
1595                            )
1596                        })?
1597                        .to_owned();
1598                    let meta_store_port = meta_store_endpoint.port().ok_or_else(|| {
1599                        ErrorCode::InternalError(
1600                            "failed to parse port from meta store endpoint".to_owned(),
1601                        )
1602                    })?;
1603                    let meta_store_database = meta_store_endpoint
1604                        .path()
1605                        .trim_start_matches('/')
1606                        .to_owned();
1607
1608                    let Ok(meta_backend) = MetaBackend::from_str(&meta_store_backend, true) else {
1609                        bail!("failed to parse meta backend: {}", meta_store_backend);
1610                    };
1611
1612                    let catalog_uri = match meta_backend {
1613                        MetaBackend::Postgres => {
1614                            format!(
1615                                "jdbc:postgresql://{}:{}/{}",
1616                                meta_store_host, meta_store_port, meta_store_database
1617                            )
1618                        }
1619                        MetaBackend::Mysql => {
1620                            format!(
1621                                "jdbc:mysql://{}:{}/{}",
1622                                meta_store_host, meta_store_port, meta_store_database
1623                            )
1624                        }
1625                        MetaBackend::Sqlite | MetaBackend::Sql | MetaBackend::Mem => {
1626                            bail!(
1627                                "Unsupported meta backend for iceberg engine table: {}",
1628                                meta_store_backend
1629                            );
1630                        }
1631                    };
1632
1633                    with_common.insert("catalog.type".to_owned(), "jdbc".to_owned());
1634                    with_common.insert("catalog.uri".to_owned(), catalog_uri);
1635                    with_common.insert("catalog.jdbc.user".to_owned(), meta_store_user);
1636                    with_common.insert("catalog.jdbc.password".to_owned(), meta_store_password);
1637                    with_common.insert("catalog.name".to_owned(), iceberg_catalog_name);
1638                }
1639
1640                with_common
1641            } else {
1642                return Err(RwError::from(ErrorCode::InvalidParameterValue(
1643                    "Only iceberg connection could be used in iceberg engine".to_owned(),
1644                )));
1645            }
1646        } else {
1647            return Err(RwError::from(ErrorCode::InvalidParameterValue(
1648                "Private Link Service has been deprecated. Please create a new connection instead."
1649                    .to_owned(),
1650            )));
1651        }
1652    };
1653
1654    // Iceberg sinks require a primary key, if none is provided, we will use the _row_id column
1655    // Fetch primary key from columns
1656    let mut pks = table
1657        .pk_column_names()
1658        .iter()
1659        .map(|c| c.to_string())
1660        .collect::<Vec<String>>();
1661
1662    // For the table without primary key. We will use `_row_id` as primary key.
1663    if pks.len() == 1 && pks[0].eq(ROW_ID_COLUMN_NAME) {
1664        pks = vec![RISINGWAVE_ICEBERG_ROW_ID.to_owned()];
1665    }
1666
1667    let sink_from = CreateSink::From(table_name.clone());
1668
1669    let mut sink_name = table_name.clone();
1670    *sink_name.0.last_mut().unwrap() = Ident::from(
1671        (ICEBERG_SINK_PREFIX.to_owned() + &sink_name.0.last().unwrap().real_value()).as_str(),
1672    );
1673    let create_sink_stmt = CreateSinkStatement {
1674        or_replace: false,
1675        if_not_exists: false,
1676        sink_name,
1677        with_properties: WithProperties(vec![]),
1678        sink_from,
1679        columns: vec![],
1680        emit_mode: None,
1681        sink_schema: None,
1682        into_table_name: None,
1683    };
1684
1685    let mut sink_handler_args = handler_args.clone();
1686
1687    let sink_with = build_iceberg_engine_sink_options(
1688        with_common.clone(),
1689        &handler_args.with_options,
1690        &table,
1691        &pks,
1692    )?;
1693
1694    if let Some(source) = source.as_mut() {
1695        source
1696            .with_properties
1697            .retain(|key, _| !is_iceberg_engine_option(key));
1698    }
1699
1700    // sink_with.insert(SINK_SNAPSHOT_OPTION.to_owned(), "false".to_owned());
1701    //
1702    // Note: in theory, we don't need to backfill from the table to the sink,
1703    // but we don't have atomic DDL now https://github.com/risingwavelabs/risingwave/issues/21863
1704    // so it may have potential data loss problem on the first barrier.
1705    //
1706    // For non-append-only table, we can always solve it by the initial sink with backfill, since
1707    // data will be present in hummock table.
1708    //
1709    // For append-only table, we need to be more careful.
1710    //
1711    // The possible cases for a table:
1712    // - For table without connector: it doesn't matter, since there's no data before the table is created
1713    // - For table with connector: we workarounded it by setting SOURCE_RATE_LIMIT to 0
1714    //   + If we support blocking DDL for table with connector, we need to be careful.
1715    // - For table with an upstream job: Specifically, CDC table from shared CDC source.
1716    //   + Data may come from both upstream connector, and CDC table backfill, so we need to pause both of them.
1717    //   + For now we don't support APPEND ONLY CDC table, so it's safe.
1718
1719    sink_handler_args.with_options =
1720        WithOptions::new(sink_with, Default::default(), connection_ref.clone());
1721    let SinkPlanContext {
1722        sink_plan,
1723        sink_catalog,
1724        ..
1725    } = gen_sink_plan(sink_handler_args, create_sink_stmt, None, true).await?;
1726    let sink_graph = build_graph(sink_plan, Some(GraphJobType::Sink))?;
1727
1728    let mut source_name = table_name.clone();
1729    *source_name.0.last_mut().unwrap() = Ident::from(
1730        (ICEBERG_SOURCE_PREFIX.to_owned() + &source_name.0.last().unwrap().real_value()).as_str(),
1731    );
1732    let create_source_stmt = CreateSourceStatement {
1733        temporary: false,
1734        if_not_exists: false,
1735        columns: vec![],
1736        source_name,
1737        wildcard_idx: Some(0),
1738        constraints: vec![],
1739        with_properties: WithProperties(vec![]),
1740        format_encode: CompatibleFormatEncode::V2(FormatEncodeOptions::none()),
1741        source_watermarks: vec![],
1742        include_column_options: vec![],
1743        cdc_table_info: None,
1744    };
1745
1746    let mut source_handler_args = handler_args.clone();
1747    let source_with = with_common;
1748    source_handler_args.with_options =
1749        WithOptions::new(source_with, Default::default(), connection_ref);
1750
1751    let overwrite_options = OverwriteOptions::new(&mut source_handler_args)?;
1752    let format_encode = create_source_stmt.format_encode.into_v2_with_warning();
1753    let (with_properties, ingest_mode) =
1754        bind_connector_props(&source_handler_args, &format_encode, true)?;
1755
1756    // Create iceberg sink table, used for iceberg source column binding. See `bind_columns_from_source_for_non_cdc` for more details.
1757    // TODO: We can derive the columns directly from table definition in the future, so that we don't need to pre-create the table catalog.
1758    let (iceberg_catalog, table_identifier, table_created) = {
1759        let sink_param = SinkParam::try_from_sink_catalog(sink_catalog.clone())?;
1760        let iceberg_sink = IcebergSink::try_from(sink_param)?;
1761        let table_created = iceberg_sink.create_table_if_not_exists().await?;
1762
1763        let iceberg_catalog = iceberg_sink.config.create_catalog().await?;
1764        let table_identifier = iceberg_sink.config.full_table_name()?;
1765        (iceberg_catalog, table_identifier, table_created)
1766    };
1767
1768    let create_source_type = CreateSourceType::for_newly_created(&session, &*with_properties);
1769    let (columns_from_resolve_source, source_info) = bind_columns_from_source(
1770        &session,
1771        &format_encode,
1772        Either::Left(&with_properties),
1773        create_source_type,
1774    )
1775    .await?;
1776    let mut col_id_gen = ColumnIdGenerator::new_initial();
1777
1778    let iceberg_source_catalog = bind_create_source_or_table_with_connector(
1779        source_handler_args,
1780        create_source_stmt.source_name,
1781        format_encode,
1782        with_properties,
1783        create_source_stmt.columns,
1784        create_source_stmt.constraints,
1785        create_source_stmt.wildcard_idx,
1786        create_source_stmt.source_watermarks,
1787        columns_from_resolve_source,
1788        source_info,
1789        create_source_stmt.include_column_options,
1790        &mut col_id_gen,
1791        create_source_type,
1792        overwrite_options.source_rate_limit,
1793        SqlColumnStrategy::FollowChecked,
1794        ingest_mode,
1795    )
1796    .await?;
1797
1798    // before we create the table, ensure the JVM is initialized as we use jdbc catalog right now.
1799    // If JVM isn't initialized successfully, current not atomic ddl will result in a partially created iceberg engine table.
1800    let _ = Jvm::get_or_init()?;
1801
1802    let catalog_writer = session.catalog_writer()?;
1803    let action = match job_type {
1804        TableJobType::SharedCdcSource => LongRunningNotificationAction::MonitorBackfillJob,
1805        _ => LongRunningNotificationAction::DiagnoseBarrierLatency,
1806    };
1807    let res = execute_with_long_running_notification(
1808        catalog_writer.create_iceberg_table(
1809            PbTableJobInfo {
1810                source,
1811                table: Some(table.to_prost()),
1812                fragment_graph: Some(graph),
1813                job_type: job_type as _,
1814            },
1815            PbSinkJobInfo {
1816                sink: Some(sink_catalog.to_proto()),
1817                fragment_graph: Some(sink_graph),
1818            },
1819            iceberg_source_catalog.to_prost(),
1820            if_not_exists,
1821        ),
1822        &session,
1823        "CREATE TABLE",
1824        action,
1825    )
1826    .await;
1827
1828    if res.is_err() {
1829        // Only clean up an iceberg table this statement created; a pre-existing
1830        // external table must survive a failed CREATE.
1831        if table_created {
1832            let _ = iceberg_catalog
1833                .drop_table(&table_identifier)
1834                .await
1835                .inspect_err(|err| {
1836                    tracing::error!(
1837                        "failed to drop iceberg table {} after create iceberg engine table failed: {}",
1838                        table_identifier,
1839                        err.as_report()
1840                    );
1841                });
1842        }
1843        res?
1844    }
1845
1846    Ok(())
1847}
1848
1849pub fn check_create_table_with_source(
1850    with_options: &WithOptions,
1851    format_encode: Option<FormatEncodeOptions>,
1852    include_column_options: &IncludeOption,
1853    cdc_table_info: &Option<CdcTableInfo>,
1854) -> Result<Option<FormatEncodeOptions>> {
1855    // skip check for cdc table
1856    if cdc_table_info.is_some() {
1857        return Ok(format_encode);
1858    }
1859    let defined_source = with_options.is_source_connector();
1860
1861    if !include_column_options.is_empty() && !defined_source {
1862        return Err(ErrorCode::InvalidInputSyntax(
1863            "INCLUDE should be used with a connector".to_owned(),
1864        )
1865        .into());
1866    }
1867    if defined_source {
1868        format_encode.as_ref().ok_or_else(|| {
1869            ErrorCode::InvalidInputSyntax("Please specify a source schema using FORMAT".to_owned())
1870        })?;
1871    }
1872    Ok(format_encode)
1873}
1874
1875fn ensure_partition_columns_are_prefix_of_primary_key(
1876    partition_columns: &[String],
1877    primary_key_columns: &[String],
1878) -> std::result::Result<(), String> {
1879    if partition_columns.len() > primary_key_columns.len() {
1880        return Err("Partition columns cannot be longer than primary key columns.".to_owned());
1881    }
1882
1883    for (i, partition_col) in partition_columns.iter().enumerate() {
1884        if primary_key_columns.get(i) != Some(partition_col) {
1885            return Err(format!(
1886                "Partition column '{}' is not a prefix of the primary key.",
1887                partition_col
1888            ));
1889        }
1890    }
1891
1892    Ok(())
1893}
1894
1895#[allow(clippy::too_many_arguments)]
1896pub async fn generate_stream_graph_for_replace_table(
1897    _session: &Arc<SessionImpl>,
1898    table_name: ObjectName,
1899    original_catalog: &Arc<TableCatalog>,
1900    handler_args: HandlerArgs,
1901    statement: Statement,
1902    col_id_gen: ColumnIdGenerator,
1903    sql_column_strategy: SqlColumnStrategy,
1904) -> Result<(
1905    StreamFragmentGraph,
1906    TableCatalog,
1907    Option<SourceCatalog>,
1908    TableJobType,
1909)> {
1910    let Statement::CreateTable {
1911        columns,
1912        constraints,
1913        source_watermarks,
1914        append_only,
1915        on_conflict,
1916        with_version_columns,
1917        wildcard_idx,
1918        cdc_table_info,
1919        format_encode,
1920        include_column_options,
1921        engine,
1922        with_options,
1923        ..
1924    } = statement
1925    else {
1926        panic!("unexpected statement type: {:?}", statement);
1927    };
1928
1929    let format_encode = format_encode
1930        .clone()
1931        .map(|format_encode| format_encode.into_v2_with_warning());
1932
1933    let engine = match engine {
1934        risingwave_sqlparser::ast::Engine::Hummock => Engine::Hummock,
1935        risingwave_sqlparser::ast::Engine::Iceberg => Engine::Iceberg,
1936    };
1937
1938    let is_drop_connector =
1939        original_catalog.associated_source_id().is_some() && format_encode.is_none();
1940    if is_drop_connector {
1941        debug_assert!(
1942            include_column_options.is_empty()
1943                && with_options
1944                    .iter()
1945                    .all(|opt| opt.name.real_value().to_lowercase() != "connector")
1946        );
1947    }
1948
1949    let props = CreateTableProps {
1950        definition: handler_args.normalized_sql.clone(),
1951        append_only,
1952        on_conflict: on_conflict.into(),
1953        with_version_columns: with_version_columns
1954            .iter()
1955            .map(|col| col.real_value())
1956            .collect(),
1957        webhook_info: original_catalog.webhook_info.clone(),
1958        engine,
1959    };
1960
1961    let ((plan, mut source, mut table), job_type) = match (format_encode, cdc_table_info.as_ref()) {
1962        (Some(format_encode), None) => (
1963            gen_create_table_plan_with_source(
1964                handler_args,
1965                ExplainOptions::default(),
1966                table_name,
1967                columns,
1968                wildcard_idx,
1969                constraints,
1970                format_encode,
1971                source_watermarks,
1972                col_id_gen,
1973                include_column_options,
1974                props,
1975                sql_column_strategy,
1976            )
1977            .await?,
1978            TableJobType::General,
1979        ),
1980        (None, None) => {
1981            let context = OptimizerContext::from_handler_args(handler_args)?;
1982            let (plan, table) = gen_create_table_plan(
1983                context,
1984                table_name,
1985                columns,
1986                constraints,
1987                col_id_gen,
1988                source_watermarks,
1989                props,
1990                true,
1991            )?;
1992            ((plan, None, table), TableJobType::General)
1993        }
1994        (None, Some(cdc_table)) => {
1995            sanity_check_for_table_on_cdc_source(
1996                append_only,
1997                &columns,
1998                &wildcard_idx,
1999                &constraints,
2000                &source_watermarks,
2001            )?;
2002
2003            let session = &handler_args.session;
2004            let (source, resolved_table_name) =
2005                get_source_and_resolved_table_name(session, cdc_table.clone(), table_name.clone())?;
2006
2007            let (cdc_with_options, external_table_name) = derive_with_options_for_cdc_table(
2008                &source.with_properties,
2009                &handler_args.with_options,
2010                cdc_table.external_table_name.clone(),
2011            )?;
2012
2013            let (column_catalogs, pk_names) = bind_cdc_table_schema(&columns, &constraints, true)?;
2014            let pk_comparisons = Box::pin(bind_cdc_pk_comparisons_externally(
2015                cdc_with_options.clone(),
2016                &pk_names,
2017            ))
2018            .await?;
2019
2020            // CDC-table branch only: see the comment at the symmetric call site in
2021            // `handle_create_table_plan`. Plain (non-CDC) tables don't hit this check.
2022            reject_pk_filtered_by_debezium_column_filter(&pk_names, &cdc_with_options)?;
2023
2024            let context: OptimizerContextRef =
2025                OptimizerContext::new(handler_args, ExplainOptions::default())?.into();
2026            let (plan, table) = gen_create_table_plan_for_cdc_table(
2027                context,
2028                source,
2029                external_table_name,
2030                columns,
2031                source_watermarks,
2032                column_catalogs,
2033                pk_names,
2034                pk_comparisons,
2035                cdc_with_options,
2036                col_id_gen,
2037                on_conflict,
2038                with_version_columns
2039                    .iter()
2040                    .map(|col| col.real_value())
2041                    .collect(),
2042                include_column_options,
2043                table_name,
2044                resolved_table_name,
2045                original_catalog.database_id,
2046                original_catalog.schema_id,
2047                original_catalog.id(),
2048                engine,
2049            )?;
2050
2051            ((plan, None, table), TableJobType::SharedCdcSource)
2052        }
2053        (Some(_), Some(_)) => {
2054            return Err(ErrorCode::NotSupported(
2055                "Data format and encoding format doesn't apply to table created from a CDC source"
2056                    .into(),
2057                "Remove the FORMAT and ENCODE specification".into(),
2058            )
2059            .into());
2060        }
2061    };
2062
2063    if table.pk_column_ids() != original_catalog.pk_column_ids() {
2064        Err(ErrorCode::InvalidInputSyntax(
2065            "alter primary key of table is not supported".to_owned(),
2066        ))?
2067    }
2068
2069    let graph = build_graph(plan, Some(GraphJobType::Table))?;
2070
2071    // Fill the original table ID.
2072    table.id = original_catalog.id();
2073    if !is_drop_connector && let Some(source_id) = original_catalog.associated_source_id() {
2074        table.associated_source_id = Some(source_id);
2075
2076        let source = source.as_mut().unwrap();
2077        source.id = source_id;
2078        source.associated_table_id = Some(table.id());
2079    }
2080
2081    Ok((graph, table, source, job_type))
2082}
2083
2084fn get_source_and_resolved_table_name(
2085    session: &Arc<SessionImpl>,
2086    cdc_table: CdcTableInfo,
2087    table_name: ObjectName,
2088) -> Result<(Arc<SourceCatalog>, String)> {
2089    let db_name = &session.database();
2090    let (_, resolved_table_name) = Binder::resolve_schema_qualified_name(db_name, &table_name)?;
2091
2092    let (source_schema, source_name) =
2093        Binder::resolve_schema_qualified_name(db_name, &cdc_table.source_name)?;
2094
2095    let source = {
2096        let catalog_reader = session.env().catalog_reader().read_guard();
2097        let schema_name = source_schema.unwrap_or(DEFAULT_SCHEMA_NAME.to_owned());
2098        let (source, _) = catalog_reader.get_source_by_name(
2099            db_name,
2100            SchemaPath::Name(schema_name.as_str()),
2101            source_name.as_str(),
2102        )?;
2103        source.clone()
2104    };
2105    check_cdc_source_select_privilege(session, &source)?;
2106
2107    Ok((source, resolved_table_name))
2108}
2109
2110pub(crate) fn check_cdc_source_select_privilege(
2111    session: &SessionImpl,
2112    source: &SourceCatalog,
2113) -> Result<()> {
2114    session.check_privileges(&[ObjectCheckItem::new(
2115        source.owner,
2116        AclMode::Select,
2117        source.name.clone(),
2118        source.id,
2119    )])
2120}
2121
2122// validate the webhook_info and also bind the webhook_info to protobuf
2123fn bind_webhook_info(
2124    session: &Arc<SessionImpl>,
2125    column_defs: &[ColumnDef],
2126    webhook_info: WebhookSourceInfo,
2127) -> Result<PbWebhookSourceInfo> {
2128    let WebhookSourceInfo {
2129        secret_ref,
2130        signature_expr,
2131        wait_for_persistence,
2132        is_batched,
2133    } = webhook_info;
2134
2135    for column in column_defs {
2136        for option_def in &column.options {
2137            match option_def.option {
2138                ColumnOption::Null => {}
2139                ColumnOption::GeneratedColumns(_) => {
2140                    return Err(ErrorCode::InvalidInputSyntax(
2141                        "generated columns are not supported for webhook tables".to_owned(),
2142                    )
2143                    .into());
2144                }
2145                ColumnOption::DefaultValue(_) | ColumnOption::DefaultValueInternal { .. } => {
2146                    return Err(ErrorCode::InvalidInputSyntax(
2147                        "default values are not supported for webhook tables".to_owned(),
2148                    )
2149                    .into());
2150                }
2151                ColumnOption::NotNull
2152                | ColumnOption::Unique { .. }
2153                | ColumnOption::ForeignKey { .. }
2154                | ColumnOption::Check(_)
2155                | ColumnOption::DialectSpecific(_) => {
2156                    return Err(ErrorCode::InvalidInputSyntax(
2157                        "only NULL column option is supported for webhook tables".to_owned(),
2158                    )
2159                    .into());
2160                }
2161            }
2162        }
2163    }
2164
2165    // validate secret_ref
2166    let (pb_secret_ref, secret_name) = if let Some(secret_ref) = secret_ref {
2167        let db_name = &session.database();
2168        let (schema_name, secret_name) =
2169            Binder::resolve_schema_qualified_name(db_name, &secret_ref.secret_name)?;
2170        let secret_catalog = session.get_secret_by_name(schema_name, &secret_name)?;
2171        (
2172            Some(PbSecretRef {
2173                secret_id: secret_catalog.id,
2174                ref_as: match secret_ref.ref_as {
2175                    SecretRefAsType::Text => PbRefAsType::Text,
2176                    SecretRefAsType::File => PbRefAsType::File,
2177                }
2178                .into(),
2179            }),
2180            Some(secret_name),
2181        )
2182    } else {
2183        (None, None)
2184    };
2185
2186    let signature_expr = if let Some(signature_expr) = signature_expr {
2187        let payload_name = if column_defs.len() == 1
2188            && column_defs[0].data_type.as_ref() == Some(&AstDataType::Jsonb)
2189        {
2190            column_defs[0].name.real_value()
2191        } else {
2192            WEBHOOK_PAYLOAD_FIELD_NAME.to_owned()
2193        };
2194        let secure_compare_context = SecureCompareContext {
2195            payload_name,
2196            secret_name,
2197        };
2198        let mut binder = Binder::new_for_ddl(session).with_secure_compare(secure_compare_context);
2199        let expr = binder.bind_expr(&signature_expr)?;
2200
2201        // validate expr, ensuring it is SECURE_COMPARE()
2202        if expr.as_function_call().is_none()
2203            || expr.as_function_call().unwrap().func_type()
2204                != crate::optimizer::plan_node::generic::ExprType::SecureCompare
2205        {
2206            return Err(ErrorCode::InvalidInputSyntax(
2207                "The signature verification function must be SECURE_COMPARE()".to_owned(),
2208            )
2209            .into());
2210        }
2211
2212        Some(expr.to_expr_proto())
2213    } else {
2214        session.notice_to_user(
2215            "VALIDATE clause is strongly recommended for safety or production usages",
2216        );
2217        None
2218    };
2219
2220    let pb_webhook_info = PbWebhookSourceInfo {
2221        secret_ref: pb_secret_ref,
2222        signature_expr,
2223        wait_for_persistence,
2224        is_batched,
2225    };
2226
2227    Ok(pb_webhook_info)
2228}
2229
2230#[cfg(test)]
2231mod tests {
2232    use risingwave_common::catalog::{
2233        DEFAULT_DATABASE_NAME, ROW_ID_COLUMN_NAME, RW_TIMESTAMP_COLUMN_NAME, RW_VNODE_COLUMN_NAME,
2234    };
2235    use risingwave_common::types::StructType;
2236
2237    use super::*;
2238    use crate::test_utils::{LocalFrontend, PROTO_FILE_DATA, create_proto_file};
2239
2240    #[test]
2241    fn test_cdc_table_bypass_pk_order_validation_properties() {
2242        for (connector, upstream_table) in [
2243            ("postgres-cdc", "public.t"),
2244            ("mysql-cdc", "db.t"),
2245            ("sqlserver-cdc", "dbo.t"),
2246        ] {
2247            let source = WithOptionsSecResolved::new(
2248                BTreeMap::from([
2249                    ("connector".into(), connector.into()),
2250                    ("database.name".into(), "db".into()),
2251                ]),
2252                Default::default(),
2253            );
2254            let (derived, _) = derive_with_options_for_cdc_table(
2255                &source,
2256                &WithOptions::default(),
2257                upstream_table.into(),
2258            )
2259            .unwrap();
2260            assert!(derived.get("bypass_pk_order_validation").is_none());
2261            let mut table_options = WithOptions::default();
2262            table_options.insert("bypass_pk_order_validation".into(), "true".into());
2263            let (mut derived, _) =
2264                derive_with_options_for_cdc_table(&source, &table_options, upstream_table.into())
2265                    .unwrap();
2266            assert_eq!(derived.get("bypass_pk_order_validation").unwrap(), "true");
2267            // A table can explicitly override a source-level setting.
2268            table_options.insert("bypass_pk_order_validation".into(), "false".into());
2269            derived =
2270                derive_with_options_for_cdc_table(&derived, &table_options, upstream_table.into())
2271                    .unwrap()
2272                    .0;
2273            assert_eq!(derived.get("bypass_pk_order_validation").unwrap(), "false");
2274            table_options.insert("bypass_pk_order_validation".into(), "typo".into());
2275            assert!(
2276                derive_with_options_for_cdc_table(&source, &table_options, upstream_table.into())
2277                    .is_err()
2278            );
2279        }
2280    }
2281
2282    #[tokio::test]
2283    async fn test_iceberg_engine_primary_key_types() {
2284        let frontend = LocalFrontend::new(Default::default()).await;
2285        for (primary_key, append_only, pk_index, supported) in [
2286            ("id, period", false, false, false),
2287            ("id, items", false, false, false),
2288            ("id, mapping", false, false, false),
2289            ("id, f", false, false, false),
2290            ("id, d", false, false, false),
2291            ("id", false, false, true),
2292            ("id, ts", false, false, true),
2293            ("", false, false, true),
2294            ("id, period", true, false, true),
2295            ("id, period", false, true, true),
2296        ] {
2297            let pk_clause = if primary_key.is_empty() {
2298                String::new()
2299            } else {
2300                format!(", PRIMARY KEY ({primary_key})")
2301            };
2302            frontend
2303                .run_sql(&format!(
2304                    "CREATE TABLE t (id INT, period STRUCT<start_ts TIMESTAMPTZ, end_ts TIMESTAMPTZ>, \
2305                     items INT[], mapping MAP(INT, INT), f REAL, d DOUBLE PRECISION, ts TIMESTAMPTZ \
2306                     {pk_clause}) {}",
2307                    if append_only { "APPEND ONLY" } else { "" }
2308                ))
2309                .await
2310                .unwrap();
2311            let session = frontend.session_ref();
2312            let table = session
2313                .env()
2314                .catalog_reader()
2315                .read_guard()
2316                .get_created_table_by_name(
2317                    DEFAULT_DATABASE_NAME,
2318                    SchemaPath::Name(DEFAULT_SCHEMA_NAME),
2319                    "t",
2320                )
2321                .unwrap()
2322                .0
2323                .clone();
2324            let pks = table
2325                .pk_column_names()
2326                .into_iter()
2327                .map(str::to_owned)
2328                .collect_vec();
2329            for write_mode in ["merge-on-read", "copy-on-write"] {
2330                if write_mode == "copy-on-write" && (append_only || pk_index) {
2331                    continue;
2332                }
2333                let options = BTreeMap::from([
2334                    ("connector".to_owned(), "iceberg".to_owned()),
2335                    ("catalog.type".to_owned(), "storage".to_owned()),
2336                    (
2337                        "warehouse.path".to_owned(),
2338                        "s3://test/warehouse".to_owned(),
2339                    ),
2340                    ("database.name".to_owned(), "public".to_owned()),
2341                    ("table.name".to_owned(), "t".to_owned()),
2342                    ("write_mode".to_owned(), write_mode.to_owned()),
2343                    ("enable_pk_index".to_owned(), pk_index.to_string()),
2344                ]);
2345                let result = build_iceberg_engine_sink_options(
2346                    options,
2347                    &WithOptions::default(),
2348                    &table,
2349                    &pks,
2350                );
2351                if supported {
2352                    result.unwrap();
2353                } else {
2354                    let err = result.unwrap_err().to_report_string();
2355                    let column = primary_key.split(", ").last().unwrap();
2356                    assert!(
2357                        err.contains(&format!(
2358                            "Iceberg engine table primary key column \"{column}\" has unsupported type"
2359                        )),
2360                        "{write_mode}: {err}"
2361                    );
2362                }
2363            }
2364            frontend.run_sql("DROP TABLE t").await.unwrap();
2365        }
2366    }
2367
2368    #[tokio::test]
2369    async fn test_cdc_relations_require_select_privilege_on_source() {
2370        let frontend = LocalFrontend::new(Default::default()).await;
2371        // PostgreSQL CDC with an explicit schema avoids querying upstream PK metadata,
2372        // so this privilege test does not require an external database.
2373        frontend
2374            .run_sql(
2375                r#"
2376                CREATE SOURCE cdc_source WITH (
2377                    connector = 'postgres-cdc',
2378                    hostname = 'localhost',
2379                    port = '5432',
2380                    username = 'postgres',
2381                    password = '',
2382                    database.name = 'db'
2383                ) FORMAT PLAIN ENCODE JSON
2384                "#,
2385            )
2386            .await
2387            .unwrap();
2388        frontend.run_sql("CREATE USER cdc_user").await.unwrap();
2389        frontend
2390            .run_sql("GRANT CREATE ON SCHEMA public TO cdc_user")
2391            .await
2392            .unwrap();
2393
2394        let user_id = frontend
2395            .session_ref()
2396            .env()
2397            .user_info_reader()
2398            .read_guard()
2399            .get_user_by_name("cdc_user")
2400            .unwrap()
2401            .id;
2402        let user_session = frontend.session_user_ref(
2403            DEFAULT_DATABASE_NAME.to_owned(),
2404            "cdc_user".to_owned(),
2405            user_id,
2406        );
2407        let create_table =
2408            "CREATE TABLE cdc_table (id INT PRIMARY KEY) FROM cdc_source TABLE 'public.t'";
2409        let create_table_source = "CREATE SOURCE cdc_table_source (id INT PRIMARY KEY) \
2410             WITH (snapshot = 'false') FROM cdc_source TABLE 'public.t'";
2411
2412        for sql in [create_table, create_table_source] {
2413            let err = frontend
2414                .run_sql_with_session(user_session.clone(), sql)
2415                .await
2416                .unwrap_err();
2417            assert!(
2418                err.to_string()
2419                    .contains("permission denied for source \"cdc_source\": \"SELECT\""),
2420                "{err:?}"
2421            );
2422        }
2423
2424        frontend
2425            .run_sql("GRANT SELECT ON SOURCE cdc_source TO cdc_user")
2426            .await
2427            .unwrap();
2428        frontend
2429            .run_sql_with_session(user_session.clone(), create_table)
2430            .await
2431            .unwrap();
2432        frontend
2433            .run_sql_with_session(user_session.clone(), create_table_source)
2434            .await
2435            .unwrap();
2436
2437        let table_source = {
2438            let catalog_reader = frontend.session_ref().env().catalog_reader().read_guard();
2439            catalog_reader
2440                .get_source_by_name(
2441                    DEFAULT_DATABASE_NAME,
2442                    SchemaPath::Name("public"),
2443                    "cdc_table_source",
2444                )
2445                .unwrap()
2446                .0
2447                .clone()
2448        };
2449        assert_eq!(table_source.with_properties.len(), 2);
2450        assert_eq!(
2451            table_source.with_properties.get_connector().as_deref(),
2452            Some("postgres-cdc")
2453        );
2454        assert_eq!(
2455            table_source
2456                .with_properties
2457                .get("snapshot")
2458                .map(String::as_str),
2459            Some("false")
2460        );
2461        assert!(table_source.with_properties.as_secret().is_empty());
2462        // The descriptor carries the resolved connect properties so that meta can validate it
2463        // against the upstream table; meta clears them before persisting the catalog, which is
2464        // covered by `test_create_cdc_table_source_dependency`.
2465        let external_table = table_source.info.external_table.as_ref().unwrap();
2466        assert!(!external_table.connect_properties.is_empty());
2467
2468        let err = frontend
2469            .run_sql_with_session(
2470                user_session.clone(),
2471                "SELECT * FROM postgres_query('cdc_table_source', 'SELECT 1')",
2472            )
2473            .await
2474            .unwrap_err();
2475        assert!(
2476            err.to_report_string()
2477                .contains("only accept shared CDC sources, not CDC table sources"),
2478            "{err:?}"
2479        );
2480
2481        frontend
2482            .run_sql("REVOKE SELECT ON SOURCE cdc_source FROM cdc_user")
2483            .await
2484            .unwrap();
2485        let err = frontend
2486            .run_sql_with_session(user_session, "ALTER TABLE cdc_table ADD COLUMN value INT")
2487            .await
2488            .unwrap_err();
2489        assert!(
2490            err.to_string()
2491                .contains("permission denied for source \"cdc_source\": \"SELECT\""),
2492            "{err:?}"
2493        );
2494    }
2495
2496    #[tokio::test]
2497    async fn test_create_table_handler() {
2498        let sql =
2499            "create table t (v1 smallint, v2 struct<v3 bigint, v4 float, v5 double>) append only;";
2500        let frontend = LocalFrontend::new(Default::default()).await;
2501        frontend.run_sql(sql).await.unwrap();
2502
2503        let session = frontend.session_ref();
2504        let catalog_reader = session.env().catalog_reader().read_guard();
2505        let schema_path = SchemaPath::Name(DEFAULT_SCHEMA_NAME);
2506
2507        // Check table exists.
2508        let (table, _) = catalog_reader
2509            .get_created_table_by_name(DEFAULT_DATABASE_NAME, schema_path, "t")
2510            .unwrap();
2511        assert_eq!(table.name(), "t");
2512
2513        let columns = table
2514            .columns
2515            .iter()
2516            .map(|col| (col.name(), col.data_type().clone()))
2517            .collect::<HashMap<&str, DataType>>();
2518
2519        let expected_columns = maplit::hashmap! {
2520            ROW_ID_COLUMN_NAME => DataType::Serial,
2521            "v1" => DataType::Int16,
2522            "v2" => StructType::new(
2523                vec![("v3", DataType::Int64),("v4", DataType::Float64),("v5", DataType::Float64)],
2524            )
2525            .with_ids([3, 4, 5].map(ColumnId::new))
2526            .into(),
2527            RW_TIMESTAMP_COLUMN_NAME => DataType::Timestamptz,
2528            RW_VNODE_COLUMN_NAME => DataType::Int16,
2529        };
2530
2531        assert_eq!(columns, expected_columns, "{columns:#?}");
2532    }
2533
2534    #[tokio::test]
2535    async fn test_create_webhook_table_with_arbitrary_columns() {
2536        let frontend = LocalFrontend::new(Default::default()).await;
2537        frontend
2538            .run_sql("create schema ingest_schema;")
2539            .await
2540            .unwrap();
2541        frontend
2542            .run_sql(
2543                r#"
2544                create table ingest_schema.orders (
2545                    id int,
2546                    customer_name varchar,
2547                    amount double precision,
2548                    primary key (id)
2549                ) with (
2550                    connector = 'webhook'
2551                ) validate as secure_compare(
2552                    headers->>'x-rw-signature',
2553                    'sha256=' || encode(hmac('webhook-secret', payload, 'sha256'), 'hex')
2554                );
2555                "#,
2556            )
2557            .await
2558            .unwrap();
2559
2560        let session = frontend.session_ref();
2561        let catalog_reader = session.env().catalog_reader().read_guard();
2562        let (table, _) = catalog_reader
2563            .get_created_table_by_name(
2564                DEFAULT_DATABASE_NAME,
2565                SchemaPath::Name("ingest_schema"),
2566                "orders",
2567            )
2568            .unwrap();
2569
2570        assert!(table.webhook_info.is_some());
2571        assert_eq!(
2572            table
2573                .columns
2574                .iter()
2575                .filter(|column| column.can_dml())
2576                .count(),
2577            3
2578        );
2579    }
2580
2581    #[tokio::test]
2582    async fn test_create_webhook_table_uses_single_jsonb_column_name_in_validate() {
2583        let frontend = LocalFrontend::new(Default::default()).await;
2584        frontend
2585            .run_sql(
2586                r#"
2587                create table webhook_single_column (
2588                    body jsonb
2589                ) with (
2590                    connector = 'webhook'
2591                ) validate as secure_compare(
2592                    headers->>'x-rw-signature',
2593                    'sha256=' || encode(hmac('webhook-secret', body, 'sha256'), 'hex')
2594                );
2595                "#,
2596            )
2597            .await
2598            .unwrap();
2599    }
2600
2601    #[tokio::test]
2602    async fn test_create_webhook_table_with_generated_columns() {
2603        let frontend = LocalFrontend::new(Default::default()).await;
2604        let err = frontend
2605            .run_sql(
2606                r#"
2607                create table webhook_generated_columns (
2608                    id int,
2609                    amount double precision,
2610                    amount_with_fee double precision as amount + 1.0
2611                ) with (
2612                    connector = 'webhook'
2613                );
2614                "#,
2615            )
2616            .await
2617            .unwrap_err();
2618
2619        assert!(
2620            err.to_string()
2621                .contains("generated columns are not supported for webhook tables"),
2622            "{err:?}"
2623        );
2624    }
2625
2626    #[tokio::test]
2627    async fn test_create_webhook_table_with_default_value() {
2628        let frontend = LocalFrontend::new(Default::default()).await;
2629        let err = frontend
2630            .run_sql(
2631                r#"
2632                create table webhook_default_value (
2633                    id int default 42,
2634                    amount double precision
2635                ) with (
2636                    connector = 'webhook'
2637                );
2638                "#,
2639            )
2640            .await
2641            .unwrap_err();
2642
2643        assert!(
2644            err.to_string()
2645                .contains("default values are not supported for webhook tables"),
2646            "{err:?}"
2647        );
2648    }
2649
2650    #[tokio::test]
2651    async fn test_create_webhook_table_with_not_null_option() {
2652        let frontend = LocalFrontend::new(Default::default()).await;
2653        let err = frontend
2654            .run_sql(
2655                r#"
2656                create table webhook_not_null (
2657                    id int not null,
2658                    amount double precision
2659                ) with (
2660                    connector = 'webhook'
2661                );
2662                "#,
2663            )
2664            .await
2665            .unwrap_err();
2666
2667        assert!(
2668            err.to_string()
2669                .contains("only NULL column option is supported for webhook tables"),
2670            "{err:?}"
2671        );
2672    }
2673
2674    #[test]
2675    fn test_bind_primary_key() {
2676        // Note: Column ID 0 is reserved for row ID column.
2677
2678        for (sql, expected) in [
2679            ("create table t (v1 int, v2 int)", Ok(&[0] as &[_])),
2680            ("create table t (v1 int primary key, v2 int)", Ok(&[1])),
2681            ("create table t (v1 int, v2 int primary key)", Ok(&[2])),
2682            (
2683                "create table t (v1 int primary key, v2 int primary key)",
2684                Err("multiple primary keys are not allowed"),
2685            ),
2686            (
2687                "create table t (v1 int primary key primary key, v2 int)",
2688                Err("multiple primary keys are not allowed"),
2689            ),
2690            (
2691                "create table t (v1 int, v2 int, primary key (v1))",
2692                Ok(&[1]),
2693            ),
2694            (
2695                "create table t (v1 int, primary key (v2), v2 int)",
2696                Ok(&[2]),
2697            ),
2698            (
2699                "create table t (primary key (v2, v1), v1 int, v2 int)",
2700                Ok(&[2, 1]),
2701            ),
2702            (
2703                "create table t (v1 int, primary key (v1), v2 int, primary key (v1))",
2704                Err("multiple primary keys are not allowed"),
2705            ),
2706            (
2707                "create table t (v1 int primary key, primary key (v1), v2 int)",
2708                Err("multiple primary keys are not allowed"),
2709            ),
2710            (
2711                "create table t (v1 int, primary key (V3), v2 int)",
2712                Err("column \"v3\" named in key does not exist"),
2713            ),
2714        ] {
2715            let mut ast = risingwave_sqlparser::parser::Parser::parse_sql(sql).unwrap();
2716            let risingwave_sqlparser::ast::Statement::CreateTable {
2717                columns: column_defs,
2718                constraints,
2719                ..
2720            } = ast.remove(0)
2721            else {
2722                panic!("test case should be create table")
2723            };
2724            let actual: Result<_> = (|| {
2725                let mut columns = bind_sql_columns(&column_defs, false)?;
2726                let mut col_id_gen = ColumnIdGenerator::new_initial();
2727                for c in &mut columns {
2728                    col_id_gen.generate(c)?;
2729                }
2730
2731                let pk_names =
2732                    bind_sql_pk_names(&column_defs, bind_table_constraints(&constraints)?)?;
2733                let (_, pk_column_ids, _) =
2734                    bind_pk_and_row_id_on_relation(columns, pk_names, true)?;
2735                Ok(pk_column_ids)
2736            })();
2737            match (expected, actual) {
2738                (Ok(expected), Ok(actual)) => assert_eq!(
2739                    expected.iter().copied().map(ColumnId::new).collect_vec(),
2740                    actual,
2741                    "sql: {sql}"
2742                ),
2743                (Ok(_), Err(actual)) => panic!("sql: {sql}\nunexpected error: {actual:?}"),
2744                (Err(_), Ok(actual)) => panic!("sql: {sql}\nexpects error but got: {actual:?}"),
2745                (Err(expected), Err(actual)) => assert!(
2746                    actual.to_string().contains(expected),
2747                    "sql: {sql}\nexpected: {expected:?}\nactual: {actual:?}"
2748                ),
2749            }
2750        }
2751    }
2752
2753    #[tokio::test]
2754    async fn test_duplicate_props_options() {
2755        let proto_file = create_proto_file(PROTO_FILE_DATA);
2756        let sql = format!(
2757            r#"CREATE TABLE t
2758    WITH (
2759        connector = 'kinesis',
2760        aws.region='user_test_topic',
2761        endpoint='172.10.1.1:9090,172.10.1.2:9090',
2762        aws.credentials.access_key_id = 'your_access_key_1',
2763        aws.credentials.secret_access_key = 'your_secret_key_1'
2764    )
2765    FORMAT PLAIN ENCODE PROTOBUF (
2766        message = '.test.TestRecord',
2767        aws.credentials.access_key_id = 'your_access_key_2',
2768        aws.credentials.secret_access_key = 'your_secret_key_2',
2769        schema.location = 'file://{}',
2770    )"#,
2771            proto_file.path().to_str().unwrap()
2772        );
2773        let frontend = LocalFrontend::new(Default::default()).await;
2774        frontend.run_sql(sql).await.unwrap();
2775
2776        let session = frontend.session_ref();
2777        let catalog_reader = session.env().catalog_reader().read_guard();
2778        let schema_path = SchemaPath::Name(DEFAULT_SCHEMA_NAME);
2779
2780        // Check source exists.
2781        let (source, _) = catalog_reader
2782            .get_source_by_name(DEFAULT_DATABASE_NAME, schema_path, "t")
2783            .unwrap();
2784        assert_eq!(source.name, "t");
2785
2786        // AwsAuth params exist in options.
2787        assert_eq!(
2788            source
2789                .info
2790                .format_encode_options
2791                .get("aws.credentials.access_key_id")
2792                .unwrap(),
2793            "your_access_key_2"
2794        );
2795        assert_eq!(
2796            source
2797                .info
2798                .format_encode_options
2799                .get("aws.credentials.secret_access_key")
2800                .unwrap(),
2801            "your_secret_key_2"
2802        );
2803
2804        // AwsAuth params exist in props.
2805        assert_eq!(
2806            source
2807                .with_properties
2808                .get("aws.credentials.access_key_id")
2809                .unwrap(),
2810            "your_access_key_1"
2811        );
2812        assert_eq!(
2813            source
2814                .with_properties
2815                .get("aws.credentials.secret_access_key")
2816                .unwrap(),
2817            "your_secret_key_1"
2818        );
2819
2820        // Options are not merged into props.
2821        assert!(!source.with_properties.contains_key("schema.location"));
2822    }
2823}