Skip to main content

risingwave_frontend/handler/
create_sink.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, BTreeSet, HashMap, HashSet};
16use std::sync::{Arc, LazyLock};
17
18use anyhow::Context;
19use either::Either;
20use iceberg::arrow::type_to_arrow_type;
21use iceberg::spec::Transform;
22use itertools::Itertools;
23use maplit::{convert_args, hashmap, hashset};
24use pgwire::pg_response::{PgResponse, StatementType};
25use risingwave_common::array::arrow::IcebergArrowConvert;
26use risingwave_common::array::arrow::arrow_schema_iceberg::DataType as ArrowDataType;
27use risingwave_common::bail;
28use risingwave_common::catalog::{
29    ColumnCatalog, ICEBERG_SINK_PREFIX, ObjectId, RISINGWAVE_ICEBERG_ROW_ID, ROW_ID_COLUMN_NAME,
30    Schema,
31};
32use risingwave_common::license::Feature;
33use risingwave_common::secret::LocalSecretManager;
34use risingwave_common::system_param::reader::SystemParamsRead;
35use risingwave_common::types::{DataType, Timestamptz};
36use risingwave_common::util::epoch::Epoch;
37use risingwave_connector::sink::catalog::{SinkCatalog, SinkFormatDesc};
38use risingwave_connector::sink::file_sink::s3::SnowflakeSink;
39use risingwave_connector::sink::iceberg::{ENABLE_PK_INDEX, ICEBERG_SINK, IcebergConfig};
40use risingwave_connector::sink::kafka::KAFKA_SINK;
41use risingwave_connector::sink::snowflake_redshift::redshift::RedshiftSink;
42use risingwave_connector::sink::snowflake_redshift::snowflake::SnowflakeV2Sink;
43use risingwave_connector::sink::{
44    CONNECTOR_TYPE_KEY, SINK_SNAPSHOT_OPTION, SINK_TYPE_OPTION, SINK_TYPE_UPSERT,
45    SINK_USER_FORCE_APPEND_ONLY_OPTION, SINK_USER_IGNORE_DELETE_OPTION, Sink, enforce_secret_sink,
46};
47use risingwave_connector::{
48    AUTO_SCHEMA_CHANGE_KEY, SINK_CREATE_TABLE_IF_NOT_EXISTS_KEY, SINK_INTERMEDIATE_TABLE_NAME,
49    SINK_TARGET_TABLE_NAME, WithPropertiesExt,
50};
51use risingwave_pb::catalog::connection_params::PbConnectionType;
52use risingwave_pb::telemetry::TelemetryDatabaseObject;
53use risingwave_sqlparser::ast::{
54    CreateSink, CreateSinkStatement, EmitMode, Encode, ExplainOptions, Format, FormatEncodeOptions,
55    ObjectName, Query, Statement,
56};
57use risingwave_sqlparser::parser::Parser;
58
59use super::RwPgResponse;
60use super::create_mv::get_column_names;
61use super::create_source::UPSTREAM_SOURCE_KEY;
62use super::util::gen_query_from_table_name;
63use crate::binder::{Binder, Relation};
64use crate::catalog::root_catalog::SchemaPath;
65use crate::catalog::table_catalog::TableType;
66use crate::error::{ErrorCode, Result, RwError};
67use crate::expr::{ExprImpl, InputRef, rewrite_now_to_proctime};
68use crate::handler::HandlerArgs;
69use crate::handler::alter_table_column::fetch_table_catalog_for_alter;
70use crate::handler::create_mv::{
71    extract_streaming_job_resource_options, parse_column_names, resolve_streaming_job_resource_type,
72};
73use crate::handler::util::{
74    LongRunningNotificationAction, check_connector_match_connection_type,
75    ensure_connection_type_allowed, ensure_local_fs_connector_allowed,
76    execute_with_long_running_notification, get_table_catalog_by_table_name,
77    reject_internal_table_dependencies,
78};
79use crate::optimizer::backfill_order_strategy::plan_backfill_order;
80use crate::optimizer::plan_node::{
81    IcebergPartitionInfo, LogicalSource, PartitionComputeInfo, StreamPlanRef as PlanRef,
82    StreamProject, ensure_sync_log_store_fragment_root, generic,
83};
84use crate::optimizer::{OptimizerContext, RelationCollectorVisitor};
85use crate::scheduler::streaming_manager::CreatingStreamingJobInfo;
86use crate::session::SessionImpl;
87use crate::session::current::notice_to_user;
88use crate::stream_fragmenter::{GraphJobType, build_graph_with_strategy};
89use crate::utils::{resolve_connection_ref_and_secret_ref, resolve_privatelink_in_with_option};
90use crate::{Explain, Planner, TableCatalog, WithOptions, WithOptionsSecResolved};
91
92static SINK_ALLOWED_CONNECTION_CONNECTOR: LazyLock<HashSet<PbConnectionType>> =
93    LazyLock::new(|| {
94        hashset! {
95            PbConnectionType::Unspecified,
96            PbConnectionType::Kafka,
97            PbConnectionType::Iceberg,
98            PbConnectionType::Elasticsearch,
99        }
100    });
101
102static SINK_ALLOWED_CONNECTION_SCHEMA_REGISTRY: LazyLock<HashSet<PbConnectionType>> =
103    LazyLock::new(|| {
104        hashset! {
105            PbConnectionType::Unspecified,
106            PbConnectionType::SchemaRegistry,
107        }
108    });
109
110const SINK_SINCE_TIMESTAMP_OPTION: &str = "since_timestamp";
111
112// used to store result of `gen_sink_plan`
113pub struct SinkPlanContext {
114    pub query: Box<Query>,
115    pub sink_plan: PlanRef,
116    pub sink_catalog: SinkCatalog,
117    pub target_table_catalog: Option<Arc<TableCatalog>>,
118    pub dependencies: HashSet<ObjectId>,
119    pub since_timestamp_epoch: Option<u64>,
120}
121
122fn maybe_fill_intermediate_table_name(
123    with_options: &mut WithOptionsSecResolved,
124    connector: &str,
125    sink_name: &str,
126) -> Result<()> {
127    let should_fill = with_options
128        .value_eq_ignore_case(SINK_CREATE_TABLE_IF_NOT_EXISTS_KEY, "true")
129        && with_options.value_eq_ignore_case(SINK_TYPE_OPTION, SINK_TYPE_UPSERT)
130        && matches!(
131            connector,
132            RedshiftSink::SINK_NAME | SnowflakeV2Sink::SINK_NAME
133        );
134    if !should_fill || with_options.contains_key(SINK_INTERMEDIATE_TABLE_NAME) {
135        return Ok(());
136    }
137
138    let table_name = with_options
139        .get(SINK_TARGET_TABLE_NAME)
140        .ok_or_else(|| ErrorCode::BindError("'table.name' option must be specified.".to_owned()))?;
141    let intermediate_table_name =
142        format!("rw_{}_{}_{}", sink_name, table_name, uuid::Uuid::new_v4());
143    with_options.insert(
144        SINK_INTERMEDIATE_TABLE_NAME.to_owned(),
145        intermediate_table_name,
146    );
147    Ok(())
148}
149
150pub async fn gen_sink_plan(
151    handler_args: HandlerArgs,
152    stmt: CreateSinkStatement,
153    explain_options: Option<ExplainOptions>,
154    is_iceberg_engine_internal: bool,
155) -> Result<SinkPlanContext> {
156    let session = handler_args.session.clone();
157    let session = session.as_ref();
158    let user_specified_columns = !stmt.columns.is_empty();
159    let db_name = &session.database();
160    let (sink_schema_name, sink_table_name) =
161        Binder::resolve_schema_qualified_name(db_name, &stmt.sink_name)?;
162
163    let mut with_options = handler_args.with_options.clone();
164    // These are frontend-level streaming job options. They must not be passed to connector
165    // property validation.
166    extract_streaming_job_resource_options(&mut with_options);
167
168    if session
169        .env()
170        .system_params_manager()
171        .get_params()
172        .load()
173        .enforce_secret()
174        && Feature::SecretManagement.check_available().is_ok()
175    {
176        enforce_secret_sink(&with_options)?;
177    }
178
179    resolve_privatelink_in_with_option(&mut with_options)?;
180    let (mut resolved_with_options, connection_type, connector_conn_ref) =
181        resolve_connection_ref_and_secret_ref(
182            with_options,
183            session,
184            Some(TelemetryDatabaseObject::Sink),
185        )?;
186
187    let since_timestamp_epoch = resolved_with_options
188        .remove(SINK_SINCE_TIMESTAMP_OPTION)
189        .map(|value| {
190            let timestamp = value.parse::<Timestamptz>().map_err(|err| {
191                ErrorCode::InvalidInputSyntax(format!(
192                    "invalid value {value:?} of '{SINK_SINCE_TIMESTAMP_OPTION}' option: {err}; \
193                     expected a timestamptz string with an explicit time zone, \
194                     for example '2024-01-01 00:00:00Z'"
195                ))
196            })?;
197            let timestamp_millis = u64::try_from(timestamp.timestamp_millis()).unwrap_or(0);
198            Ok::<_, RwError>(Epoch::from_unix_millis_or_earliest(timestamp_millis).0)
199        })
200        .transpose()?;
201    if since_timestamp_epoch.is_some() {
202        Feature::SinkSinceTimestamp.check_available()?;
203    }
204
205    ensure_connection_type_allowed(connection_type, &SINK_ALLOWED_CONNECTION_CONNECTOR)?;
206
207    // if not using connection, we don't need to check connector match connection type
208    if !matches!(connection_type, PbConnectionType::Unspecified) {
209        let Some(connector) = resolved_with_options.get_connector() else {
210            return Err(RwError::from(ErrorCode::ProtocolError(format!(
211                "missing field '{}' in WITH clause",
212                CONNECTOR_TYPE_KEY
213            ))));
214        };
215        check_connector_match_connection_type(connector.as_str(), &connection_type)?;
216    }
217
218    let partition_info = get_partition_compute_info(&resolved_with_options).await?;
219
220    let context = if let Some(explain_options) = explain_options {
221        OptimizerContext::new(handler_args.clone(), explain_options)?
222    } else {
223        OptimizerContext::from_handler_args(handler_args.clone())?
224    };
225    let is_auto_schema_change = resolved_with_options
226        .get(AUTO_SCHEMA_CHANGE_KEY)
227        .map(|value| {
228            value.parse::<bool>().map_err(|_| {
229                ErrorCode::InvalidInputSyntax(format!(
230                    "invalid value {} of '{}' option, expect",
231                    value, AUTO_SCHEMA_CHANGE_KEY
232                ))
233            })
234        })
235        .transpose()?
236        .unwrap_or(false);
237
238    if is_auto_schema_change && !is_iceberg_engine_internal {
239        Feature::SinkAutoSchemaChange.check_available()?;
240    }
241
242    let sink_into_table_name = stmt.into_table_name.as_ref().map(|name| name.real_value());
243    if sink_into_table_name.is_some() {
244        let prev = resolved_with_options.insert(CONNECTOR_TYPE_KEY.to_owned(), "table".to_owned());
245
246        if prev.is_some() {
247            return Err(RwError::from(ErrorCode::BindError(
248                "In the case of sinking into table, the 'connector' parameter should not be provided.".to_owned(),
249            )));
250        }
251    }
252    let connector = resolved_with_options
253        .get(CONNECTOR_TYPE_KEY)
254        .cloned()
255        .ok_or_else(|| ErrorCode::BindError(format!("missing field '{CONNECTOR_TYPE_KEY}'")))?;
256    ensure_local_fs_connector_allowed(session, &connector)?;
257
258    // Used for debezium's table name
259    let sink_from_table_name;
260    // `true` means that sink statement has the form: `CREATE SINK s1 FROM ...`
261    // `false` means that sink statement has the form: `CREATE SINK s1 AS <query>`
262    let direct_sink_from_name: Option<(ObjectName, bool)>;
263    let mut query = match stmt.sink_from {
264        CreateSink::From(from_name) => {
265            sink_from_table_name = from_name.0.last().unwrap().real_value();
266            direct_sink_from_name = Some((from_name.clone(), is_auto_schema_change));
267            if is_auto_schema_change && sink_into_table_name.is_some() {
268                return Err(RwError::from(ErrorCode::InvalidInputSyntax(
269                    "auto schema change not supported for sink-into-table".to_owned(),
270                )));
271            }
272            maybe_fill_intermediate_table_name(
273                &mut resolved_with_options,
274                &connector,
275                &sink_table_name,
276            )?;
277            Box::new(gen_query_from_table_name(from_name))
278        }
279        CreateSink::AsQuery(query) => {
280            if is_auto_schema_change {
281                return Err(RwError::from(ErrorCode::InvalidInputSyntax(
282                    "auto schema change not supported for CREATE SINK AS QUERY".to_owned(),
283                )));
284            }
285            sink_from_table_name = sink_table_name.clone();
286            direct_sink_from_name = None;
287            query
288        }
289    };
290
291    if is_iceberg_engine_internal && let Some((from_name, _)) = &direct_sink_from_name {
292        let (table, _) = get_table_catalog_by_table_name(session, from_name)?;
293        let pk_names = table.pk_column_names();
294        if pk_names.len() == 1 && pk_names[0].eq(ROW_ID_COLUMN_NAME) {
295            let [stmt]: [_; 1] = Parser::parse_sql(&format!(
296                "select {} as {}, * from {}",
297                ROW_ID_COLUMN_NAME, RISINGWAVE_ICEBERG_ROW_ID, from_name
298            ))
299            .context("unable to parse query")?
300            .try_into()
301            .unwrap();
302            let Statement::Query(parsed_query) = stmt else {
303                panic!("unexpected statement: {:?}", stmt);
304            };
305            query = parsed_query;
306        }
307    }
308
309    let (sink_database_id, sink_schema_id) =
310        session.get_database_and_schema_id_for_create(sink_schema_name.clone())?;
311
312    if since_timestamp_epoch.is_some() {
313        if sink_into_table_name.is_some() {
314            return Err(ErrorCode::BindError(format!(
315                "`{SINK_SINCE_TIMESTAMP_OPTION}` does not support `CREATE SINK INTO TABLE`"
316            ))
317            .into());
318        }
319        if is_iceberg_engine_internal {
320            return Err(ErrorCode::BindError(format!(
321                "`{SINK_SINCE_TIMESTAMP_OPTION}` does not support iceberg engine internal sinks"
322            ))
323            .into());
324        }
325        if let Some((from_name, _)) = &direct_sink_from_name {
326            let (table, _) = get_table_catalog_by_table_name(session, from_name)?;
327            if table.database_id != sink_database_id {
328                return Err(ErrorCode::NotSupported(
329                    format!(
330                        "`{SINK_SINCE_TIMESTAMP_OPTION}` does not support cross-database sinks"
331                    ),
332                    "Please create the sink in the same database as the upstream table.".to_owned(),
333                )
334                .into());
335            }
336        }
337    }
338
339    let (
340        dependent_relations,
341        dependent_udfs,
342        dependent_secrets,
343        bound,
344        auto_refresh_schema_from_table,
345    ) = {
346        let mut binder = Binder::new_for_stream(session);
347        let auto_refresh_schema_from_table = if let Some((from_name, true)) = &direct_sink_from_name
348        {
349            let from_relation = binder.bind_relation_by_name(from_name, None, None, true)?;
350            if let Relation::BaseTable(table) = from_relation {
351                if table.table_catalog.table_type != TableType::Table {
352                    return Err(ErrorCode::InvalidInputSyntax(format!(
353                        "auto schema change is supported only on TABLE, but got {:?}",
354                        table.table_catalog.table_type
355                    ))
356                    .into());
357                }
358                if table.table_catalog.database_id != sink_database_id {
359                    return Err(ErrorCode::InvalidInputSyntax(
360                        "auto schema change sinks do not support cross-database tables".to_owned(),
361                    )
362                    .into());
363                }
364                for col in &table.table_catalog.columns {
365                    if !col.is_hidden() && (col.is_generated() || col.is_rw_sys_column()) {
366                        return Err(ErrorCode::InvalidInputSyntax(format!(
367                            "auto schema change is not supported for tables with visible generated columns or visible system columns, but found column {}",
368                            col.name()
369                        ))
370                        .into());
371                    }
372                }
373                Some(table.table_catalog)
374            } else {
375                return Err(RwError::from(ErrorCode::NotSupported(
376                    "auto schema change only supported for TABLE".to_owned(),
377                    "try recreating the sink from table".to_owned(),
378                )));
379            }
380        } else {
381            None
382        };
383
384        let bound = binder.bind_query(&query)?;
385
386        (
387            binder.included_relations().clone(),
388            binder.included_udfs().clone(),
389            binder.included_secrets().clone(),
390            bound,
391            auto_refresh_schema_from_table,
392        )
393    };
394
395    reject_internal_table_dependencies(session, &dependent_relations, "CREATE SINK")?;
396
397    let col_names = if sink_into_table_name.is_some() {
398        parse_column_names(&stmt.columns)
399    } else {
400        // If column names not specified, use the name in the bound query, which is equal with the plan root's original field name.
401        get_column_names(&bound, stmt.columns)?
402    };
403
404    let emit_on_window_close = stmt.emit_mode == Some(EmitMode::OnWindowClose);
405    if emit_on_window_close {
406        context.warn_to_user("EMIT ON WINDOW CLOSE is currently an experimental feature. Please use it with caution.");
407    }
408
409    let format_desc = match stmt.sink_schema {
410        // Case A: new syntax `format ... encode ...`
411        Some(f) => {
412            validate_compatibility(&connector, &f)?;
413            Some(bind_sink_format_desc(session,f)?)
414        }
415        None => match resolved_with_options.get(SINK_TYPE_OPTION) {
416            // Case B: old syntax `type = '...'`
417            Some(t) => SinkFormatDesc::from_legacy_type(&connector, t)?.map(|mut f| {
418                session.notice_to_user("Consider using the newer syntax `FORMAT ... ENCODE ...` instead of `type = '...'`.");
419                if let Some(v) = resolved_with_options.get(SINK_USER_FORCE_APPEND_ONLY_OPTION) {
420                    f.options.insert(SINK_USER_FORCE_APPEND_ONLY_OPTION.into(), v.into());
421                }
422                if let Some(v) = resolved_with_options.get(SINK_USER_IGNORE_DELETE_OPTION) {
423                    f.options.insert(SINK_USER_IGNORE_DELETE_OPTION.into(), v.into());
424                }
425                f
426            }),
427            // Case C: no format + encode required
428            None => None,
429        },
430    };
431
432    let definition = context.normalized_sql().to_owned();
433    let mut plan_root = if is_iceberg_engine_internal {
434        Planner::new_for_iceberg_table_engine_sink(context.into()).plan_query(bound)?
435    } else {
436        Planner::new_for_stream(context.into()).plan_query(bound)?
437    };
438    if let Some(col_names) = &col_names {
439        plan_root.set_out_names(col_names.clone())?;
440    };
441
442    let without_snapshot = matches!(
443        resolved_with_options.remove(SINK_SNAPSHOT_OPTION),
444        Some(flag) if flag.eq_ignore_ascii_case("false")
445    );
446
447    if since_timestamp_epoch.is_some() && !without_snapshot {
448        return Err(ErrorCode::BindError(format!(
449            "`{SINK_SINCE_TIMESTAMP_OPTION}` requires `snapshot = false`"
450        ))
451        .into());
452    }
453
454    let target_table_catalog = stmt
455        .into_table_name
456        .as_ref()
457        .map(|table_name| fetch_table_catalog_for_alter(session, table_name).map(|t| t.0))
458        .transpose()?;
459
460    if let Some(target_table_catalog) = &target_table_catalog {
461        if let Some(col_names) = col_names {
462            let target_table_columns = target_table_catalog
463                .columns()
464                .iter()
465                .map(|c| c.name())
466                .collect::<BTreeSet<_>>();
467            for c in col_names {
468                if !target_table_columns.contains(c.as_str()) {
469                    return Err(RwError::from(ErrorCode::BindError(format!(
470                        "Column {} not found in table {}",
471                        c,
472                        target_table_catalog.name()
473                    ))));
474                }
475            }
476        }
477        if target_table_catalog
478            .columns()
479            .iter()
480            .any(|col| !col.nullable())
481        {
482            notice_to_user(format!(
483                "The target table `{}` contains NOT NULL columns. Rows written by the sink that violate those constraints will be ignored silently.",
484                target_table_catalog.name(),
485            ));
486        }
487    }
488
489    let sink_plan = plan_root.gen_sink_plan(
490        sink_table_name,
491        definition,
492        resolved_with_options,
493        emit_on_window_close,
494        db_name.to_owned(),
495        sink_from_table_name,
496        format_desc,
497        without_snapshot,
498        since_timestamp_epoch.is_some(),
499        is_iceberg_engine_internal,
500        target_table_catalog.clone(),
501        partition_info,
502        user_specified_columns,
503        auto_refresh_schema_from_table,
504    )?;
505
506    let sink_desc = sink_plan.sink_desc().clone();
507
508    let mut sink_plan: PlanRef = sink_plan.into_stream_plan()?;
509    sink_plan = ensure_sync_log_store_fragment_root(sink_plan);
510
511    let ctx = sink_plan.ctx();
512    let explain_trace = ctx.is_explain_trace();
513    if explain_trace {
514        ctx.trace("Create Sink:");
515        ctx.trace(sink_plan.explain_to_string());
516    }
517    tracing::trace!("sink_plan: {:?}", sink_plan.explain_to_string());
518
519    // TODO(rc): To be consistent with UDF dependency check, we should collect relation dependencies
520    // during binding instead of visiting the optimized plan.
521    let dependencies =
522        RelationCollectorVisitor::collect_with(dependent_relations, sink_plan.clone())
523            .into_iter()
524            .chain(dependent_udfs.iter().copied().map_into())
525            .chain(
526                dependent_secrets
527                    .iter()
528                    .copied()
529                    .map(|id| id.as_object_id()),
530            )
531            .collect();
532
533    let sink_catalog = sink_desc.into_catalog(
534        sink_schema_id,
535        sink_database_id,
536        session.user_id(),
537        connector_conn_ref,
538    );
539
540    if let Some(table_catalog) = &target_table_catalog {
541        for column in sink_catalog.full_columns() {
542            if !column.can_dml() {
543                unreachable!(
544                    "cannot derive generated columns or the `_rw_timestamp` system column in a sink catalog, but found one"
545                );
546            }
547        }
548
549        let table_columns_without_rw_timestamp = table_catalog.columns_without_rw_timestamp();
550        let exprs = derive_default_column_project_for_sink(
551            &sink_catalog,
552            sink_plan.schema(),
553            &table_columns_without_rw_timestamp,
554            user_specified_columns,
555        )?;
556
557        let logical_project = generic::Project::new(exprs, sink_plan);
558
559        sink_plan = StreamProject::new(logical_project).into();
560
561        let exprs = LogicalSource::derive_output_exprs_from_generated_columns(
562            &table_columns_without_rw_timestamp,
563        )?;
564
565        if let Some(exprs) = exprs {
566            let logical_project = generic::Project::new(exprs, sink_plan);
567            sink_plan = StreamProject::new(logical_project).into();
568        }
569    };
570
571    Ok(SinkPlanContext {
572        query,
573        sink_plan,
574        sink_catalog,
575        target_table_catalog,
576        dependencies,
577        since_timestamp_epoch,
578    })
579}
580
581// This function is used to return partition compute info for a sink. More details refer in `PartitionComputeInfo`.
582// Return:
583// `Some(PartitionComputeInfo)` if the sink need to compute partition.
584// `None` if the sink does not need to compute partition.
585pub async fn get_partition_compute_info(
586    with_options: &WithOptionsSecResolved,
587) -> Result<Option<PartitionComputeInfo>> {
588    let (options, secret_refs) = with_options.clone().into_parts();
589    let Some(connector) = options.get(UPSTREAM_SOURCE_KEY).cloned() else {
590        return Ok(None);
591    };
592    let properties = LocalSecretManager::global().fill_secrets(options, secret_refs)?;
593    match connector.as_str() {
594        ICEBERG_SINK => {
595            let iceberg_config = IcebergConfig::from_btreemap(properties)?;
596            get_partition_compute_info_for_iceberg(&iceberg_config).await
597        }
598        _ => Ok(None),
599    }
600}
601
602async fn get_partition_compute_info_for_iceberg(
603    iceberg_config: &IcebergConfig,
604) -> Result<Option<PartitionComputeInfo>> {
605    if iceberg_config.enable_pk_index {
606        Feature::IcebergSinkWithPkIndex.check_available()?;
607    }
608
609    // TODO: check table if exists
610    if iceberg_config.create_table_if_not_exists {
611        return Ok(None);
612    }
613    let table = iceberg_config.load_table().await?;
614    let partition_spec = table.metadata().default_partition_spec();
615    if partition_spec.is_unpartitioned() {
616        return Ok(None);
617    }
618
619    // Separate the partition spec into two parts: sparse partition and range partition.
620    // Sparse partition means that the data distribution is more sparse at a given time.
621    // Range partition means that the data distribution is likely same at a given time.
622    // Only compute the partition and shuffle by them for the sparse partition.
623    let has_sparse_partition = partition_spec.fields().iter().any(|f| match f.transform {
624        // Sparse partition
625        Transform::Identity | Transform::Truncate(_) | Transform::Bucket(_) => true,
626        // Range partition
627        Transform::Year
628        | Transform::Month
629        | Transform::Day
630        | Transform::Hour
631        | Transform::Void
632        | Transform::Unknown => false,
633    });
634    if !has_sparse_partition {
635        return Ok(None);
636    }
637
638    let arrow_type = type_to_arrow_type(&iceberg::spec::Type::Struct(
639        table.metadata().default_partition_type().clone(),
640    ))
641    .map_err(|_| {
642        RwError::from(ErrorCode::SinkError(
643            "Failed to convert the Iceberg partition type to an Arrow type".into(),
644        ))
645    })?;
646    let ArrowDataType::Struct(struct_fields) = arrow_type else {
647        return Err(RwError::from(ErrorCode::SinkError(
648            "The Iceberg partition type must be a struct type".into(),
649        )));
650    };
651
652    let schema = table.metadata().current_schema();
653    let partition_fields = partition_spec
654        .fields()
655        .iter()
656        .map(|f| {
657            let source_f =
658                schema
659                    .field_by_id(f.source_id)
660                    .ok_or(RwError::from(ErrorCode::SinkError(
661                        "Failed to look up the Iceberg partition field".into(),
662                    )))?;
663            Ok((source_f.name.clone(), f.transform))
664        })
665        .collect::<Result<Vec<_>>>()?;
666
667    Ok(Some(PartitionComputeInfo::Iceberg(IcebergPartitionInfo {
668        partition_type: IcebergArrowConvert.struct_from_fields(&struct_fields)?,
669        partition_fields,
670    })))
671}
672
673pub async fn handle_create_sink(
674    mut handle_args: HandlerArgs,
675    stmt: CreateSinkStatement,
676    is_iceberg_engine_internal: bool,
677) -> Result<RwPgResponse> {
678    let session = handle_args.session.clone();
679
680    session.check_cluster_limits().await?;
681
682    let mode = if stmt.or_replace {
683        prepare_replace_sink(&mut handle_args, &stmt)?
684    } else {
685        let if_not_exists = stmt.if_not_exists;
686        if let Either::Right(resp) = session.check_relation_name_duplicated(
687            stmt.sink_name.clone(),
688            StatementType::CREATE_SINK,
689            if_not_exists,
690        )? {
691            return Ok(resp);
692        }
693
694        if stmt.sink_name.base_name().starts_with(ICEBERG_SINK_PREFIX) {
695            return Err(RwError::from(ErrorCode::InvalidInputSyntax(format!(
696                "Sink name cannot start with reserved prefix '{}'",
697                ICEBERG_SINK_PREFIX
698            ))));
699        }
700
701        SinkCreateMode::Create { if_not_exists }
702    };
703
704    create_sink_or_replace(handle_args, stmt, is_iceberg_engine_internal, mode).await
705}
706
707enum SinkCreateMode {
708    Create { if_not_exists: bool },
709    Replace { original_sink: Arc<SinkCatalog> },
710}
711
712impl SinkCreateMode {
713    fn statement_name(&self) -> &'static str {
714        match self {
715            SinkCreateMode::Create { .. } => "CREATE SINK",
716            SinkCreateMode::Replace { .. } => "REPLACE SINK",
717        }
718    }
719}
720
721fn is_iceberg_pk_index_properties(properties: &BTreeMap<String, String>) -> bool {
722    properties
723        .get(CONNECTOR_TYPE_KEY)
724        .is_some_and(|connector| connector.eq_ignore_ascii_case(ICEBERG_SINK))
725        && properties
726            .get(ENABLE_PK_INDEX)
727            .is_some_and(|value| value.eq_ignore_ascii_case("true"))
728}
729
730fn ensure_replace_sink_not_iceberg_pk_index(properties: &BTreeMap<String, String>) -> Result<()> {
731    if is_iceberg_pk_index_properties(properties) {
732        return Err(ErrorCode::NotSupported(
733            "REPLACE SINK does not support Iceberg sinks with `enable_pk_index='true'`".to_owned(),
734            "the Iceberg pk-index writer has internal state and must be rebuilt by snapshot backfill"
735                .to_owned(),
736        )
737        .into());
738    }
739    Ok(())
740}
741
742async fn create_sink_or_replace(
743    mut handle_args: HandlerArgs,
744    stmt: CreateSinkStatement,
745    is_iceberg_engine_internal: bool,
746    mode: SinkCreateMode,
747) -> Result<RwPgResponse> {
748    let session = handle_args.session.clone();
749
750    let resource_type =
751        resolve_streaming_job_resource_type(session.as_ref(), &mut handle_args.with_options)?;
752
753    let (sink, graph, dependencies, since_timestamp_epoch) = {
754        let backfill_order_strategy = handle_args.with_options.backfill_order_strategy();
755        let SinkPlanContext {
756            query,
757            sink_plan: plan,
758            sink_catalog: mut sink,
759            target_table_catalog,
760            dependencies,
761            since_timestamp_epoch,
762        } = gen_sink_plan(handle_args, stmt, None, is_iceberg_engine_internal).await?;
763
764        let has_order_by = !query.order_by.is_empty();
765        if has_order_by {
766            plan.ctx().warn_to_user(
767                r#"The ORDER BY clause in the CREATE SINK statement has no effect at all."#
768                    .to_owned(),
769            );
770        }
771
772        match &mode {
773            SinkCreateMode::Create { .. } => {
774                if let Some(table_catalog) = &target_table_catalog {
775                    sink.original_target_columns = table_catalog.columns_without_rw_timestamp();
776                }
777            }
778            SinkCreateMode::Replace { original_sink } => {
779                if target_table_catalog.is_some() {
780                    return Err(ErrorCode::NotSupported(
781                        "REPLACE SINK INTO TABLE is not supported yet".to_owned(),
782                        "replace ordinary sinks first".to_owned(),
783                    )
784                    .into());
785                }
786
787                sink.schema_id = original_sink.schema_id;
788                sink.database_id = original_sink.database_id;
789                sink.name = original_sink.name.clone();
790                sink.owner = original_sink.owner;
791            }
792        }
793
794        let backfill_order =
795            plan_backfill_order(session.as_ref(), backfill_order_strategy, plan.clone())?;
796        let graph =
797            build_graph_with_strategy(plan, Some(GraphJobType::Sink), Some(backfill_order))?;
798
799        (sink, graph, dependencies, since_timestamp_epoch)
800    };
801
802    let statement_name = mode.statement_name();
803    let catalog_writer = session.catalog_writer()?;
804    match mode {
805        SinkCreateMode::Create { if_not_exists } => {
806            let _job_guard = session.env().creating_streaming_job_tracker().guard(
807                CreatingStreamingJobInfo::new(
808                    session.session_id(),
809                    sink.database_id,
810                    sink.schema_id,
811                    sink.name.clone(),
812                ),
813            );
814
815            execute_with_long_running_notification(
816                catalog_writer.create_sink(
817                    sink.to_proto(),
818                    graph,
819                    dependencies,
820                    resource_type,
821                    if_not_exists,
822                    since_timestamp_epoch,
823                ),
824                &session,
825                statement_name,
826                LongRunningNotificationAction::MonitorBackfillJob,
827            )
828            .await?;
829        }
830        SinkCreateMode::Replace { original_sink } => {
831            let original_sink_id = original_sink.id;
832            execute_with_long_running_notification(
833                catalog_writer.replace_sink(
834                    original_sink_id,
835                    sink.to_proto(),
836                    graph,
837                    dependencies,
838                    resource_type,
839                ),
840                &session,
841                statement_name,
842                LongRunningNotificationAction::DiagnoseBarrierLatency,
843            )
844            .await?;
845
846            tracing::info!(
847                old_sink_id = %original_sink_id,
848                sink_name = %sink.name,
849                "replace sink plan submitted"
850            );
851        }
852    }
853
854    Ok(PgResponse::empty_result(StatementType::CREATE_SINK))
855}
856
857fn prepare_replace_sink(
858    handle_args: &mut HandlerArgs,
859    stmt: &CreateSinkStatement,
860) -> Result<SinkCreateMode> {
861    let session = handle_args.session.clone();
862    if stmt.if_not_exists {
863        return Err(ErrorCode::InvalidInputSyntax(
864            "REPLACE SINK does not support IF NOT EXISTS".to_owned(),
865        )
866        .into());
867    }
868    if !matches!(&stmt.sink_from, CreateSink::From(_)) {
869        return Err(ErrorCode::NotSupported(
870            "REPLACE SINK currently only supports REPLACE SINK ... FROM table_or_mv".to_owned(),
871            "use REPLACE SINK name FROM existing_relation ...".to_owned(),
872        )
873        .into());
874    }
875    if stmt.into_table_name.is_some() {
876        return Err(ErrorCode::NotSupported(
877            "REPLACE SINK INTO TABLE is not supported yet".to_owned(),
878            "replace ordinary sinks first".to_owned(),
879        )
880        .into());
881    }
882    if handle_args
883        .with_options
884        .get(AUTO_SCHEMA_CHANGE_KEY)
885        .is_some_and(|value| value.eq_ignore_ascii_case("true"))
886    {
887        return Err(ErrorCode::NotSupported(
888            "REPLACE SINK with auto schema change is not supported yet".to_owned(),
889            "disable auto schema change for this replacement".to_owned(),
890        )
891        .into());
892    }
893    if handle_args
894        .with_options
895        .contains_key(SINK_SINCE_TIMESTAMP_OPTION)
896    {
897        return Err(ErrorCode::NotSupported(
898            "REPLACE SINK with since_timestamp is not supported yet".to_owned(),
899            "create a new sink with since_timestamp instead".to_owned(),
900        )
901        .into());
902    }
903    ensure_replace_sink_not_iceberg_pk_index(&handle_args.with_options)?;
904    match handle_args.with_options.get(SINK_SNAPSHOT_OPTION) {
905        Some(value) if !value.eq_ignore_ascii_case("false") => {
906            return Err(ErrorCode::InvalidInputSyntax(
907                "REPLACE SINK must not enable snapshot backfill".to_owned(),
908            )
909            .into());
910        }
911        Some(_) => {}
912        None => {
913            handle_args
914                .with_options
915                .insert(SINK_SNAPSHOT_OPTION.to_owned(), "false".to_owned());
916        }
917    }
918
919    let db_name = session.database();
920    let (sink_schema_name, sink_table_name) =
921        Binder::resolve_schema_qualified_name(&db_name, &stmt.sink_name)?;
922    let original_sink = {
923        let search_path = session.config().search_path();
924        let user_name = session.user_name();
925        let schema_path = SchemaPath::new(sink_schema_name.as_deref(), &search_path, &user_name);
926        let reader = session.env().catalog_reader().read_guard();
927        let (sink, schema_name) =
928            reader.get_created_sink_by_name(&db_name, schema_path, &sink_table_name)?;
929        session.check_privilege_for_drop_alter(schema_name, &**sink)?;
930        if sink.target_table.is_some() {
931            return Err(ErrorCode::NotSupported(
932                "REPLACE SINK INTO TABLE is not supported yet".to_owned(),
933                "replace ordinary sinks first".to_owned(),
934            )
935            .into());
936        }
937        if sink.auto_refresh_schema_from_table.is_some() {
938            return Err(ErrorCode::NotSupported(
939                "REPLACE SINK with auto schema change is not supported yet".to_owned(),
940                "drop and recreate this auto schema change sink".to_owned(),
941            )
942            .into());
943        }
944        ensure_replace_sink_not_iceberg_pk_index(&sink.properties)?;
945        sink.clone()
946    };
947
948    Ok(SinkCreateMode::Replace { original_sink })
949}
950
951pub fn fetch_incoming_sinks(
952    session: &Arc<SessionImpl>,
953    table: &TableCatalog,
954) -> Result<Vec<Arc<SinkCatalog>>> {
955    let reader = session.env().catalog_reader().read_guard();
956    let schema = reader.get_schema_by_id(table.database_id, table.schema_id)?;
957    let Some(incoming_sinks) = schema.table_incoming_sinks(table.id) else {
958        return Ok(vec![]);
959    };
960    let mut sinks = vec![];
961    for sink_id in incoming_sinks {
962        sinks.push(
963            schema
964                .get_sink_by_id(*sink_id)
965                .expect("should exist")
966                .clone(),
967        );
968    }
969    Ok(sinks)
970}
971
972fn derive_sink_to_table_expr(
973    sink_schema: &Schema,
974    idx: usize,
975    target_type: &DataType,
976) -> Result<ExprImpl> {
977    let input_type = &sink_schema.fields()[idx].data_type;
978
979    if !target_type.equals_datatype(input_type) {
980        bail!(
981            "column type mismatch: {:?} vs {:?}, column name: {:?}",
982            target_type,
983            input_type,
984            sink_schema.fields()[idx].name
985        );
986    } else {
987        Ok(ExprImpl::InputRef(Box::new(InputRef::new(
988            idx,
989            input_type.clone(),
990        ))))
991    }
992}
993
994pub(crate) fn derive_default_column_project_for_sink(
995    sink: &SinkCatalog,
996    sink_schema: &Schema,
997    columns: &[ColumnCatalog],
998    user_specified_columns: bool,
999) -> Result<Vec<ExprImpl>> {
1000    assert_eq!(sink.full_schema().len(), sink_schema.len());
1001
1002    let default_column_exprs = TableCatalog::default_column_exprs(columns);
1003
1004    let mut exprs = vec![];
1005
1006    let sink_visible_col_idxes = sink
1007        .full_columns()
1008        .iter()
1009        .positions(|c| !c.is_hidden())
1010        .collect_vec();
1011    let sink_visible_col_idxes_by_name = sink
1012        .full_columns()
1013        .iter()
1014        .enumerate()
1015        .filter(|(_, c)| !c.is_hidden())
1016        .map(|(i, c)| (c.name(), i))
1017        .collect::<BTreeMap<_, _>>();
1018
1019    // Without a column list, the sink's columns go to the table's DML columns by position, skipping
1020    // generated columns.
1021    let mut dml_idx = 0;
1022    for (idx, column) in columns.iter().enumerate() {
1023        if !column.can_dml() {
1024            continue;
1025        }
1026        let sink_col_pos = dml_idx;
1027        dml_idx += 1;
1028
1029        let default_col_expr =
1030            || -> ExprImpl { rewrite_now_to_proctime(default_column_exprs[idx].clone()) };
1031
1032        let sink_col_expr = |sink_col_idx: usize| -> Result<ExprImpl> {
1033            derive_sink_to_table_expr(sink_schema, sink_col_idx, column.data_type())
1034        };
1035
1036        // If users specified the columns to be inserted e.g. `CREATE SINK s INTO t(a, b)`, the expressions of `Project` will be generated accordingly.
1037        // The missing columns will be filled with default value (`null` if not explicitly defined).
1038        // Otherwise, e.g. `CREATE SINK s INTO t`, the columns will be matched by their order in `select` query and the target table.
1039        if user_specified_columns {
1040            if let Some(idx) = sink_visible_col_idxes_by_name.get(column.name()) {
1041                exprs.push(sink_col_expr(*idx)?);
1042            } else {
1043                exprs.push(default_col_expr());
1044            }
1045        } else {
1046            if sink_col_pos < sink_visible_col_idxes.len() {
1047                exprs.push(sink_col_expr(sink_visible_col_idxes[sink_col_pos])?);
1048            } else {
1049                exprs.push(default_col_expr());
1050            };
1051        }
1052    }
1053    Ok(exprs)
1054}
1055
1056/// Transforms the (format, encode, options) from sqlparser AST into an internal struct `SinkFormatDesc`.
1057/// This is an analogy to (part of) [`crate::handler::create_source::bind_columns_from_source`]
1058/// which transforms sqlparser AST `SourceSchemaV2` into `StreamSourceInfo`.
1059fn bind_sink_format_desc(
1060    session: &SessionImpl,
1061    value: FormatEncodeOptions,
1062) -> Result<SinkFormatDesc> {
1063    use risingwave_connector::sink::catalog::{SinkEncode, SinkFormat};
1064    use risingwave_connector::sink::encoder::TimestamptzHandlingMode;
1065    use risingwave_sqlparser::ast::{Encode as E, Format as F};
1066
1067    let format = match value.format {
1068        F::Plain => SinkFormat::AppendOnly,
1069        F::Upsert => SinkFormat::Upsert,
1070        F::Debezium => SinkFormat::Debezium,
1071        f @ (F::Native | F::DebeziumMongo | F::Maxwell | F::Canal | F::None) => {
1072            return Err(ErrorCode::BindError(format!("sink format unsupported: {f}")).into());
1073        }
1074    };
1075    let encode = match value.row_encode {
1076        E::Json => SinkEncode::Json,
1077        E::Protobuf => SinkEncode::Protobuf,
1078        E::Avro => SinkEncode::Avro,
1079        E::Template => SinkEncode::Template,
1080        E::Parquet => SinkEncode::Parquet,
1081        E::Bytes => SinkEncode::Bytes,
1082        e @ (E::Native | E::Csv | E::None | E::Text) => {
1083            return Err(ErrorCode::BindError(format!("sink encode unsupported: {e}")).into());
1084        }
1085    };
1086
1087    let mut key_encode = None;
1088    if let Some(encode) = value.key_encode {
1089        match encode {
1090            E::Text => key_encode = Some(SinkEncode::Text),
1091            E::Bytes => key_encode = Some(SinkEncode::Bytes),
1092            _ => {
1093                return Err(ErrorCode::BindError(format!(
1094                    "sink key encode unsupported: {encode}, only TEXT and BYTES supported"
1095                ))
1096                .into());
1097            }
1098        }
1099    }
1100
1101    let (props, connection_type_flag, schema_registry_conn_ref) =
1102        resolve_connection_ref_and_secret_ref(
1103            WithOptions::try_from(value.row_options.as_slice())?,
1104            session,
1105            Some(TelemetryDatabaseObject::Sink),
1106        )?;
1107    ensure_connection_type_allowed(
1108        connection_type_flag,
1109        &SINK_ALLOWED_CONNECTION_SCHEMA_REGISTRY,
1110    )?;
1111    let (mut options, secret_refs) = props.into_parts();
1112
1113    options
1114        .entry(TimestamptzHandlingMode::OPTION_KEY.to_owned())
1115        .or_insert(TimestamptzHandlingMode::FRONTEND_DEFAULT.to_owned());
1116
1117    Ok(SinkFormatDesc {
1118        format,
1119        encode,
1120        options,
1121        secret_refs,
1122        key_encode,
1123        connection_id: schema_registry_conn_ref,
1124    })
1125}
1126
1127static CONNECTORS_COMPATIBLE_FORMATS: LazyLock<HashMap<String, HashMap<Format, Vec<Encode>>>> =
1128    LazyLock::new(|| {
1129        use risingwave_connector::sink::Sink as _;
1130        use risingwave_connector::sink::file_sink::azblob::AzblobSink;
1131        use risingwave_connector::sink::file_sink::fs::FsSink;
1132        use risingwave_connector::sink::file_sink::gcs::GcsSink;
1133        use risingwave_connector::sink::file_sink::opendal_sink::FileSink;
1134        use risingwave_connector::sink::file_sink::s3::S3Sink;
1135        use risingwave_connector::sink::file_sink::webhdfs::WebhdfsSink;
1136        use risingwave_connector::sink::google_pubsub::GooglePubSubSink;
1137        use risingwave_connector::sink::kafka::KafkaSink;
1138        use risingwave_connector::sink::kinesis::KinesisSink;
1139        use risingwave_connector::sink::mqtt::MqttSink;
1140        use risingwave_connector::sink::pulsar::PulsarSink;
1141        use risingwave_connector::sink::redis::RedisSink;
1142
1143        convert_args!(hashmap!(
1144                GooglePubSubSink::SINK_NAME => hashmap!(
1145                    Format::Plain => vec![Encode::Json],
1146                ),
1147                KafkaSink::SINK_NAME => hashmap!(
1148                    Format::Plain => vec![Encode::Json, Encode::Avro, Encode::Protobuf, Encode::Bytes],
1149                    Format::Upsert => vec![Encode::Json, Encode::Avro, Encode::Protobuf],
1150                    Format::Debezium => vec![Encode::Json],
1151                ),
1152                FileSink::<S3Sink>::SINK_NAME => hashmap!(
1153                    Format::Plain => vec![Encode::Parquet, Encode::Json],
1154                ),
1155                FileSink::<SnowflakeSink>::SINK_NAME => hashmap!(
1156                    Format::Plain => vec![Encode::Parquet, Encode::Json],
1157                ),
1158                FileSink::<GcsSink>::SINK_NAME => hashmap!(
1159                    Format::Plain => vec![Encode::Parquet, Encode::Json],
1160                ),
1161                FileSink::<AzblobSink>::SINK_NAME => hashmap!(
1162                    Format::Plain => vec![Encode::Parquet, Encode::Json],
1163                ),
1164                FileSink::<WebhdfsSink>::SINK_NAME => hashmap!(
1165                    Format::Plain => vec![Encode::Parquet, Encode::Json],
1166                ),
1167                FileSink::<FsSink>::SINK_NAME => hashmap!(
1168                    Format::Plain => vec![Encode::Parquet, Encode::Json],
1169                ),
1170                KinesisSink::SINK_NAME => hashmap!(
1171                    Format::Plain => vec![Encode::Json],
1172                    Format::Upsert => vec![Encode::Json],
1173                    Format::Debezium => vec![Encode::Json],
1174                ),
1175                MqttSink::SINK_NAME => hashmap!(
1176                    Format::Plain => vec![Encode::Json, Encode::Protobuf],
1177                ),
1178                PulsarSink::SINK_NAME => hashmap!(
1179                    Format::Plain => vec![Encode::Json],
1180                    Format::Upsert => vec![Encode::Json],
1181                    Format::Debezium => vec![Encode::Json],
1182                ),
1183                RedisSink::SINK_NAME => hashmap!(
1184                    Format::Plain => vec![Encode::Json, Encode::Template],
1185                    Format::Upsert => vec![Encode::Json, Encode::Template],
1186                ),
1187        ))
1188    });
1189
1190pub fn validate_compatibility(connector: &str, format_desc: &FormatEncodeOptions) -> Result<()> {
1191    let compatible_formats = CONNECTORS_COMPATIBLE_FORMATS
1192        .get(connector)
1193        .ok_or_else(|| {
1194            ErrorCode::BindError(format!(
1195                "connector {} is not supported by FORMAT ... ENCODE ... syntax",
1196                connector
1197            ))
1198        })?;
1199    let compatible_encodes = compatible_formats.get(&format_desc.format).ok_or_else(|| {
1200        ErrorCode::BindError(format!(
1201            "connector {} does not support format {:?}",
1202            connector, format_desc.format
1203        ))
1204    })?;
1205    if !compatible_encodes.contains(&format_desc.row_encode) {
1206        return Err(ErrorCode::BindError(format!(
1207            "connector {} does not support format {:?} with encode {:?}",
1208            connector, format_desc.format, format_desc.row_encode
1209        ))
1210        .into());
1211    }
1212
1213    // only allow Kafka connector work with `bytes` as key encode
1214    if let Some(encode) = &format_desc.key_encode
1215        && connector != KAFKA_SINK
1216        && matches!(encode, Encode::Bytes)
1217    {
1218        return Err(ErrorCode::BindError(format!(
1219            "key encode bytes only works with kafka connector, but found {}",
1220            connector
1221        ))
1222        .into());
1223    }
1224
1225    Ok(())
1226}
1227
1228#[cfg(test)]
1229pub mod tests {
1230    use std::collections::BTreeMap;
1231
1232    use risingwave_common::catalog::{CreateType, DEFAULT_DATABASE_NAME, DEFAULT_SCHEMA_NAME};
1233    use risingwave_common::config::FrontendConfig;
1234    use risingwave_connector::sink::Sink;
1235    use risingwave_connector::sink::snowflake_redshift::redshift::RedshiftSink;
1236    use risingwave_connector::sink::snowflake_redshift::snowflake::SnowflakeV2Sink;
1237    use risingwave_connector::{
1238        SINK_CREATE_TABLE_IF_NOT_EXISTS_KEY, SINK_INTERMEDIATE_TABLE_NAME, SINK_TARGET_TABLE_NAME,
1239    };
1240
1241    use crate::WithOptionsSecResolved;
1242    use crate::catalog::root_catalog::SchemaPath;
1243    use crate::handler::create_sink::maybe_fill_intermediate_table_name;
1244    use crate::test_utils::{LocalFrontend, PROTO_FILE_DATA, create_proto_file};
1245
1246    #[test]
1247    fn test_fill_intermediate_table_name_for_upsert_auto_create_only() {
1248        for (connector, sink_type, create_table, should_fill) in [
1249            (SnowflakeV2Sink::SINK_NAME, "append-only", false, false),
1250            (SnowflakeV2Sink::SINK_NAME, "append-only", true, false),
1251            (SnowflakeV2Sink::SINK_NAME, "upsert", false, false),
1252            (SnowflakeV2Sink::SINK_NAME, "upsert", true, true),
1253            (RedshiftSink::SINK_NAME, "upsert", true, true),
1254            ("jdbc", "upsert", true, false),
1255        ] {
1256            let mut options = WithOptionsSecResolved::without_secrets(BTreeMap::from([
1257                ("type".to_owned(), sink_type.to_owned()),
1258                (
1259                    SINK_CREATE_TABLE_IF_NOT_EXISTS_KEY.to_owned(),
1260                    create_table.to_string(),
1261                ),
1262                (SINK_TARGET_TABLE_NAME.to_owned(), "target".to_owned()),
1263            ]));
1264
1265            maybe_fill_intermediate_table_name(&mut options, connector, "sink").unwrap();
1266
1267            assert_eq!(
1268                options.contains_key(SINK_INTERMEDIATE_TABLE_NAME),
1269                should_fill,
1270                "connector={connector}, type={sink_type}, create_table={create_table}"
1271            );
1272        }
1273    }
1274
1275    #[test]
1276    fn test_fill_intermediate_table_name_preserves_user_value() {
1277        let mut options = WithOptionsSecResolved::without_secrets(BTreeMap::from([
1278            ("type".to_owned(), "upsert".to_owned()),
1279            (
1280                SINK_CREATE_TABLE_IF_NOT_EXISTS_KEY.to_owned(),
1281                "true".to_owned(),
1282            ),
1283            (SINK_TARGET_TABLE_NAME.to_owned(), "target".to_owned()),
1284            (
1285                SINK_INTERMEDIATE_TABLE_NAME.to_owned(),
1286                "custom_cdc".to_owned(),
1287            ),
1288        ]));
1289
1290        maybe_fill_intermediate_table_name(&mut options, SnowflakeV2Sink::SINK_NAME, "sink")
1291            .unwrap();
1292
1293        assert_eq!(
1294            options.get(SINK_INTERMEDIATE_TABLE_NAME).unwrap(),
1295            "custom_cdc"
1296        );
1297    }
1298
1299    #[tokio::test]
1300    async fn test_create_sink_handler() {
1301        let proto_file = create_proto_file(PROTO_FILE_DATA);
1302        let sql = format!(
1303            r#"CREATE SOURCE t1
1304    WITH (connector = 'kafka', kafka.topic = 'abc', kafka.brokers = 'localhost:1001')
1305    FORMAT PLAIN ENCODE PROTOBUF (message = '.test.TestRecord', schema.location = 'file://{}')"#,
1306            proto_file.path().to_str().unwrap()
1307        );
1308        let frontend = LocalFrontend::new(Default::default()).await;
1309        frontend.run_sql(sql).await.unwrap();
1310
1311        let sql = "create materialized view mv1 as select t1.country from t1;";
1312        frontend.run_sql(sql).await.unwrap();
1313
1314        let sql = r#"CREATE SINK snk1 FROM mv1
1315                    WITH (connector = 'jdbc', mysql.endpoint = '127.0.0.1:3306', mysql.table =
1316                        '<table_name>', mysql.database = '<database_name>', mysql.user = '<user_name>',
1317                        mysql.password = '<password>', type = 'append-only', force_append_only = 'true');"#.to_owned();
1318        frontend.run_sql(sql).await.unwrap();
1319
1320        let session = frontend.session_ref();
1321        let catalog_reader = session.env().catalog_reader().read_guard();
1322        let schema_path = SchemaPath::Name(DEFAULT_SCHEMA_NAME);
1323
1324        // Check source exists.
1325        let (source, _) = catalog_reader
1326            .get_source_by_name(DEFAULT_DATABASE_NAME, schema_path, "t1")
1327            .unwrap();
1328        assert_eq!(source.name, "t1");
1329
1330        // Check table exists.
1331        let (table, schema_name) = catalog_reader
1332            .get_created_table_by_name(DEFAULT_DATABASE_NAME, schema_path, "mv1")
1333            .unwrap();
1334        assert_eq!(table.name(), "mv1");
1335        let schema_name = schema_name.to_owned();
1336
1337        // Check sink exists.
1338        let (sink, _) = catalog_reader
1339            .get_created_sink_by_name(
1340                DEFAULT_DATABASE_NAME,
1341                SchemaPath::Name(&schema_name),
1342                "snk1",
1343            )
1344            .unwrap();
1345        assert_eq!(sink.name, "snk1");
1346        drop(catalog_reader);
1347
1348        let sql = r#"REPLACE SINK snk1 FROM mv1
1349                    WITH (connector = 'jdbc', mysql.endpoint = '127.0.0.1:3306', mysql.table =
1350                        '<table_name>', mysql.database = '<database_name>', mysql.user = '<user_name>',
1351                        mysql.password = '<password>', type = 'append-only', force_append_only = 'true');"#.to_owned();
1352        frontend.run_sql(sql).await.unwrap();
1353
1354        let catalog_reader = session.env().catalog_reader().read_guard();
1355        let (sink, _) = catalog_reader
1356            .get_created_sink_by_name(
1357                DEFAULT_DATABASE_NAME,
1358                SchemaPath::Name(&schema_name),
1359                "snk1",
1360            )
1361            .unwrap();
1362        assert_eq!(sink.name, "snk1");
1363        // Frontend leaves the replacement job foreground for the meta foreground wait path.
1364        // Meta switches it to background when marking the job Creating during cutover.
1365        assert_eq!(sink.create_type, CreateType::Foreground);
1366
1367        let sql = r#"REPLACE SINK snk1 FROM mv1
1368                    WITH (connector = 'iceberg', type = 'upsert', enable_pk_index = 'true');"#
1369            .to_owned();
1370        let err = frontend.run_sql(sql).await.unwrap_err();
1371        assert!(
1372            err.to_string().contains(
1373                "REPLACE SINK does not support Iceberg sinks with `enable_pk_index='true'`"
1374            ),
1375            "{err:?}"
1376        );
1377    }
1378
1379    #[tokio::test]
1380    async fn test_create_fs_sink_requires_frontend_config() {
1381        let frontend = LocalFrontend::with_frontend_config(
1382            Default::default(),
1383            FrontendConfig {
1384                unsafe_enable_local_fs_connector: false,
1385                ..Default::default()
1386            },
1387        )
1388        .await;
1389        frontend.run_sql("CREATE TABLE t(v int);").await.unwrap();
1390        frontend
1391            .run_sql("CREATE MATERIALIZED VIEW mv AS SELECT * FROM t;")
1392            .await
1393            .unwrap();
1394
1395        let err = frontend
1396            .run_sql(
1397                r#"CREATE SINK local_sink FROM mv
1398                    WITH (
1399                        connector = 'fs',
1400                        fs.path = '/tmp/rw-local-sink',
1401                        type = 'append-only',
1402                        force_append_only = 'true'
1403                    ) FORMAT PLAIN ENCODE JSON (force_append_only = 'true');"#
1404                    .to_owned(),
1405            )
1406            .await
1407            .unwrap_err();
1408
1409        assert!(
1410            err.to_string()
1411                .contains("frontend.unsafe_enable_local_fs_connector = true"),
1412            "{err:?}"
1413        );
1414    }
1415}