-
Notifications
You must be signed in to change notification settings - Fork 591
/
create_source.rs
1821 lines (1677 loc) · 69.5 KB
/
create_source.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024 RisingWave Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
use std::sync::LazyLock;
use anyhow::{anyhow, Context};
use either::Either;
use itertools::Itertools;
use maplit::{convert_args, hashmap};
use pgwire::pg_response::{PgResponse, StatementType};
use risingwave_common::array::arrow::{FromArrow, IcebergArrowConvert};
use risingwave_common::bail_not_implemented;
use risingwave_common::catalog::{
is_column_ids_dedup, ColumnCatalog, ColumnDesc, ColumnId, Schema, TableId,
INITIAL_SOURCE_VERSION_ID, KAFKA_TIMESTAMP_COLUMN_NAME,
};
use risingwave_common::types::DataType;
use risingwave_connector::parser::additional_columns::{
build_additional_column_catalog, get_supported_additional_columns,
};
use risingwave_connector::parser::{
fetch_json_schema_and_map_to_columns, AvroParserConfig, DebeziumAvroParserConfig,
ProtobufParserConfig, SpecificParserConfig, TimestamptzHandling, DEBEZIUM_IGNORE_KEY,
};
use risingwave_connector::schema::schema_registry::{
name_strategy_from_str, SchemaRegistryAuth, SCHEMA_REGISTRY_PASSWORD, SCHEMA_REGISTRY_USERNAME,
};
use risingwave_connector::sink::iceberg::IcebergConfig;
use risingwave_connector::source::cdc::{
CDC_SHARING_MODE_KEY, CDC_SNAPSHOT_BACKFILL, CDC_SNAPSHOT_MODE_KEY, CDC_TRANSACTIONAL_KEY,
CDC_WAIT_FOR_STREAMING_START_TIMEOUT, CITUS_CDC_CONNECTOR, MONGODB_CDC_CONNECTOR,
MYSQL_CDC_CONNECTOR, POSTGRES_CDC_CONNECTOR,
};
use risingwave_connector::source::datagen::DATAGEN_CONNECTOR;
use risingwave_connector::source::iceberg::ICEBERG_CONNECTOR;
use risingwave_connector::source::nexmark::source::{get_event_data_types_with_names, EventType};
use risingwave_connector::source::test_source::TEST_CONNECTOR;
use risingwave_connector::source::{
ConnectorProperties, GCS_CONNECTOR, GOOGLE_PUBSUB_CONNECTOR, KAFKA_CONNECTOR,
KINESIS_CONNECTOR, MQTT_CONNECTOR, NATS_CONNECTOR, NEXMARK_CONNECTOR, OPENDAL_S3_CONNECTOR,
POSIX_FS_CONNECTOR, PULSAR_CONNECTOR, S3_CONNECTOR,
};
use risingwave_connector::WithPropertiesExt;
use risingwave_pb::catalog::{PbSchemaRegistryNameStrategy, StreamSourceInfo, WatermarkDesc};
use risingwave_pb::plan_common::additional_column::ColumnType as AdditionalColumnType;
use risingwave_pb::plan_common::{EncodeType, FormatType};
use risingwave_pb::stream_plan::stream_fragment_graph::Parallelism;
use risingwave_sqlparser::ast::{
get_delimiter, AstString, ColumnDef, ConnectorSchema, CreateSourceStatement, Encode, Format,
ObjectName, ProtobufSchema, SourceWatermark, TableConstraint,
};
use risingwave_sqlparser::parser::IncludeOption;
use thiserror_ext::AsReport;
use super::RwPgResponse;
use crate::binder::Binder;
use crate::catalog::source_catalog::SourceCatalog;
use crate::catalog::{DatabaseId, SchemaId};
use crate::error::ErrorCode::{self, Deprecated, InvalidInputSyntax, NotSupported, ProtocolError};
use crate::error::{Result, RwError};
use crate::expr::Expr;
use crate::handler::create_table::{
bind_pk_on_relation, bind_sql_column_constraints, bind_sql_columns, bind_sql_pk_names,
ensure_table_constraints_supported, ColumnIdGenerator,
};
use crate::handler::util::SourceSchemaCompatExt;
use crate::handler::HandlerArgs;
use crate::optimizer::plan_node::generic::SourceNodeKind;
use crate::optimizer::plan_node::{LogicalSource, ToStream, ToStreamContext};
use crate::session::SessionImpl;
use crate::utils::{resolve_privatelink_in_with_option, resolve_secret_in_with_options};
use crate::{bind_data_type, build_graph, OptimizerContext, WithOptions};
pub(crate) const UPSTREAM_SOURCE_KEY: &str = "connector";
/// Map a JSON schema to a relational schema
async fn extract_json_table_schema(
schema_config: &Option<(AstString, bool)>,
with_properties: &BTreeMap<String, String>,
format_encode_options: &mut BTreeMap<String, String>,
) -> Result<Option<Vec<ColumnCatalog>>> {
match schema_config {
None => Ok(None),
Some((schema_location, use_schema_registry)) => {
let schema_registry_auth = use_schema_registry.then(|| {
let auth = SchemaRegistryAuth::from(&*format_encode_options);
try_consume_string_from_options(format_encode_options, SCHEMA_REGISTRY_USERNAME);
try_consume_string_from_options(format_encode_options, SCHEMA_REGISTRY_PASSWORD);
auth
});
Ok(Some(
fetch_json_schema_and_map_to_columns(
&schema_location.0,
schema_registry_auth,
with_properties,
)
.await?
.into_iter()
.map(|col| ColumnCatalog {
column_desc: col.into(),
is_hidden: false,
})
.collect_vec(),
))
}
}
}
/// Note: these columns are added in `SourceStreamChunkRowWriter::do_action`.
/// May also look for the usage of `SourceColumnType`.
pub fn debezium_cdc_source_schema() -> Vec<ColumnCatalog> {
let columns = vec![
ColumnCatalog {
column_desc: ColumnDesc::named("payload", ColumnId::placeholder(), DataType::Jsonb),
is_hidden: false,
},
ColumnCatalog::offset_column(),
ColumnCatalog::cdc_table_name_column(),
];
columns
}
fn json_schema_infer_use_schema_registry(schema_config: &Option<(AstString, bool)>) -> bool {
match schema_config {
None => false,
Some((_, use_registry)) => *use_registry,
}
}
/// Map an Avro schema to a relational schema.
async fn extract_avro_table_schema(
info: &StreamSourceInfo,
with_properties: &BTreeMap<String, String>,
format_encode_options: &mut BTreeMap<String, String>,
is_debezium: bool,
) -> Result<Vec<ColumnCatalog>> {
let parser_config = SpecificParserConfig::new(info, with_properties)?;
try_consume_string_from_options(format_encode_options, SCHEMA_REGISTRY_USERNAME);
try_consume_string_from_options(format_encode_options, SCHEMA_REGISTRY_PASSWORD);
consume_aws_config_from_options(format_encode_options);
let vec_column_desc = if is_debezium {
let conf = DebeziumAvroParserConfig::new(parser_config.encoding_config).await?;
conf.map_to_columns()?
} else {
if let risingwave_connector::parser::EncodingProperties::Avro(avro_props) =
&parser_config.encoding_config
&& !avro_props.use_schema_registry
&& !format_encode_options
.get("with_deprecated_file_header")
.is_some_and(|v| v == "true")
{
bail_not_implemented!(issue = 12871, "avro without schema registry");
}
let conf = AvroParserConfig::new(parser_config.encoding_config).await?;
conf.map_to_columns()?
};
Ok(vec_column_desc
.into_iter()
.map(|col| ColumnCatalog {
column_desc: col.into(),
is_hidden: false,
})
.collect_vec())
}
async fn extract_debezium_avro_table_pk_columns(
info: &StreamSourceInfo,
with_properties: &WithOptions,
) -> Result<Vec<String>> {
let parser_config = SpecificParserConfig::new(info, with_properties)?;
let conf = DebeziumAvroParserConfig::new(parser_config.encoding_config).await?;
Ok(conf.extract_pks()?.drain(..).map(|c| c.name).collect())
}
/// Map a protobuf schema to a relational schema.
async fn extract_protobuf_table_schema(
schema: &ProtobufSchema,
with_properties: &BTreeMap<String, String>,
format_encode_options: &mut BTreeMap<String, String>,
) -> Result<Vec<ColumnCatalog>> {
let info = StreamSourceInfo {
proto_message_name: schema.message_name.0.clone(),
row_schema_location: schema.row_schema_location.0.clone(),
use_schema_registry: schema.use_schema_registry,
format: FormatType::Plain.into(),
row_encode: EncodeType::Protobuf.into(),
format_encode_options: format_encode_options.clone(),
..Default::default()
};
let parser_config = SpecificParserConfig::new(&info, with_properties)?;
try_consume_string_from_options(format_encode_options, SCHEMA_REGISTRY_USERNAME);
try_consume_string_from_options(format_encode_options, SCHEMA_REGISTRY_PASSWORD);
consume_aws_config_from_options(format_encode_options);
let conf = ProtobufParserConfig::new(parser_config.encoding_config).await?;
let column_descs = conf.map_to_columns()?;
Ok(column_descs
.into_iter()
.map(|col| ColumnCatalog {
column_desc: col.into(),
is_hidden: false,
})
.collect_vec())
}
fn non_generated_sql_columns(columns: &[ColumnDef]) -> Vec<ColumnDef> {
columns
.iter()
.filter(|c| !c.is_generated())
.cloned()
.collect()
}
fn try_consume_string_from_options(
format_encode_options: &mut BTreeMap<String, String>,
key: &str,
) -> Option<AstString> {
format_encode_options.remove(key).map(AstString)
}
fn consume_string_from_options(
format_encode_options: &mut BTreeMap<String, String>,
key: &str,
) -> Result<AstString> {
try_consume_string_from_options(format_encode_options, key).ok_or(RwError::from(ProtocolError(
format!("missing field {} in options", key),
)))
}
fn consume_aws_config_from_options(format_encode_options: &mut BTreeMap<String, String>) {
format_encode_options.retain(|key, _| !key.starts_with("aws."))
}
pub fn get_json_schema_location(
format_encode_options: &mut BTreeMap<String, String>,
) -> Result<Option<(AstString, bool)>> {
let schema_location = try_consume_string_from_options(format_encode_options, "schema.location");
let schema_registry = try_consume_string_from_options(format_encode_options, "schema.registry");
match (schema_location, schema_registry) {
(None, None) => Ok(None),
(None, Some(schema_registry)) => Ok(Some((schema_registry, true))),
(Some(schema_location), None) => Ok(Some((schema_location, false))),
(Some(_), Some(_)) => Err(RwError::from(ProtocolError(
"only need either the schema location or the schema registry".to_string(),
))),
}
}
fn get_schema_location(
format_encode_options: &mut BTreeMap<String, String>,
) -> Result<(AstString, bool)> {
let schema_location = try_consume_string_from_options(format_encode_options, "schema.location");
let schema_registry = try_consume_string_from_options(format_encode_options, "schema.registry");
match (schema_location, schema_registry) {
(None, None) => Err(RwError::from(ProtocolError(
"missing either a schema location or a schema registry".to_string(),
))),
(None, Some(schema_registry)) => Ok((schema_registry, true)),
(Some(schema_location), None) => Ok((schema_location, false)),
(Some(_), Some(_)) => Err(RwError::from(ProtocolError(
"only need either the schema location or the schema registry".to_string(),
))),
}
}
#[inline]
fn get_name_strategy_or_default(name_strategy: Option<AstString>) -> Result<Option<i32>> {
match name_strategy {
None => Ok(None),
Some(name) => Ok(Some(name_strategy_from_str(name.0.as_str())
.ok_or_else(|| RwError::from(ProtocolError(format!("\
expect strategy name in topic_name_strategy, record_name_strategy and topic_record_name_strategy, but got {}", name))))? as i32)),
}
}
/// resolve the schema of the source from external schema file, return the relation's columns. see <https://www.risingwave.dev/docs/current/sql-create-source> for more information.
/// return `(columns, source info)`
pub(crate) async fn bind_columns_from_source(
session: &SessionImpl,
source_schema: &ConnectorSchema,
with_properties: &BTreeMap<String, String>,
) -> Result<(Option<Vec<ColumnCatalog>>, StreamSourceInfo)> {
const MESSAGE_NAME_KEY: &str = "message";
const KEY_MESSAGE_NAME_KEY: &str = "key.message";
const NAME_STRATEGY_KEY: &str = "schema.registry.name.strategy";
let is_kafka: bool = with_properties.is_kafka_connector();
let format_encode_options = WithOptions::try_from(source_schema.row_options())?.into_inner();
let mut format_encode_options_to_consume = format_encode_options.clone();
fn get_key_message_name(options: &mut BTreeMap<String, String>) -> Option<String> {
consume_string_from_options(options, KEY_MESSAGE_NAME_KEY)
.map(|ele| Some(ele.0))
.unwrap_or(None)
}
fn get_sr_name_strategy_check(
options: &mut BTreeMap<String, String>,
use_sr: bool,
) -> Result<Option<i32>> {
let name_strategy = get_name_strategy_or_default(try_consume_string_from_options(
options,
NAME_STRATEGY_KEY,
))?;
if !use_sr && name_strategy.is_some() {
return Err(RwError::from(ProtocolError(
"schema registry name strategy only works with schema registry enabled".to_string(),
)));
}
Ok(name_strategy)
}
let mut stream_source_info = StreamSourceInfo {
format: format_to_prost(&source_schema.format) as i32,
row_encode: row_encode_to_prost(&source_schema.row_encode) as i32,
format_encode_options,
..Default::default()
};
if source_schema.format == Format::Debezium {
try_consume_string_from_options(&mut format_encode_options_to_consume, DEBEZIUM_IGNORE_KEY);
}
let columns = match (&source_schema.format, &source_schema.row_encode) {
(Format::Native, Encode::Native)
| (Format::Plain, Encode::Bytes)
| (Format::DebeziumMongo, Encode::Json) => None,
(Format::Plain, Encode::Protobuf) => {
let (row_schema_location, use_schema_registry) =
get_schema_location(&mut format_encode_options_to_consume)?;
let protobuf_schema = ProtobufSchema {
message_name: consume_string_from_options(
&mut format_encode_options_to_consume,
MESSAGE_NAME_KEY,
)?,
row_schema_location,
use_schema_registry,
};
let name_strategy = get_sr_name_strategy_check(
&mut format_encode_options_to_consume,
protobuf_schema.use_schema_registry,
)?;
stream_source_info.use_schema_registry = protobuf_schema.use_schema_registry;
stream_source_info
.row_schema_location
.clone_from(&protobuf_schema.row_schema_location.0);
stream_source_info
.proto_message_name
.clone_from(&protobuf_schema.message_name.0);
stream_source_info.key_message_name =
get_key_message_name(&mut format_encode_options_to_consume);
stream_source_info.name_strategy =
name_strategy.unwrap_or(PbSchemaRegistryNameStrategy::Unspecified as i32);
Some(
extract_protobuf_table_schema(
&protobuf_schema,
with_properties,
&mut format_encode_options_to_consume,
)
.await?,
)
}
(format @ (Format::Plain | Format::Upsert | Format::Debezium), Encode::Avro) => {
let (row_schema_location, use_schema_registry) =
get_schema_location(&mut format_encode_options_to_consume)?;
if matches!(format, Format::Debezium) && !use_schema_registry {
return Err(RwError::from(ProtocolError(
"schema location for DEBEZIUM_AVRO row format is not supported".to_string(),
)));
}
let message_name = try_consume_string_from_options(
&mut format_encode_options_to_consume,
MESSAGE_NAME_KEY,
);
let name_strategy = get_sr_name_strategy_check(
&mut format_encode_options_to_consume,
use_schema_registry,
)?;
stream_source_info.use_schema_registry = use_schema_registry;
stream_source_info
.row_schema_location
.clone_from(&row_schema_location.0);
stream_source_info.proto_message_name = message_name.unwrap_or(AstString("".into())).0;
stream_source_info.key_message_name =
get_key_message_name(&mut format_encode_options_to_consume);
stream_source_info.name_strategy =
name_strategy.unwrap_or(PbSchemaRegistryNameStrategy::Unspecified as i32);
Some(
extract_avro_table_schema(
&stream_source_info,
with_properties,
&mut format_encode_options_to_consume,
matches!(format, Format::Debezium),
)
.await?,
)
}
(Format::Plain, Encode::Csv) => {
let chars =
consume_string_from_options(&mut format_encode_options_to_consume, "delimiter")?.0;
let delimiter = get_delimiter(chars.as_str()).context("failed to parse delimiter")?;
let has_header = try_consume_string_from_options(
&mut format_encode_options_to_consume,
"without_header",
)
.map(|s| s.0 == "false")
.unwrap_or(true);
if is_kafka && has_header {
return Err(RwError::from(ProtocolError(
"CSV HEADER is not supported when creating table with Kafka connector"
.to_owned(),
)));
}
stream_source_info.csv_delimiter = delimiter as i32;
stream_source_info.csv_has_header = has_header;
None
}
(
Format::Plain | Format::Upsert | Format::Maxwell | Format::Canal | Format::Debezium,
Encode::Json,
) => {
if matches!(
source_schema.format,
Format::Plain | Format::Upsert | Format::Debezium
) {
// Parse the value but throw it away.
// It would be too late to report error in `SpecificParserConfig::new`,
// which leads to recovery loop.
// TODO: rely on SpecificParserConfig::new to validate, like Avro
TimestamptzHandling::from_options(&format_encode_options_to_consume)
.map_err(|err| InvalidInputSyntax(err.message))?;
try_consume_string_from_options(
&mut format_encode_options_to_consume,
TimestamptzHandling::OPTION_KEY,
);
}
let schema_config = get_json_schema_location(&mut format_encode_options_to_consume)?;
stream_source_info.use_schema_registry =
json_schema_infer_use_schema_registry(&schema_config);
extract_json_table_schema(
&schema_config,
with_properties,
&mut format_encode_options_to_consume,
)
.await?
}
(Format::None, Encode::None) => {
if with_properties.is_iceberg_connector() {
Some(
extract_iceberg_columns(with_properties)
.await
.map_err(|err| ProtocolError(err.to_report_string()))?,
)
} else {
None
}
}
(format, encoding) => {
return Err(RwError::from(ProtocolError(format!(
"Unknown combination {:?} {:?}",
format, encoding
))));
}
};
if !format_encode_options_to_consume.is_empty() {
let err_string = format!(
"Get unknown format_encode_options for {:?} {:?}: {}",
source_schema.format,
source_schema.row_encode,
format_encode_options_to_consume
.keys()
.map(|k| k.to_string())
.collect::<Vec<String>>()
.join(","),
);
session.notice_to_user(err_string);
}
Ok((columns, stream_source_info))
}
fn bind_columns_from_source_for_cdc(
session: &SessionImpl,
source_schema: &ConnectorSchema,
) -> Result<(Option<Vec<ColumnCatalog>>, StreamSourceInfo)> {
let format_encode_options = WithOptions::try_from(source_schema.row_options())?.into_inner();
let mut format_encode_options_to_consume = format_encode_options.clone();
match (&source_schema.format, &source_schema.row_encode) {
(Format::Plain, Encode::Json) => (),
(format, encoding) => {
// Note: parser will also check this. Just be extra safe here
return Err(RwError::from(ProtocolError(format!(
"Row format for CDC connectors should be either omitted or set to `FORMAT PLAIN ENCODE JSON`, got: {:?} {:?}",
format, encoding
))));
}
};
let columns = debezium_cdc_source_schema();
let schema_config = get_json_schema_location(&mut format_encode_options_to_consume)?;
let stream_source_info = StreamSourceInfo {
format: format_to_prost(&source_schema.format) as i32,
row_encode: row_encode_to_prost(&source_schema.row_encode) as i32,
format_encode_options,
use_schema_registry: json_schema_infer_use_schema_registry(&schema_config),
cdc_source_job: true,
is_distributed: false,
..Default::default()
};
if !format_encode_options_to_consume.is_empty() {
let err_string = format!(
"Get unknown format_encode_options for {:?} {:?}: {}",
source_schema.format,
source_schema.row_encode,
format_encode_options_to_consume
.keys()
.map(|k| k.to_string())
.collect::<Vec<String>>()
.join(","),
);
session.notice_to_user(err_string);
}
Ok((Some(columns), stream_source_info))
}
/// add connector-spec columns to the end of column catalog
pub fn handle_addition_columns(
with_properties: &BTreeMap<String, String>,
mut additional_columns: IncludeOption,
columns: &mut Vec<ColumnCatalog>,
is_cdc_backfill_table: bool,
) -> Result<()> {
let connector_name = with_properties.get_connector().unwrap(); // there must be a connector in source
if get_supported_additional_columns(connector_name.as_str(), is_cdc_backfill_table).is_none()
&& !additional_columns.is_empty()
{
return Err(RwError::from(ProtocolError(format!(
"Connector {} accepts no additional column but got {:?}",
connector_name, additional_columns
))));
}
let latest_col_id: ColumnId = columns
.iter()
.map(|col| col.column_desc.column_id)
.max()
.unwrap(); // there must be at least one column in the column catalog
while let Some(item) = additional_columns.pop() {
{
// only allow header column have inner field
if item.inner_field.is_some()
&& !item.column_type.real_value().eq_ignore_ascii_case("header")
{
return Err(RwError::from(ProtocolError(format!(
"Only header column can have inner field, but got {:?}",
item.column_type.real_value(),
))));
}
}
let data_type_name: Option<String> = item
.header_inner_expect_type
.map(|dt| format!("{:?}", dt).to_lowercase());
columns.push(build_additional_column_catalog(
latest_col_id.next(),
connector_name.as_str(),
item.column_type.real_value().as_str(),
item.column_alias.map(|alias| alias.real_value()),
item.inner_field.as_deref(),
data_type_name.as_deref(),
true,
is_cdc_backfill_table,
)?);
}
Ok(())
}
/// Bind columns from both source and sql defined.
pub(crate) fn bind_all_columns(
source_schema: &ConnectorSchema,
cols_from_source: Option<Vec<ColumnCatalog>>,
cols_from_sql: Vec<ColumnCatalog>,
col_defs_from_sql: &[ColumnDef],
wildcard_idx: Option<usize>,
) -> Result<Vec<ColumnCatalog>> {
if let Some(cols_from_source) = cols_from_source {
if cols_from_sql.is_empty() {
Ok(cols_from_source)
} else if let Some(wildcard_idx) = wildcard_idx {
if col_defs_from_sql.iter().any(|c| !c.is_generated()) {
Err(RwError::from(NotSupported(
"Only generated columns are allowed in user-defined schema from SQL"
.to_string(),
"Remove the non-generated columns".to_string(),
)))
} else {
// Replace `*` with `cols_from_source`
let mut cols_from_sql = cols_from_sql;
let mut cols_from_source = cols_from_source;
let mut cols_from_sql_r = cols_from_sql.split_off(wildcard_idx);
cols_from_sql.append(&mut cols_from_source);
cols_from_sql.append(&mut cols_from_sql_r);
Ok(cols_from_sql)
}
} else {
// TODO(yuhao): https://github.com/risingwavelabs/risingwave/issues/12209
Err(RwError::from(ProtocolError(
format!("User-defined schema from SQL is not allowed with FORMAT {} ENCODE {}. \
Please refer to https://www.risingwave.dev/docs/current/sql-create-source/ for more information.", source_schema.format, source_schema.row_encode))))
}
} else {
if wildcard_idx.is_some() {
return Err(RwError::from(NotSupported(
"Wildcard in user-defined schema is only allowed when there exists columns from external schema".to_string(),
"Remove the wildcard or use a source with external schema".to_string(),
)));
}
// FIXME(yuhao): cols_from_sql should be None is no `()` is given.
if cols_from_sql.is_empty() {
return Err(RwError::from(ProtocolError(
"Schema definition is required, either from SQL or schema registry.".to_string(),
)));
}
match (&source_schema.format, &source_schema.row_encode) {
(Format::DebeziumMongo, Encode::Json) => {
let mut columns = vec![
ColumnCatalog {
column_desc: ColumnDesc::named("_id", 0.into(), DataType::Varchar),
is_hidden: false,
},
ColumnCatalog {
column_desc: ColumnDesc::named("payload", 0.into(), DataType::Jsonb),
is_hidden: false,
},
];
let non_generated_sql_defined_columns =
non_generated_sql_columns(col_defs_from_sql);
if non_generated_sql_defined_columns.len() != 2
|| non_generated_sql_defined_columns[0].name.real_value() != columns[0].name()
|| non_generated_sql_defined_columns[1].name.real_value() != columns[1].name()
{
return Err(RwError::from(ProtocolError(
"the not generated columns of the source with row format DebeziumMongoJson
must be (_id [Jsonb | Varchar | Int32 | Int64], payload jsonb)."
.to_string(),
)));
}
// ok to unwrap since it was checked at `bind_sql_columns`
let key_data_type = bind_data_type(
non_generated_sql_defined_columns[0]
.data_type
.as_ref()
.unwrap(),
)?;
match key_data_type {
DataType::Jsonb | DataType::Varchar | DataType::Int32 | DataType::Int64 => {
columns[0].column_desc.data_type = key_data_type.clone();
}
_ => {
return Err(RwError::from(ProtocolError(
"the `_id` column of the source with row format DebeziumMongoJson
must be [Jsonb | Varchar | Int32 | Int64]"
.to_string(),
)));
}
}
// ok to unwrap since it was checked at `bind_sql_columns`
let value_data_type = bind_data_type(
non_generated_sql_defined_columns[1]
.data_type
.as_ref()
.unwrap(),
)?;
if !matches!(value_data_type, DataType::Jsonb) {
return Err(RwError::from(ProtocolError(
"the `payload` column of the source with row format DebeziumMongoJson
must be Jsonb datatype"
.to_string(),
)));
}
Ok(columns)
}
(Format::Plain, Encode::Bytes) => {
if cols_from_sql.len() != 1 || cols_from_sql[0].data_type() != &DataType::Bytea {
return Err(RwError::from(ProtocolError(
"ENCODE BYTES only accepts one BYTEA type column".to_string(),
)));
}
Ok(cols_from_sql)
}
(_, _) => Ok(cols_from_sql),
}
}
}
/// Bind column from source. Add key column to table columns if necessary.
/// Return `pk_names`.
pub(crate) async fn bind_source_pk(
source_schema: &ConnectorSchema,
source_info: &StreamSourceInfo,
columns: &mut [ColumnCatalog],
sql_defined_pk_names: Vec<String>,
with_properties: &WithOptions,
) -> Result<Vec<String>> {
let sql_defined_pk = !sql_defined_pk_names.is_empty();
let key_column_name: Option<String> = {
// iter columns to check if contains additional columns from key part
// return the key column names if exists
columns.iter().find_map(|catalog| {
if matches!(
catalog.column_desc.additional_column.column_type,
Some(AdditionalColumnType::Key(_))
) {
Some(catalog.name().to_string())
} else {
None
}
})
};
let additional_column_names = columns
.iter()
.filter_map(|col| {
if col.column_desc.additional_column.column_type.is_some() {
Some(col.name().to_string())
} else {
None
}
})
.collect_vec();
let res = match (&source_schema.format, &source_schema.row_encode) {
(Format::Native, Encode::Native) | (Format::None, Encode::None) | (Format::Plain, _) => {
sql_defined_pk_names
}
// For all Upsert formats, we only accept one and only key column as primary key.
// Additional KEY columns must be set in this case and must be primary key.
(Format::Upsert, encode @ Encode::Json | encode @ Encode::Avro) => {
if let Some(ref key_column_name) = key_column_name
&& sql_defined_pk
{
if sql_defined_pk_names.len() != 1 {
return Err(RwError::from(ProtocolError(format!(
"upsert {:?} supports only one primary key column ({}).",
encode, key_column_name
))));
}
// the column name have been converted to real value in `handle_addition_columns`
// so we don't ignore ascii case here
if !key_column_name.eq(sql_defined_pk_names[0].as_str()) {
return Err(RwError::from(ProtocolError(format!(
"upsert {}'s key column {} not match with sql defined primary key {}",
encode, key_column_name, sql_defined_pk_names[0]
))));
}
sql_defined_pk_names
} else {
return if key_column_name.is_none() {
Err(RwError::from(ProtocolError(format!(
"INCLUDE KEY clause must be set for FORMAT UPSERT ENCODE {:?}",
encode
))))
} else {
Err(RwError::from(ProtocolError(format!(
"Primary key must be specified to {} when creating source with FORMAT UPSERT ENCODE {:?}",
key_column_name.unwrap(), encode))))
};
}
}
(Format::Debezium, Encode::Json) => {
if !additional_column_names.is_empty() {
return Err(RwError::from(ProtocolError(format!(
"FORMAT DEBEZIUM forbids additional columns, but got {:?}",
additional_column_names
))));
}
if !sql_defined_pk {
return Err(RwError::from(ProtocolError(
"Primary key must be specified when creating source with FORMAT DEBEZIUM."
.to_string(),
)));
}
sql_defined_pk_names
}
(Format::Debezium, Encode::Avro) => {
if !additional_column_names.is_empty() {
return Err(RwError::from(ProtocolError(format!(
"FORMAT DEBEZIUM forbids additional columns, but got {:?}",
additional_column_names
))));
}
if sql_defined_pk {
sql_defined_pk_names
} else {
let pk_names =
extract_debezium_avro_table_pk_columns(source_info, with_properties).await?;
// extract pk(s) from schema registry
for pk_name in &pk_names {
columns
.iter()
.find(|c: &&ColumnCatalog| c.name().eq(pk_name))
.ok_or_else(|| {
RwError::from(ProtocolError(format!(
"avro's key column {} not exists in avro's row schema",
pk_name
)))
})?;
}
pk_names
}
}
(Format::DebeziumMongo, Encode::Json) => {
if sql_defined_pk {
sql_defined_pk_names
} else {
vec!["_id".to_string()]
}
}
(Format::Maxwell, Encode::Json) => {
if !additional_column_names.is_empty() {
return Err(RwError::from(ProtocolError(format!(
"FORMAT MAXWELL forbids additional columns, but got {:?}",
additional_column_names
))));
}
if !sql_defined_pk {
return Err(RwError::from(ProtocolError(
"Primary key must be specified when creating source with FORMAT MAXWELL ENCODE JSON."
.to_string(),
)));
}
sql_defined_pk_names
}
(Format::Canal, Encode::Json) => {
if !additional_column_names.is_empty() {
return Err(RwError::from(ProtocolError(format!(
"FORMAT CANAL forbids additional columns, but got {:?}",
additional_column_names
))));
}
if !sql_defined_pk {
return Err(RwError::from(ProtocolError(
"Primary key must be specified when creating source with FORMAT CANAL ENCODE JSON."
.to_string(),
)));
}
sql_defined_pk_names
}
(format, encoding) => {
return Err(RwError::from(ProtocolError(format!(
"Unknown combination {:?} {:?}",
format, encoding
))));
}
};
Ok(res)
}
// Add a hidden column `_rw_kafka_timestamp` to each message from Kafka source.
fn check_and_add_timestamp_column(with_properties: &WithOptions, columns: &mut Vec<ColumnCatalog>) {
if with_properties.is_kafka_connector() {
if columns.iter().any(|col| {
matches!(
col.column_desc.additional_column.column_type,
Some(AdditionalColumnType::Timestamp(_))
)
}) {
// already has timestamp column, no need to add a new one
return;
}
// add a hidden column `_rw_kafka_timestamp` to each message from Kafka source
let mut catalog = build_additional_column_catalog(
ColumnId::placeholder(),
KAFKA_CONNECTOR,
"timestamp",
Some(KAFKA_TIMESTAMP_COLUMN_NAME.to_string()),
None,
None,
true,
false,
)
.unwrap();
catalog.is_hidden = true;
columns.push(catalog);
}
}
pub(super) fn bind_source_watermark(
session: &SessionImpl,
name: String,
source_watermarks: Vec<SourceWatermark>,
column_catalogs: &[ColumnCatalog],
) -> Result<Vec<WatermarkDesc>> {
let mut binder = Binder::new_for_ddl(session);
binder.bind_columns_to_context(name.clone(), column_catalogs)?;
let watermark_descs = source_watermarks
.into_iter()
.map(|source_watermark| {
let col_name = source_watermark.column.real_value();
let watermark_idx = binder.get_column_binding_index(name.clone(), &col_name)?;
let expr = binder.bind_expr(source_watermark.expr)?;
let watermark_col_type = column_catalogs[watermark_idx].data_type();
let watermark_expr_type = &expr.return_type();
if watermark_col_type != watermark_expr_type {
Err(RwError::from(ErrorCode::BindError(
format!("The return value type of the watermark expression must be identical to the watermark column data type. Current data type of watermark return value: `{}`, column `{}`",watermark_expr_type, watermark_col_type),
)))
} else {
let expr_proto = expr.to_expr_proto();
Ok::<_, RwError>(WatermarkDesc {
watermark_idx: watermark_idx as u32,
expr: Some(expr_proto),
})
}
})
.try_collect()?;
Ok(watermark_descs)
}
// TODO: Better design if we want to support ENCODE KEY where we will have 4 dimensional array
static CONNECTORS_COMPATIBLE_FORMATS: LazyLock<HashMap<String, HashMap<Format, Vec<Encode>>>> =
LazyLock::new(|| {
convert_args!(hashmap!(
KAFKA_CONNECTOR => hashmap!(
Format::Plain => vec![Encode::Json, Encode::Protobuf, Encode::Avro, Encode::Bytes, Encode::Csv],
Format::Upsert => vec![Encode::Json, Encode::Avro],
Format::Debezium => vec![Encode::Json, Encode::Avro],
Format::Maxwell => vec![Encode::Json],
Format::Canal => vec![Encode::Json],
Format::DebeziumMongo => vec![Encode::Json],
),
PULSAR_CONNECTOR => hashmap!(
Format::Plain => vec![Encode::Json, Encode::Protobuf, Encode::Avro, Encode::Bytes],
Format::Upsert => vec![Encode::Json, Encode::Avro],
Format::Debezium => vec![Encode::Json],
Format::Maxwell => vec![Encode::Json],
Format::Canal => vec![Encode::Json],
),
KINESIS_CONNECTOR => hashmap!(
Format::Plain => vec![Encode::Json, Encode::Protobuf, Encode::Avro, Encode::Bytes],
Format::Upsert => vec![Encode::Json, Encode::Avro],
Format::Debezium => vec![Encode::Json],
Format::Maxwell => vec![Encode::Json],
Format::Canal => vec![Encode::Json],
),
GOOGLE_PUBSUB_CONNECTOR => hashmap!(
Format::Plain => vec![Encode::Json, Encode::Protobuf, Encode::Avro, Encode::Bytes],
Format::Debezium => vec![Encode::Json],
Format::Maxwell => vec![Encode::Json],
Format::Canal => vec![Encode::Json],
),
NEXMARK_CONNECTOR => hashmap!(
Format::Native => vec![Encode::Native],
Format::Plain => vec![Encode::Bytes],
),
DATAGEN_CONNECTOR => hashmap!(
Format::Native => vec![Encode::Native],
Format::Plain => vec![Encode::Bytes, Encode::Json],
),
S3_CONNECTOR => hashmap!(
Format::Plain => vec![Encode::Csv, Encode::Json],