-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathpartitions.go
More file actions
580 lines (493 loc) · 16.6 KB
/
partitions.go
File metadata and controls
580 lines (493 loc) · 16.6 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
// 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.
package iceberg
import (
"encoding/json"
"errors"
"fmt"
"iter"
"net/url"
"slices"
"strings"
)
const (
PartitionDataIDStart = 1000
InitialPartitionSpecID = 0
unassignedFieldID = 0
)
// UnpartitionedSpec is the default unpartitioned spec which can
// be used for comparisons or to just provide a convenience for referencing
// the same unpartitioned spec object.
var UnpartitionedSpec = &PartitionSpec{id: 0}
// PartitionField represents how one partition value is derived from the
// source column by transformation.
type PartitionField struct {
// SourceIDs contains the source column ids from the table's schema.
// For single-argument transforms this will have exactly one element.
// For multi-argument transforms this will have multiple elements.
SourceIDs []int `json:"-"`
// FieldID is the partition field id across all the table partition specs
FieldID int `json:"field-id"`
// Name is the name of the partition field itself
Name string `json:"name"`
// Transform is the transform used to produce the partition value
Transform Transform `json:"transform"`
// escapedName is a cached URL-escaped version of Name for performance
// This is populated during initialization and not serialized
escapedName string
}
// SourceID returns the first source column id. For single-argument transforms
// this is the only source column. For multi-argument transforms this is the
// first source column.
func (p PartitionField) SourceID() int {
if len(p.SourceIDs) == 0 {
return 0
}
return p.SourceIDs[0]
}
// EscapedName returns the URL-escaped version of the partition field name.
func (p *PartitionField) EscapedName() string {
if p.escapedName == "" {
p.escapedName = url.QueryEscape(p.Name)
}
return p.escapedName
}
func (p PartitionField) MarshalJSON() ([]byte, error) {
if len(p.SourceIDs) > 1 {
return json.Marshal(struct {
SourceIDs []int `json:"source-ids"`
FieldID int `json:"field-id"`
Name string `json:"name"`
Transform Transform `json:"transform"`
}{p.SourceIDs, p.FieldID, p.Name, p.Transform})
}
return json.Marshal(struct {
SourceID int `json:"source-id"`
FieldID int `json:"field-id"`
Name string `json:"name"`
Transform Transform `json:"transform"`
}{p.SourceID(), p.FieldID, p.Name, p.Transform})
}
func (p PartitionField) Equals(other PartitionField) bool {
return slices.Equal(p.SourceIDs, other.SourceIDs) &&
p.FieldID == other.FieldID &&
p.Name == other.Name &&
p.Transform.Equals(other.Transform)
}
func (p *PartitionField) String() string {
if len(p.SourceIDs) > 1 {
return fmt.Sprintf("%d: %s: %s(%v)", p.FieldID, p.Name, p.Transform, p.SourceIDs)
}
return fmt.Sprintf("%d: %s: %s(%d)", p.FieldID, p.Name, p.Transform, p.SourceID())
}
func (p *PartitionField) UnmarshalJSON(b []byte) error {
var raw map[string]json.RawMessage
if err := json.Unmarshal(b, &raw); err != nil {
return fmt.Errorf("%w: failed to unmarshal partition field", err)
}
if _, ok := raw["source-id"]; ok {
if _, ok := raw["source-ids"]; ok {
return errors.New("partition field cannot contain both source-id and source-ids")
}
}
aux := struct {
SourceID int `json:"source-id"`
SourceIDs []int `json:"source-ids,omitempty"`
FieldID int `json:"field-id"`
Name string `json:"name"`
TransformString string `json:"transform"`
}{}
if err := json.Unmarshal(b, &aux); err != nil {
return err
}
p.FieldID = aux.FieldID
p.Name = aux.Name
if len(aux.SourceIDs) > 0 {
p.SourceIDs = aux.SourceIDs
} else {
p.SourceIDs = []int{aux.SourceID}
}
var err error
if p.Transform, err = ParseTransform(aux.TransformString); err != nil {
return err
}
return nil
}
// PartitionSpec captures the transformation from table data to partition values
type PartitionSpec struct {
// any change to a PartitionSpec will produce a new spec id
id int
fields []PartitionField
// this is populated by initialize after creation
sourceIdToFields map[int][]PartitionField
}
type PartitionOption func(*PartitionSpec) error
// BindToSchema creates a new PartitionSpec by copying the fields from the
// existing spec verifying compatibility with the schema.
//
// If newSpecID is not nil, it will be used as the spec id for the new spec.
// Otherwise, the existing spec id will be used.
// If a field in the spec is incompatible with the schema, an error will be
// returned.
func (p *PartitionSpec) BindToSchema(schema *Schema, lastPartitionID *int, newSpecID *int) (PartitionSpec, error) {
opts := make([]PartitionOption, 0)
if newSpecID != nil {
opts = append(opts, WithSpecID(*newSpecID))
} else {
opts = append(opts, WithSpecID(p.id))
}
for _, field := range p.Fields() {
opts = append(opts, AddPartitionFieldBySourceID(field.SourceID(), field.Name, field.Transform, schema, &field.FieldID))
}
freshSpec, err := NewPartitionSpecOpts(opts...)
if err != nil {
return PartitionSpec{}, err
}
if err = freshSpec.assignPartitionFieldIds(lastPartitionID); err != nil {
return PartitionSpec{}, err
}
return freshSpec, err
}
func NewPartitionSpecOpts(opts ...PartitionOption) (PartitionSpec, error) {
spec := PartitionSpec{
id: 0,
}
for _, opt := range opts {
if err := opt(&spec); err != nil {
return PartitionSpec{}, fmt.Errorf("%w: %w", ErrInvalidPartitionSpec, err)
}
}
spec.initialize()
return spec, nil
}
func WithSpecID(id int) PartitionOption {
return func(p *PartitionSpec) error {
p.id = id
return nil
}
}
func AddPartitionFieldByName(sourceName string, targetName string, transform Transform, schema *Schema, fieldID *int) PartitionOption {
return func(p *PartitionSpec) error {
if schema == nil {
return errors.New("cannot add partition field with nil schema")
}
field, ok := schema.FindFieldByName(sourceName)
if !ok {
return fmt.Errorf("cannot find source column with name: %s in schema", sourceName)
}
err := p.addSpecFieldInternal(targetName, field, transform, fieldID)
if err != nil {
return err
}
return nil
}
}
func AddPartitionFieldBySourceID(sourceID int, targetName string, transform Transform, schema *Schema, fieldID *int) PartitionOption {
return func(p *PartitionSpec) error {
if schema == nil {
return errors.New("cannot add partition field with nil schema")
}
field, ok := schema.FindFieldByID(sourceID)
if !ok {
return fmt.Errorf("cannot find source column with id: %d in schema", sourceID)
}
err := p.addSpecFieldInternal(targetName, field, transform, fieldID)
if err != nil {
return err
}
return nil
}
}
func (p *PartitionSpec) addSpecFieldInternal(targetName string, field NestedField, transform Transform, fieldID *int) error {
if targetName == "" {
return errors.New("cannot use empty partition name")
}
for _, existingField := range p.fields {
if existingField.Name == targetName {
return errors.New("duplicate partition name: " + targetName)
}
}
var fieldIDValue int
if fieldID == nil {
fieldIDValue = unassignedFieldID
} else {
fieldIDValue = *fieldID
}
if err := p.checkForRedundantPartitions(field.ID, transform); err != nil {
return err
}
unboundField := PartitionField{
SourceIDs: []int{field.ID},
FieldID: fieldIDValue,
Name: targetName,
Transform: transform,
}
p.fields = append(p.fields, unboundField)
return nil
}
func (p *PartitionSpec) checkForRedundantPartitions(sourceID int, transform Transform) error {
if fields, ok := p.sourceIdToFields[sourceID]; ok {
for _, f := range fields {
if f.Transform.Equals(transform) {
return fmt.Errorf("cannot add redundant partition with source id %d and transform %s. A partition with the same source id and transform already exists with name: %s",
sourceID,
transform,
f.Name)
}
}
}
return nil
}
func (p *PartitionSpec) Len() int {
return len(p.fields)
}
func (ps *PartitionSpec) assignPartitionFieldIds(lastAssignedFieldIDPtr *int) error {
// This is set_field_ids from iceberg-rust
// Already assigned partition ids. If we see one of these during iteration,
// we skip it.
assignedIds := make(map[int]struct{})
for _, field := range ps.fields {
if field.FieldID != unassignedFieldID {
if _, exists := assignedIds[field.FieldID]; exists {
return fmt.Errorf("duplicate field ID provided: %d", field.FieldID)
}
assignedIds[field.FieldID] = struct{}{}
}
}
lastAssignedFieldID := ps.LastAssignedFieldID()
if lastAssignedFieldIDPtr != nil {
lastAssignedFieldID = *lastAssignedFieldIDPtr
}
for i := range ps.fields {
if ps.fields[i].FieldID == unassignedFieldID {
// Find the next available ID by incrementing from the last known good ID.
lastAssignedFieldID++
for {
if _, exists := assignedIds[lastAssignedFieldID]; !exists {
break // Found an unused ID.
}
lastAssignedFieldID++
}
// Assign the new ID and immediately record it as used.
ps.fields[i].FieldID = lastAssignedFieldID
} else {
lastAssignedFieldID = max(lastAssignedFieldID, ps.fields[i].FieldID)
}
}
return nil
}
// NewPartitionSpec creates a new PartitionSpec with the given fields.
//
// The fields are not verified against a schema, use NewPartitionSpecOpts if you have to ensure compatibility.
func NewPartitionSpec(fields ...PartitionField) PartitionSpec {
return NewPartitionSpecID(InitialPartitionSpecID, fields...)
}
// NewPartitionSpecID creates a new PartitionSpec with the given fields and id.
//
// The fields are not verified against a schema, use NewPartitionSpecOpts if you have to ensure compatibility.
func NewPartitionSpecID(id int, fields ...PartitionField) PartitionSpec {
ret := PartitionSpec{id: id, fields: fields}
ret.initialize()
return ret
}
// CompatibleWith returns true if this partition spec is considered
// compatible with the passed in partition spec. This means that the two
// specs have equivalent field lists regardless of the spec id.
func (ps *PartitionSpec) CompatibleWith(other *PartitionSpec) bool {
if ps == other {
return true
}
if len(ps.fields) != len(other.fields) {
return false
}
return slices.EqualFunc(ps.fields, other.fields, func(left, right PartitionField) bool {
return slices.Equal(left.SourceIDs, right.SourceIDs) && left.Name == right.Name &&
left.Transform == right.Transform
})
}
// Equals returns true iff the field lists are the same AND the spec id
// is the same between this partition spec and the provided one.
func (ps PartitionSpec) Equals(other PartitionSpec) bool {
return ps.id == other.id && slices.EqualFunc(ps.fields, other.fields, func(a, b PartitionField) bool {
return a.Equals(b)
})
}
// Fields returns an iterator over the partition fields in this spec.
func (ps *PartitionSpec) Fields() iter.Seq2[int, PartitionField] {
return slices.All(ps.fields)
}
func (ps PartitionSpec) MarshalJSON() ([]byte, error) {
if ps.fields == nil {
ps.fields = []PartitionField{}
}
return json.Marshal(struct {
ID int `json:"spec-id"`
Fields []PartitionField `json:"fields"`
}{ps.id, ps.fields})
}
func (ps *PartitionSpec) UnmarshalJSON(b []byte) error {
aux := struct {
ID int `json:"spec-id"`
Fields []PartitionField `json:"fields"`
}{ID: ps.id, Fields: ps.fields}
if err := json.Unmarshal(b, &aux); err != nil {
return err
}
ps.id, ps.fields = aux.ID, aux.Fields
ps.initialize()
return nil
}
func (ps *PartitionSpec) initialize() {
ps.sourceIdToFields = make(map[int][]PartitionField)
for i := range ps.fields {
ps.sourceIdToFields[ps.fields[i].SourceID()] = append(ps.sourceIdToFields[ps.fields[i].SourceID()], ps.fields[i])
}
}
func (ps *PartitionSpec) ID() int { return ps.id }
func (ps *PartitionSpec) NumFields() int { return len(ps.fields) }
func (ps *PartitionSpec) Field(i int) PartitionField { return ps.fields[i] }
func (ps PartitionSpec) IsUnpartitioned() bool {
if len(ps.fields) == 0 {
return true
}
for _, f := range ps.fields {
if _, ok := f.Transform.(VoidTransform); !ok {
return false
}
}
return true
}
func (ps *PartitionSpec) FieldsBySourceID(fieldID int) []PartitionField {
return slices.Clone(ps.sourceIdToFields[fieldID])
}
func (ps PartitionSpec) String() string {
var b strings.Builder
b.WriteByte('[')
for i, f := range ps.fields {
if i == 0 {
b.WriteString("\n")
}
b.WriteString("\t")
b.WriteString(f.String())
b.WriteString("\n")
}
b.WriteByte(']')
return b.String()
}
func (ps *PartitionSpec) LastAssignedFieldID() int {
if len(ps.fields) == 0 {
return PartitionDataIDStart - 1
}
id := ps.fields[0].FieldID
for _, f := range ps.fields[1:] {
if f.FieldID > id {
id = f.FieldID
}
}
if id == unassignedFieldID {
// If no fields have been assigned an ID, return the default starting ID.
return PartitionDataIDStart - 1
}
return id
}
// PartitionType produces a struct of the partition spec.
//
// The partition fields should be optional:
// - All partition transforms are required to produce null if the input value
// is null. This can happen when the source column is optional.
// - Partition fields may be added later, in which case not all files would
// have the result field and it may be null.
//
// There is a case where we can guarantee that a partition field in the first
// and only parittion spec that uses a required source column will never be
// null, but it doesn't seem worth tracking this case.
func (ps *PartitionSpec) PartitionType(schema *Schema) *StructType {
nestedFields := []NestedField{}
for _, field := range ps.fields {
sourceType, ok := schema.FindTypeByID(field.SourceID())
if !ok {
continue
}
resultType := field.Transform.ResultType(sourceType)
nestedFields = append(nestedFields, NestedField{
ID: field.FieldID,
Name: field.Name,
Type: resultType,
Required: false,
})
}
return &StructType{FieldList: nestedFields}
}
// PartitionToPath produces a proper partition path from the data and schema by
// converting the values to human readable strings and properly escaping.
//
// The path will be in the form of `name1=value1/name2=value2/...`.
//
// This does not apply the transforms to the data, it is assumed the provided data
// has already been transformed appropriately.
func (ps *PartitionSpec) PartitionToPath(data StructLike, sc *Schema) string {
partType := ps.PartitionType(sc)
if len(partType.FieldList) == 0 {
return ""
}
// Use strings.Builder for efficient string concatenation
// Estimate capacity: escaped_name + "=" + escaped_value + "/" per field
var sb strings.Builder
estimatedSize := 0
for i := range partType.Fields() {
estimatedSize += len(ps.fields[i].EscapedName()) + 20 // name + "=" + avg value + "/"
}
sb.Grow(estimatedSize)
for i := range partType.Fields() {
if i > 0 {
sb.WriteByte('/')
}
// Use pre-escaped field name (now guaranteed to be initialized)
sb.WriteString(ps.fields[i].EscapedName())
sb.WriteByte('=')
// Only escape the value (which changes per row)
valueStr := ps.fields[i].Transform.ToHumanStr(data.Get(i))
sb.WriteString(url.QueryEscape(valueStr))
}
return sb.String()
}
// GeneratePartitionFieldName returns default partition field name based on field transform type
//
// The default names are aligned with other client implementations
// https://github.com/apache/iceberg/blob/main/core/src/main/java/org/apache/iceberg/BaseUpdatePartitionSpec.java#L518-L563
func GeneratePartitionFieldName(schema *Schema, field PartitionField) (string, error) {
if len(field.Name) > 0 {
return field.Name, nil
}
sourceName, exists := schema.FindColumnName(field.SourceID())
if !exists {
return "", fmt.Errorf("could not find field with id %d", field.SourceID())
}
transform := field.Transform
switch t := transform.(type) {
case IdentityTransform:
return sourceName, nil
case VoidTransform:
return sourceName + "_null", nil
case BucketTransform:
return fmt.Sprintf("%s_bucket_%d", sourceName, t.NumBuckets), nil
case TruncateTransform:
return fmt.Sprintf("%s_trunc_%d", sourceName, t.Width), nil
default:
return sourceName + "_" + t.String(), nil
}
}