Skip to main content

risingwave_connector/sink/formatter/
mod.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use anyhow::{Context, anyhow};
16use risingwave_common::array::StreamChunk;
17use risingwave_common::catalog::Field;
18
19use crate::sink::redis::REDIS_VALUE_TYPE_STREAM;
20use crate::sink::{Result, SinkError};
21
22mod append_only;
23mod debezium_json;
24mod upsert;
25
26pub use append_only::AppendOnlyFormatter;
27pub use debezium_json::{DebeziumAdapterOpts, DebeziumJsonFormatter};
28use risingwave_common::catalog::Schema;
29use risingwave_common::types::DataType;
30pub use upsert::UpsertFormatter;
31
32use super::catalog::{SinkEncode, SinkFormat, SinkFormatDesc};
33use super::encoder::bytes::BytesEncoder;
34use super::encoder::template::TemplateEncoder;
35use super::encoder::text::TextEncoder;
36use super::encoder::{
37    DateHandlingMode, JsonbHandlingMode, KafkaConnectParams, TimeHandlingMode,
38    TimestamptzHandlingMode,
39};
40use super::redis::{
41    CHANNEL, CHANNEL_COLUMN, KEY_FORMAT, LAT_NAME, LON_NAME, MEMBER_NAME, REDIS_VALUE_TYPE,
42    REDIS_VALUE_TYPE_GEO, REDIS_VALUE_TYPE_PUBSUB, REDIS_VALUE_TYPE_STRING, STREAM, STREAM_COLUMN,
43    VALUE_FORMAT,
44};
45use crate::sink::encoder::{
46    AvroEncoder, AvroHeader, JsonEncoder, ProtoEncoder, ProtoHeader, TimestampHandlingMode,
47};
48
49/// Transforms a `StreamChunk` into a sequence of key-value pairs according a specific format,
50/// for example append-only, upsert or debezium.
51pub trait SinkFormatter {
52    type K;
53    type V;
54
55    /// * Key may be None so that messages are partitioned using round-robin.
56    ///   For example append-only without `primary_key` (aka `downstream_pk`) set.
57    /// * Value may be None so that messages with same key are removed during log compaction.
58    ///   For example debezium tombstone event.
59    #[expect(clippy::type_complexity)]
60    fn format_chunk(
61        &self,
62        chunk: &StreamChunk,
63    ) -> impl Iterator<Item = Result<(Option<Self::K>, Option<Self::V>)>>;
64}
65
66/// `tri!` in generators yield `Err` and return `()`
67/// `?` in generators return `Err`
68#[macro_export]
69macro_rules! tri {
70    ($expr:expr) => {
71        match $expr {
72            Ok(val) => val,
73            Err(err) => {
74                yield Err(err);
75                return;
76            }
77        }
78    };
79}
80
81pub enum SinkFormatterImpl {
82    // append-only
83    AppendOnlyJson(AppendOnlyFormatter<JsonEncoder, JsonEncoder>),
84    AppendOnlyTextJson(AppendOnlyFormatter<TextEncoder, JsonEncoder>),
85    AppendOnlyBytesJson(AppendOnlyFormatter<BytesEncoder, JsonEncoder>),
86    AppendOnlyAvro(AppendOnlyFormatter<AvroEncoder, AvroEncoder>),
87    AppendOnlyTextAvro(AppendOnlyFormatter<TextEncoder, AvroEncoder>),
88    AppendOnlyBytesAvro(AppendOnlyFormatter<BytesEncoder, AvroEncoder>),
89    AppendOnlyProto(AppendOnlyFormatter<JsonEncoder, ProtoEncoder>),
90    AppendOnlyTextProto(AppendOnlyFormatter<TextEncoder, ProtoEncoder>),
91    AppendOnlyBytesProto(AppendOnlyFormatter<BytesEncoder, ProtoEncoder>),
92    AppendOnlyTemplate(AppendOnlyFormatter<TemplateEncoder, TemplateEncoder>),
93    AppendOnlyTextTemplate(AppendOnlyFormatter<TextEncoder, TemplateEncoder>),
94    AppendOnlyBytesTemplate(AppendOnlyFormatter<BytesEncoder, TemplateEncoder>),
95    AppendOnlyBytes(AppendOnlyFormatter<BytesEncoder, BytesEncoder>),
96    // upsert
97    UpsertJson(UpsertFormatter<JsonEncoder, JsonEncoder>),
98    UpsertTextJson(UpsertFormatter<TextEncoder, JsonEncoder>),
99    UpsertBytesJson(UpsertFormatter<BytesEncoder, JsonEncoder>),
100    UpsertAvro(UpsertFormatter<AvroEncoder, AvroEncoder>),
101    UpsertTextAvro(UpsertFormatter<TextEncoder, AvroEncoder>),
102    UpsertBytesAvro(UpsertFormatter<BytesEncoder, AvroEncoder>),
103    // `UpsertFormatter<ProtoEncoder, ProtoEncoder>` is intentionally left out
104    // to avoid using `ProtoEncoder` as key:
105    // <https://docs.confluent.io/platform/7.7/control-center/topics/schema.html#c3-schemas-best-practices-key-value-pairs>
106    UpsertTextProto(UpsertFormatter<TextEncoder, ProtoEncoder>),
107    UpsertBytesProto(UpsertFormatter<BytesEncoder, ProtoEncoder>),
108    UpsertTemplate(UpsertFormatter<TemplateEncoder, TemplateEncoder>),
109    UpsertTextTemplate(UpsertFormatter<TextEncoder, TemplateEncoder>),
110    UpsertBytesTemplate(UpsertFormatter<BytesEncoder, TemplateEncoder>),
111    // debezium
112    DebeziumJson(DebeziumJsonFormatter),
113}
114
115#[derive(Debug, Clone)]
116pub struct EncoderParams<'a> {
117    format_desc: &'a SinkFormatDesc,
118    schema: Schema,
119    db_name: String,
120    sink_from_name: String,
121    topic: &'a str,
122}
123
124/// Each encoder shall be able to be built from parameters.
125///
126/// This is not part of `RowEncoder` trait, because that one is about how an encoder completes its
127/// own job as a self-contained unit, with a custom `new` asking for only necessary info; while this
128/// one is about how different encoders can be selected from a common SQL interface.
129pub trait EncoderBuild: Sized {
130    /// Pass `pk_indices: None` for value/payload and `Some` for key. Certain encoder builds
131    /// differently when used as key vs value.
132    async fn build(params: EncoderParams<'_>, pk_indices: Option<Vec<usize>>) -> Result<Self>;
133}
134
135impl EncoderBuild for JsonEncoder {
136    async fn build(b: EncoderParams<'_>, pk_indices: Option<Vec<usize>>) -> Result<Self> {
137        let date_mode = DateHandlingMode::from_options(&b.format_desc.options)?;
138        let timestamptz_mode = TimestamptzHandlingMode::from_options(&b.format_desc.options)?;
139        let jsonb_handling_mode = JsonbHandlingMode::from_options(&b.format_desc.options)?;
140        let encoder = JsonEncoder::new(
141            b.schema,
142            pk_indices,
143            date_mode,
144            TimestampHandlingMode::Milli,
145            timestamptz_mode,
146            TimeHandlingMode::Milli,
147            jsonb_handling_mode,
148        );
149        let encoder = if let Some(s) = b.format_desc.options.get("schemas.enable") {
150            match s.to_lowercase().parse::<bool>() {
151                Ok(true) => {
152                    let kafka_connect = KafkaConnectParams {
153                        schema_name: format!("{}.{}", b.db_name, b.sink_from_name),
154                    };
155                    encoder.with_kafka_connect(kafka_connect)
156                }
157                Ok(false) => encoder,
158                _ => {
159                    return Err(SinkError::Config(anyhow!(
160                        "schemas.enable is expected to be `true` or `false`, got {s}",
161                    )));
162                }
163            }
164        } else {
165            encoder
166        };
167        Ok(encoder)
168    }
169}
170
171impl EncoderBuild for ProtoEncoder {
172    async fn build(b: EncoderParams<'_>, pk_indices: Option<Vec<usize>>) -> Result<Self> {
173        // TODO: better to be a compile-time assert
174        assert!(pk_indices.is_none());
175        // By passing `None` as `aws_auth_props`, reading from `s3://` not supported yet.
176        let (descriptor, sid) =
177            crate::schema::protobuf::fetch_descriptor(&b.format_desc.options, b.topic, None)
178                .await
179                .map_err(|e| SinkError::Config(anyhow!(e)))?;
180        let header = match sid {
181            None => ProtoHeader::None,
182            Some(sid) => ProtoHeader::ConfluentSchemaRegistry(sid),
183        };
184        ProtoEncoder::new(b.schema, None, descriptor, header)
185    }
186}
187
188fn ensure_only_one_pk<'a>(
189    data_type_name: &'a str,
190    params: &'a EncoderParams<'_>,
191    pk_indices: &'a Option<Vec<usize>>,
192) -> Result<(usize, &'a Field)> {
193    let Some(pk_indices) = pk_indices else {
194        return Err(SinkError::Config(anyhow!(
195            "{}Encoder requires primary key columns to be specified",
196            data_type_name
197        )));
198    };
199    if pk_indices.len() != 1 {
200        return Err(SinkError::Config(anyhow!(
201            "KEY ENCODE {} expects only one primary key, but got {}",
202            data_type_name,
203            pk_indices.len(),
204        )));
205    }
206
207    let schema_ref = params.schema.fields().get(pk_indices[0]).ok_or_else(|| {
208        SinkError::Config(anyhow!(
209            "The primary key column index {} is out of bounds in schema {:?}",
210            pk_indices[0],
211            params.schema
212        ))
213    })?;
214
215    Ok((pk_indices[0], schema_ref))
216}
217
218impl EncoderBuild for BytesEncoder {
219    async fn build(params: EncoderParams<'_>, pk_indices: Option<Vec<usize>>) -> Result<Self> {
220        match pk_indices {
221            // This is being used as a key encoder
222            Some(_) => {
223                let (pk_index, schema_ref) = ensure_only_one_pk("BYTES", &params, &pk_indices)?;
224                if let DataType::Bytea = schema_ref.data_type() {
225                    Ok(BytesEncoder::new(params.schema, pk_index))
226                } else {
227                    Err(SinkError::Config(anyhow!(
228                        "The key encode is BYTES, but the primary key column {} has type {}",
229                        schema_ref.name,
230                        schema_ref.data_type
231                    )))
232                }
233            }
234            // This is being used as a value encoder
235            None => {
236                // Ensure the schema has exactly one column and it's of type BYTEA
237                if params.schema.len() != 1 {
238                    return Err(SinkError::Config(anyhow!(
239                        "ENCODE BYTES requires exactly one column, got {} columns",
240                        params.schema.len()
241                    )));
242                }
243
244                let field = &params.schema.fields[0];
245                if let DataType::Bytea = field.data_type {
246                    Ok(BytesEncoder::new(params.schema, 0))
247                } else {
248                    Err(SinkError::Config(anyhow!(
249                        "ENCODE BYTES requires the column to be of type BYTEA, but got type {}",
250                        field.data_type
251                    )))
252                }
253            }
254        }
255    }
256}
257
258impl EncoderBuild for TextEncoder {
259    async fn build(params: EncoderParams<'_>, pk_indices: Option<Vec<usize>>) -> Result<Self> {
260        let (pk_index, schema_ref) = ensure_only_one_pk("TEXT", &params, &pk_indices)?;
261        match &schema_ref.data_type() {
262            DataType::Varchar
263            | DataType::Boolean
264            | DataType::Int16
265            | DataType::Int32
266            | DataType::Int64
267            | DataType::Int256
268            | DataType::Serial => {}
269            _ => {
270                // why we don't allow float as text for key encode: https://github.com/risingwavelabs/risingwave/pull/16377#discussion_r1591864960
271                return Err(SinkError::Config(anyhow!(
272                    "The key encode is TEXT, but the primary key column {} has type {}. The key encode TEXT requires the primary key column to be of type varchar, bool, small int, int, big int, serial or rw_int256.",
273                    schema_ref.name,
274                    schema_ref.data_type
275                )));
276            }
277        }
278
279        Ok(Self::new(params.schema, pk_index))
280    }
281}
282
283impl EncoderBuild for AvroEncoder {
284    async fn build(b: EncoderParams<'_>, pk_indices: Option<Vec<usize>>) -> Result<Self> {
285        use crate::schema::{SchemaLoader, SchemaVersion};
286
287        let loader = SchemaLoader::from_format_options(b.topic, &b.format_desc.options)
288            .await
289            .map_err(|e| SinkError::Config(anyhow!(e)))?;
290
291        let (schema_version, avro) = match pk_indices {
292            Some(_) => loader
293                .load_key_schema()
294                .await
295                .map_err(|e| SinkError::Config(anyhow!(e)))?,
296            None => loader
297                .load_val_schema()
298                .await
299                .map_err(|e| SinkError::Config(anyhow!(e)))?,
300        };
301        AvroEncoder::new(
302            b.schema,
303            pk_indices,
304            std::sync::Arc::new(avro),
305            match schema_version {
306                SchemaVersion::Confluent(x) => AvroHeader::ConfluentSchemaRegistry(x),
307                SchemaVersion::Glue(x) => AvroHeader::GlueSchemaRegistry(x),
308            },
309        )
310    }
311}
312
313impl EncoderBuild for TemplateEncoder {
314    async fn build(b: EncoderParams<'_>, pk_indices: Option<Vec<usize>>) -> Result<Self> {
315        let redis_value_type = b
316            .format_desc
317            .options
318            .get(REDIS_VALUE_TYPE)
319            .map_or(REDIS_VALUE_TYPE_STRING, |s| s.as_str());
320        match redis_value_type {
321            REDIS_VALUE_TYPE_STRING => {
322                let option_name = match pk_indices {
323                    Some(_) => KEY_FORMAT,
324                    None => VALUE_FORMAT,
325                };
326                let template = b.format_desc.options.get(option_name).ok_or_else(|| {
327                    SinkError::Config(anyhow!("Cannot find '{option_name}',please set it."))
328                })?;
329                Ok(TemplateEncoder::new_string(
330                    b.schema,
331                    pk_indices,
332                    template.clone(),
333                ))
334            }
335            REDIS_VALUE_TYPE_GEO => match pk_indices {
336                Some(_) => {
337                    let member_name = b.format_desc.options.get(MEMBER_NAME).ok_or_else(|| {
338                        SinkError::Config(anyhow!("Cannot find `{MEMBER_NAME}`,please set it."))
339                    })?;
340                    let template = b.format_desc.options.get(KEY_FORMAT).ok_or_else(|| {
341                        SinkError::Config(anyhow!("Cannot find `{KEY_FORMAT}`,please set it."))
342                    })?;
343                    TemplateEncoder::new_geo_key(
344                        b.schema,
345                        pk_indices,
346                        member_name,
347                        template.clone(),
348                    )
349                }
350                None => {
351                    let lat_name = b.format_desc.options.get(LAT_NAME).ok_or_else(|| {
352                        SinkError::Config(anyhow!("Cannot find `{LAT_NAME}`, please set it."))
353                    })?;
354                    let lon_name = b.format_desc.options.get(LON_NAME).ok_or_else(|| {
355                        SinkError::Config(anyhow!("Cannot find `{LON_NAME}`,please set it."))
356                    })?;
357                    TemplateEncoder::new_geo_value(b.schema, pk_indices, lat_name, lon_name)
358                }
359            },
360            REDIS_VALUE_TYPE_PUBSUB => match pk_indices {
361                Some(_) => {
362                    let channel = b.format_desc.options.get(CHANNEL).cloned();
363                    let channel_column = b.format_desc.options.get(CHANNEL_COLUMN).cloned();
364                    if (channel.is_none() && channel_column.is_none())
365                        || (channel.is_some() && channel_column.is_some())
366                    {
367                        return Err(SinkError::Config(anyhow!(
368                            "`{CHANNEL}` and `{CHANNEL_COLUMN}` only one can be set"
369                        )));
370                    }
371                    TemplateEncoder::new_pubsub_stream_key(
372                        b.schema,
373                        pk_indices,
374                        channel,
375                        channel_column,
376                    )
377                }
378                None => {
379                    let template = b.format_desc.options.get(VALUE_FORMAT).ok_or_else(|| {
380                        SinkError::Config(anyhow!("Cannot find '{VALUE_FORMAT}',please set it."))
381                    })?;
382                    Ok(TemplateEncoder::new_string(
383                        b.schema,
384                        pk_indices,
385                        template.clone(),
386                    ))
387                }
388            },
389            REDIS_VALUE_TYPE_STREAM => match pk_indices {
390                Some(_) => {
391                    let stream = b.format_desc.options.get(STREAM).cloned();
392                    let stream_column = b.format_desc.options.get(STREAM_COLUMN).cloned();
393                    if (stream.is_none() && stream_column.is_none())
394                        || (stream.is_some() && stream_column.is_some())
395                    {
396                        return Err(SinkError::Config(anyhow!(
397                            "`{STREAM}` and `{STREAM_COLUMN}` only one can be set"
398                        )));
399                    }
400                    TemplateEncoder::new_pubsub_stream_key(
401                        b.schema,
402                        pk_indices,
403                        stream,
404                        stream_column,
405                    )
406                }
407                None => {
408                    let value_template =
409                        b.format_desc.options.get(VALUE_FORMAT).ok_or_else(|| {
410                            SinkError::Config(anyhow!(
411                                "Cannot find '{VALUE_FORMAT}',please set it."
412                            ))
413                        })?;
414                    let key_template = b.format_desc.options.get(KEY_FORMAT).ok_or_else(|| {
415                        SinkError::Config(anyhow!("Cannot find '{KEY_FORMAT}',please set it."))
416                    })?;
417
418                    Ok(TemplateEncoder::new_stream_value(
419                        b.schema,
420                        pk_indices,
421                        key_template.clone(),
422                        value_template.clone(),
423                    ))
424                }
425            },
426            _ => Err(SinkError::Config(anyhow!(
427                "The value type {} is not supported",
428                redis_value_type
429            ))),
430        }
431    }
432}
433
434struct FormatterParams<'a> {
435    builder: EncoderParams<'a>,
436    pk_indices: Vec<usize>,
437}
438
439/// Each formatter shall be able to be built from parameters.
440///
441/// This is not part of `SinkFormatter` trait, because that is about how a formatter completes its
442/// own job as a self-contained unit, with a custom `new` asking for only necessary info; while this
443/// one is about how different formatters can be selected from a common SQL interface.
444trait FormatterBuild: Sized {
445    async fn build(b: FormatterParams<'_>) -> Result<Self>;
446}
447
448impl<KE: EncoderBuild, VE: EncoderBuild> FormatterBuild for AppendOnlyFormatter<KE, VE> {
449    async fn build(b: FormatterParams<'_>) -> Result<Self> {
450        let key_encoder = match b.pk_indices.is_empty() {
451            true => None,
452            false => Some(KE::build(b.builder.clone(), Some(b.pk_indices)).await?),
453        };
454        let val_encoder = VE::build(b.builder, None).await?;
455        Ok(AppendOnlyFormatter::new(key_encoder, val_encoder))
456    }
457}
458
459impl<KE: EncoderBuild, VE: EncoderBuild> FormatterBuild for UpsertFormatter<KE, VE> {
460    async fn build(b: FormatterParams<'_>) -> Result<Self> {
461        let key_encoder = KE::build(b.builder.clone(), Some(b.pk_indices))
462            .await
463            .with_context(|| "Failed to build key encoder")?;
464        let val_encoder = VE::build(b.builder, None)
465            .await
466            .with_context(|| "Failed to build value encoder")?;
467        Ok(UpsertFormatter::new(key_encoder, val_encoder))
468    }
469}
470
471impl FormatterBuild for DebeziumJsonFormatter {
472    async fn build(b: FormatterParams<'_>) -> Result<Self> {
473        assert_eq!(b.builder.format_desc.encode, SinkEncode::Json);
474
475        Ok(DebeziumJsonFormatter::new(
476            b.builder.schema,
477            b.pk_indices,
478            b.builder.db_name,
479            b.builder.sink_from_name,
480            DebeziumAdapterOpts::default(),
481        ))
482    }
483}
484
485impl SinkFormatterImpl {
486    pub async fn new(
487        format_desc: &SinkFormatDesc,
488        schema: Schema,
489        pk_indices: Vec<usize>,
490        db_name: String,
491        sink_from_name: String,
492        topic: &str,
493    ) -> Result<Self> {
494        use SinkEncode as E;
495        use SinkFormat as F;
496        use SinkFormatterImpl as Impl;
497        let p = FormatterParams {
498            builder: EncoderParams {
499                format_desc,
500                schema,
501                db_name,
502                sink_from_name,
503                topic,
504            },
505            pk_indices,
506        };
507
508        // When defining `SinkFormatterImpl` we already linked each variant (eg `AppendOnlyJson`) to
509        // an instantiation (eg `AppendOnlyFormatter<JsonEncoder, JsonEncoder>`) that implements the
510        // trait `FormatterBuild`.
511        //
512        // Here we just need to match a `(format, encode)` to a variant, and rustc shall be able to
513        // find the corresponding instantiation.
514
515        // However,
516        //   `Impl::AppendOnlyJson(FormatterBuild::build(p).await?)`
517        // fails to be inferred without the following dummy wrapper.
518        async fn build<T: FormatterBuild>(p: FormatterParams<'_>) -> Result<T> {
519            T::build(p).await
520        }
521
522        Ok(
523            match (
524                &format_desc.format,
525                &format_desc.encode,
526                &format_desc.key_encode,
527            ) {
528                (F::AppendOnly, E::Json, Some(E::Text)) => {
529                    Impl::AppendOnlyTextJson(build(p).await?)
530                }
531                (F::AppendOnly, E::Json, Some(E::Bytes)) => {
532                    Impl::AppendOnlyBytesJson(build(p).await?)
533                }
534                (F::AppendOnly, E::Json, None) => Impl::AppendOnlyJson(build(p).await?),
535                (F::AppendOnly, E::Avro, Some(E::Text)) => {
536                    Impl::AppendOnlyTextAvro(build(p).await?)
537                }
538                (F::AppendOnly, E::Avro, Some(E::Bytes)) => {
539                    Impl::AppendOnlyBytesAvro(build(p).await?)
540                }
541                (F::AppendOnly, E::Avro, None) => Impl::AppendOnlyAvro(build(p).await?),
542                (F::AppendOnly, E::Protobuf, Some(E::Text)) => {
543                    Impl::AppendOnlyTextProto(build(p).await?)
544                }
545                (F::AppendOnly, E::Protobuf, Some(E::Bytes)) => {
546                    Impl::AppendOnlyBytesProto(build(p).await?)
547                }
548                (F::AppendOnly, E::Protobuf, None) => Impl::AppendOnlyProto(build(p).await?),
549                (F::AppendOnly, E::Template, Some(E::Text)) => {
550                    Impl::AppendOnlyTextTemplate(build(p).await?)
551                }
552                (F::AppendOnly, E::Template, Some(E::Bytes)) => {
553                    Impl::AppendOnlyBytesTemplate(build(p).await?)
554                }
555                (F::AppendOnly, E::Template, None) => Impl::AppendOnlyTemplate(build(p).await?),
556                (F::AppendOnly, E::Bytes, None) => Impl::AppendOnlyBytes(build(p).await?),
557                (F::Upsert, E::Json, Some(E::Text)) => Impl::UpsertTextJson(build(p).await?),
558                (F::Upsert, E::Json, Some(E::Bytes)) => {
559                    Impl::UpsertBytesJson(build(p).await?)
560                }
561                (F::Upsert, E::Json, None) => Impl::UpsertJson(build(p).await?),
562                (F::Upsert, E::Avro, Some(E::Text)) => Impl::UpsertTextAvro(build(p).await?),
563                (F::Upsert, E::Avro, Some(E::Bytes)) => {
564                    Impl::UpsertBytesAvro(build(p).await?)
565                }
566                (F::Upsert, E::Avro, None) => Impl::UpsertAvro(build(p).await?),
567                (F::Upsert, E::Protobuf, Some(E::Text)) => Impl::UpsertTextProto(build(p).await?),
568                (F::Upsert, E::Protobuf, Some(E::Bytes)) => {
569                    Impl::UpsertBytesProto(build(p).await?)
570                }
571                (F::Upsert, E::Template, Some(E::Text)) => {
572                    Impl::UpsertTextTemplate(build(p).await?)
573                }
574                (F::Upsert, E::Template, Some(E::Bytes)) => {
575                    Impl::UpsertBytesTemplate(build(p).await?)
576                }
577                (F::Upsert, E::Template, None) => Impl::UpsertTemplate(build(p).await?),
578                (F::Debezium, E::Json, None) => Impl::DebeziumJson(build(p).await?),
579                (F::AppendOnly | F::Upsert, E::Text, _) => {
580                    return Err(SinkError::Config(anyhow!(
581                        "ENCODE TEXT is only valid as key encode."
582                    )));
583                }
584                (F::AppendOnly, E::Avro, _)
585                | (F::Upsert, E::Protobuf, _)
586                | (F::Upsert, E::Bytes, _)
587                | (F::Debezium, E::Json, Some(_))
588                | (F::Debezium, E::Avro | E::Protobuf | E::Template | E::Text | E::Bytes, _)
589                | (_, E::Parquet, _)
590                | (_, _, Some(E::Parquet))
591                | (F::AppendOnly, E::Bytes, Some(_))
592                | (F::AppendOnly | F::Upsert, _, Some(E::Template) | Some(E::Json) | Some(E::Avro) | Some(E::Protobuf)) // reject other encode as key encode
593                => {
594                    return Err(SinkError::Config(anyhow!(
595                        "sink format/encode/key_encode unsupported: {:?} {:?} {:?}",
596                        format_desc.format,
597                        format_desc.encode,
598                        format_desc.key_encode
599                    )));
600                }
601            },
602        )
603    }
604}
605
606/// Macro to dispatch formatting implementation for all supported sink formatter types.
607/// Used when the message key can be either bytes or string.
608///
609/// Takes a formatter implementation ($impl), binds it to a name ($name),
610/// and executes the provided code block ($body) with that binding.
611#[macro_export]
612macro_rules! dispatch_sink_formatter_impl {
613    ($impl:expr, $name:ident, $body:expr) => {
614        match $impl {
615            SinkFormatterImpl::AppendOnlyJson($name) => $body,
616            SinkFormatterImpl::AppendOnlyBytesJson($name) => $body,
617            SinkFormatterImpl::AppendOnlyTextJson($name) => $body,
618            SinkFormatterImpl::AppendOnlyAvro($name) => $body,
619            SinkFormatterImpl::AppendOnlyTextAvro($name) => $body,
620            SinkFormatterImpl::AppendOnlyBytesAvro($name) => $body,
621            SinkFormatterImpl::AppendOnlyProto($name) => $body,
622            SinkFormatterImpl::AppendOnlyTextProto($name) => $body,
623            SinkFormatterImpl::AppendOnlyBytesProto($name) => $body,
624
625            SinkFormatterImpl::UpsertJson($name) => $body,
626            SinkFormatterImpl::UpsertBytesJson($name) => $body,
627            SinkFormatterImpl::UpsertTextJson($name) => $body,
628            SinkFormatterImpl::UpsertAvro($name) => $body,
629            SinkFormatterImpl::UpsertTextAvro($name) => $body,
630            SinkFormatterImpl::UpsertBytesAvro($name) => $body,
631            SinkFormatterImpl::UpsertTextProto($name) => $body,
632            SinkFormatterImpl::UpsertBytesProto($name) => $body,
633            SinkFormatterImpl::DebeziumJson($name) => $body,
634            SinkFormatterImpl::AppendOnlyTextTemplate($name) => $body,
635            SinkFormatterImpl::AppendOnlyTemplate($name) => $body,
636            SinkFormatterImpl::UpsertTextTemplate($name) => $body,
637            SinkFormatterImpl::UpsertTemplate($name) => $body,
638            SinkFormatterImpl::AppendOnlyBytesTemplate($name) => $body,
639            SinkFormatterImpl::UpsertBytesTemplate($name) => $body,
640            SinkFormatterImpl::AppendOnlyBytes($name) => $body,
641        }
642    };
643}
644
645/// Macro to dispatch formatting implementation for sink formatters that require string keys.
646/// Used when the message key must be a string (excludes some Avro and bytes implementations).
647///
648/// Similar to `dispatch_sink_formatter_impl`, but excludes certain formatter types
649/// that don't support string keys (e.g., `AppendOnlyAvro`, `UpsertAvro`).
650/// These cases are marked as unreachable!() since they should never occur
651/// in contexts requiring string keys.
652#[macro_export]
653macro_rules! dispatch_sink_formatter_str_key_impl {
654    ($impl:expr, $name:ident, $body:expr $(,$attr:meta)?) => {
655        $(#[$attr])?
656        match $impl {
657            SinkFormatterImpl::AppendOnlyJson($name) => $body,
658            SinkFormatterImpl::AppendOnlyBytesJson(_) => unreachable!(),
659            SinkFormatterImpl::AppendOnlyTextJson($name) => $body,
660            SinkFormatterImpl::AppendOnlyAvro(_) => unreachable!(),
661            SinkFormatterImpl::AppendOnlyTextAvro($name) => $body,
662            SinkFormatterImpl::AppendOnlyBytesAvro(_) => unreachable!(),
663            SinkFormatterImpl::AppendOnlyProto($name) => $body,
664            SinkFormatterImpl::AppendOnlyTextProto($name) => $body,
665            SinkFormatterImpl::AppendOnlyBytesProto(_) => unreachable!(),
666
667            SinkFormatterImpl::UpsertJson($name) => $body,
668            SinkFormatterImpl::UpsertTextJson($name) => $body,
669            SinkFormatterImpl::UpsertAvro(_) => unreachable!(),
670            SinkFormatterImpl::UpsertTextAvro($name) => $body,
671            SinkFormatterImpl::UpsertBytesAvro(_) => unreachable!(),
672            SinkFormatterImpl::UpsertTextProto($name) => $body,
673            SinkFormatterImpl::UpsertBytesProto(_) => unreachable!(),
674            SinkFormatterImpl::DebeziumJson($name) => $body,
675            SinkFormatterImpl::AppendOnlyTextTemplate($name) => $body,
676            SinkFormatterImpl::AppendOnlyTemplate($name) => $body,
677            SinkFormatterImpl::UpsertTextTemplate($name) => $body,
678            SinkFormatterImpl::UpsertBytesJson(_) => unreachable!(),
679            SinkFormatterImpl::UpsertTemplate($name) => $body,
680            SinkFormatterImpl::AppendOnlyBytesTemplate(_) => unreachable!(),
681            SinkFormatterImpl::UpsertBytesTemplate(_) => unreachable!(),
682            SinkFormatterImpl::AppendOnlyBytes(_) => unreachable!(),
683        }
684    };
685}