1use std::collections::HashMap;
16use std::str::FromStr;
17use std::sync::LazyLock;
18
19use anyhow::{Context, anyhow};
20use iceberg::arrow::schema_to_arrow_schema;
21use iceberg::metadata_columns::{
22 RESERVED_COL_NAME_LAST_UPDATED_SEQUENCE_NUMBER, RESERVED_COL_NAME_ROW_ID,
23};
24use iceberg::spec::{
25 FormatVersion, NullOrder, SortDirection, SortField, SortOrder, TableProperties, Transform,
26 UnboundPartitionField, UnboundPartitionSpec,
27};
28use iceberg::table::Table;
29use iceberg::{Catalog, NamespaceIdent, TableCreation};
30use itertools::Itertools;
31use regex::Regex;
32use risingwave_common::array::arrow::arrow_schema_iceberg::{
33 self, DataType as ArrowDataType, Field as ArrowField, Fields as ArrowFields,
34 Schema as ArrowSchema,
35};
36use risingwave_common::array::arrow::{IcebergArrowConvert, IcebergCreateTableArrowConvert};
37use risingwave_common::bail;
38use risingwave_common::catalog::{ColumnDesc, Schema};
39use risingwave_common::util::iter_util::ZipEqFast;
40use url::Url;
41
42use super::{IcebergConfig, PARTITION_DATA_ID_START, SinkError};
43use crate::connector_common::{IcebergCatalogKind, IcebergCatalogRuntime};
44use crate::sink::{Result, SinkParam};
45
46static ORDER_KEY_COLUMN_RE: LazyLock<Regex> =
47 LazyLock::new(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*$").expect("valid order key regex"));
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct IcebergOrderKeyField {
51 pub column: String,
52 pub direction: SortDirection,
53 pub null_order: NullOrder,
54}
55
56impl IcebergOrderKeyField {
57 fn default_null_order(direction: SortDirection) -> NullOrder {
58 match direction {
59 SortDirection::Ascending => NullOrder::First,
60 SortDirection::Descending => NullOrder::Last,
61 }
62 }
63}
64
65pub async fn create_and_validate_table_impl(
66 config: &IcebergConfig,
67 param: &SinkParam,
68) -> Result<Table> {
69 let table = create_and_load_table_impl(config, param).await?;
70
71 let sink_schema = param.schema();
72 let iceberg_arrow_schema = schema_to_arrow_schema(table.metadata().current_schema())
73 .map_err(|err| SinkError::Iceberg(anyhow!(err)))?;
74
75 try_matches_arrow_schema(&sink_schema, &iceberg_arrow_schema)
76 .map_err(|err| SinkError::Iceberg(anyhow!(err)))?;
77
78 Ok(table)
79}
80
81pub async fn create_and_load_table_impl(
88 config: &IcebergConfig,
89 param: &SinkParam,
90) -> Result<Table> {
91 if config.create_table_if_not_exists {
92 create_table_if_not_exists_impl(config, param).await?;
93 }
94
95 let table = config
96 .load_table()
97 .await
98 .map_err(|err| SinkError::Iceberg(anyhow!(err)))?;
99
100 if config.enable_pk_index {
101 let table_format_version = table.metadata().format_version();
102 if table_format_version < FormatVersion::V2 {
103 return Err(SinkError::Config(anyhow!(
104 "`enable_pk_index` requires an Iceberg table with format version >= 2, \
105 but the target table is format version {}",
106 table_format_version
107 )));
108 }
109 }
110
111 Ok(table)
112}
113
114pub fn validate_row_lineage_column_names(
118 format_version: FormatVersion,
119 columns: &[ColumnDesc],
120) -> Result<()> {
121 if format_version < FormatVersion::V3 {
122 return Ok(());
123 }
124 if let Some(column) = columns.iter().find(|column| {
125 [
126 RESERVED_COL_NAME_ROW_ID,
127 RESERVED_COL_NAME_LAST_UPDATED_SEQUENCE_NUMBER,
128 ]
129 .contains(&column.name.as_str())
130 }) {
131 return Err(SinkError::Config(anyhow!(
132 "cannot create an Iceberg V3 table with column `{}` because the name is reserved \
133 for row lineage metadata; please rename the column",
134 column.name
135 )));
136 }
137 Ok(())
138}
139
140pub(super) async fn create_table_if_not_exists_impl(
142 config: &IcebergConfig,
143 param: &SinkParam,
144) -> Result<bool> {
145 let catalog = config.create_catalog().await?;
146 let table_id = config
147 .full_table_name()
148 .context("Unable to parse table name")?;
149 let namespace = table_id.namespace().clone();
150 let table_name = table_id.name().to_owned();
151 create_namespace_if_not_exists(catalog.as_ref(), &namespace).await?;
152
153 if catalog
154 .table_exists(&table_id)
155 .await
156 .map_err(|e| SinkError::Iceberg(anyhow!(e)))?
157 {
158 return Ok(false);
159 }
160
161 if config.table_format_version() < FormatVersion::V3
162 && let Some(column) = param
163 .columns
164 .iter()
165 .find(|column| column.data_type.contains_variant())
166 {
167 return Err(SinkError::Config(anyhow!(
168 "creating an Iceberg table with VARIANT column `{}` requires `format_version = '3'`",
169 column.name
170 )));
171 }
172 validate_row_lineage_column_names(config.table_format_version(), ¶m.columns)?;
173
174 let iceberg_create_table_arrow_convert = IcebergCreateTableArrowConvert::default();
175 let arrow_fields = param
177 .columns
178 .iter()
179 .map(|column| {
180 Ok(iceberg_create_table_arrow_convert
181 .to_arrow_field(&column.name, &column.data_type)
182 .map_err(|e| SinkError::Iceberg(anyhow!(e)))
183 .context(format!(
184 "failed to convert {}: {} to arrow type",
185 column.name, column.data_type
186 ))?)
187 })
188 .collect::<Result<Vec<ArrowField>>>()?;
189 let arrow_schema = arrow_schema_iceberg::Schema::new(arrow_fields);
190 let iceberg_schema = iceberg::arrow::arrow_schema_to_schema(&arrow_schema)
191 .map_err(|e| SinkError::Iceberg(anyhow!(e)))
192 .context("failed to convert arrow schema to iceberg schema")?;
193
194 let location = {
195 let mut names = namespace.clone().inner();
196 names.push(table_name.clone());
197 match &config.common.warehouse_path {
198 Some(warehouse_path) => {
199 let is_s3_tables = warehouse_path.starts_with("arn:aws:s3tables");
200 let is_bq_catalog_federation = warehouse_path.starts_with("bq://");
202 let url = Url::parse(warehouse_path);
203 if url.is_err() || is_s3_tables || is_bq_catalog_federation {
204 if config
207 .common
208 .is_rest_catalog()
209 .map_err(|err| SinkError::Config(anyhow!(err)))?
210 {
211 None
212 } else {
213 bail!(format!("Invalid warehouse path: {}", warehouse_path))
214 }
215 } else if warehouse_path.ends_with('/') {
216 Some(format!("{}{}", warehouse_path, names.join("/")))
217 } else {
218 Some(format!("{}/{}", warehouse_path, names.join("/")))
219 }
220 }
221 None => None,
222 }
223 };
224
225 let location = default_table_location_from_namespace(
226 catalog.as_ref(),
227 &namespace,
228 &table_name,
229 location,
230 config.default_table_location_from_namespace,
231 )
232 .await?;
233
234 let partition_spec = match &config.partition_by {
235 Some(partition_by) => {
236 let mut partition_fields = Vec::<UnboundPartitionField>::new();
237 for (i, (column, transform)) in parse_partition_by_exprs(partition_by.clone())?
238 .into_iter()
239 .enumerate()
240 {
241 match iceberg_schema.field_id_by_name(&column) {
242 Some(id) => partition_fields.push(
243 UnboundPartitionField::builder()
244 .source_id(id)
245 .transform(transform)
246 .name(format!("_p_{}", column))
247 .field_id(PARTITION_DATA_ID_START + i as i32)
248 .build(),
249 ),
250 None => bail!(format!(
251 "Partition source column does not exist in schema: {}",
252 column
253 )),
254 };
255 }
256 Some(
257 UnboundPartitionSpec::builder()
258 .with_spec_id(0)
259 .add_partition_fields(partition_fields)
260 .map_err(|e| SinkError::Iceberg(anyhow!(e)))
261 .context("failed to add partition columns")?
262 .build(),
263 )
264 }
265 None => None,
266 };
267
268 let sort_order = match &config.order_key {
269 Some(order_key) => Some(build_sort_order(order_key, &iceberg_schema)?),
270 None => None,
271 };
272
273 let properties = if matches!(
276 config.catalog_kind()?,
277 IcebergCatalogKind::Glue(IcebergCatalogRuntime::NativeRust)
278 ) {
279 HashMap::new()
280 } else {
281 HashMap::from([(
282 TableProperties::PROPERTY_FORMAT_VERSION.to_owned(),
283 (config.format_version as u8).to_string(),
284 )])
285 };
286
287 let table_creation_builder = TableCreation::builder()
288 .name(table_name)
289 .schema(iceberg_schema)
290 .format_version(config.table_format_version())
291 .properties(properties);
292
293 let table_creation = match (location, partition_spec, sort_order) {
294 (Some(location), Some(partition_spec), Some(sort_order)) => table_creation_builder
295 .location(location)
296 .partition_spec(partition_spec)
297 .sort_order(sort_order)
298 .build(),
299 (Some(location), Some(partition_spec), None) => table_creation_builder
300 .location(location)
301 .partition_spec(partition_spec)
302 .build(),
303 (Some(location), None, Some(sort_order)) => table_creation_builder
304 .location(location)
305 .sort_order(sort_order)
306 .build(),
307 (Some(location), None, None) => table_creation_builder.location(location).build(),
308 (None, Some(partition_spec), Some(sort_order)) => table_creation_builder
309 .partition_spec(partition_spec)
310 .sort_order(sort_order)
311 .build(),
312 (None, Some(partition_spec), None) => table_creation_builder
313 .partition_spec(partition_spec)
314 .build(),
315 (None, None, Some(sort_order)) => table_creation_builder.sort_order(sort_order).build(),
316 (None, None, None) => table_creation_builder.build(),
317 };
318
319 catalog
320 .create_table(&namespace, table_creation)
321 .await
322 .map_err(|e| SinkError::Iceberg(anyhow!(e)))
323 .context("failed to create iceberg table")?;
324 Ok(true)
325}
326
327async fn default_table_location_from_namespace(
328 catalog: &dyn Catalog,
329 namespace: &NamespaceIdent,
330 table_name: &str,
331 location: Option<String>,
332 enabled: bool,
333) -> Result<Option<String>> {
334 if location.is_some() || !enabled {
335 return Ok(location);
336 }
337
338 let namespace = catalog
339 .get_namespace(namespace)
340 .await
341 .map_err(|e| SinkError::Iceberg(anyhow!(e)))
342 .context("failed to load iceberg namespace for default table location")?;
343 Ok(namespace
344 .properties()
345 .get("location")
346 .filter(|location| !location.is_empty())
347 .map(|location| format!("{}/{table_name}", location.trim_end_matches('/'))))
348}
349
350async fn create_namespace_if_not_exists(
351 catalog: &dyn Catalog,
352 namespace: &NamespaceIdent,
353) -> Result<()> {
354 let mut namespaces = vec![namespace.clone()];
355 let mut parent = namespace.parent();
356 while let Some(parent_namespace) = parent {
357 parent = parent_namespace.parent();
358 namespaces.push(parent_namespace);
359 }
360
361 for namespace in namespaces.into_iter().rev() {
362 if !catalog
363 .namespace_exists(&namespace)
364 .await
365 .map_err(|e| SinkError::Iceberg(anyhow!(e)))?
366 {
367 catalog
368 .create_namespace(&namespace, HashMap::default())
369 .await
370 .map_err(|e| SinkError::Iceberg(anyhow!(e)))
371 .with_context(|| format!("failed to create iceberg namespace: {namespace}"))?;
372 }
373 }
374
375 Ok(())
376}
377
378const MAP_KEY: &str = "key";
379const MAP_VALUE: &str = "value";
380
381fn field_is_compatible(
382 rw_type: &risingwave_common::types::DataType,
383 arrow_field: &ArrowField,
384) -> anyhow::Result<bool> {
385 use risingwave_common::types::DataType as RwDataType;
386
387 let arrow_is_variant = matches!(
391 IcebergArrowConvert.type_from_field(arrow_field),
392 Ok(RwDataType::Variant)
393 );
394 if matches!(rw_type, RwDataType::Variant) || arrow_is_variant {
395 return Ok(matches!(rw_type, RwDataType::Variant) && arrow_is_variant);
396 }
397
398 let converted_arrow_data_type = IcebergArrowConvert
399 .to_arrow_field("", rw_type)
400 .map_err(|e| anyhow!(e))?
401 .data_type()
402 .clone();
403
404 match (rw_type, &converted_arrow_data_type, arrow_field.data_type()) {
405 (_, ArrowDataType::Decimal128(_, _), ArrowDataType::Decimal128(_, _)) => Ok(true),
406 (_, ArrowDataType::Binary, ArrowDataType::LargeBinary)
407 | (_, ArrowDataType::LargeBinary, ArrowDataType::Binary) => Ok(true),
408 (RwDataType::List(list), ArrowDataType::List(_), ArrowDataType::List(element)) => {
409 field_is_compatible(list.elem(), element)
410 }
411 (RwDataType::Map(map), ArrowDataType::Map(_, _), ArrowDataType::Map(entries, _)) => {
412 let ArrowDataType::Struct(fields) = entries.data_type() else {
413 return Ok(false);
414 };
415 let key = fields.iter().find(|field| field.name() == MAP_KEY);
416 let value = fields.iter().find(|field| field.name() == MAP_VALUE);
417 match (key, value) {
418 (Some(key), Some(value)) => Ok(field_is_compatible(map.key(), key)?
419 && field_is_compatible(map.value(), value)?),
420 _ => Ok(false),
421 }
422 }
423 (
424 RwDataType::Struct(rw_fields),
425 ArrowDataType::Struct(_),
426 ArrowDataType::Struct(arrow_fields),
427 ) => {
428 if rw_fields.len() != arrow_fields.len() {
429 return Ok(false);
430 }
431 for ((rw_name, rw_type), arrow_field) in rw_fields.iter().zip_eq_fast(arrow_fields) {
434 if rw_name != arrow_field.name().as_str() {
435 return Ok(false);
436 }
437 if !field_is_compatible(rw_type, arrow_field)? {
438 return Ok(false);
439 }
440 }
441 Ok(true)
442 }
443 (_, left, right) => Ok(left.equals_datatype(right)),
444 }
445}
446
447fn check_compatibility(
448 schema_fields: HashMap<&str, &risingwave_common::types::DataType>,
449 fields: &ArrowFields,
450) -> anyhow::Result<bool> {
451 for arrow_field in fields {
452 let our_field_type = schema_fields
453 .get(arrow_field.name().as_str())
454 .ok_or_else(|| anyhow!("Field {} not found in our schema", arrow_field.name()))?;
455
456 if !field_is_compatible(our_field_type, arrow_field)? {
457 let converted_arrow_data_type = IcebergArrowConvert
458 .to_arrow_field("", our_field_type)
459 .map_err(|e| anyhow!(e))?
460 .data_type()
461 .clone();
462 bail!(
463 "field {}'s type is incompatible\nRisingWave converted data type: {}\niceberg's data type: {}",
464 arrow_field.name(),
465 converted_arrow_data_type,
466 arrow_field.data_type()
467 );
468 }
469 }
470 Ok(true)
471}
472
473pub fn try_matches_arrow_schema(rw_schema: &Schema, arrow_schema: &ArrowSchema) -> Result<()> {
475 if rw_schema.fields.len() != arrow_schema.fields().len() {
476 bail!(
477 "Schema length mismatch, risingwave is {}, and iceberg is {}",
478 rw_schema.fields.len(),
479 arrow_schema.fields.len()
480 );
481 }
482
483 let mut schema_fields = HashMap::new();
484 rw_schema.fields.iter().for_each(|field| {
485 let res = schema_fields.insert(field.name.as_str(), &field.data_type);
486 assert!(res.is_none())
488 });
489
490 check_compatibility(schema_fields, &arrow_schema.fields)?;
491
492 for (idx, (rw_field, arrow_field)) in rw_schema
495 .fields
496 .iter()
497 .zip_eq_fast(arrow_schema.fields().iter())
498 .enumerate()
499 {
500 if rw_field.name.as_str() != arrow_field.name().as_str() {
501 bail!(
502 "Column order mismatch at position {}: the sink has column `{}` but the \
503 Iceberg table has column `{}`. The Iceberg sink maps columns to the table \
504 by position, so the sink's column order must match the Iceberg table \
505 columns [{}].",
506 idx,
507 rw_field.name,
508 arrow_field.name(),
509 arrow_schema.fields().iter().map(|f| f.name()).join(", "),
510 );
511 }
512 }
513
514 Ok(())
515}
516
517pub fn parse_partition_by_exprs(
518 expr: String,
519) -> std::result::Result<Vec<(String, Transform)>, anyhow::Error> {
520 let re = Regex::new(r"(?<transform>\w+)(\(((?<n>\d+)?(?:,|(,\s)))?(?<field>\w+)\))?").unwrap();
522 if !re.is_match(&expr) {
523 bail!(format!(
524 "Invalid partition fields: {}\nHINT: Supported formats are column, transform(column), transform(n,column), transform(n, column)",
525 expr
526 ))
527 }
528 let caps = re.captures_iter(&expr);
529
530 let mut partition_columns = vec![];
531
532 for mat in caps {
533 let (column, transform) = if mat.name("n").is_none() && mat.name("field").is_none() {
534 (&mat["transform"], Transform::Identity)
535 } else {
536 let mut func = mat["transform"].to_owned();
537 if func == "bucket" || func == "truncate" {
538 let n = &mat
539 .name("n")
540 .ok_or_else(|| anyhow!("The `n` must be set with `bucket` and `truncate`"))?
541 .as_str();
542 func = format!("{func}[{n}]");
543 }
544 (
545 &mat["field"],
546 Transform::from_str(&func)
547 .with_context(|| format!("invalid transform function {}", func))?,
548 )
549 };
550 partition_columns.push((column.to_owned(), transform));
551 }
552 Ok(partition_columns)
553}
554
555pub fn parse_order_key_exprs(
556 expr: String,
557) -> std::result::Result<Vec<IcebergOrderKeyField>, anyhow::Error> {
558 let mut order_keys = Vec::new();
559 let mut seen_columns = std::collections::HashSet::new();
560
561 for raw_item in expr.split(',') {
562 let item = raw_item.trim();
563 if item.is_empty() {
564 bail!("Invalid order key: empty item in `{expr}`");
565 }
566
567 let tokens = item.split_whitespace().collect_vec();
568 if tokens.is_empty() {
569 bail!("Invalid order key item `{item}`");
570 }
571 if tokens.len() > 4 {
572 bail!(
573 "Invalid order key item `{item}`\nHINT: Supported format is `column [asc|desc] [nulls first|last]`"
574 );
575 }
576
577 let column = tokens[0];
578 if !ORDER_KEY_COLUMN_RE.is_match(column) {
579 bail!(
580 "Invalid order key column `{column}`\nHINT: Only plain column names are supported in order_key"
581 );
582 }
583 if !seen_columns.insert(column.to_ascii_lowercase()) {
584 bail!("Duplicate column `{column}` in order_key");
585 }
586
587 let mut direction = SortDirection::Ascending;
588 let mut null_order = None;
589 let mut idx = 1;
590 while idx < tokens.len() {
591 match tokens[idx].to_ascii_lowercase().as_str() {
592 "asc" => {
593 direction = SortDirection::Ascending;
594 idx += 1;
595 }
596 "desc" => {
597 direction = SortDirection::Descending;
598 idx += 1;
599 }
600 "nulls" => {
601 let order = tokens.get(idx + 1).ok_or_else(|| {
602 anyhow!(
603 "Invalid order key item `{item}`: `NULLS` must be followed by `FIRST` or `LAST`"
604 )
605 })?;
606 null_order = Some(match order.to_ascii_lowercase().as_str() {
607 "first" => NullOrder::First,
608 "last" => NullOrder::Last,
609 _ => bail!(
610 "Invalid order key item `{item}`\nHINT: `NULLS` must be followed by `FIRST` or `LAST`"
611 ),
612 });
613 idx += 2;
614 }
615 token => {
616 bail!(
617 "Invalid order key token `{token}` in `{item}`\nHINT: Supported format is `column [asc|desc] [nulls first|last]`"
618 );
619 }
620 }
621 }
622
623 order_keys.push(IcebergOrderKeyField {
624 column: column.to_owned(),
625 direction,
626 null_order: null_order
627 .unwrap_or_else(|| IcebergOrderKeyField::default_null_order(direction)),
628 });
629 }
630
631 if order_keys.is_empty() {
632 bail!("order_key must not be empty");
633 }
634
635 Ok(order_keys)
636}
637
638pub fn validate_order_key_columns<'a>(
639 order_key: &str,
640 columns: impl IntoIterator<Item = &'a str>,
641) -> std::result::Result<Vec<IcebergOrderKeyField>, anyhow::Error> {
642 let parsed = parse_order_key_exprs(order_key.to_owned())?;
643 let columns = columns
644 .into_iter()
645 .map(|column| column.to_ascii_lowercase())
646 .collect::<std::collections::HashSet<_>>();
647 for item in &parsed {
648 if item.column.starts_with('_') {
649 bail!(
650 "System column `{}` is not allowed in order_key",
651 item.column
652 );
653 }
654 if !columns.contains(&item.column.to_ascii_lowercase()) {
655 bail!("Order key column does not exist in schema: {}", item.column);
656 }
657 }
658 Ok(parsed)
659}
660
661fn build_sort_order(order_key: &str, schema: &iceberg::spec::Schema) -> Result<SortOrder> {
662 let order_fields = validate_order_key_columns(
663 order_key,
664 schema
665 .as_struct()
666 .fields()
667 .iter()
668 .map(|field| field.name.as_str()),
669 )?;
670 let mut builder = SortOrder::builder();
671 for field in order_fields {
672 let source_id = schema.field_id_by_name(&field.column).ok_or_else(|| {
673 anyhow!(
674 "Order key column does not exist in schema: {}",
675 field.column
676 )
677 })?;
678 builder.with_sort_field(
679 SortField::builder()
680 .source_id(source_id)
681 .transform(Transform::Identity)
682 .direction(field.direction)
683 .null_order(field.null_order)
684 .build(),
685 );
686 }
687 builder
688 .build(schema)
689 .map_err(|e| SinkError::Iceberg(anyhow!(e)))
690}