-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtypes.rs
More file actions
1210 lines (1067 loc) · 43.2 KB
/
types.rs
File metadata and controls
1210 lines (1067 loc) · 43.2 KB
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
//! Type mapping from DuckLake types to Arrow types
use std::collections::HashMap;
#[cfg(test)]
use std::sync::Arc;
use crate::metadata_provider::DuckLakeTableColumn;
use crate::{DuckLakeError, Result};
use arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit};
use parquet::file::metadata::ParquetMetaData;
/// Convert a DuckLake type string to an Arrow DataType
pub fn ducklake_to_arrow_type(ducklake_type: &str) -> Result<DataType> {
// Normalize type string (lowercase, remove whitespace)
let normalized = ducklake_type.trim().to_lowercase();
// Handle parameterized types first
if let Some(decimal_params) = parse_decimal(&normalized)? {
return Ok(decimal_params);
}
// Handle basic types
match normalized.as_str() {
// Boolean
"boolean" | "bool" => Ok(DataType::Boolean),
// Integers
"int8" | "tinyint" => Ok(DataType::Int8),
"int16" | "smallint" => Ok(DataType::Int16),
"int32" | "int" | "integer" => Ok(DataType::Int32),
"int64" | "bigint" | "long" => Ok(DataType::Int64),
"uint8" | "utinyint" => Ok(DataType::UInt8),
"uint16" | "usmallint" => Ok(DataType::UInt16),
"uint32" | "uint" | "uinteger" => Ok(DataType::UInt32),
"uint64" | "ubigint" => Ok(DataType::UInt64),
// Floating point
"float32" | "float" | "real" => Ok(DataType::Float32),
"float64" | "double" => Ok(DataType::Float64),
// Temporal types
"time" => Ok(DataType::Time64(TimeUnit::Microsecond)),
"date" => Ok(DataType::Date32),
"timestamp" => Ok(DataType::Timestamp(TimeUnit::Microsecond, None)),
"timestamptz" | "timestamp with time zone" => Ok(DataType::Timestamp(
TimeUnit::Microsecond,
Some("UTC".into()),
)),
"timestamp_s" => Ok(DataType::Timestamp(TimeUnit::Second, None)),
"timestamp_ms" => Ok(DataType::Timestamp(TimeUnit::Millisecond, None)),
"timestamp_ns" => Ok(DataType::Timestamp(TimeUnit::Nanosecond, None)),
"interval" => Ok(DataType::Interval(IntervalUnit::MonthDayNano)),
// String types
"varchar" | "text" | "string" => Ok(DataType::Utf8),
"json" => Ok(DataType::Utf8), // JSON stored as UTF8 string
// Binary types
"blob" | "binary" | "bytea" => Ok(DataType::Binary),
"uuid" => Ok(DataType::FixedSizeBinary(16)),
// Geometry types (stored as binary WKB format)
"point" | "linestring" | "polygon" | "multipoint" | "multilinestring" | "multipolygon"
| "geometrycollection" | "linestring z" | "geometry" => Ok(DataType::Binary),
// Time with timezone - not directly supported, use string
"timetz" | "time with time zone" => Ok(DataType::Utf8),
_ => {
// Check for complex types (list, struct, map)
if normalized.starts_with("list") || normalized.starts_with("array") {
Err(DuckLakeError::UnsupportedType(format!(
"Complex type '{}' not yet supported. Please open an issue at https://github.com/hotdata-dev/datafusion-ducklake if you need this feature.",
ducklake_type
)))
} else if normalized.starts_with("struct") {
Err(DuckLakeError::UnsupportedType(format!(
"Struct type '{}' not yet supported. Please open an issue at https://github.com/hotdata-dev/datafusion-ducklake if you need this feature.",
ducklake_type
)))
} else if normalized.starts_with("map") {
Err(DuckLakeError::UnsupportedType(format!(
"Map type '{}' not yet supported. Please open an issue at https://github.com/hotdata-dev/datafusion-ducklake if you need this feature.",
ducklake_type
)))
} else {
Err(DuckLakeError::UnsupportedType(ducklake_type.to_string()))
}
},
}
}
/// Convert an Arrow DataType to a DuckLake type string
///
/// This is the reverse of `ducklake_to_arrow_type()`.
pub fn arrow_to_ducklake_type(arrow_type: &DataType) -> Result<String> {
match arrow_type {
// Boolean
DataType::Boolean => Ok("boolean".to_string()),
// Integers
DataType::Int8 => Ok("int8".to_string()),
DataType::Int16 => Ok("int16".to_string()),
DataType::Int32 => Ok("int32".to_string()),
DataType::Int64 => Ok("int64".to_string()),
DataType::UInt8 => Ok("uint8".to_string()),
DataType::UInt16 => Ok("uint16".to_string()),
DataType::UInt32 => Ok("uint32".to_string()),
DataType::UInt64 => Ok("uint64".to_string()),
// Floating point
DataType::Float32 => Ok("float32".to_string()),
DataType::Float64 => Ok("float64".to_string()),
// Temporal types
DataType::Date32 | DataType::Date64 => Ok("date".to_string()),
DataType::Time32(_) | DataType::Time64(_) => Ok("time".to_string()),
DataType::Timestamp(TimeUnit::Second, None) => Ok("timestamp_s".to_string()),
DataType::Timestamp(TimeUnit::Millisecond, None) => Ok("timestamp_ms".to_string()),
DataType::Timestamp(TimeUnit::Microsecond, None) => Ok("timestamp".to_string()),
DataType::Timestamp(TimeUnit::Nanosecond, None) => Ok("timestamp_ns".to_string()),
DataType::Timestamp(_, Some(_)) => Ok("timestamptz".to_string()),
DataType::Interval(_) => Ok("interval".to_string()),
// String types
DataType::Utf8 | DataType::LargeUtf8 => Ok("varchar".to_string()),
// Binary types
DataType::Binary | DataType::LargeBinary => Ok("blob".to_string()),
DataType::FixedSizeBinary(16) => Ok("uuid".to_string()),
DataType::FixedSizeBinary(_) => Ok("blob".to_string()),
// Decimal types
DataType::Decimal128(precision, scale) | DataType::Decimal256(precision, scale) => {
Ok(format!("decimal({}, {})", precision, scale))
},
// Null type - map to varchar as there's no direct equivalent
DataType::Null => Ok("varchar".to_string()),
// Complex types - not yet supported for writing
DataType::List(_) | DataType::LargeList(_) | DataType::FixedSizeList(_, _) => {
Err(DuckLakeError::UnsupportedType(format!(
"List type '{}' not yet supported for writing",
arrow_type
)))
},
DataType::Struct(_) => Err(DuckLakeError::UnsupportedType(format!(
"Struct type '{}' not yet supported for writing",
arrow_type
))),
DataType::Map(_, _) => Err(DuckLakeError::UnsupportedType(format!(
"Map type '{}' not yet supported for writing",
arrow_type
))),
// Other unsupported types
other => Err(DuckLakeError::UnsupportedType(format!(
"Arrow type '{}' has no DuckLake equivalent",
other
))),
}
}
/// Maximum precision for Arrow Decimal256
const DECIMAL_MAX_PRECISION: u8 = 76;
/// Validate decimal precision and scale bounds
fn validate_decimal_precision_scale(precision: u8, scale: i8, type_str: &str) -> Result<()> {
if precision == 0 {
return Err(DuckLakeError::UnsupportedType(format!(
"Decimal precision must be >= 1, got 0 in type '{}'",
type_str
)));
}
if precision > DECIMAL_MAX_PRECISION {
return Err(DuckLakeError::UnsupportedType(format!(
"Decimal precision must be <= {}, got {} in type '{}'",
DECIMAL_MAX_PRECISION, precision, type_str
)));
}
if scale >= 0 && scale as u8 > precision {
return Err(DuckLakeError::UnsupportedType(format!(
"Decimal scale ({}) must not exceed precision ({}) in type '{}'",
scale, precision, type_str
)));
}
Ok(())
}
/// Parse decimal type with precision and scale
/// Format: "decimal(precision, scale)" or "decimal(precision)"
///
/// Returns `Ok(None)` if the type string is not a decimal type.
/// Returns `Err` if it is a decimal type but has invalid precision/scale.
fn parse_decimal(type_str: &str) -> Result<Option<DataType>> {
if !type_str.starts_with("decimal") && !type_str.starts_with("numeric") {
return Ok(None);
}
// Extract parameters from parentheses
let start = match type_str.find('(') {
Some(s) => s,
None => return Ok(None),
};
let end = match type_str.find(')') {
Some(e) => e,
None => return Ok(None),
};
let params = &type_str[start + 1..end];
let parts: Vec<&str> = params.split(',').map(|s| s.trim()).collect();
match parts.len() {
1 => {
let precision: u8 = parts[0].parse().map_err(|_| {
DuckLakeError::UnsupportedType(format!(
"Invalid decimal precision '{}' in type '{}'",
parts[0], type_str
))
})?;
validate_decimal_precision_scale(precision, 0, type_str)?;
Ok(Some(DataType::Decimal128(precision, 0)))
},
2 => {
let precision: u8 = parts[0].parse().map_err(|_| {
DuckLakeError::UnsupportedType(format!(
"Invalid decimal precision '{}' in type '{}'",
parts[0], type_str
))
})?;
let scale: i8 = parts[1].parse().map_err(|_| {
DuckLakeError::UnsupportedType(format!(
"Invalid decimal scale '{}' in type '{}'",
parts[1], type_str
))
})?;
validate_decimal_precision_scale(precision, scale, type_str)?;
if precision > 38 {
Ok(Some(DataType::Decimal256(precision, scale)))
} else {
Ok(Some(DataType::Decimal128(precision, scale)))
}
},
n => Err(DuckLakeError::UnsupportedType(format!(
"Invalid decimal type: expected at most 2 parameters (precision, scale), got {} in type '{}'",
n, type_str
))),
}
}
/// Normalize a DuckLake type string to its canonical form.
///
/// Converts aliases and case variants to the canonical DuckLake type string.
/// For example: "int" -> "int32", "INTEGER" -> "int32", "text" -> "varchar".
///
/// Returns the canonical type string, or an error if the type is unrecognized.
pub fn normalize_ducklake_type(ducklake_type: &str) -> Result<String> {
let arrow_type = ducklake_to_arrow_type(ducklake_type)?;
arrow_to_ducklake_type(&arrow_type)
}
/// Check if a type can be safely promoted (widened) to another type.
///
/// Type promotion allows safe widening of numeric types during schema evolution.
/// Both type strings are normalized before comparison.
///
/// Supported promotions:
/// - Signed integer widening: int8 -> int16 -> int32 -> int64
/// - Unsigned integer widening: uint8 -> uint16 -> uint32 -> uint64
/// - Float widening: float32 -> float64
/// - Integer to float: any int -> float64
/// - Timestamp: timestamp -> timestamptz
/// - Decimal: smaller precision/scale -> larger precision/scale
pub fn is_promotable(from: &str, to: &str) -> bool {
let from_arrow = match ducklake_to_arrow_type(from) {
Ok(t) => t,
Err(_) => return false,
};
let to_arrow = match ducklake_to_arrow_type(to) {
Ok(t) => t,
Err(_) => return false,
};
is_arrow_promotable(&from_arrow, &to_arrow)
}
/// Check if one Arrow DataType can be safely promoted to another.
fn is_arrow_promotable(from: &DataType, to: &DataType) -> bool {
use DataType::*;
// Same type is trivially promotable
if from == to {
return true;
}
fn signed_int_rank(dt: &DataType) -> Option<u8> {
match dt {
Int8 => Some(0),
Int16 => Some(1),
Int32 => Some(2),
Int64 => Some(3),
_ => None,
}
}
fn unsigned_int_rank(dt: &DataType) -> Option<u8> {
match dt {
UInt8 => Some(0),
UInt16 => Some(1),
UInt32 => Some(2),
UInt64 => Some(3),
_ => None,
}
}
// Signed integer widening
if let (Some(from_rank), Some(to_rank)) = (signed_int_rank(from), signed_int_rank(to)) {
return from_rank < to_rank;
}
// Unsigned integer widening
if let (Some(from_rank), Some(to_rank)) = (unsigned_int_rank(from), unsigned_int_rank(to)) {
return from_rank < to_rank;
}
// Float widening
if matches!(from, Float32) && matches!(to, Float64) {
return true;
}
// Integer to float64 (safe for reasonable values)
if signed_int_rank(from).is_some() && matches!(to, Float64) {
return true;
}
// Timestamp -> TimestampTZ
if matches!(from, Timestamp(_, None)) && matches!(to, Timestamp(_, Some(_))) {
return true;
}
// Decimal widening: integer digits don't shrink AND fractional digits don't shrink.
// We check (tp - ts >= fp - fs) to ensure the integer part has enough room,
// in addition to (ts >= fs) for the fractional part.
match (from, to) {
(Decimal128(fp, fs) | Decimal256(fp, fs), Decimal128(tp, ts) | Decimal256(tp, ts)) => {
let from_int_digits = *fp as i16 - *fs as i16;
let to_int_digits = *tp as i16 - *ts as i16;
ts >= fs && to_int_digits >= from_int_digits
},
_ => false,
}
}
/// Check if two DuckLake type strings are compatible for schema evolution.
///
/// Types are compatible if they normalize to the same canonical type,
/// or if the existing type can be safely promoted to the new type.
pub fn types_compatible(existing_type: &str, new_type: &str) -> bool {
// First try normalization: if both normalize to the same canonical form, they match
let existing_normalized = match normalize_ducklake_type(existing_type) {
Ok(t) => t,
Err(_) => return false,
};
let new_normalized = match normalize_ducklake_type(new_type) {
Ok(t) => t,
Err(_) => return false,
};
if existing_normalized == new_normalized {
return true;
}
// Then check if promotion is allowed
is_promotable(existing_type, new_type)
}
/// Build an Arrow schema from a list of DuckLake table columns
pub fn build_arrow_schema(columns: &[DuckLakeTableColumn]) -> Result<Schema> {
let fields: Result<Vec<Field>> = columns
.iter()
.map(|col| {
let data_type = ducklake_to_arrow_type(&col.column_type)?;
Ok(Field::new(&col.column_name, data_type, col.is_nullable))
})
.collect();
Ok(Schema::new(fields?))
}
/// Extract field_id to column_name mapping from Parquet metadata.
/// DuckLake column_id == Parquet field_id, enabling column matching after renames.
pub fn extract_parquet_field_ids(metadata: &ParquetMetaData) -> HashMap<i32, String> {
let schema_descr = metadata.file_metadata().schema_descr();
let mut field_id_map = HashMap::new();
for i in 0..schema_descr.num_columns() {
let column = schema_descr.column(i);
let basic_info = column.self_type().get_basic_info();
if basic_info.has_id() {
let field_id = basic_info.id();
let column_name = column.name().to_string();
field_id_map.insert(field_id, column_name);
}
}
field_id_map
}
/// Build a schema for reading Parquet files with renamed columns.
/// Returns (read_schema, name_mapping) where read_schema uses original Parquet names
/// and name_mapping maps old->new for columns that were renamed.
pub fn build_read_schema_with_field_id_mapping(
current_columns: &[DuckLakeTableColumn],
parquet_field_ids: &HashMap<i32, String>,
) -> Result<(Schema, HashMap<String, String>)> {
let mut name_mapping: HashMap<String, String> = HashMap::new();
let fields: Result<Vec<Field>> = current_columns
.iter()
.map(|col| {
let data_type = ducklake_to_arrow_type(&col.column_type)?;
let field_id = i32::try_from(col.column_id).map_err(|_| {
DuckLakeError::Internal(format!(
"column_id {} for column '{}' exceeds i32 range for Parquet field_id",
col.column_id, col.column_name
))
})?;
let (read_name, needs_rename) =
if let Some(parquet_name) = parquet_field_ids.get(&field_id) {
if parquet_name != &col.column_name {
(parquet_name.clone(), true) // Column was renamed
} else {
(col.column_name.clone(), false)
}
} else {
(col.column_name.clone(), false) // No field_id, use current name
};
if needs_rename {
name_mapping.insert(read_name.clone(), col.column_name.clone());
}
Ok(Field::new(read_name, data_type, col.is_nullable))
})
.collect();
Ok((Schema::new(fields?), name_mapping))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_build_read_schema_with_renamed_columns() {
// Simulate: column was originally named "user_id", now renamed to "userId"
let current_columns = vec![
DuckLakeTableColumn {
column_id: 1,
column_name: "userId".to_string(), // Current name (renamed)
column_type: "int32".to_string(),
is_nullable: true,
},
DuckLakeTableColumn {
column_id: 2,
column_name: "name".to_string(), // Not renamed
column_type: "varchar".to_string(),
is_nullable: true,
},
];
// Parquet file has original names
let mut parquet_field_ids = HashMap::new();
parquet_field_ids.insert(1, "user_id".to_string()); // Original name
parquet_field_ids.insert(2, "name".to_string()); // Same name
let (read_schema, name_mapping) =
build_read_schema_with_field_id_mapping(¤t_columns, &parquet_field_ids).unwrap();
// Read schema should have original Parquet names
assert_eq!(read_schema.field(0).name(), "user_id");
assert_eq!(read_schema.field(1).name(), "name");
// Name mapping should map old name to new name
assert_eq!(name_mapping.len(), 1);
assert_eq!(name_mapping.get("user_id"), Some(&"userId".to_string()));
}
#[test]
fn test_build_read_schema_no_rename_needed() {
let current_columns = vec![DuckLakeTableColumn {
column_id: 1,
column_name: "id".to_string(),
column_type: "int32".to_string(),
is_nullable: true,
}];
let mut parquet_field_ids = HashMap::new();
parquet_field_ids.insert(1, "id".to_string()); // Same name
let (read_schema, name_mapping) =
build_read_schema_with_field_id_mapping(¤t_columns, &parquet_field_ids).unwrap();
assert_eq!(read_schema.field(0).name(), "id");
assert!(name_mapping.is_empty()); // No rename needed
}
#[test]
fn test_build_read_schema_no_field_ids() {
// External file without field_ids
let current_columns = vec![DuckLakeTableColumn {
column_id: 1,
column_name: "id".to_string(),
column_type: "int32".to_string(),
is_nullable: true,
}];
let parquet_field_ids = HashMap::new(); // No field_ids in Parquet
let (read_schema, name_mapping) =
build_read_schema_with_field_id_mapping(¤t_columns, &parquet_field_ids).unwrap();
// Falls back to current column name
assert_eq!(read_schema.field(0).name(), "id");
assert!(name_mapping.is_empty());
}
#[test]
fn test_basic_types() {
assert_eq!(
ducklake_to_arrow_type("boolean").unwrap(),
DataType::Boolean
);
assert_eq!(ducklake_to_arrow_type("int32").unwrap(), DataType::Int32);
assert_eq!(ducklake_to_arrow_type("int64").unwrap(), DataType::Int64);
assert_eq!(
ducklake_to_arrow_type("float64").unwrap(),
DataType::Float64
);
assert_eq!(ducklake_to_arrow_type("varchar").unwrap(), DataType::Utf8);
assert_eq!(ducklake_to_arrow_type("blob").unwrap(), DataType::Binary);
}
#[test]
fn test_decimal_types() {
assert_eq!(
ducklake_to_arrow_type("decimal(10, 2)").unwrap(),
DataType::Decimal128(10, 2)
);
assert_eq!(
ducklake_to_arrow_type("decimal(38, 10)").unwrap(),
DataType::Decimal128(38, 10)
);
}
#[test]
fn test_temporal_types() {
assert_eq!(ducklake_to_arrow_type("date").unwrap(), DataType::Date32);
assert_eq!(
ducklake_to_arrow_type("timestamp").unwrap(),
DataType::Timestamp(TimeUnit::Microsecond, None)
);
}
#[test]
fn test_unsupported_list_type_errors() {
// Test list type returns error
let result = ducklake_to_arrow_type("list<int32>");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("list<int32>"));
assert!(msg.contains("not yet supported"));
assert!(msg.contains("open an issue"));
},
_ => panic!("Expected UnsupportedType error for list type"),
}
}
#[test]
fn test_unsupported_array_type_errors() {
// Test array type returns error
let result = ducklake_to_arrow_type("array<varchar>");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("array<varchar>"));
assert!(msg.contains("not yet supported"));
},
_ => panic!("Expected UnsupportedType error for array type"),
}
}
#[test]
fn test_unsupported_struct_type_errors() {
// Test struct type returns error
let result = ducklake_to_arrow_type("struct<a:int32,b:varchar>");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("struct<a:int32,b:varchar>"));
assert!(msg.contains("not yet supported"));
assert!(msg.contains("open an issue"));
},
_ => panic!("Expected UnsupportedType error for struct type"),
}
}
#[test]
fn test_unsupported_map_type_errors() {
// Test map type returns error
let result = ducklake_to_arrow_type("map<varchar,int32>");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("map<varchar,int32>"));
assert!(msg.contains("not yet supported"));
assert!(msg.contains("open an issue"));
},
_ => panic!("Expected UnsupportedType error for map type"),
}
}
#[test]
fn test_nested_complex_types_error() {
// Test nested complex types return error
let result = ducklake_to_arrow_type("list<struct<a:int32,b:varchar>>");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("list<struct<a:int32,b:varchar>>"));
assert!(msg.contains("not yet supported"));
},
_ => panic!("Expected UnsupportedType error for nested complex type"),
}
}
#[test]
fn test_unknown_type_error() {
// Test completely unknown types also return error
let result = ducklake_to_arrow_type("completely_unknown_type");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert_eq!(msg, "completely_unknown_type");
},
_ => panic!("Expected UnsupportedType error for unknown type"),
}
}
#[test]
fn test_arrow_to_ducklake_basic_types() {
assert_eq!(
arrow_to_ducklake_type(&DataType::Boolean).unwrap(),
"boolean"
);
assert_eq!(arrow_to_ducklake_type(&DataType::Int8).unwrap(), "int8");
assert_eq!(arrow_to_ducklake_type(&DataType::Int16).unwrap(), "int16");
assert_eq!(arrow_to_ducklake_type(&DataType::Int32).unwrap(), "int32");
assert_eq!(arrow_to_ducklake_type(&DataType::Int64).unwrap(), "int64");
assert_eq!(arrow_to_ducklake_type(&DataType::UInt8).unwrap(), "uint8");
assert_eq!(arrow_to_ducklake_type(&DataType::UInt16).unwrap(), "uint16");
assert_eq!(arrow_to_ducklake_type(&DataType::UInt32).unwrap(), "uint32");
assert_eq!(arrow_to_ducklake_type(&DataType::UInt64).unwrap(), "uint64");
assert_eq!(
arrow_to_ducklake_type(&DataType::Float32).unwrap(),
"float32"
);
assert_eq!(
arrow_to_ducklake_type(&DataType::Float64).unwrap(),
"float64"
);
assert_eq!(arrow_to_ducklake_type(&DataType::Utf8).unwrap(), "varchar");
assert_eq!(arrow_to_ducklake_type(&DataType::Binary).unwrap(), "blob");
}
#[test]
fn test_arrow_to_ducklake_temporal_types() {
assert_eq!(arrow_to_ducklake_type(&DataType::Date32).unwrap(), "date");
assert_eq!(arrow_to_ducklake_type(&DataType::Date64).unwrap(), "date");
assert_eq!(
arrow_to_ducklake_type(&DataType::Time64(TimeUnit::Microsecond)).unwrap(),
"time"
);
assert_eq!(
arrow_to_ducklake_type(&DataType::Timestamp(TimeUnit::Microsecond, None)).unwrap(),
"timestamp"
);
assert_eq!(
arrow_to_ducklake_type(&DataType::Timestamp(
TimeUnit::Microsecond,
Some("UTC".into())
))
.unwrap(),
"timestamptz"
);
}
#[test]
fn test_arrow_to_ducklake_decimal() {
assert_eq!(
arrow_to_ducklake_type(&DataType::Decimal128(10, 2)).unwrap(),
"decimal(10, 2)"
);
assert_eq!(
arrow_to_ducklake_type(&DataType::Decimal256(40, 5)).unwrap(),
"decimal(40, 5)"
);
}
#[test]
fn test_arrow_to_ducklake_uuid() {
assert_eq!(
arrow_to_ducklake_type(&DataType::FixedSizeBinary(16)).unwrap(),
"uuid"
);
// Non-16 byte fixed size binary becomes blob
assert_eq!(
arrow_to_ducklake_type(&DataType::FixedSizeBinary(32)).unwrap(),
"blob"
);
}
#[test]
fn test_arrow_to_ducklake_roundtrip() {
// Verify roundtrip: arrow -> ducklake -> arrow for common types
let test_types = vec![
DataType::Boolean,
DataType::Int32,
DataType::Int64,
DataType::Float64,
DataType::Utf8,
DataType::Binary,
DataType::Date32,
DataType::Timestamp(TimeUnit::Microsecond, None),
DataType::Decimal128(10, 2),
];
for original in test_types {
let ducklake = arrow_to_ducklake_type(&original).unwrap();
let back = ducklake_to_arrow_type(&ducklake).unwrap();
assert_eq!(original, back, "Roundtrip failed for {:?}", original);
}
}
#[test]
fn test_arrow_to_ducklake_unsupported_list() {
let list_type = DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let result = arrow_to_ducklake_type(&list_type);
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("List type"));
assert!(msg.contains("not yet supported"));
},
_ => panic!("Expected UnsupportedType error"),
}
}
#[test]
fn test_arrow_to_ducklake_unsupported_struct() {
let struct_type = DataType::Struct(vec![Field::new("a", DataType::Int32, true)].into());
let result = arrow_to_ducklake_type(&struct_type);
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("Struct type"));
assert!(msg.contains("not yet supported"));
},
_ => panic!("Expected UnsupportedType error"),
}
}
#[test]
fn test_decimal_precision_zero_rejected() {
let result = ducklake_to_arrow_type("decimal(0, 0)");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("precision must be >= 1"));
},
_ => panic!("Expected UnsupportedType error for precision=0"),
}
}
#[test]
fn test_decimal_precision_too_large_rejected() {
let result = ducklake_to_arrow_type("decimal(77, 0)");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("precision must be <= 76"));
},
_ => panic!("Expected UnsupportedType error for precision=77"),
}
}
#[test]
fn test_decimal_precision_255_rejected() {
let result = ducklake_to_arrow_type("decimal(255, 0)");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("precision must be <= 76"));
},
_ => panic!("Expected UnsupportedType error for precision=255"),
}
}
#[test]
fn test_decimal_scale_exceeds_precision_rejected() {
let result = ducklake_to_arrow_type("decimal(10, 11)");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("scale (11) must not exceed precision (10)"));
},
_ => panic!("Expected UnsupportedType error for scale > precision"),
}
}
#[test]
fn test_decimal_valid_edge_cases() {
assert_eq!(
ducklake_to_arrow_type("decimal(1, 0)").unwrap(),
DataType::Decimal128(1, 0)
);
assert_eq!(
ducklake_to_arrow_type("decimal(38, 0)").unwrap(),
DataType::Decimal128(38, 0)
);
assert_eq!(
ducklake_to_arrow_type("decimal(39, 0)").unwrap(),
DataType::Decimal256(39, 0)
);
assert_eq!(
ducklake_to_arrow_type("decimal(76, 0)").unwrap(),
DataType::Decimal256(76, 0)
);
assert_eq!(
ducklake_to_arrow_type("decimal(10, 10)").unwrap(),
DataType::Decimal128(10, 10)
);
}
#[test]
fn test_decimal_negative_precision_rejected() {
let result = ducklake_to_arrow_type("decimal(-1, 0)");
assert!(result.is_err());
}
#[test]
fn test_decimal_too_many_parameters_rejected() {
let result = ducklake_to_arrow_type("decimal(1,2,3)");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("expected at most 2 parameters"));
assert!(msg.contains("got 3"));
},
_ => panic!("Expected UnsupportedType error for 3 parameters"),
}
let result = ducklake_to_arrow_type("decimal(10,2,5,3)");
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("expected at most 2 parameters"));
assert!(msg.contains("got 4"));
},
_ => panic!("Expected UnsupportedType error for 4 parameters"),
}
}
#[test]
fn test_decimal_negative_scale_valid() {
assert_eq!(
ducklake_to_arrow_type("decimal(10, -2)").unwrap(),
DataType::Decimal128(10, -2)
);
}
#[test]
fn test_build_schema_with_unsupported_type() {
// Test that build_arrow_schema propagates complex type errors
let columns = vec![
DuckLakeTableColumn {
column_id: 1,
column_name: "id".to_string(),
column_type: "int32".to_string(),
is_nullable: true,
},
DuckLakeTableColumn {
column_id: 2,
column_name: "data".to_string(),
column_type: "list<int32>".to_string(),
is_nullable: true,
},
];
let result = build_arrow_schema(&columns);
assert!(result.is_err());
match result {
Err(DuckLakeError::UnsupportedType(msg)) => {
assert!(msg.contains("list<int32>"));
},
_ => panic!("Expected UnsupportedType error when building schema with complex type"),
}
}
#[test]
fn test_column_id_i32_max_succeeds() {
let columns = vec![DuckLakeTableColumn {
column_id: i32::MAX as i64,
column_name: "id".to_string(),
column_type: "int32".to_string(),
is_nullable: true,
}];
let mut parquet_field_ids = HashMap::new();
parquet_field_ids.insert(i32::MAX, "id".to_string());
let result = build_read_schema_with_field_id_mapping(&columns, &parquet_field_ids);
assert!(result.is_ok(), "column_id = i32::MAX should succeed");
}
#[test]
fn test_column_id_overflow_returns_error() {
let columns = vec![DuckLakeTableColumn {
column_id: i32::MAX as i64 + 1, // 2147483648, exceeds i32 range
column_name: "id".to_string(),
column_type: "int32".to_string(),
is_nullable: true,
}];
let parquet_field_ids = HashMap::new();
let result = build_read_schema_with_field_id_mapping(&columns, &parquet_field_ids);
assert!(result.is_err(), "column_id > i32::MAX should fail");
match result {
Err(DuckLakeError::Internal(msg)) => {
assert!(
msg.contains("2147483648"),
"Error should contain the overflowing value: {}",
msg
);
assert!(
msg.contains("exceeds i32 range"),
"Error should explain the issue: {}",
msg
);
},
_ => panic!("Expected Internal error for column_id overflow"),
}
}
#[test]
fn test_column_id_negative_within_i32_range_succeeds() {
let columns = vec![DuckLakeTableColumn {
column_id: -1,
column_name: "id".to_string(),
column_type: "int32".to_string(),
is_nullable: true,
}];
let mut parquet_field_ids = HashMap::new();
parquet_field_ids.insert(-1_i32, "id".to_string());
let result = build_read_schema_with_field_id_mapping(&columns, &parquet_field_ids);
assert!(
result.is_ok(),
"Negative column_id within i32 range should succeed"
);
}
// ── normalize_ducklake_type tests ──
#[test]
fn test_normalize_int_aliases() {
assert_eq!(normalize_ducklake_type("int").unwrap(), "int32");
assert_eq!(normalize_ducklake_type("integer").unwrap(), "int32");
assert_eq!(normalize_ducklake_type("INT").unwrap(), "int32");
assert_eq!(normalize_ducklake_type("Integer").unwrap(), "int32");
assert_eq!(normalize_ducklake_type("int32").unwrap(), "int32");
}
#[test]
fn test_normalize_bigint_aliases() {
assert_eq!(normalize_ducklake_type("bigint").unwrap(), "int64");
assert_eq!(normalize_ducklake_type("long").unwrap(), "int64");
assert_eq!(normalize_ducklake_type("BIGINT").unwrap(), "int64");
assert_eq!(normalize_ducklake_type("int64").unwrap(), "int64");
}
#[test]
fn test_normalize_string_aliases() {