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