risingwave_frontend/handler/
create_sink.rs

1// Copyright 2025 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 either::Either;
19use iceberg::arrow::type_to_arrow_type;
20use iceberg::spec::Transform;
21use itertools::Itertools;
22use maplit::{convert_args, hashmap, hashset};
23use pgwire::pg_response::{PgResponse, StatementType};
24use risingwave_common::array::arrow::IcebergArrowConvert;
25use risingwave_common::array::arrow::arrow_schema_iceberg::DataType as ArrowDataType;
26use risingwave_common::bail;
27use risingwave_common::catalog::{ColumnCatalog, ICEBERG_SINK_PREFIX, ObjectId, Schema, UserId};
28use risingwave_common::license::Feature;
29use risingwave_common::secret::LocalSecretManager;
30use risingwave_common::system_param::reader::SystemParamsRead;
31use risingwave_common::types::DataType;
32use risingwave_connector::sink::catalog::{SinkCatalog, SinkFormatDesc};
33use risingwave_connector::sink::file_sink::s3::SnowflakeSink;
34use risingwave_connector::sink::iceberg::{ICEBERG_SINK, IcebergConfig};
35use risingwave_connector::sink::kafka::KAFKA_SINK;
36use risingwave_connector::sink::snowflake_redshift::redshift::RedshiftSink;
37use risingwave_connector::sink::snowflake_redshift::snowflake::SnowflakeV2Sink;
38use risingwave_connector::sink::{
39    CONNECTOR_TYPE_KEY, SINK_SNAPSHOT_OPTION, SINK_TYPE_OPTION, SINK_USER_FORCE_APPEND_ONLY_OPTION,
40    Sink, enforce_secret_sink,
41};
42use risingwave_connector::{
43    AUTO_SCHEMA_CHANGE_KEY, SINK_CREATE_TABLE_IF_NOT_EXISTS_KEY, SINK_INTERMEDIATE_TABLE_NAME,
44    SINK_TARGET_TABLE_NAME, WithPropertiesExt,
45};
46use risingwave_pb::catalog::connection_params::PbConnectionType;
47use risingwave_pb::telemetry::TelemetryDatabaseObject;
48use risingwave_sqlparser::ast::{
49    CreateSink, CreateSinkStatement, EmitMode, Encode, ExplainOptions, Format, FormatEncodeOptions,
50    ObjectName, Query,
51};
52
53use super::RwPgResponse;
54use super::create_mv::get_column_names;
55use super::create_source::UPSTREAM_SOURCE_KEY;
56use super::util::gen_query_from_table_name;
57use crate::binder::{Binder, Relation};
58use crate::catalog::table_catalog::TableType;
59use crate::error::{ErrorCode, Result, RwError};
60use crate::expr::{ExprImpl, InputRef, rewrite_now_to_proctime};
61use crate::handler::HandlerArgs;
62use crate::handler::alter_table_column::fetch_table_catalog_for_alter;
63use crate::handler::create_mv::parse_column_names;
64use crate::handler::util::{
65    LongRunningNotificationAction, check_connector_match_connection_type,
66    ensure_connection_type_allowed, execute_with_long_running_notification,
67};
68use crate::optimizer::backfill_order_strategy::plan_backfill_order;
69use crate::optimizer::plan_node::{
70    IcebergPartitionInfo, LogicalSource, PartitionComputeInfo, StreamPlanRef as PlanRef,
71    StreamProject, generic,
72};
73use crate::optimizer::{OptimizerContext, RelationCollectorVisitor};
74use crate::scheduler::streaming_manager::CreatingStreamingJobInfo;
75use crate::session::SessionImpl;
76use crate::session::current::notice_to_user;
77use crate::stream_fragmenter::{GraphJobType, build_graph_with_strategy};
78use crate::utils::{resolve_connection_ref_and_secret_ref, resolve_privatelink_in_with_option};
79use crate::{Explain, Planner, TableCatalog, WithOptions, WithOptionsSecResolved};
80
81static SINK_ALLOWED_CONNECTION_CONNECTOR: LazyLock<HashSet<PbConnectionType>> =
82    LazyLock::new(|| {
83        hashset! {
84            PbConnectionType::Unspecified,
85            PbConnectionType::Kafka,
86            PbConnectionType::Iceberg,
87            PbConnectionType::Elasticsearch,
88        }
89    });
90
91static SINK_ALLOWED_CONNECTION_SCHEMA_REGISTRY: LazyLock<HashSet<PbConnectionType>> =
92    LazyLock::new(|| {
93        hashset! {
94            PbConnectionType::Unspecified,
95            PbConnectionType::SchemaRegistry,
96        }
97    });
98
99// used to store result of `gen_sink_plan`
100pub struct SinkPlanContext {
101    pub query: Box<Query>,
102    pub sink_plan: PlanRef,
103    pub sink_catalog: SinkCatalog,
104    pub target_table_catalog: Option<Arc<TableCatalog>>,
105    pub dependencies: HashSet<ObjectId>,
106}
107
108pub async fn gen_sink_plan(
109    handler_args: HandlerArgs,
110    stmt: CreateSinkStatement,
111    explain_options: Option<ExplainOptions>,
112    is_iceberg_engine_internal: bool,
113) -> Result<SinkPlanContext> {
114    let session = handler_args.session.clone();
115    let session = session.as_ref();
116    let user_specified_columns = !stmt.columns.is_empty();
117    let db_name = &session.database();
118    let (sink_schema_name, sink_table_name) =
119        Binder::resolve_schema_qualified_name(db_name, &stmt.sink_name)?;
120
121    let mut with_options = handler_args.with_options.clone();
122
123    if session
124        .env()
125        .system_params_manager()
126        .get_params()
127        .load()
128        .enforce_secret()
129        && Feature::SecretManagement.check_available().is_ok()
130    {
131        enforce_secret_sink(&with_options)?;
132    }
133
134    resolve_privatelink_in_with_option(&mut with_options)?;
135    let (mut resolved_with_options, connection_type, connector_conn_ref) =
136        resolve_connection_ref_and_secret_ref(
137            with_options,
138            session,
139            Some(TelemetryDatabaseObject::Sink),
140        )?;
141    ensure_connection_type_allowed(connection_type, &SINK_ALLOWED_CONNECTION_CONNECTOR)?;
142
143    // if not using connection, we don't need to check connector match connection type
144    if !matches!(connection_type, PbConnectionType::Unspecified) {
145        let Some(connector) = resolved_with_options.get_connector() else {
146            return Err(RwError::from(ErrorCode::ProtocolError(format!(
147                "missing field '{}' in WITH clause",
148                CONNECTOR_TYPE_KEY
149            ))));
150        };
151        check_connector_match_connection_type(connector.as_str(), &connection_type)?;
152    }
153
154    let partition_info = get_partition_compute_info(&resolved_with_options).await?;
155
156    let context = if let Some(explain_options) = explain_options {
157        OptimizerContext::new(handler_args.clone(), explain_options)
158    } else {
159        OptimizerContext::from_handler_args(handler_args.clone())
160    };
161
162    let is_auto_schema_change = resolved_with_options
163        .remove(AUTO_SCHEMA_CHANGE_KEY)
164        .map(|value| {
165            value.parse::<bool>().map_err(|_| {
166                ErrorCode::InvalidInputSyntax(format!(
167                    "invalid value {} of '{}' option, expect",
168                    value, AUTO_SCHEMA_CHANGE_KEY
169                ))
170            })
171        })
172        .transpose()?
173        .unwrap_or(false);
174
175    if is_auto_schema_change {
176        Feature::SinkAutoSchemaChange.check_available()?;
177    }
178
179    let sink_into_table_name = stmt.into_table_name.as_ref().map(|name| name.real_value());
180    if sink_into_table_name.is_some() {
181        let prev = resolved_with_options.insert(CONNECTOR_TYPE_KEY.to_owned(), "table".to_owned());
182
183        if prev.is_some() {
184            return Err(RwError::from(ErrorCode::BindError(
185                "In the case of sinking into table, the 'connector' parameter should not be provided.".to_owned(),
186            )));
187        }
188    }
189    let connector = resolved_with_options
190        .get(CONNECTOR_TYPE_KEY)
191        .cloned()
192        .ok_or_else(|| ErrorCode::BindError(format!("missing field '{CONNECTOR_TYPE_KEY}'")))?;
193
194    // Used for debezium's table name
195    let sink_from_table_name;
196    // `true` means that sink statement has the form: `CREATE SINK s1 FROM ...`
197    // `false` means that sink statement has the form: `CREATE SINK s1 AS <query>`
198    let direct_sink_from_name: Option<(ObjectName, bool)>;
199    let query = match stmt.sink_from {
200        CreateSink::From(from_name) => {
201            sink_from_table_name = from_name.0.last().unwrap().real_value();
202            direct_sink_from_name = Some((from_name.clone(), is_auto_schema_change));
203            if is_auto_schema_change && sink_into_table_name.is_some() {
204                return Err(RwError::from(ErrorCode::InvalidInputSyntax(
205                    "auto schema change not supported for sink-into-table".to_owned(),
206                )));
207            }
208            if resolved_with_options
209                .value_eq_ignore_case(SINK_CREATE_TABLE_IF_NOT_EXISTS_KEY, "true")
210                && connector == RedshiftSink::SINK_NAME
211                || connector == SnowflakeV2Sink::SINK_NAME
212            {
213                if let Some(table_name) = resolved_with_options.get(SINK_TARGET_TABLE_NAME) {
214                    // auto fill intermediate table name if target table name is specified
215                    if resolved_with_options
216                        .get(SINK_INTERMEDIATE_TABLE_NAME)
217                        .is_none()
218                    {
219                        // generate the intermediate table name with random value appended to the target table name
220                        let intermediate_table_name = format!(
221                            "rw_{}_{}_{}",
222                            sink_table_name,
223                            table_name,
224                            uuid::Uuid::new_v4()
225                        );
226                        resolved_with_options.insert(
227                            SINK_INTERMEDIATE_TABLE_NAME.to_owned(),
228                            intermediate_table_name,
229                        );
230                    }
231                } else {
232                    return Err(RwError::from(ErrorCode::BindError(
233                        "'table.name' option must be specified.".to_owned(),
234                    )));
235                }
236            }
237            Box::new(gen_query_from_table_name(from_name))
238        }
239        CreateSink::AsQuery(query) => {
240            if is_auto_schema_change {
241                return Err(RwError::from(ErrorCode::InvalidInputSyntax(
242                    "auto schema change not supported for CREATE SINK AS QUERY".to_owned(),
243                )));
244            }
245            sink_from_table_name = sink_table_name.clone();
246            direct_sink_from_name = None;
247            query
248        }
249    };
250
251    let (sink_database_id, sink_schema_id) =
252        session.get_database_and_schema_id_for_create(sink_schema_name.clone())?;
253
254    let (dependent_relations, dependent_udfs, bound, auto_refresh_schema_from_table) = {
255        let mut binder = Binder::new_for_stream(session);
256        let auto_refresh_schema_from_table = if let Some((from_name, true)) = &direct_sink_from_name
257        {
258            let from_relation = binder.bind_relation_by_name(from_name, None, None, true)?;
259            if let Relation::BaseTable(table) = from_relation {
260                if table.table_catalog.table_type != TableType::Table {
261                    return Err(ErrorCode::InvalidInputSyntax(format!(
262                        "auto schema change only support on TABLE, but got {:?}",
263                        table.table_catalog.table_type
264                    ))
265                    .into());
266                }
267                if table.table_catalog.database_id != sink_database_id {
268                    return Err(ErrorCode::InvalidInputSyntax(
269                        "auto schema change sink does not support created from cross database table".to_owned()
270                    )
271                        .into());
272                }
273                for col in &table.table_catalog.columns {
274                    if !col.is_hidden() && (col.is_generated() || col.is_rw_sys_column()) {
275                        return Err(ErrorCode::InvalidInputSyntax(format!("auto schema change not supported for table with non-hidden generated column or sys column, but got {}", col.name())).into());
276                    }
277                }
278                Some(table.table_catalog)
279            } else {
280                return Err(RwError::from(ErrorCode::NotSupported(
281                    "auto schema change only supported for TABLE".to_owned(),
282                    "try recreating the sink from table".to_owned(),
283                )));
284            }
285        } else {
286            None
287        };
288
289        let bound = binder.bind_query(&query)?;
290
291        (
292            binder.included_relations().clone(),
293            binder.included_udfs().clone(),
294            bound,
295            auto_refresh_schema_from_table,
296        )
297    };
298
299    let col_names = if sink_into_table_name.is_some() {
300        parse_column_names(&stmt.columns)
301    } else {
302        // If column names not specified, use the name in the bound query, which is equal with the plan root's original field name.
303        get_column_names(&bound, stmt.columns)?
304    };
305
306    let emit_on_window_close = stmt.emit_mode == Some(EmitMode::OnWindowClose);
307    if emit_on_window_close {
308        context.warn_to_user("EMIT ON WINDOW CLOSE is currently an experimental feature. Please use it with caution.");
309    }
310
311    let format_desc = match stmt.sink_schema {
312        // Case A: new syntax `format ... encode ...`
313        Some(f) => {
314            validate_compatibility(&connector, &f)?;
315            Some(bind_sink_format_desc(session,f)?)
316        }
317        None => match resolved_with_options.get(SINK_TYPE_OPTION) {
318            // Case B: old syntax `type = '...'`
319            Some(t) => SinkFormatDesc::from_legacy_type(&connector, t)?.map(|mut f| {
320                session.notice_to_user("Consider using the newer syntax `FORMAT ... ENCODE ...` instead of `type = '...'`.");
321                if let Some(v) = resolved_with_options.get(SINK_USER_FORCE_APPEND_ONLY_OPTION) {
322                    f.options.insert(SINK_USER_FORCE_APPEND_ONLY_OPTION.into(), v.into());
323                }
324                f
325            }),
326            // Case C: no format + encode required
327            None => None,
328        },
329    };
330
331    let definition = context.normalized_sql().to_owned();
332    let mut plan_root = if is_iceberg_engine_internal {
333        Planner::new_for_iceberg_table_engine_sink(context.into()).plan_query(bound)?
334    } else {
335        Planner::new_for_stream(context.into()).plan_query(bound)?
336    };
337    if let Some(col_names) = &col_names {
338        plan_root.set_out_names(col_names.clone())?;
339    };
340
341    let without_backfill = match resolved_with_options.remove(SINK_SNAPSHOT_OPTION) {
342        Some(flag) if flag.eq_ignore_ascii_case("false") => {
343            if direct_sink_from_name.is_some() || is_iceberg_engine_internal {
344                true
345            } else {
346                return Err(ErrorCode::BindError(
347                    "`snapshot = false` only support `CREATE SINK FROM MV or TABLE`".to_owned(),
348                )
349                .into());
350            }
351        }
352        _ => false,
353    };
354
355    let target_table_catalog = stmt
356        .into_table_name
357        .as_ref()
358        .map(|table_name| fetch_table_catalog_for_alter(session, table_name).map(|t| t.0))
359        .transpose()?;
360
361    if let Some(target_table_catalog) = &target_table_catalog {
362        if let Some(col_names) = col_names {
363            let target_table_columns = target_table_catalog
364                .columns()
365                .iter()
366                .map(|c| c.name())
367                .collect::<BTreeSet<_>>();
368            for c in col_names {
369                if !target_table_columns.contains(c.as_str()) {
370                    return Err(RwError::from(ErrorCode::BindError(format!(
371                        "Column {} not found in table {}",
372                        c,
373                        target_table_catalog.name()
374                    ))));
375                }
376            }
377        }
378        if target_table_catalog
379            .columns()
380            .iter()
381            .any(|col| !col.nullable())
382        {
383            notice_to_user(format!(
384                "The target table `{}` contains columns with NOT NULL constraints. Any sinked rows violating the constraints will be ignored silently.",
385                target_table_catalog.name(),
386            ));
387        }
388    }
389
390    let sink_plan = plan_root.gen_sink_plan(
391        sink_table_name,
392        definition,
393        resolved_with_options,
394        emit_on_window_close,
395        db_name.to_owned(),
396        sink_from_table_name,
397        format_desc,
398        without_backfill,
399        target_table_catalog.clone(),
400        partition_info,
401        user_specified_columns,
402        auto_refresh_schema_from_table,
403    )?;
404
405    let sink_desc = sink_plan.sink_desc().clone();
406
407    let mut sink_plan: PlanRef = sink_plan.into();
408
409    let ctx = sink_plan.ctx();
410    let explain_trace = ctx.is_explain_trace();
411    if explain_trace {
412        ctx.trace("Create Sink:");
413        ctx.trace(sink_plan.explain_to_string());
414    }
415    tracing::trace!("sink_plan: {:?}", sink_plan.explain_to_string());
416
417    // TODO(rc): To be consistent with UDF dependency check, we should collect relation dependencies
418    // during binding instead of visiting the optimized plan.
419    let dependencies =
420        RelationCollectorVisitor::collect_with(dependent_relations, sink_plan.clone())
421            .into_iter()
422            .chain(dependent_udfs.iter().copied().map_into())
423            .collect();
424
425    let sink_catalog = sink_desc.into_catalog(
426        sink_schema_id,
427        sink_database_id,
428        UserId::new(session.user_id()),
429        connector_conn_ref,
430    );
431
432    if let Some(table_catalog) = &target_table_catalog {
433        for column in sink_catalog.full_columns() {
434            if !column.can_dml() {
435                unreachable!(
436                    "can not derive generated columns and system column `_rw_timestamp` in a sink's catalog, but meet one"
437                );
438            }
439        }
440
441        let table_columns_without_rw_timestamp = table_catalog.columns_without_rw_timestamp();
442        let exprs = derive_default_column_project_for_sink(
443            &sink_catalog,
444            sink_plan.schema(),
445            &table_columns_without_rw_timestamp,
446            user_specified_columns,
447        )?;
448
449        let logical_project = generic::Project::new(exprs, sink_plan);
450
451        sink_plan = StreamProject::new(logical_project).into();
452
453        let exprs = LogicalSource::derive_output_exprs_from_generated_columns(
454            &table_columns_without_rw_timestamp,
455        )?;
456
457        if let Some(exprs) = exprs {
458            let logical_project = generic::Project::new(exprs, sink_plan);
459            sink_plan = StreamProject::new(logical_project).into();
460        }
461    };
462
463    Ok(SinkPlanContext {
464        query,
465        sink_plan,
466        sink_catalog,
467        target_table_catalog,
468        dependencies,
469    })
470}
471
472// This function is used to return partition compute info for a sink. More details refer in `PartitionComputeInfo`.
473// Return:
474// `Some(PartitionComputeInfo)` if the sink need to compute partition.
475// `None` if the sink does not need to compute partition.
476pub async fn get_partition_compute_info(
477    with_options: &WithOptionsSecResolved,
478) -> Result<Option<PartitionComputeInfo>> {
479    let (options, secret_refs) = with_options.clone().into_parts();
480    let Some(connector) = options.get(UPSTREAM_SOURCE_KEY).cloned() else {
481        return Ok(None);
482    };
483    let properties = LocalSecretManager::global().fill_secrets(options, secret_refs)?;
484    match connector.as_str() {
485        ICEBERG_SINK => {
486            let iceberg_config = IcebergConfig::from_btreemap(properties)?;
487            get_partition_compute_info_for_iceberg(&iceberg_config).await
488        }
489        _ => Ok(None),
490    }
491}
492
493#[allow(clippy::unused_async)]
494async fn get_partition_compute_info_for_iceberg(
495    _iceberg_config: &IcebergConfig,
496) -> Result<Option<PartitionComputeInfo>> {
497    // TODO: check table if exists
498    if _iceberg_config.create_table_if_not_exists {
499        return Ok(None);
500    }
501    let table = _iceberg_config.load_table().await?;
502    let partition_spec = table.metadata().default_partition_spec();
503    if partition_spec.is_unpartitioned() {
504        return Ok(None);
505    }
506
507    // Separate the partition spec into two parts: sparse partition and range partition.
508    // Sparse partition means that the data distribution is more sparse at a given time.
509    // Range partition means that the data distribution is likely same at a given time.
510    // Only compute the partition and shuffle by them for the sparse partition.
511    let has_sparse_partition = partition_spec.fields().iter().any(|f| match f.transform {
512        // Sparse partition
513        Transform::Identity | Transform::Truncate(_) | Transform::Bucket(_) => true,
514        // Range partition
515        Transform::Year
516        | Transform::Month
517        | Transform::Day
518        | Transform::Hour
519        | Transform::Void
520        | Transform::Unknown => false,
521    });
522    if !has_sparse_partition {
523        return Ok(None);
524    }
525
526    let arrow_type = type_to_arrow_type(&iceberg::spec::Type::Struct(
527        table.metadata().default_partition_type().clone(),
528    ))
529    .map_err(|_| {
530        RwError::from(ErrorCode::SinkError(
531            "Fail to convert iceberg partition type to arrow type".into(),
532        ))
533    })?;
534    let ArrowDataType::Struct(struct_fields) = arrow_type else {
535        return Err(RwError::from(ErrorCode::SinkError(
536            "Partition type of iceberg should be a struct type".into(),
537        )));
538    };
539
540    let schema = table.metadata().current_schema();
541    let partition_fields = partition_spec
542        .fields()
543        .iter()
544        .map(|f| {
545            let source_f =
546                schema
547                    .field_by_id(f.source_id)
548                    .ok_or(RwError::from(ErrorCode::SinkError(
549                        "Fail to look up iceberg partition field".into(),
550                    )))?;
551            Ok((source_f.name.clone(), f.transform))
552        })
553        .collect::<Result<Vec<_>>>()?;
554
555    Ok(Some(PartitionComputeInfo::Iceberg(IcebergPartitionInfo {
556        partition_type: IcebergArrowConvert.struct_from_fields(&struct_fields)?,
557        partition_fields,
558    })))
559}
560
561pub async fn handle_create_sink(
562    handle_args: HandlerArgs,
563    stmt: CreateSinkStatement,
564    is_iceberg_engine_internal: bool,
565) -> Result<RwPgResponse> {
566    let session = handle_args.session.clone();
567
568    session.check_cluster_limits().await?;
569
570    let if_not_exists = stmt.if_not_exists;
571    if let Either::Right(resp) = session.check_relation_name_duplicated(
572        stmt.sink_name.clone(),
573        StatementType::CREATE_SINK,
574        if_not_exists,
575    )? {
576        return Ok(resp);
577    }
578
579    if stmt.sink_name.base_name().starts_with(ICEBERG_SINK_PREFIX) {
580        return Err(RwError::from(ErrorCode::InvalidInputSyntax(format!(
581            "Sink name cannot start with reserved prefix '{}'",
582            ICEBERG_SINK_PREFIX
583        ))));
584    }
585
586    let (mut sink, graph, target_table_catalog, dependencies) = {
587        let backfill_order_strategy = handle_args.with_options.backfill_order_strategy();
588
589        let SinkPlanContext {
590            query,
591            sink_plan: plan,
592            sink_catalog: sink,
593            target_table_catalog,
594            dependencies,
595        } = gen_sink_plan(handle_args, stmt, None, is_iceberg_engine_internal).await?;
596
597        let has_order_by = !query.order_by.is_empty();
598        if has_order_by {
599            plan.ctx().warn_to_user(
600                r#"The ORDER BY clause in the CREATE SINK statement has no effect at all."#
601                    .to_owned(),
602            );
603        }
604
605        let backfill_order =
606            plan_backfill_order(session.as_ref(), backfill_order_strategy, plan.clone())?;
607
608        let graph =
609            build_graph_with_strategy(plan, Some(GraphJobType::Sink), Some(backfill_order))?;
610
611        (sink, graph, target_table_catalog, dependencies)
612    };
613
614    if let Some(table_catalog) = target_table_catalog {
615        sink.original_target_columns = table_catalog.columns_without_rw_timestamp();
616    }
617
618    let _job_guard =
619        session
620            .env()
621            .creating_streaming_job_tracker()
622            .guard(CreatingStreamingJobInfo::new(
623                session.session_id(),
624                sink.database_id,
625                sink.schema_id,
626                sink.name.clone(),
627            ));
628
629    let catalog_writer = session.catalog_writer()?;
630    execute_with_long_running_notification(
631        catalog_writer.create_sink(sink.to_proto(), graph, dependencies, if_not_exists),
632        &session,
633        "CREATE SINK",
634        LongRunningNotificationAction::MonitorBackfillJob,
635    )
636    .await?;
637
638    Ok(PgResponse::empty_result(StatementType::CREATE_SINK))
639}
640
641pub fn fetch_incoming_sinks(
642    session: &Arc<SessionImpl>,
643    table: &TableCatalog,
644) -> Result<Vec<Arc<SinkCatalog>>> {
645    let reader = session.env().catalog_reader().read_guard();
646    let schema = reader.get_schema_by_id(table.database_id, table.schema_id)?;
647    let Some(incoming_sinks) = schema.table_incoming_sinks(table.id) else {
648        return Ok(vec![]);
649    };
650    let mut sinks = vec![];
651    for sink_id in incoming_sinks {
652        sinks.push(
653            schema
654                .get_sink_by_id(*sink_id)
655                .expect("should exist")
656                .clone(),
657        );
658    }
659    Ok(sinks)
660}
661
662fn derive_sink_to_table_expr(
663    sink_schema: &Schema,
664    idx: usize,
665    target_type: &DataType,
666) -> Result<ExprImpl> {
667    let input_type = &sink_schema.fields()[idx].data_type;
668
669    if !target_type.equals_datatype(input_type) {
670        bail!(
671            "column type mismatch: {:?} vs {:?}, column name: {:?}",
672            target_type,
673            input_type,
674            sink_schema.fields()[idx].name
675        );
676    } else {
677        Ok(ExprImpl::InputRef(Box::new(InputRef::new(
678            idx,
679            input_type.clone(),
680        ))))
681    }
682}
683
684pub(crate) fn derive_default_column_project_for_sink(
685    sink: &SinkCatalog,
686    sink_schema: &Schema,
687    columns: &[ColumnCatalog],
688    user_specified_columns: bool,
689) -> Result<Vec<ExprImpl>> {
690    assert_eq!(sink.full_schema().len(), sink_schema.len());
691
692    let default_column_exprs = TableCatalog::default_column_exprs(columns);
693
694    let mut exprs = vec![];
695
696    let sink_visible_col_idxes = sink
697        .full_columns()
698        .iter()
699        .positions(|c| !c.is_hidden())
700        .collect_vec();
701    let sink_visible_col_idxes_by_name = sink
702        .full_columns()
703        .iter()
704        .enumerate()
705        .filter(|(_, c)| !c.is_hidden())
706        .map(|(i, c)| (c.name(), i))
707        .collect::<BTreeMap<_, _>>();
708
709    for (idx, column) in columns.iter().enumerate() {
710        if !column.can_dml() {
711            continue;
712        }
713
714        let default_col_expr =
715            || -> ExprImpl { rewrite_now_to_proctime(default_column_exprs[idx].clone()) };
716
717        let sink_col_expr = |sink_col_idx: usize| -> Result<ExprImpl> {
718            derive_sink_to_table_expr(sink_schema, sink_col_idx, column.data_type())
719        };
720
721        // 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.
722        // The missing columns will be filled with default value (`null` if not explicitly defined).
723        // Otherwise, e.g. `CREATE SINK s INTO t`, the columns will be matched by their order in `select` query and the target table.
724        #[allow(clippy::collapsible_else_if)]
725        if user_specified_columns {
726            if let Some(idx) = sink_visible_col_idxes_by_name.get(column.name()) {
727                exprs.push(sink_col_expr(*idx)?);
728            } else {
729                exprs.push(default_col_expr());
730            }
731        } else {
732            if idx < sink_visible_col_idxes.len() {
733                exprs.push(sink_col_expr(sink_visible_col_idxes[idx])?);
734            } else {
735                exprs.push(default_col_expr());
736            };
737        }
738    }
739    Ok(exprs)
740}
741
742/// Transforms the (format, encode, options) from sqlparser AST into an internal struct `SinkFormatDesc`.
743/// This is an analogy to (part of) [`crate::handler::create_source::bind_columns_from_source`]
744/// which transforms sqlparser AST `SourceSchemaV2` into `StreamSourceInfo`.
745fn bind_sink_format_desc(
746    session: &SessionImpl,
747    value: FormatEncodeOptions,
748) -> Result<SinkFormatDesc> {
749    use risingwave_connector::sink::catalog::{SinkEncode, SinkFormat};
750    use risingwave_connector::sink::encoder::TimestamptzHandlingMode;
751    use risingwave_sqlparser::ast::{Encode as E, Format as F};
752
753    let format = match value.format {
754        F::Plain => SinkFormat::AppendOnly,
755        F::Upsert => SinkFormat::Upsert,
756        F::Debezium => SinkFormat::Debezium,
757        f @ (F::Native | F::DebeziumMongo | F::Maxwell | F::Canal | F::None) => {
758            return Err(ErrorCode::BindError(format!("sink format unsupported: {f}")).into());
759        }
760    };
761    let encode = match value.row_encode {
762        E::Json => SinkEncode::Json,
763        E::Protobuf => SinkEncode::Protobuf,
764        E::Avro => SinkEncode::Avro,
765        E::Template => SinkEncode::Template,
766        E::Parquet => SinkEncode::Parquet,
767        E::Bytes => SinkEncode::Bytes,
768        e @ (E::Native | E::Csv | E::None | E::Text) => {
769            return Err(ErrorCode::BindError(format!("sink encode unsupported: {e}")).into());
770        }
771    };
772
773    let mut key_encode = None;
774    if let Some(encode) = value.key_encode {
775        match encode {
776            E::Text => key_encode = Some(SinkEncode::Text),
777            E::Bytes => key_encode = Some(SinkEncode::Bytes),
778            _ => {
779                return Err(ErrorCode::BindError(format!(
780                    "sink key encode unsupported: {encode}, only TEXT and BYTES supported"
781                ))
782                .into());
783            }
784        }
785    }
786
787    let (props, connection_type_flag, schema_registry_conn_ref) =
788        resolve_connection_ref_and_secret_ref(
789            WithOptions::try_from(value.row_options.as_slice())?,
790            session,
791            Some(TelemetryDatabaseObject::Sink),
792        )?;
793    ensure_connection_type_allowed(
794        connection_type_flag,
795        &SINK_ALLOWED_CONNECTION_SCHEMA_REGISTRY,
796    )?;
797    let (mut options, secret_refs) = props.into_parts();
798
799    options
800        .entry(TimestamptzHandlingMode::OPTION_KEY.to_owned())
801        .or_insert(TimestamptzHandlingMode::FRONTEND_DEFAULT.to_owned());
802
803    Ok(SinkFormatDesc {
804        format,
805        encode,
806        options,
807        secret_refs,
808        key_encode,
809        connection_id: schema_registry_conn_ref,
810    })
811}
812
813static CONNECTORS_COMPATIBLE_FORMATS: LazyLock<HashMap<String, HashMap<Format, Vec<Encode>>>> =
814    LazyLock::new(|| {
815        use risingwave_connector::sink::Sink as _;
816        use risingwave_connector::sink::file_sink::azblob::AzblobSink;
817        use risingwave_connector::sink::file_sink::fs::FsSink;
818        use risingwave_connector::sink::file_sink::gcs::GcsSink;
819        use risingwave_connector::sink::file_sink::opendal_sink::FileSink;
820        use risingwave_connector::sink::file_sink::s3::S3Sink;
821        use risingwave_connector::sink::file_sink::webhdfs::WebhdfsSink;
822        use risingwave_connector::sink::google_pubsub::GooglePubSubSink;
823        use risingwave_connector::sink::kafka::KafkaSink;
824        use risingwave_connector::sink::kinesis::KinesisSink;
825        use risingwave_connector::sink::mqtt::MqttSink;
826        use risingwave_connector::sink::pulsar::PulsarSink;
827        use risingwave_connector::sink::redis::RedisSink;
828
829        convert_args!(hashmap!(
830                GooglePubSubSink::SINK_NAME => hashmap!(
831                    Format::Plain => vec![Encode::Json],
832                ),
833                KafkaSink::SINK_NAME => hashmap!(
834                    Format::Plain => vec![Encode::Json, Encode::Avro, Encode::Protobuf, Encode::Bytes],
835                    Format::Upsert => vec![Encode::Json, Encode::Avro, Encode::Protobuf],
836                    Format::Debezium => vec![Encode::Json],
837                ),
838                FileSink::<S3Sink>::SINK_NAME => hashmap!(
839                    Format::Plain => vec![Encode::Parquet, Encode::Json],
840                ),
841                FileSink::<SnowflakeSink>::SINK_NAME => hashmap!(
842                    Format::Plain => vec![Encode::Parquet, Encode::Json],
843                ),
844                FileSink::<GcsSink>::SINK_NAME => hashmap!(
845                    Format::Plain => vec![Encode::Parquet, Encode::Json],
846                ),
847                FileSink::<AzblobSink>::SINK_NAME => hashmap!(
848                    Format::Plain => vec![Encode::Parquet, Encode::Json],
849                ),
850                FileSink::<WebhdfsSink>::SINK_NAME => hashmap!(
851                    Format::Plain => vec![Encode::Parquet, Encode::Json],
852                ),
853                FileSink::<FsSink>::SINK_NAME => hashmap!(
854                    Format::Plain => vec![Encode::Parquet, Encode::Json],
855                ),
856                KinesisSink::SINK_NAME => hashmap!(
857                    Format::Plain => vec![Encode::Json],
858                    Format::Upsert => vec![Encode::Json],
859                    Format::Debezium => vec![Encode::Json],
860                ),
861                MqttSink::SINK_NAME => hashmap!(
862                    Format::Plain => vec![Encode::Json, Encode::Protobuf],
863                ),
864                PulsarSink::SINK_NAME => hashmap!(
865                    Format::Plain => vec![Encode::Json],
866                    Format::Upsert => vec![Encode::Json],
867                    Format::Debezium => vec![Encode::Json],
868                ),
869                RedisSink::SINK_NAME => hashmap!(
870                    Format::Plain => vec![Encode::Json, Encode::Template],
871                    Format::Upsert => vec![Encode::Json, Encode::Template],
872                ),
873        ))
874    });
875
876pub fn validate_compatibility(connector: &str, format_desc: &FormatEncodeOptions) -> Result<()> {
877    let compatible_formats = CONNECTORS_COMPATIBLE_FORMATS
878        .get(connector)
879        .ok_or_else(|| {
880            ErrorCode::BindError(format!(
881                "connector {} is not supported by FORMAT ... ENCODE ... syntax",
882                connector
883            ))
884        })?;
885    let compatible_encodes = compatible_formats.get(&format_desc.format).ok_or_else(|| {
886        ErrorCode::BindError(format!(
887            "connector {} does not support format {:?}",
888            connector, format_desc.format
889        ))
890    })?;
891    if !compatible_encodes.contains(&format_desc.row_encode) {
892        return Err(ErrorCode::BindError(format!(
893            "connector {} does not support format {:?} with encode {:?}",
894            connector, format_desc.format, format_desc.row_encode
895        ))
896        .into());
897    }
898
899    // only allow Kafka connector work with `bytes` as key encode
900    if let Some(encode) = &format_desc.key_encode
901        && connector != KAFKA_SINK
902        && matches!(encode, Encode::Bytes)
903    {
904        return Err(ErrorCode::BindError(format!(
905            "key encode bytes only works with kafka connector, but found {}",
906            connector
907        ))
908        .into());
909    }
910
911    Ok(())
912}
913
914#[cfg(test)]
915pub mod tests {
916    use risingwave_common::catalog::{DEFAULT_DATABASE_NAME, DEFAULT_SCHEMA_NAME};
917
918    use crate::catalog::root_catalog::SchemaPath;
919    use crate::test_utils::{LocalFrontend, PROTO_FILE_DATA, create_proto_file};
920
921    #[tokio::test]
922    async fn test_create_sink_handler() {
923        let proto_file = create_proto_file(PROTO_FILE_DATA);
924        let sql = format!(
925            r#"CREATE SOURCE t1
926    WITH (connector = 'kafka', kafka.topic = 'abc', kafka.brokers = 'localhost:1001')
927    FORMAT PLAIN ENCODE PROTOBUF (message = '.test.TestRecord', schema.location = 'file://{}')"#,
928            proto_file.path().to_str().unwrap()
929        );
930        let frontend = LocalFrontend::new(Default::default()).await;
931        frontend.run_sql(sql).await.unwrap();
932
933        let sql = "create materialized view mv1 as select t1.country from t1;";
934        frontend.run_sql(sql).await.unwrap();
935
936        let sql = r#"CREATE SINK snk1 FROM mv1
937                    WITH (connector = 'jdbc', mysql.endpoint = '127.0.0.1:3306', mysql.table =
938                        '<table_name>', mysql.database = '<database_name>', mysql.user = '<user_name>',
939                        mysql.password = '<password>', type = 'append-only', force_append_only = 'true');"#.to_owned();
940        frontend.run_sql(sql).await.unwrap();
941
942        let session = frontend.session_ref();
943        let catalog_reader = session.env().catalog_reader().read_guard();
944        let schema_path = SchemaPath::Name(DEFAULT_SCHEMA_NAME);
945
946        // Check source exists.
947        let (source, _) = catalog_reader
948            .get_source_by_name(DEFAULT_DATABASE_NAME, schema_path, "t1")
949            .unwrap();
950        assert_eq!(source.name, "t1");
951
952        // Check table exists.
953        let (table, schema_name) = catalog_reader
954            .get_created_table_by_name(DEFAULT_DATABASE_NAME, schema_path, "mv1")
955            .unwrap();
956        assert_eq!(table.name(), "mv1");
957
958        // Check sink exists.
959        let (sink, _) = catalog_reader
960            .get_created_sink_by_name(DEFAULT_DATABASE_NAME, SchemaPath::Name(schema_name), "snk1")
961            .unwrap();
962        assert_eq!(sink.name, "snk1");
963    }
964}