-
Notifications
You must be signed in to change notification settings - Fork 189
/
partition.rs
1869 lines (1703 loc) · 60.9 KB
/
partition.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
// 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.
/*!
* Partitioning
*/
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;
use super::transform::Transform;
use super::{NestedField, Schema, SchemaRef, StructType};
use crate::{Error, ErrorKind, Result};
pub(crate) const UNPARTITIONED_LAST_ASSIGNED_ID: i32 = 999;
pub(crate) const DEFAULT_PARTITION_SPEC_ID: i32 = 0;
/// Reference to [`BoundPartitionSpec`].
pub type BoundPartitionSpecRef = Arc<BoundPartitionSpec>;
/// Partition fields capture the transform from table data to partition values.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, TypedBuilder)]
#[serde(rename_all = "kebab-case")]
pub struct PartitionField {
/// A source column id from the table’s schema
pub source_id: i32,
/// A partition field id that is used to identify a partition field and is unique within a partition spec.
/// In v2 table metadata, it is unique across all partition specs.
pub field_id: i32,
/// A partition name.
pub name: String,
/// A transform that is applied to the source column to produce a partition value.
pub transform: Transform,
}
impl PartitionField {
/// To unbound partition field
pub fn into_unbound(self) -> UnboundPartitionField {
self.into()
}
}
/// Partition spec that defines how to produce a tuple of partition values from a record.
/// `PartitionSpec` is bound to a specific schema.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct BoundPartitionSpec {
/// Identifier for PartitionSpec
spec_id: i32,
/// Details of the partition spec
fields: Vec<PartitionField>,
/// The schema this partition spec is bound to
schema: SchemaRef,
/// Type of the partition spec
partition_type: StructType,
}
/// Reference to [`SchemalessPartitionSpec`].
pub type SchemalessPartitionSpecRef = Arc<SchemalessPartitionSpec>;
/// Partition spec that defines how to produce a tuple of partition values from a record.
/// Schemaless partition specs are never constructed manually. They occur when a table is mutated
/// and partition spec and schemas are updated. While old partition specs are retained, the bound
/// schema might not be available anymore as part of the table metadata.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct SchemalessPartitionSpec {
/// Identifier for PartitionSpec
spec_id: i32,
/// Details of the partition spec
fields: Vec<PartitionField>,
}
impl BoundPartitionSpec {
/// Create partition spec builder
pub fn builder(schema: impl Into<SchemaRef>) -> PartitionSpecBuilder {
PartitionSpecBuilder::new(schema)
}
/// Get a new unpatitioned partition spec
pub fn unpartition_spec(schema: impl Into<SchemaRef>) -> Self {
Self {
spec_id: DEFAULT_PARTITION_SPEC_ID,
fields: vec![],
schema: schema.into(),
partition_type: StructType::new(vec![]),
}
}
/// Spec id of the partition spec
pub fn spec_id(&self) -> i32 {
self.spec_id
}
/// Fields of the partition spec
pub fn fields(&self) -> &[PartitionField] {
&self.fields
}
/// The schema this partition spec is bound to
pub fn schema(&self) -> &Schema {
&self.schema
}
/// The schema ref this partition spec is bound to
pub fn schema_ref(&self) -> &SchemaRef {
&self.schema
}
/// Returns if the partition spec is unpartitioned.
///
/// A [`PartitionSpec`] is unpartitioned if it has no fields or all fields are [`Transform::Void`] transform.
pub fn is_unpartitioned(&self) -> bool {
self.fields.is_empty() || self.fields.iter().all(|f| f.transform == Transform::Void)
}
/// Turn this partition spec into an unbound partition spec.
///
/// The `field_id` is retained as `partition_id` in the unbound partition spec.
pub fn into_unbound(self) -> UnboundPartitionSpec {
self.into()
}
/// Turn this partition spec into a preserved partition spec.
pub fn into_schemaless(self) -> SchemalessPartitionSpec {
self.into()
}
/// Check if this partition spec has sequential partition ids.
/// Sequential ids start from 1000 and increment by 1 for each field.
/// This is required for spec version 1
pub fn has_sequential_ids(&self) -> bool {
has_sequential_ids(self.fields.iter().map(|f| f.field_id))
}
/// Get the highest field id in the partition spec.
/// If the partition spec is unpartitioned, it returns the last unpartitioned last assigned id (999).
pub fn highest_field_id(&self) -> Option<i32> {
self.fields.iter().map(|f| f.field_id).max()
}
/// Returns the partition type of this partition spec.
pub fn partition_type(&self) -> &StructType {
&self.partition_type
}
/// Check if this partition spec is compatible with another partition spec.
///
/// Returns true if the partition spec is equal to the other spec with partition field ids ignored and
/// spec_id ignored. The following must be identical:
/// * The number of fields
/// * Field order
/// * Field names
/// * Source column ids
/// * Transforms
pub fn is_compatible_with_schemaless(&self, other: &SchemalessPartitionSpec) -> bool {
if self.fields.len() != other.fields.len() {
return false;
}
for (this_field, other_field) in self.fields.iter().zip(other.fields.iter()) {
if this_field.source_id != other_field.source_id
|| this_field.name != other_field.name
|| this_field.transform != other_field.transform
{
return false;
}
}
true
}
}
impl SchemalessPartitionSpec {
/// Fields of the partition spec
pub fn fields(&self) -> &[PartitionField] {
&self.fields
}
/// Spec id of the partition spec
pub fn spec_id(&self) -> i32 {
self.spec_id
}
/// Bind this schemaless partition spec to a schema.
pub fn bind(self, schema: impl Into<SchemaRef>) -> Result<BoundPartitionSpec> {
PartitionSpecBuilder::new_from_unbound(self.into_unbound(), schema)?.build()
}
/// Get a new unpatitioned partition spec
pub fn unpartition_spec() -> Self {
Self {
spec_id: DEFAULT_PARTITION_SPEC_ID,
fields: vec![],
}
}
/// Returns the partition type of this partition spec.
pub fn partition_type(&self, schema: &Schema) -> Result<StructType> {
PartitionSpecBuilder::partition_type(&self.fields, schema)
}
/// Convert to unbound partition spec
pub fn into_unbound(self) -> UnboundPartitionSpec {
self.into()
}
}
/// Reference to [`UnboundPartitionSpec`].
pub type UnboundPartitionSpecRef = Arc<UnboundPartitionSpec>;
/// Unbound partition field can be built without a schema and later bound to a schema.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, TypedBuilder)]
#[serde(rename_all = "kebab-case")]
pub struct UnboundPartitionField {
/// A source column id from the table’s schema
pub source_id: i32,
/// A partition field id that is used to identify a partition field and is unique within a partition spec.
/// In v2 table metadata, it is unique across all partition specs.
#[builder(default, setter(strip_option))]
pub field_id: Option<i32>,
/// A partition name.
pub name: String,
/// A transform that is applied to the source column to produce a partition value.
pub transform: Transform,
}
/// Unbound partition spec can be built without a schema and later bound to a schema.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
#[serde(rename_all = "kebab-case")]
pub struct UnboundPartitionSpec {
/// Identifier for PartitionSpec
pub(crate) spec_id: Option<i32>,
/// Details of the partition spec
pub(crate) fields: Vec<UnboundPartitionField>,
}
impl UnboundPartitionSpec {
/// Create unbound partition spec builder
pub fn builder() -> UnboundPartitionSpecBuilder {
UnboundPartitionSpecBuilder::default()
}
/// Bind this unbound partition spec to a schema.
pub fn bind(self, schema: impl Into<SchemaRef>) -> Result<BoundPartitionSpec> {
PartitionSpecBuilder::new_from_unbound(self, schema)?.build()
}
/// Spec id of the partition spec
pub fn spec_id(&self) -> Option<i32> {
self.spec_id
}
/// Fields of the partition spec
pub fn fields(&self) -> &[UnboundPartitionField] {
&self.fields
}
/// Change the spec id of the partition spec
pub fn with_spec_id(self, spec_id: i32) -> Self {
Self {
spec_id: Some(spec_id),
..self
}
}
}
fn has_sequential_ids(field_ids: impl Iterator<Item = i32>) -> bool {
for (index, field_id) in field_ids.enumerate() {
let expected_id = (UNPARTITIONED_LAST_ASSIGNED_ID as i64)
.checked_add(1)
.and_then(|id| id.checked_add(index as i64))
.unwrap_or(i64::MAX);
if field_id as i64 != expected_id {
return false;
}
}
true
}
impl From<PartitionField> for UnboundPartitionField {
fn from(field: PartitionField) -> Self {
UnboundPartitionField {
source_id: field.source_id,
field_id: Some(field.field_id),
name: field.name,
transform: field.transform,
}
}
}
impl From<BoundPartitionSpec> for UnboundPartitionSpec {
fn from(spec: BoundPartitionSpec) -> Self {
UnboundPartitionSpec {
spec_id: Some(spec.spec_id),
fields: spec.fields.into_iter().map(Into::into).collect(),
}
}
}
impl From<SchemalessPartitionSpec> for UnboundPartitionSpec {
fn from(spec: SchemalessPartitionSpec) -> Self {
UnboundPartitionSpec {
spec_id: Some(spec.spec_id),
fields: spec.fields.into_iter().map(Into::into).collect(),
}
}
}
impl From<BoundPartitionSpec> for SchemalessPartitionSpec {
fn from(spec: BoundPartitionSpec) -> Self {
SchemalessPartitionSpec {
spec_id: spec.spec_id,
fields: spec.fields,
}
}
}
/// Create a new UnboundPartitionSpec
#[derive(Debug, Default)]
pub struct UnboundPartitionSpecBuilder {
spec_id: Option<i32>,
fields: Vec<UnboundPartitionField>,
}
impl UnboundPartitionSpecBuilder {
/// Create a new partition spec builder with the given schema.
pub fn new() -> Self {
Self {
spec_id: None,
fields: vec![],
}
}
/// Set the spec id for the partition spec.
pub fn with_spec_id(mut self, spec_id: i32) -> Self {
self.spec_id = Some(spec_id);
self
}
/// Add a new partition field to the partition spec from an unbound partition field.
pub fn add_partition_field(
self,
source_id: i32,
target_name: impl ToString,
transformation: Transform,
) -> Result<Self> {
let field = UnboundPartitionField {
source_id,
field_id: None,
name: target_name.to_string(),
transform: transformation,
};
self.add_partition_field_internal(field)
}
/// Add multiple partition fields to the partition spec.
pub fn add_partition_fields(
self,
fields: impl IntoIterator<Item = UnboundPartitionField>,
) -> Result<Self> {
let mut builder = self;
for field in fields {
builder = builder.add_partition_field_internal(field)?;
}
Ok(builder)
}
fn add_partition_field_internal(mut self, field: UnboundPartitionField) -> Result<Self> {
self.check_name_set_and_unique(&field.name)?;
self.check_for_redundant_partitions(field.source_id, &field.transform)?;
if let Some(partition_field_id) = field.field_id {
self.check_partition_id_unique(partition_field_id)?;
}
self.fields.push(field);
Ok(self)
}
/// Build the unbound partition spec.
pub fn build(self) -> UnboundPartitionSpec {
UnboundPartitionSpec {
spec_id: self.spec_id,
fields: self.fields,
}
}
}
/// Create valid partition specs for a given schema.
#[derive(Debug)]
pub struct PartitionSpecBuilder {
spec_id: Option<i32>,
last_assigned_field_id: i32,
fields: Vec<UnboundPartitionField>,
schema: SchemaRef,
}
impl PartitionSpecBuilder {
/// Create a new partition spec builder with the given schema.
pub fn new(schema: impl Into<SchemaRef>) -> Self {
Self {
spec_id: None,
fields: vec![],
last_assigned_field_id: UNPARTITIONED_LAST_ASSIGNED_ID,
schema: schema.into(),
}
}
/// Create a new partition spec builder from an existing unbound partition spec.
pub fn new_from_unbound(
unbound: UnboundPartitionSpec,
schema: impl Into<SchemaRef>,
) -> Result<Self> {
let mut builder =
Self::new(schema).with_spec_id(unbound.spec_id.unwrap_or(DEFAULT_PARTITION_SPEC_ID));
for field in unbound.fields {
builder = builder.add_unbound_field(field)?;
}
Ok(builder)
}
/// Set the last assigned field id for the partition spec.
///
/// Set this field when a new partition spec is created for an existing TableMetaData.
/// As `field_id` must be unique in V2 metadata, this should be set to
/// the highest field id used previously.
pub fn with_last_assigned_field_id(mut self, last_assigned_field_id: i32) -> Self {
self.last_assigned_field_id = last_assigned_field_id;
self
}
/// Set the spec id for the partition spec.
pub fn with_spec_id(mut self, spec_id: i32) -> Self {
self.spec_id = Some(spec_id);
self
}
/// Add a new partition field to the partition spec.
pub fn add_partition_field(
self,
source_name: impl AsRef<str>,
target_name: impl Into<String>,
transform: Transform,
) -> Result<Self> {
let source_id = self
.schema
.field_by_name(source_name.as_ref())
.ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!(
"Cannot find source column with name: {} in schema",
source_name.as_ref()
),
)
})?
.id;
let field = UnboundPartitionField {
source_id,
field_id: None,
name: target_name.into(),
transform,
};
self.add_unbound_field(field)
}
/// Add a new partition field to the partition spec.
///
/// If partition field id is set, it is used as the field id.
/// Otherwise, a new `field_id` is assigned.
pub fn add_unbound_field(mut self, field: UnboundPartitionField) -> Result<Self> {
self.check_name_set_and_unique(&field.name)?;
self.check_for_redundant_partitions(field.source_id, &field.transform)?;
Self::check_name_does_not_collide_with_schema(&field, &self.schema)?;
Self::check_transform_compatibility(&field, &self.schema)?;
if let Some(partition_field_id) = field.field_id {
self.check_partition_id_unique(partition_field_id)?;
}
// Non-fallible from here
self.fields.push(field);
Ok(self)
}
/// Wrapper around `with_unbound_fields` to add multiple partition fields.
pub fn add_unbound_fields(
self,
fields: impl IntoIterator<Item = UnboundPartitionField>,
) -> Result<Self> {
let mut builder = self;
for field in fields {
builder = builder.add_unbound_field(field)?;
}
Ok(builder)
}
/// Build a bound partition spec with the given schema.
pub fn build(self) -> Result<BoundPartitionSpec> {
let fields = Self::set_field_ids(self.fields, self.last_assigned_field_id)?;
let partition_type = Self::partition_type(&fields, &self.schema)?;
Ok(BoundPartitionSpec {
spec_id: self.spec_id.unwrap_or(DEFAULT_PARTITION_SPEC_ID),
fields,
partition_type,
schema: self.schema,
})
}
fn set_field_ids(
fields: Vec<UnboundPartitionField>,
last_assigned_field_id: i32,
) -> Result<Vec<PartitionField>> {
let mut last_assigned_field_id = last_assigned_field_id;
// Already assigned partition ids. If we see one of these during iteration,
// we skip it.
let assigned_ids = fields
.iter()
.filter_map(|f| f.field_id)
.collect::<std::collections::HashSet<_>>();
fn _check_add_1(prev: i32) -> Result<i32> {
prev.checked_add(1).ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
"Cannot assign more partition ids. Overflow.",
)
})
}
let mut bound_fields = Vec::with_capacity(fields.len());
for field in fields.into_iter() {
let partition_field_id = if let Some(partition_field_id) = field.field_id {
last_assigned_field_id = std::cmp::max(last_assigned_field_id, partition_field_id);
partition_field_id
} else {
last_assigned_field_id = _check_add_1(last_assigned_field_id)?;
while assigned_ids.contains(&last_assigned_field_id) {
last_assigned_field_id = _check_add_1(last_assigned_field_id)?;
}
last_assigned_field_id
};
bound_fields.push(PartitionField {
source_id: field.source_id,
field_id: partition_field_id,
name: field.name,
transform: field.transform,
})
}
Ok(bound_fields)
}
/// Returns the partition type of this partition spec.
fn partition_type(fields: &Vec<PartitionField>, schema: &Schema) -> Result<StructType> {
let mut struct_fields = Vec::with_capacity(fields.len());
for partition_field in fields {
let field = schema
.field_by_id(partition_field.source_id)
.ok_or_else(|| {
Error::new(
// This should never occur as check_transform_compatibility
// already ensures that the source field exists in the schema
ErrorKind::Unexpected,
format!(
"No column with source column id {} in schema {:?}",
partition_field.source_id, schema
),
)
})?;
let res_type = partition_field.transform.result_type(&field.field_type)?;
let field =
NestedField::optional(partition_field.field_id, &partition_field.name, res_type)
.into();
struct_fields.push(field);
}
Ok(StructType::new(struct_fields))
}
/// Ensure that the partition name is unique among columns in the schema.
/// Duplicate names are allowed if:
/// 1. The column is sourced from the column with the same name.
/// 2. AND the transformation is identity
fn check_name_does_not_collide_with_schema(
field: &UnboundPartitionField,
schema: &Schema,
) -> Result<()> {
match schema.field_by_name(field.name.as_str()) {
Some(schema_collision) => {
if field.transform == Transform::Identity {
if schema_collision.id == field.source_id {
Ok(())
} else {
Err(Error::new(
ErrorKind::DataInvalid,
format!(
"Cannot create identity partition sourced from different field in schema. Field name '{}' has id `{}` in schema but partition source id is `{}`",
field.name, schema_collision.id, field.source_id
),
))
}
} else {
Err(Error::new(
ErrorKind::DataInvalid,
format!(
"Cannot create partition with name: '{}' that conflicts with schema field and is not an identity transform.",
field.name
),
))
}
}
None => Ok(()),
}
}
/// Ensure that the transformation of the field is compatible with type of the field
/// in the schema. Implicitly also checks if the source field exists in the schema.
fn check_transform_compatibility(field: &UnboundPartitionField, schema: &Schema) -> Result<()> {
let schema_field = schema.field_by_id(field.source_id).ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!(
"Cannot find partition source field with id `{}` in schema",
field.source_id
),
)
})?;
if field.transform != Transform::Void {
if !schema_field.field_type.is_primitive() {
return Err(Error::new(
ErrorKind::DataInvalid,
format!(
"Cannot partition by non-primitive source field: '{}'.",
schema_field.field_type
),
));
}
if field
.transform
.result_type(&schema_field.field_type)
.is_err()
{
return Err(Error::new(
ErrorKind::DataInvalid,
format!(
"Invalid source type: '{}' for transform: '{}'.",
schema_field.field_type,
field.transform.dedup_name()
),
));
}
}
Ok(())
}
}
/// Contains checks that are common to both PartitionSpecBuilder and UnboundPartitionSpecBuilder
trait CorePartitionSpecValidator {
/// Ensure that the partition name is unique among the partition fields and is not empty.
fn check_name_set_and_unique(&self, name: &str) -> Result<()> {
if name.is_empty() {
return Err(Error::new(
ErrorKind::DataInvalid,
"Cannot use empty partition name",
));
}
if self.fields().iter().any(|f| f.name == name) {
return Err(Error::new(
ErrorKind::DataInvalid,
format!("Cannot use partition name more than once: {}", name),
));
}
Ok(())
}
/// For a single source-column transformations must be unique.
fn check_for_redundant_partitions(&self, source_id: i32, transform: &Transform) -> Result<()> {
let collision = self.fields().iter().find(|f| {
f.source_id == source_id && f.transform.dedup_name() == transform.dedup_name()
});
if let Some(collision) = collision {
Err(Error::new(
ErrorKind::DataInvalid,
format!(
"Cannot add redundant partition with source id `{}` and transform `{}`. A partition with the same source id and transform already exists with name `{}`",
source_id, transform.dedup_name(), collision.name
),
))
} else {
Ok(())
}
}
/// Check field / partition_id unique within the partition spec if set
fn check_partition_id_unique(&self, field_id: i32) -> Result<()> {
if self.fields().iter().any(|f| f.field_id == Some(field_id)) {
return Err(Error::new(
ErrorKind::DataInvalid,
format!(
"Cannot use field id more than once in one PartitionSpec: {}",
field_id
),
));
}
Ok(())
}
fn fields(&self) -> &Vec<UnboundPartitionField>;
}
impl CorePartitionSpecValidator for PartitionSpecBuilder {
fn fields(&self) -> &Vec<UnboundPartitionField> {
&self.fields
}
}
impl CorePartitionSpecValidator for UnboundPartitionSpecBuilder {
fn fields(&self) -> &Vec<UnboundPartitionField> {
&self.fields
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::spec::{PrimitiveType, Type};
#[test]
fn test_partition_spec() {
let spec = r#"
{
"spec-id": 1,
"fields": [ {
"source-id": 4,
"field-id": 1000,
"name": "ts_day",
"transform": "day"
}, {
"source-id": 1,
"field-id": 1001,
"name": "id_bucket",
"transform": "bucket[16]"
}, {
"source-id": 2,
"field-id": 1002,
"name": "id_truncate",
"transform": "truncate[4]"
} ]
}
"#;
let partition_spec: SchemalessPartitionSpec = serde_json::from_str(spec).unwrap();
assert_eq!(4, partition_spec.fields[0].source_id);
assert_eq!(1000, partition_spec.fields[0].field_id);
assert_eq!("ts_day", partition_spec.fields[0].name);
assert_eq!(Transform::Day, partition_spec.fields[0].transform);
assert_eq!(1, partition_spec.fields[1].source_id);
assert_eq!(1001, partition_spec.fields[1].field_id);
assert_eq!("id_bucket", partition_spec.fields[1].name);
assert_eq!(Transform::Bucket(16), partition_spec.fields[1].transform);
assert_eq!(2, partition_spec.fields[2].source_id);
assert_eq!(1002, partition_spec.fields[2].field_id);
assert_eq!("id_truncate", partition_spec.fields[2].name);
assert_eq!(Transform::Truncate(4), partition_spec.fields[2].transform);
}
#[test]
fn test_is_unpartitioned() {
let schema = Schema::builder()
.with_fields(vec![
NestedField::required(1, "id", Type::Primitive(crate::spec::PrimitiveType::Int))
.into(),
NestedField::required(
2,
"name",
Type::Primitive(crate::spec::PrimitiveType::String),
)
.into(),
])
.build()
.unwrap();
let partition_spec = BoundPartitionSpec::builder(schema.clone())
.with_spec_id(1)
.build()
.unwrap();
assert!(
partition_spec.is_unpartitioned(),
"Empty partition spec should be unpartitioned"
);
let partition_spec = BoundPartitionSpec::builder(schema.clone())
.add_unbound_fields(vec![
UnboundPartitionField::builder()
.source_id(1)
.name("id".to_string())
.transform(Transform::Identity)
.build(),
UnboundPartitionField::builder()
.source_id(2)
.name("name_string".to_string())
.transform(Transform::Void)
.build(),
])
.unwrap()
.with_spec_id(1)
.build()
.unwrap();
assert!(
!partition_spec.is_unpartitioned(),
"Partition spec with one non void transform should not be unpartitioned"
);
let partition_spec = BoundPartitionSpec::builder(schema.clone())
.with_spec_id(1)
.add_unbound_fields(vec![
UnboundPartitionField::builder()
.source_id(1)
.name("id_void".to_string())
.transform(Transform::Void)
.build(),
UnboundPartitionField::builder()
.source_id(2)
.name("name_void".to_string())
.transform(Transform::Void)
.build(),
])
.unwrap()
.build()
.unwrap();
assert!(
partition_spec.is_unpartitioned(),
"Partition spec with all void field should be unpartitioned"
);
}
#[test]
fn test_unbound_partition_spec() {
let spec = r#"
{
"spec-id": 1,
"fields": [ {
"source-id": 4,
"field-id": 1000,
"name": "ts_day",
"transform": "day"
}, {
"source-id": 1,
"field-id": 1001,
"name": "id_bucket",
"transform": "bucket[16]"
}, {
"source-id": 2,
"field-id": 1002,
"name": "id_truncate",
"transform": "truncate[4]"
} ]
}
"#;
let partition_spec: UnboundPartitionSpec = serde_json::from_str(spec).unwrap();
assert_eq!(Some(1), partition_spec.spec_id);
assert_eq!(4, partition_spec.fields[0].source_id);
assert_eq!(Some(1000), partition_spec.fields[0].field_id);
assert_eq!("ts_day", partition_spec.fields[0].name);
assert_eq!(Transform::Day, partition_spec.fields[0].transform);
assert_eq!(1, partition_spec.fields[1].source_id);
assert_eq!(Some(1001), partition_spec.fields[1].field_id);
assert_eq!("id_bucket", partition_spec.fields[1].name);
assert_eq!(Transform::Bucket(16), partition_spec.fields[1].transform);
assert_eq!(2, partition_spec.fields[2].source_id);
assert_eq!(Some(1002), partition_spec.fields[2].field_id);
assert_eq!("id_truncate", partition_spec.fields[2].name);
assert_eq!(Transform::Truncate(4), partition_spec.fields[2].transform);
let spec = r#"
{
"fields": [ {
"source-id": 4,
"name": "ts_day",
"transform": "day"
} ]
}
"#;
let partition_spec: UnboundPartitionSpec = serde_json::from_str(spec).unwrap();
assert_eq!(None, partition_spec.spec_id);
assert_eq!(4, partition_spec.fields[0].source_id);
assert_eq!(None, partition_spec.fields[0].field_id);
assert_eq!("ts_day", partition_spec.fields[0].name);
assert_eq!(Transform::Day, partition_spec.fields[0].transform);
}
#[test]
fn test_new_unpartition() {
let schema = Schema::builder()
.with_fields(vec![
NestedField::required(1, "id", Type::Primitive(crate::spec::PrimitiveType::Int))
.into(),
NestedField::required(
2,
"name",
Type::Primitive(crate::spec::PrimitiveType::String),
)
.into(),
])
.build()
.unwrap();
let partition_spec = BoundPartitionSpec::builder(schema.clone())
.with_spec_id(0)
.build()
.unwrap();
let partition_type = partition_spec.partition_type();
assert_eq!(0, partition_type.fields().len());
let unpartition_spec = BoundPartitionSpec::unpartition_spec(schema);
assert_eq!(partition_spec, unpartition_spec);
}
#[test]
fn test_partition_type() {
let spec = r#"
{
"spec-id": 1,
"fields": [ {
"source-id": 4,
"field-id": 1000,
"name": "ts_day",
"transform": "day"
}, {
"source-id": 1,
"field-id": 1001,
"name": "id_bucket",
"transform": "bucket[16]"
}, {
"source-id": 2,
"field-id": 1002,
"name": "id_truncate",
"transform": "truncate[4]"
} ]
}
"#;
let partition_spec: SchemalessPartitionSpec = serde_json::from_str(spec).unwrap();
let schema = Schema::builder()
.with_fields(vec![
NestedField::required(1, "id", Type::Primitive(crate::spec::PrimitiveType::Int))
.into(),
NestedField::required(
2,
"name",
Type::Primitive(crate::spec::PrimitiveType::String),
)
.into(),
NestedField::required(
3,
"ts",
Type::Primitive(crate::spec::PrimitiveType::Timestamp),
)
.into(),
NestedField::required(
4,
"ts_day",
Type::Primitive(crate::spec::PrimitiveType::Timestamp),
)
.into(),
NestedField::required(
5,
"id_bucket",
Type::Primitive(crate::spec::PrimitiveType::Int),
)
.into(),
NestedField::required(
6,
"id_truncate",