Repository navigation
Expand file tree
/
Copy pathschema.rs
More file actions
3853 lines (3522 loc) · 143 KB
/
Copy pathschema.rs
File metadata and controls
3853 lines (3522 loc) · 143 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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 crate::spec::core_options::{
first_row_supports_changelog_producer, ChangelogProducer, CoreOptions, MergeEngine,
BLOB_DESCRIPTOR_FIELD_OPTION, BLOB_FIELD_OPTION, BLOB_VIEW_FIELD_OPTION, BUCKET_KEY_OPTION,
QUERY_AUTH_ENABLED_OPTION, SEQUENCE_FIELD_OPTION,
};
use crate::spec::types::{ArrayType, DataType, MapType, MultisetType, RowType, VarCharType};
use crate::spec::{
remove_field_scoped_options, rename_field_scoped_options, AggregationConfig, BlobType,
ColumnMove, ColumnMoveType, PartialUpdateConfig,
};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use std::collections::{HashMap, HashSet};
const BLOB_FIELD_DIRECTIVE: &str = "__BLOB_FIELD";
const BLOB_DESCRIPTOR_FIELD_DIRECTIVE: &str = "__BLOB_DESCRIPTOR_FIELD";
const BLOB_VIEW_FIELD_DIRECTIVE: &str = "__BLOB_VIEW_FIELD";
/// The table schema for paimon table.
///
/// Impl References: <https://github.com/apache/paimon/blob/release-0.8.2/paimon-core/src/main/java/org/apache/paimon/schema/TableSchema.java#L47>
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TableSchema {
/// version of schema for paimon
version: i32,
id: i64,
fields: Vec<DataField>,
highest_field_id: i32,
partition_keys: Vec<String>,
primary_keys: Vec<String>,
options: HashMap<String, String>,
comment: Option<String>,
time_millis: i64,
}
impl TableSchema {
pub const CURRENT_VERSION: i32 = 3;
/// Create a TableSchema from a Schema with the given ID.
///
/// Reference: <https://github.com/apache/paimon/blob/release-0.8.2/paimon-core/src/main/java/org/apache/paimon/schema/TableSchema.java#L373>
pub fn new(id: i64, schema: &Schema) -> Self {
let fields = schema.fields().to_vec();
let highest_field_id = Self::current_highest_field_id(&fields);
Self {
version: Self::CURRENT_VERSION,
id,
fields,
highest_field_id,
partition_keys: schema.partition_keys().to_vec(),
primary_keys: schema.primary_keys().to_vec(),
options: schema.options().clone(),
comment: schema.comment().map(|s| s.to_string()),
time_millis: chrono::Utc::now().timestamp_millis(),
}
}
/// Get the highest field ID from a list of fields, including fields nested
/// inside row types (mirrors Java `RowType.currentHighestFieldId`).
pub fn current_highest_field_id(fields: &[DataField]) -> i32 {
fields
.iter()
.map(|f| f.id().max(highest_nested_field_id(f.data_type())))
.max()
.unwrap_or(-1)
}
pub fn version(&self) -> i32 {
self.version
}
pub fn id(&self) -> i64 {
self.id
}
pub fn fields(&self) -> &[DataField] {
&self.fields
}
pub fn highest_field_id(&self) -> i32 {
self.highest_field_id
}
pub fn partition_keys(&self) -> &[String] {
&self.partition_keys
}
pub fn partition_fields(&self) -> Vec<DataField> {
self.partition_keys
.iter()
.filter_map(|key| self.fields.iter().find(|f| f.name() == key).cloned())
.collect()
}
pub fn primary_keys(&self) -> &[String] {
&self.primary_keys
}
/// Primary keys with partition columns removed.
///
/// Within a single partition the partition columns are constant, so they
/// are redundant in the KV key. Java Paimon calls these "trimmed primary keys".
pub fn trimmed_primary_keys(&self) -> Vec<String> {
if self.partition_keys.is_empty() {
return self.primary_keys.clone();
}
let partition_set: HashSet<&str> = self.partition_keys.iter().map(String::as_str).collect();
self.primary_keys
.iter()
.filter(|pk| !partition_set.contains(pk.as_str()))
.cloned()
.collect()
}
pub fn options(&self) -> &HashMap<String, String> {
&self.options
}
/// Typed view over this schema's table options.
pub fn core_options(&self) -> CoreOptions<'_> {
CoreOptions::new(&self.options)
}
/// Create a copy of this schema with extra options merged in.
///
/// A stored `query-auth.enabled = true` can't be turned off by a dynamic override.
pub fn copy_with_options(&self, mut extra: HashMap<String, String>) -> Self {
if self.core_options().query_auth_enabled() {
extra.insert(QUERY_AUTH_ENABLED_OPTION.to_string(), "true".to_string());
}
let mut new_schema = self.clone();
new_schema.options.extend(extra);
new_schema
}
/// Create a copy of this schema with the options replaced entirely,
/// keeping id, fields, keys, comment, and timestamps.
///
/// Corresponds to Java `TableSchema.copy(Map<String, String> newOptions)`,
/// which constructs a new schema with the given options rather than
/// merging them.
pub fn copy_with_replaced_options(&self, options: HashMap<String, String>) -> Self {
let mut new_schema = self.clone();
new_schema.options = options;
new_schema
}
/// Validate the structural invariants of an externally supplied, already
/// resolved schema, without normalizing or mutating it.
///
/// This is the safety check for [`crate::table::Table::from_resolved_schema`],
/// whose input is untrusted JSON. It rejects the malformed shapes that would
/// otherwise panic or silently read the wrong column downstream:
/// - duplicate top-level field names (a projected name could resolve to a
/// different field than a predicate on the same name),
/// - duplicate field ids (including nested), which break schema-evolution
/// column mapping,
/// - primary-key or partition columns that do not exist (e.g. the
/// `PartitionComputer` unwraps on a missing partition column),
/// - primary keys that are exactly the partition columns (the read path
/// selects the key-value merge path from the raw primary keys but feeds
/// the reader the *trimmed* keys, which are then empty, panicking on a
/// zero-column key),
/// - reserved system field names / ids (e.g. a user column named `_ROW_ID`
/// would be silently replaced by the system row number on read).
///
/// It intentionally does NOT run create-time policy checks (merge-engine,
/// changelog, aggregation, rowkind, blob strategy, bucket-key existence, …):
/// those normalize the schema or reject shapes that are valid to *read*,
/// which is not this entry point's contract.
pub(crate) fn validate_resolved_structure(&self) -> crate::Result<()> {
let field_names: Vec<String> = self.fields.iter().map(|f| f.name().to_string()).collect();
Schema::validate_no_duplicate_fields(&field_names)?;
Schema::validate_primary_keys(&field_names, &self.primary_keys)?;
Schema::validate_partition_keys(&field_names, &self.partition_keys)?;
Schema::validate_primary_keys_not_partition_only(&self.partition_keys, &self.primary_keys)?;
self.validate_no_duplicate_field_ids()?;
self.validate_no_reserved_fields()?;
Ok(())
}
/// Reject reserved system field names, the `_KEY_` key-field prefix, and
/// reserved system field ids, mirroring Java `SpecialFields`. A user column
/// colliding with a system field (e.g. `_ROW_ID`) is otherwise excluded
/// from the physical read and silently filled with the system value.
fn validate_no_reserved_fields(&self) -> crate::Result<()> {
// Java SpecialFields.SYSTEM_FIELD_ID_START = Integer.MAX_VALUE / 2.
const SYSTEM_FIELD_ID_START: i32 = i32::MAX / 2;
validate_no_reserved_field_names(&self.fields)?;
for field in &self.fields {
if field.id() >= SYSTEM_FIELD_ID_START {
return Err(crate::Error::DataInvalid {
message: format!(
"Field '{}' uses reserved system field id {}",
field.name(),
field.id()
),
source: None,
});
}
}
Ok(())
}
/// Reject duplicate field ids, including ids nested inside complex types.
/// Field ids key schema-evolution column mapping, so a collision would map
/// two logical columns onto one id.
fn validate_no_duplicate_field_ids(&self) -> crate::Result<()> {
let mut seen = HashSet::new();
let mut ids = Vec::new();
collect_field_ids(&self.fields, &mut ids);
for id in ids {
if !seen.insert(id) {
return Err(crate::Error::DataInvalid {
message: format!("Table schema must not contain duplicate field id: {id}"),
source: None,
});
}
}
Ok(())
}
/// Apply a list of schema changes and return a new schema with incremented ID.
///
/// Column-level changes operate on **top-level** columns only: a
/// `field_names` path with more than one element (a nested struct field) is
/// rejected with [`crate::Error::Unsupported`].
///
/// Column errors ([`crate::Error::ColumnNotExist`] /
/// [`crate::Error::ColumnAlreadyExist`]) are returned with an empty table
/// name; the calling catalog fills in the table's full name.
pub fn apply_changes(&self, changes: Vec<crate::spec::SchemaChange>) -> crate::Result<Self> {
use crate::spec::SchemaChange;
// Column errors carry no table name here; the catalog layer fills it in.
let full_name = "";
// Both flags are read from the pre-alter options, mirroring Java
// `SchemaManager.applySchemaChanges`.
let disable_null_to_not_null = self
.options
.get(crate::spec::DISABLE_ALTER_COLUMN_NULL_TO_NOT_NULL_OPTION)
.map(|v| v == "true")
.unwrap_or(true);
let allow_explicit_cast = self
.options
.get(crate::spec::DISABLE_EXPLICIT_TYPE_CASTING_OPTION)
.map(|v| v != "true")
.unwrap_or(true);
let mut new_schema = self.clone();
new_schema.id += 1;
new_schema.time_millis = chrono::Utc::now().timestamp_millis();
// Operate on an owned field list, then write it back.
let mut fields = std::mem::take(&mut new_schema.fields);
let mut highest_field_id = new_schema.highest_field_id;
for change in changes {
match change {
SchemaChange::SetOption { key, value } => {
new_schema.options.insert(key, value);
}
SchemaChange::RemoveOption { key } => {
new_schema.options.remove(&key);
}
SchemaChange::UpdateComment { comment } => {
new_schema.comment = comment;
}
SchemaChange::AddColumn {
field_names,
mut data_type,
mut comment,
column_move,
} => {
let name = top_level_field(&field_names)?;
if field_index(&fields, name).is_some() {
return Err(crate::Error::ColumnAlreadyExist {
full_name: full_name.to_string(),
column: name.to_string(),
});
}
if let Some(directive) = parse_blob_comment_directive(comment.as_deref())? {
append_csv_option(&mut new_schema.options, directive.option_key, name);
comment = directive.comment;
data_type = normalize_blob_field_type(name, data_type)?;
}
// Mirrors Java: an added column has no value for existing
// rows, so it must be nullable.
if !data_type.is_nullable() {
return Err(crate::Error::ConfigInvalid {
message: format!("Column {name} cannot specify NOT NULL."),
});
}
highest_field_id += 1;
let id = highest_field_id;
let data_type = reassign_field_ids(data_type, &mut highest_field_id);
let field =
DataField::new(id, name.to_string(), data_type).with_description(comment);
insert_field_with_move(&mut fields, field, column_move.as_ref(), full_name)?;
}
SchemaChange::RenameColumn {
field_names,
new_name,
} => {
let name = top_level_field(&field_names)?;
// Existing partition data is laid out with the old key name
// in paths and metadata; renaming would break resolution.
if new_schema.partition_keys.iter().any(|k| k == name) {
return Err(crate::Error::Unsupported {
message: format!("Cannot rename partition column: [{name}]"),
});
}
assert_not_updating_primary_key_index_column(&self.options, name, "rename")?;
let idx =
field_index(&fields, name).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: name.to_string(),
})?;
if new_name != name && field_index(&fields, &new_name).is_some() {
return Err(crate::Error::ColumnAlreadyExist {
full_name: full_name.to_string(),
column: new_name,
});
}
fields[idx] = fields[idx].clone().with_name(new_name.clone());
rename_in_keys(&mut new_schema.primary_keys, name, &new_name);
rename_in_option_list(
&mut new_schema.options,
BUCKET_KEY_OPTION,
name,
&new_name,
);
rename_in_option_list(
&mut new_schema.options,
SEQUENCE_FIELD_OPTION,
name,
&new_name,
);
// Field-scoped aggregation options encode the column in the
// key (`fields.<col>.aggregate-function` / `.list-agg-delimiter`),
// so they must be rewritten too, mirroring Java
// `SchemaManager.applyRenameColumnsToOptions`.
rename_field_scoped_options(&mut new_schema.options, name, &new_name);
}
SchemaChange::DropColumn { field_names } => {
let name = top_level_field(&field_names)?;
let idx =
field_index(&fields, name).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: name.to_string(),
})?;
if new_schema.partition_keys.iter().any(|k| k == name)
|| new_schema.primary_keys.iter().any(|k| k == name)
{
return Err(crate::Error::Unsupported {
message: format!(
"Cannot drop partition or primary key column '{name}' of table {full_name}"
),
});
}
assert_not_updating_primary_key_index_column(&self.options, name, "drop")?;
// Dropping a column referenced by `bucket-key` / `sequence.field`
// would silently break bucket assignment / sequence ordering on
// existing data (e.g. `bucket_key_indices` becomes empty and writes
// fall back to bucket 0), so reject it instead.
{
let core_options = CoreOptions::new(&new_schema.options);
if core_options
.bucket_key()
.is_some_and(|keys| keys.iter().any(|k| k == name))
{
return Err(crate::Error::Unsupported {
message: format!(
"Cannot drop column '{name}' referenced by '{BUCKET_KEY_OPTION}'"
),
});
}
if core_options.sequence_fields().contains(&name) {
return Err(crate::Error::Unsupported {
message: format!(
"Cannot drop column '{name}' referenced by '{SEQUENCE_FIELD_OPTION}'"
),
});
}
}
if fields.len() == 1 {
return Err(crate::Error::Unsupported {
message: "Cannot drop all fields in table".to_string(),
});
}
fields.remove(idx);
// Drop the column's field-scoped aggregation options so no
// orphaned `fields.<col>.*` keys remain (which would otherwise
// fail the aggregation re-validation below).
remove_field_scoped_options(&mut new_schema.options, name);
}
SchemaChange::UpdateColumnType {
field_names,
new_data_type,
keep_nullability,
} => {
let name = top_level_field(&field_names)?;
// Existing partitions, bucket assignment, and key encoding
// were all written with the old key type.
if new_schema.partition_keys.iter().any(|k| k == name) {
return Err(crate::Error::Unsupported {
message: format!("Cannot update partition column: [{name}]"),
});
}
if new_schema.primary_keys.iter().any(|k| k == name) {
return Err(crate::Error::Unsupported {
message: "Cannot update primary key".to_string(),
});
}
assert_not_updating_primary_key_index_column(
&self.options,
name,
"update type of",
)?;
let idx =
field_index(&fields, name).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: name.to_string(),
})?;
let old = &fields[idx];
// Mirrors Java `assertNotChangingBlobColumnType`: BLOB
// columns use a dedicated storage layout that other types
// cannot be converted to or from.
if old.data_type().is_blob_type() || new_data_type.is_blob_type() {
return Err(crate::Error::Unsupported {
message: format!(
"Cannot change column type involving BLOB: [{name}] {:?} -> {new_data_type:?}",
old.data_type()
),
});
}
let target = if keep_nullability {
new_data_type.copy_with_nullable(old.data_type().is_nullable())?
} else {
assert_nullability_change(
old.data_type().is_nullable(),
new_data_type.is_nullable(),
name,
disable_null_to_not_null,
)?;
new_data_type
};
// Existing data files keep the old schema; the read path
// casts old columns to the new type, so the change must be
// both a supported Paimon cast and executable by arrow.
let arrow_castable = arrow_cast::can_cast_types(
&crate::arrow::paimon_type_to_arrow(old.data_type())?,
&crate::arrow::paimon_type_to_arrow(&target)?,
);
if !crate::spec::supports_cast(old.data_type(), &target, allow_explicit_cast)
|| !arrow_castable
{
return Err(crate::Error::Unsupported {
message: format!(
"Column type {name}[{:?}] cannot be converted to {target:?} without losing information.",
old.data_type()
),
});
}
fields[idx] = DataField::new(old.id(), old.name().to_string(), target)
.with_description(old.description().map(|s| s.to_string()));
}
SchemaChange::UpdateColumnNullability {
field_names,
new_nullability,
} => {
let name = top_level_field(&field_names)?;
// Primary keys are normalized to NOT NULL at create time;
// a nullable key column would break key/bucket semantics.
if new_nullability && new_schema.primary_keys.iter().any(|k| k == name) {
return Err(crate::Error::Unsupported {
message: "Cannot change nullability of primary key".to_string(),
});
}
let idx =
field_index(&fields, name).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: name.to_string(),
})?;
let old = &fields[idx];
assert_nullability_change(
old.data_type().is_nullable(),
new_nullability,
name,
disable_null_to_not_null,
)?;
let nt = old.data_type().copy_with_nullable(new_nullability)?;
fields[idx] = DataField::new(old.id(), old.name().to_string(), nt)
.with_description(old.description().map(|s| s.to_string()));
}
SchemaChange::UpdateColumnComment {
field_names,
new_comment,
} => {
let name = top_level_field(&field_names)?;
let idx =
field_index(&fields, name).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: name.to_string(),
})?;
fields[idx] = fields[idx].clone().with_description(Some(new_comment));
}
SchemaChange::UpdateColumnPosition { column_move } => {
apply_move(&mut fields, &column_move, full_name)?;
}
}
}
new_schema.fields = fields;
new_schema.highest_field_id =
highest_field_id.max(Self::current_highest_field_id(&new_schema.fields));
if PartialUpdateConfig::new(&new_schema.options).is_enabled()
&& self.core_options().ignore_delete()
&& !CoreOptions::new(&new_schema.options).ignore_delete()
{
return Err(crate::Error::Unsupported {
message: "Cannot change ignore-delete from true to false.".to_string(),
});
}
// Re-run create-time validations on the final schema, mirroring Java
// `SchemaValidation.validateTableSchema` after applying changes.
validate_no_reserved_field_names(&new_schema.fields)?;
Schema::validate_key_field_types(
&new_schema.fields,
&new_schema.primary_keys,
&new_schema.options,
)?;
Schema::validate_blob_fields(
&new_schema.fields,
&new_schema.partition_keys,
&new_schema.options,
)?;
Schema::validate_vector_store_fields(
&new_schema.fields,
&new_schema.partition_keys,
&new_schema.options,
)?;
PartialUpdateConfig::new(&new_schema.options)
.validate_create_mode(!new_schema.primary_keys.is_empty())?;
AggregationConfig::new(&new_schema.options)
.validate_create_mode(&new_schema.primary_keys, &new_schema.fields)?;
Schema::validate_first_row_changelog_producer(&new_schema.options)?;
Schema::validate_rowkind_field(
&new_schema.options,
&new_schema.primary_keys,
&new_schema.fields,
)?;
Schema::validate_bucket_keys(
&new_schema.options,
&new_schema.fields,
&new_schema.partition_keys,
&new_schema.primary_keys,
)?;
Schema::validate_read_batch_size(&new_schema.options)?;
Ok(new_schema)
}
pub fn comment(&self) -> Option<&str> {
self.comment.as_deref()
}
pub fn time_millis(&self) -> i64 {
self.time_millis
}
/// Compute the effective bucket key columns.
///
/// Priority: explicit `bucket-key` option > primary keys > all non-partition fields.
pub fn bucket_keys(&self) -> Vec<String> {
let core_options = CoreOptions::new(&self.options);
if let Some(keys) = core_options.bucket_key() {
return keys;
}
if !self.primary_keys.is_empty() {
return self.trimmed_primary_keys();
}
let partition_set: HashSet<&str> = self.partition_keys.iter().map(String::as_str).collect();
self.fields
.iter()
.filter(|f| !partition_set.contains(f.name()))
.map(|f| f.name().to_string())
.collect()
}
}
/// Reject column names reserved for system use, mirroring Java `SpecialFields`:
/// the five `SYSTEM_FIELD_NAMES` and the `_KEY_` key-field prefix.
///
/// A user column colliding with a system field is otherwise excluded from the
/// physical read and silently filled with the system value.
fn validate_no_reserved_field_names(fields: &[DataField]) -> crate::Result<()> {
// Java SpecialFields.SYSTEM_FIELD_NAMES.
const SYSTEM_FIELD_NAMES: [&str; 5] = [
SEQUENCE_NUMBER_FIELD_NAME,
VALUE_KIND_FIELD_NAME,
"_LEVEL",
ROW_KIND_FIELD_NAME,
ROW_ID_FIELD_NAME,
];
const KEY_FIELD_PREFIX: &str = "_KEY_";
for field in fields {
let name = field.name();
if name.starts_with(KEY_FIELD_PREFIX) || SYSTEM_FIELD_NAMES.contains(&name) {
return Err(crate::Error::ConfigInvalid {
message: format!(
"Field name '{name}' is reserved for system use and cannot be used in a table schema"
),
});
}
}
Ok(())
}
/// Extract the single top-level column name from a `field_names` path.
///
/// Nested struct field paths (length > 1) are not yet supported.
fn top_level_field(field_names: &[String]) -> crate::Result<&str> {
match field_names {
[name] => Ok(name.as_str()),
[] => Err(crate::Error::ConfigInvalid {
message: "Schema change has empty fieldNames".to_string(),
}),
_ => Err(crate::Error::Unsupported {
message: format!("Altering nested struct fields is not supported yet: {field_names:?}"),
}),
}
}
/// Index of the field with the given name, if any.
fn field_index(fields: &[DataField], name: &str) -> Option<usize> {
fields.iter().position(|f| f.name() == name)
}
/// Mirrors Java `SchemaManager.assertNullabilityChange`: converting a nullable
/// column to NOT NULL is rejected unless explicitly enabled, because existing
/// rows may already contain NULLs.
fn assert_nullability_change(
old_nullable: bool,
new_nullable: bool,
field_name: &str,
disable_null_to_not_null: bool,
) -> crate::Result<()> {
if disable_null_to_not_null && old_nullable && !new_nullable {
return Err(crate::Error::Unsupported {
message: format!(
"Cannot update column type from nullable to non nullable for {field_name}. \
You can set table configuration option 'alter-column-null-to-not-null.disabled' = 'false' \
to allow converting null columns to not null"
),
});
}
Ok(())
}
/// Reject destructive changes to columns referenced by a primary-key index.
///
/// The index metadata and existing index files are tied to the original column
/// name and type. Mirrors Java
/// `SchemaManager.assertNotUpdatingPrimaryKeyIndexColumn`.
fn assert_not_updating_primary_key_index_column(
options: &HashMap<String, String>,
field_name: &str,
operation: &str,
) -> crate::Result<()> {
let core_options = CoreOptions::new(options);
let is_vector_index_column = core_options.primary_key_vector_index_enabled()
&& core_options
.primary_key_vector_index_columns()?
.iter()
.any(|column| column == field_name);
let is_full_text_index_column = core_options
.primary_key_full_text_index_columns()
.iter()
.any(|column| column == field_name);
if is_vector_index_column || is_full_text_index_column {
return Err(crate::Error::Unsupported {
message: format!("Cannot {operation} primary-key index column: [{field_name}]"),
});
}
Ok(())
}
/// Rename a key in a partition/primary key list, if present.
fn rename_in_keys(keys: &mut [String], old: &str, new: &str) {
for key in keys.iter_mut() {
if key == old {
*key = new.to_string();
}
}
}
/// Rename a column inside a comma-separated column-list option (`bucket-key`,
/// `sequence.field`), if the option is set and references the column.
///
/// Mirrors Java `SchemaManager.applyRenameColumnsToOptions`.
fn rename_in_option_list(
options: &mut HashMap<String, String>,
option_key: &str,
old: &str,
new: &str,
) {
let Some(value) = options.get(option_key) else {
return;
};
let renamed = value
.split(',')
.map(|col| if col == old { new } else { col })
.collect::<Vec<_>>()
.join(",");
options.insert(option_key.to_string(), renamed);
}
/// The highest field ID nested inside a data type, or -1 if it contains none.
fn highest_nested_field_id(data_type: &DataType) -> i32 {
match data_type {
DataType::Array(t) => highest_nested_field_id(t.element_type()),
DataType::Multiset(t) => highest_nested_field_id(t.element_type()),
DataType::Map(t) => {
highest_nested_field_id(t.key_type()).max(highest_nested_field_id(t.value_type()))
}
DataType::Row(t) => t
.fields()
.iter()
.map(|f| f.id().max(highest_nested_field_id(f.data_type())))
.max()
.unwrap_or(-1),
_ => -1,
}
}
/// Collect the field ids of `fields` and of any fields nested inside their
/// complex types, in traversal order. Used to detect duplicate ids.
fn collect_field_ids(fields: &[DataField], out: &mut Vec<i32>) {
for field in fields {
out.push(field.id());
collect_nested_field_ids(field.data_type(), out);
}
}
fn collect_nested_field_ids(data_type: &DataType, out: &mut Vec<i32>) {
match data_type {
DataType::Array(t) => collect_nested_field_ids(t.element_type(), out),
DataType::Multiset(t) => collect_nested_field_ids(t.element_type(), out),
DataType::Map(t) => {
collect_nested_field_ids(t.key_type(), out);
collect_nested_field_ids(t.value_type(), out);
}
DataType::Row(t) => collect_field_ids(t.fields(), out),
_ => {}
}
}
/// Reassign the IDs of all row fields nested inside a data type from the
/// table-wide highest field ID, so they cannot collide with existing fields.
///
/// Mirrors Java `ReassignFieldId`: IDs nested inside a field's type are
/// assigned before the field's own ID.
fn reassign_field_ids(data_type: DataType, next_id: &mut i32) -> DataType {
let nullable = data_type.is_nullable();
match data_type {
DataType::Array(t) => DataType::Array(ArrayType::with_nullable(
nullable,
reassign_field_ids(t.element_type().clone(), next_id),
)),
DataType::Multiset(t) => DataType::Multiset(MultisetType::with_nullable(
nullable,
reassign_field_ids(t.element_type().clone(), next_id),
)),
DataType::Map(t) => DataType::Map(MapType::with_nullable(
nullable,
reassign_field_ids(t.key_type().clone(), next_id),
reassign_field_ids(t.value_type().clone(), next_id),
)),
DataType::Row(t) => {
let fields = t
.fields()
.iter()
.map(|f| {
let typ = reassign_field_ids(f.data_type().clone(), next_id);
*next_id += 1;
DataField::new(*next_id, f.name().to_string(), typ)
.with_description(f.description().map(|s| s.to_string()))
})
.collect();
DataType::Row(RowType::with_nullable(nullable, fields))
}
other => other,
}
}
struct BlobCommentDirective {
option_key: &'static str,
comment: Option<String>,
}
fn parse_blob_comment_directive(
comment: Option<&str>,
) -> crate::Result<Option<BlobCommentDirective>> {
let Some(comment) = comment else {
return Ok(None);
};
let comment = comment.trim();
if !comment.starts_with("__BLOB") {
return Ok(None);
}
let Some((option_key, marker)) = match_blob_comment_directive(comment) else {
return Err(crate::Error::ConfigInvalid {
message: format!(
"Unsupported BLOB comment directive '{comment}'. Supported directives are \
'{BLOB_FIELD_DIRECTIVE}', '{BLOB_DESCRIPTOR_FIELD_DIRECTIVE}', and \
'{BLOB_VIEW_FIELD_DIRECTIVE}'."
),
});
};
let real_comment = if comment.len() == marker.len() {
None
} else {
let real_comment = comment[marker.len() + 1..].trim();
(!real_comment.is_empty()).then(|| real_comment.to_string())
};
Ok(Some(BlobCommentDirective {
option_key,
comment: real_comment,
}))
}
fn match_blob_comment_directive(comment: &str) -> Option<(&'static str, &'static str)> {
[
(BLOB_VIEW_FIELD_DIRECTIVE, BLOB_VIEW_FIELD_OPTION),
(
BLOB_DESCRIPTOR_FIELD_DIRECTIVE,
BLOB_DESCRIPTOR_FIELD_OPTION,
),
(BLOB_FIELD_DIRECTIVE, BLOB_FIELD_OPTION),
]
.into_iter()
.find_map(|(marker, option_key)| {
if !comment.starts_with(marker) {
return None;
}
if comment.len() == marker.len() || comment.as_bytes().get(marker.len()) == Some(&b';') {
Some((option_key, marker))
} else {
None
}
})
}
fn append_csv_option(options: &mut HashMap<String, String>, key: &'static str, field_name: &str) {
let value = append_csv_field(options.get(key).map(String::as_str), field_name);
options.insert(key.to_string(), value);
}
fn append_csv_field(existing: Option<&str>, field_name: &str) -> String {
let mut fields = existing
.into_iter()
.flat_map(|value| value.split(','))
.map(str::trim)
.filter(|field| !field.is_empty())
.map(ToString::to_string)
.collect::<Vec<_>>();
if !fields.iter().any(|field| field == field_name) {
fields.push(field_name.to_string());
}
fields.join(",")
}
fn normalize_blob_field_type(field_name: &str, data_type: DataType) -> crate::Result<DataType> {
let nullable = data_type.is_nullable();
match data_type {
DataType::Blob(_) => Ok(data_type),
DataType::Binary(_) | DataType::VarBinary(_) => {
Ok(DataType::Blob(BlobType::with_nullable(nullable)))
}
other => Err(crate::Error::ConfigInvalid {
message: format!(
"BLOB field option references non-binary column '{field_name}' with type {other:?}"
),
}),
}
}
/// Insert a brand-new field according to an optional move (used by `AddColumn`).
fn insert_field_with_move(
fields: &mut Vec<DataField>,
field: DataField,
column_move: Option<&ColumnMove>,
full_name: &str,
) -> crate::Result<()> {
let Some(mv) = column_move else {
fields.push(field);
return Ok(());
};
match mv.move_type() {
ColumnMoveType::FIRST => fields.insert(0, field),
ColumnMoveType::LAST => fields.push(field),
ColumnMoveType::AFTER | ColumnMoveType::BEFORE => {
let reference = move_reference(mv)?;
let ref_idx =
field_index(fields, reference).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: reference.to_string(),
})?;
let at = match mv.move_type() {
ColumnMoveType::AFTER => ref_idx + 1,
_ => ref_idx,
};
fields.insert(at, field);
}
}
Ok(())
}
/// Move an existing field to a new position (used by `UpdateColumnPosition`).
///
/// Mirrors Java `SchemaManager.applyMove`: remove the field first, then resolve
/// the reference index in the reduced list so the offset is already adjusted.
fn apply_move(fields: &mut Vec<DataField>, mv: &ColumnMove, full_name: &str) -> crate::Result<()> {
let idx = field_index(fields, mv.field_name()).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: mv.field_name().to_string(),
})?;
let field = fields.remove(idx);
match mv.move_type() {
ColumnMoveType::FIRST => fields.insert(0, field),
ColumnMoveType::LAST => fields.push(field),
ColumnMoveType::AFTER | ColumnMoveType::BEFORE => {
let reference = move_reference(mv)?;
let ref_idx =
field_index(fields, reference).ok_or_else(|| crate::Error::ColumnNotExist {
full_name: full_name.to_string(),
column: reference.to_string(),
})?;
let at = match mv.move_type() {
ColumnMoveType::AFTER => ref_idx + 1,
_ => ref_idx,
};
fields.insert(at, field);
}
}
Ok(())
}
/// The reference (anchor) field name required by `AFTER`/`BEFORE` moves.
fn move_reference(mv: &ColumnMove) -> crate::Result<&str> {
mv.reference_field_name()
.ok_or_else(|| crate::Error::ConfigInvalid {
message: format!(
"Move of type {:?} requires a reference field name",
mv.move_type()
),
})
}
pub const ROW_ID_FIELD_NAME: &str = "_ROW_ID";
pub const ROW_ID_FIELD_ID: i32 = i32::MAX - 5;
pub const SEQUENCE_NUMBER_FIELD_NAME: &str = "_SEQUENCE_NUMBER";
/// Must match Java Paimon's `SpecialFields.SEQUENCE_NUMBER` (Integer.MAX_VALUE - 1).
pub const SEQUENCE_NUMBER_FIELD_ID: i32 = i32::MAX - 1;
pub const VALUE_KIND_FIELD_NAME: &str = "_VALUE_KIND";
/// Must match Java Paimon's `SpecialFields.VALUE_KIND` (Integer.MAX_VALUE - 2).
pub const VALUE_KIND_FIELD_ID: i32 = i32::MAX - 2;
pub const ROW_KIND_FIELD_NAME: &str = "rowkind";