github.com/parquet-go/parquet-go@v0.20.0/column.go (about) 1 package parquet 2 3 import ( 4 "encoding/binary" 5 "fmt" 6 "io" 7 "reflect" 8 9 "github.com/parquet-go/parquet-go/compress" 10 "github.com/parquet-go/parquet-go/deprecated" 11 "github.com/parquet-go/parquet-go/encoding" 12 "github.com/parquet-go/parquet-go/format" 13 "github.com/parquet-go/parquet-go/internal/unsafecast" 14 ) 15 16 // Column represents a column in a parquet file. 17 // 18 // Methods of Column values are safe to call concurrently from multiple 19 // goroutines. 20 // 21 // Column instances satisfy the Node interface. 22 type Column struct { 23 typ Type 24 file *File 25 schema *format.SchemaElement 26 order *format.ColumnOrder 27 path columnPath 28 columns []*Column 29 chunks []*format.ColumnChunk 30 columnIndex []*format.ColumnIndex 31 offsetIndex []*format.OffsetIndex 32 encoding encoding.Encoding 33 compression compress.Codec 34 35 depth int8 36 maxRepetitionLevel byte 37 maxDefinitionLevel byte 38 index int16 39 } 40 41 // Type returns the type of the column. 42 // 43 // The returned value is unspecified if c is not a leaf column. 44 func (c *Column) Type() Type { return c.typ } 45 46 // Optional returns true if the column is optional. 47 func (c *Column) Optional() bool { return schemaRepetitionTypeOf(c.schema) == format.Optional } 48 49 // Repeated returns true if the column may repeat. 50 func (c *Column) Repeated() bool { return schemaRepetitionTypeOf(c.schema) == format.Repeated } 51 52 // Required returns true if the column is required. 53 func (c *Column) Required() bool { return schemaRepetitionTypeOf(c.schema) == format.Required } 54 55 // Leaf returns true if c is a leaf column. 56 func (c *Column) Leaf() bool { return c.index >= 0 } 57 58 // Fields returns the list of fields on the column. 59 func (c *Column) Fields() []Field { 60 fields := make([]Field, len(c.columns)) 61 for i, column := range c.columns { 62 fields[i] = column 63 } 64 return fields 65 } 66 67 // Encoding returns the encodings used by this column. 68 func (c *Column) Encoding() encoding.Encoding { return c.encoding } 69 70 // Compression returns the compression codecs used by this column. 71 func (c *Column) Compression() compress.Codec { return c.compression } 72 73 // Path of the column in the parquet schema. 74 func (c *Column) Path() []string { return c.path[1:] } 75 76 // Name returns the column name. 77 func (c *Column) Name() string { return c.schema.Name } 78 79 // ID returns column field id 80 func (c *Column) ID() int { return int(c.schema.FieldID) } 81 82 // Columns returns the list of child columns. 83 // 84 // The method returns the same slice across multiple calls, the program must 85 // treat it as a read-only value. 86 func (c *Column) Columns() []*Column { return c.columns } 87 88 // Column returns the child column matching the given name. 89 func (c *Column) Column(name string) *Column { 90 for _, child := range c.columns { 91 if child.Name() == name { 92 return child 93 } 94 } 95 return nil 96 } 97 98 // Pages returns a reader exposing all pages in this column, across row groups. 99 func (c *Column) Pages() Pages { 100 if c.index < 0 { 101 return emptyPages{} 102 } 103 r := &columnPages{ 104 pages: make([]filePages, len(c.file.rowGroups)), 105 } 106 for i := range r.pages { 107 r.pages[i].init(c.file.rowGroups[i].(*fileRowGroup).columns[c.index].(*fileColumnChunk)) 108 } 109 return r 110 } 111 112 type columnPages struct { 113 pages []filePages 114 index int 115 } 116 117 func (c *columnPages) ReadPage() (Page, error) { 118 for { 119 if c.index >= len(c.pages) { 120 return nil, io.EOF 121 } 122 p, err := c.pages[c.index].ReadPage() 123 if err == nil || err != io.EOF { 124 return p, err 125 } 126 c.index++ 127 } 128 } 129 130 func (c *columnPages) SeekToRow(rowIndex int64) error { 131 c.index = 0 132 133 for c.index < len(c.pages) && c.pages[c.index].chunk.rowGroup.NumRows >= rowIndex { 134 rowIndex -= c.pages[c.index].chunk.rowGroup.NumRows 135 c.index++ 136 } 137 138 if c.index < len(c.pages) { 139 if err := c.pages[c.index].SeekToRow(rowIndex); err != nil { 140 return err 141 } 142 for i := range c.pages[c.index:] { 143 p := &c.pages[c.index+i] 144 if err := p.SeekToRow(0); err != nil { 145 return err 146 } 147 } 148 } 149 return nil 150 } 151 152 func (c *columnPages) Close() error { 153 var lastErr error 154 155 for i := range c.pages { 156 if err := c.pages[i].Close(); err != nil { 157 lastErr = err 158 } 159 } 160 161 c.pages = nil 162 c.index = 0 163 return lastErr 164 } 165 166 // Depth returns the position of the column relative to the root. 167 func (c *Column) Depth() int { return int(c.depth) } 168 169 // MaxRepetitionLevel returns the maximum value of repetition levels on this 170 // column. 171 func (c *Column) MaxRepetitionLevel() int { return int(c.maxRepetitionLevel) } 172 173 // MaxDefinitionLevel returns the maximum value of definition levels on this 174 // column. 175 func (c *Column) MaxDefinitionLevel() int { return int(c.maxDefinitionLevel) } 176 177 // Index returns the position of the column in a row. Only leaf columns have a 178 // column index, the method returns -1 when called on non-leaf columns. 179 func (c *Column) Index() int { return int(c.index) } 180 181 // GoType returns the Go type that best represents the parquet column. 182 func (c *Column) GoType() reflect.Type { return goTypeOf(c) } 183 184 // Value returns the sub-value in base for the child column at the given 185 // index. 186 func (c *Column) Value(base reflect.Value) reflect.Value { 187 return base.MapIndex(reflect.ValueOf(&c.schema.Name).Elem()) 188 } 189 190 // String returns a human-readable string representation of the column. 191 func (c *Column) String() string { return c.path.String() + ": " + sprint(c.Name(), c) } 192 193 func (c *Column) forEachLeaf(do func(*Column)) { 194 if len(c.columns) == 0 { 195 do(c) 196 } else { 197 for _, child := range c.columns { 198 child.forEachLeaf(do) 199 } 200 } 201 } 202 203 func openColumns(file *File) (*Column, error) { 204 cl := columnLoader{} 205 206 c, err := cl.open(file, nil) 207 if err != nil { 208 return nil, err 209 } 210 211 // Validate that there aren't extra entries in the row group columns, 212 // which would otherwise indicate that there are dangling data pages 213 // in the file. 214 for index, rowGroup := range file.metadata.RowGroups { 215 if cl.rowGroupColumnIndex != len(rowGroup.Columns) { 216 return nil, fmt.Errorf("row group at index %d contains %d columns but %d were referenced by the column schemas", 217 index, len(rowGroup.Columns), cl.rowGroupColumnIndex) 218 } 219 } 220 221 _, err = c.setLevels(0, 0, 0, 0) 222 return c, err 223 } 224 225 func (c *Column) setLevels(depth, repetition, definition, index int) (int, error) { 226 if depth > MaxColumnDepth { 227 return -1, fmt.Errorf("cannot represent parquet columns with more than %d nested levels: %s", MaxColumnDepth, c.path) 228 } 229 if index > MaxColumnIndex { 230 return -1, fmt.Errorf("cannot represent parquet rows with more than %d columns: %s", MaxColumnIndex, c.path) 231 } 232 if repetition > MaxRepetitionLevel { 233 return -1, fmt.Errorf("cannot represent parquet columns with more than %d repetition levels: %s", MaxRepetitionLevel, c.path) 234 } 235 if definition > MaxDefinitionLevel { 236 return -1, fmt.Errorf("cannot represent parquet columns with more than %d definition levels: %s", MaxDefinitionLevel, c.path) 237 } 238 239 switch schemaRepetitionTypeOf(c.schema) { 240 case format.Optional: 241 definition++ 242 case format.Repeated: 243 repetition++ 244 definition++ 245 } 246 247 c.depth = int8(depth) 248 c.maxRepetitionLevel = byte(repetition) 249 c.maxDefinitionLevel = byte(definition) 250 depth++ 251 252 if len(c.columns) > 0 { 253 c.index = -1 254 } else { 255 c.index = int16(index) 256 index++ 257 } 258 259 var err error 260 for _, child := range c.columns { 261 if index, err = child.setLevels(depth, repetition, definition, index); err != nil { 262 return -1, err 263 } 264 } 265 return index, nil 266 } 267 268 type columnLoader struct { 269 schemaIndex int 270 columnOrderIndex int 271 rowGroupColumnIndex int 272 } 273 274 func (cl *columnLoader) open(file *File, path []string) (*Column, error) { 275 c := &Column{ 276 file: file, 277 schema: &file.metadata.Schema[cl.schemaIndex], 278 } 279 c.path = columnPath(path).append(c.schema.Name) 280 281 cl.schemaIndex++ 282 numChildren := int(c.schema.NumChildren) 283 284 if numChildren == 0 { 285 c.typ = schemaElementTypeOf(c.schema) 286 287 if cl.columnOrderIndex < len(file.metadata.ColumnOrders) { 288 c.order = &file.metadata.ColumnOrders[cl.columnOrderIndex] 289 cl.columnOrderIndex++ 290 } 291 292 rowGroups := file.metadata.RowGroups 293 rowGroupColumnIndex := cl.rowGroupColumnIndex 294 cl.rowGroupColumnIndex++ 295 296 c.chunks = make([]*format.ColumnChunk, 0, len(rowGroups)) 297 c.columnIndex = make([]*format.ColumnIndex, 0, len(rowGroups)) 298 c.offsetIndex = make([]*format.OffsetIndex, 0, len(rowGroups)) 299 300 for i, rowGroup := range rowGroups { 301 if rowGroupColumnIndex >= len(rowGroup.Columns) { 302 return nil, fmt.Errorf("row group at index %d does not have enough columns", i) 303 } 304 c.chunks = append(c.chunks, &rowGroup.Columns[rowGroupColumnIndex]) 305 } 306 307 if len(file.columnIndexes) > 0 { 308 for i := range rowGroups { 309 if rowGroupColumnIndex >= len(file.columnIndexes) { 310 return nil, fmt.Errorf("row group at index %d does not have enough column index pages", i) 311 } 312 c.columnIndex = append(c.columnIndex, &file.columnIndexes[rowGroupColumnIndex]) 313 } 314 } 315 316 if len(file.offsetIndexes) > 0 { 317 for i := range rowGroups { 318 if rowGroupColumnIndex >= len(file.offsetIndexes) { 319 return nil, fmt.Errorf("row group at index %d does not have enough offset index pages", i) 320 } 321 c.offsetIndex = append(c.offsetIndex, &file.offsetIndexes[rowGroupColumnIndex]) 322 } 323 } 324 325 if len(c.chunks) > 0 { 326 // Pick the encoding and compression codec of the first chunk. 327 // 328 // Technically each column chunk may use a different compression 329 // codec, and each page of the column chunk might have a different 330 // encoding. Exposing these details does not provide a lot of value 331 // to the end user. 332 // 333 // Programs that wish to determine the encoding and compression of 334 // each page of the column should iterate through the pages and read 335 // the page headers to determine which compression and encodings are 336 // applied. 337 for _, encoding := range c.chunks[0].MetaData.Encoding { 338 if c.encoding == nil { 339 c.encoding = LookupEncoding(encoding) 340 } 341 if encoding != format.Plain && encoding != format.RLE { 342 c.encoding = LookupEncoding(encoding) 343 break 344 } 345 } 346 c.compression = LookupCompressionCodec(c.chunks[0].MetaData.Codec) 347 } 348 349 return c, nil 350 } 351 352 c.typ = &groupType{} 353 c.columns = make([]*Column, numChildren) 354 355 for i := range c.columns { 356 if cl.schemaIndex >= len(file.metadata.Schema) { 357 return nil, fmt.Errorf("column %q has more children than there are schemas in the file: %d > %d", 358 c.schema.Name, cl.schemaIndex+1, len(file.metadata.Schema)) 359 } 360 361 var err error 362 c.columns[i], err = cl.open(file, c.path) 363 if err != nil { 364 return nil, fmt.Errorf("%s: %w", c.schema.Name, err) 365 } 366 } 367 368 return c, nil 369 } 370 371 func schemaElementTypeOf(s *format.SchemaElement) Type { 372 if lt := s.LogicalType; lt != nil { 373 // A logical type exists, the Type interface implementations in this 374 // package are all based on the logical parquet types declared in the 375 // format sub-package so we can return them directly via a pointer type 376 // conversion. 377 switch { 378 case lt.UTF8 != nil: 379 return (*stringType)(lt.UTF8) 380 case lt.Map != nil: 381 return (*mapType)(lt.Map) 382 case lt.List != nil: 383 return (*listType)(lt.List) 384 case lt.Enum != nil: 385 return (*enumType)(lt.Enum) 386 case lt.Decimal != nil: 387 // A parquet decimal can be one of several different physical types. 388 if t := s.Type; t != nil { 389 var typ Type 390 switch kind := Kind(*s.Type); kind { 391 case Int32: 392 typ = Int32Type 393 case Int64: 394 typ = Int64Type 395 case FixedLenByteArray: 396 if s.TypeLength == nil { 397 panic("DECIMAL using FIXED_LEN_BYTE_ARRAY must specify a length") 398 } 399 typ = FixedLenByteArrayType(int(*s.TypeLength)) 400 default: 401 panic("DECIMAL must be of type INT32, INT64, or FIXED_LEN_BYTE_ARRAY but got " + kind.String()) 402 } 403 return &decimalType{ 404 decimal: *lt.Decimal, 405 Type: typ, 406 } 407 } 408 case lt.Date != nil: 409 return (*dateType)(lt.Date) 410 case lt.Time != nil: 411 return (*timeType)(lt.Time) 412 case lt.Timestamp != nil: 413 return (*timestampType)(lt.Timestamp) 414 case lt.Integer != nil: 415 return (*intType)(lt.Integer) 416 case lt.Unknown != nil: 417 return (*nullType)(lt.Unknown) 418 case lt.Json != nil: 419 return (*jsonType)(lt.Json) 420 case lt.Bson != nil: 421 return (*bsonType)(lt.Bson) 422 case lt.UUID != nil: 423 return (*uuidType)(lt.UUID) 424 } 425 } 426 427 if ct := s.ConvertedType; ct != nil { 428 // This column contains no logical type but has a converted type, it 429 // was likely created by an older parquet writer. Convert the legacy 430 // type representation to the equivalent logical parquet type. 431 switch *ct { 432 case deprecated.UTF8: 433 return &stringType{} 434 case deprecated.Map: 435 return &mapType{} 436 case deprecated.MapKeyValue: 437 return &groupType{} 438 case deprecated.List: 439 return &listType{} 440 case deprecated.Enum: 441 return &enumType{} 442 case deprecated.Decimal: 443 if s.Scale != nil && s.Precision != nil { 444 // A parquet decimal can be one of several different physical types. 445 if t := s.Type; t != nil { 446 var typ Type 447 switch kind := Kind(*s.Type); kind { 448 case Int32: 449 typ = Int32Type 450 case Int64: 451 typ = Int64Type 452 case FixedLenByteArray: 453 if s.TypeLength == nil { 454 panic("DECIMAL using FIXED_LEN_BYTE_ARRAY must specify a length") 455 } 456 typ = FixedLenByteArrayType(int(*s.TypeLength)) 457 case ByteArray: 458 typ = ByteArrayType 459 default: 460 panic("DECIMAL must be of type INT32, INT64, BYTE_ARRAY or FIXED_LEN_BYTE_ARRAY but got " + kind.String()) 461 } 462 return &decimalType{ 463 decimal: format.DecimalType{ 464 Scale: *s.Scale, 465 Precision: *s.Precision, 466 }, 467 Type: typ, 468 } 469 } 470 } 471 case deprecated.Date: 472 return &dateType{} 473 case deprecated.TimeMillis: 474 return &timeType{IsAdjustedToUTC: true, Unit: Millisecond.TimeUnit()} 475 case deprecated.TimeMicros: 476 return &timeType{IsAdjustedToUTC: true, Unit: Microsecond.TimeUnit()} 477 case deprecated.TimestampMillis: 478 return ×tampType{IsAdjustedToUTC: true, Unit: Millisecond.TimeUnit()} 479 case deprecated.TimestampMicros: 480 return ×tampType{IsAdjustedToUTC: true, Unit: Microsecond.TimeUnit()} 481 case deprecated.Uint8: 482 return &unsignedIntTypes[0] 483 case deprecated.Uint16: 484 return &unsignedIntTypes[1] 485 case deprecated.Uint32: 486 return &unsignedIntTypes[2] 487 case deprecated.Uint64: 488 return &unsignedIntTypes[3] 489 case deprecated.Int8: 490 return &signedIntTypes[0] 491 case deprecated.Int16: 492 return &signedIntTypes[1] 493 case deprecated.Int32: 494 return &signedIntTypes[2] 495 case deprecated.Int64: 496 return &signedIntTypes[3] 497 case deprecated.Json: 498 return &jsonType{} 499 case deprecated.Bson: 500 return &bsonType{} 501 case deprecated.Interval: 502 // TODO 503 } 504 } 505 506 if t := s.Type; t != nil { 507 // The column only has a physical type, convert it to one of the 508 // primitive types supported by this package. 509 switch kind := Kind(*t); kind { 510 case Boolean: 511 return BooleanType 512 case Int32: 513 return Int32Type 514 case Int64: 515 return Int64Type 516 case Int96: 517 return Int96Type 518 case Float: 519 return FloatType 520 case Double: 521 return DoubleType 522 case ByteArray: 523 return ByteArrayType 524 case FixedLenByteArray: 525 if s.TypeLength != nil { 526 return FixedLenByteArrayType(int(*s.TypeLength)) 527 } 528 } 529 } 530 531 // If we reach this point, we are likely reading a parquet column that was 532 // written with a non-standard type or is in a newer version of the format 533 // than this package supports. 534 return &nullType{} 535 } 536 537 func schemaRepetitionTypeOf(s *format.SchemaElement) format.FieldRepetitionType { 538 if s.RepetitionType != nil { 539 return *s.RepetitionType 540 } 541 return format.Required 542 } 543 544 func (c *Column) decompress(compressedPageData []byte, uncompressedPageSize int32) (page *buffer, err error) { 545 page = buffers.get(int(uncompressedPageSize)) 546 page.data, err = c.compression.Decode(page.data, compressedPageData) 547 if err != nil { 548 page.unref() 549 page = nil 550 } 551 return page, err 552 } 553 554 // DecodeDataPageV1 decodes a data page from the header, compressed data, and 555 // optional dictionary passed as arguments. 556 func (c *Column) DecodeDataPageV1(header DataPageHeaderV1, page []byte, dict Dictionary) (Page, error) { 557 return c.decodeDataPageV1(header, &buffer{data: page}, dict, -1) 558 } 559 560 func (c *Column) decodeDataPageV1(header DataPageHeaderV1, page *buffer, dict Dictionary, size int32) (Page, error) { 561 var pageData = page.data 562 var err error 563 564 if isCompressed(c.compression) { 565 if page, err = c.decompress(pageData, size); err != nil { 566 return nil, fmt.Errorf("decompressing data page v1: %w", err) 567 } 568 defer page.unref() 569 pageData = page.data 570 } 571 572 var numValues = int(header.NumValues()) 573 var repetitionLevels *buffer 574 var definitionLevels *buffer 575 576 if c.maxRepetitionLevel > 0 { 577 encoding := lookupLevelEncoding(header.RepetitionLevelEncoding(), c.maxRepetitionLevel) 578 repetitionLevels, pageData, err = decodeLevelsV1(encoding, numValues, pageData) 579 if err != nil { 580 return nil, fmt.Errorf("decoding repetition levels of data page v1: %w", err) 581 } 582 defer repetitionLevels.unref() 583 } 584 585 if c.maxDefinitionLevel > 0 { 586 encoding := lookupLevelEncoding(header.DefinitionLevelEncoding(), c.maxDefinitionLevel) 587 definitionLevels, pageData, err = decodeLevelsV1(encoding, numValues, pageData) 588 if err != nil { 589 return nil, fmt.Errorf("decoding definition levels of data page v1: %w", err) 590 } 591 defer definitionLevels.unref() 592 593 // Data pages v1 did not embed the number of null values, 594 // so we have to compute it from the definition levels. 595 numValues -= countLevelsNotEqual(definitionLevels.data, c.maxDefinitionLevel) 596 } 597 598 return c.decodeDataPage(header, numValues, repetitionLevels, definitionLevels, page, pageData, dict) 599 } 600 601 // DecodeDataPageV2 decodes a data page from the header, compressed data, and 602 // optional dictionary passed as arguments. 603 func (c *Column) DecodeDataPageV2(header DataPageHeaderV2, page []byte, dict Dictionary) (Page, error) { 604 return c.decodeDataPageV2(header, &buffer{data: page}, dict, -1) 605 } 606 607 func (c *Column) decodeDataPageV2(header DataPageHeaderV2, page *buffer, dict Dictionary, size int32) (Page, error) { 608 var numValues = int(header.NumValues()) 609 var pageData = page.data 610 var err error 611 var repetitionLevels *buffer 612 var definitionLevels *buffer 613 614 if length := header.RepetitionLevelsByteLength(); length > 0 { 615 if c.maxRepetitionLevel == 0 { 616 // In some cases we've observed files which have a non-zero 617 // repetition level despite the column not being repeated 618 // (nor nested within a repeated column). 619 // 620 // See https://github.com/apache/parquet-testing/pull/24 621 pageData, err = skipLevelsV2(pageData, length) 622 } else { 623 encoding := lookupLevelEncoding(header.RepetitionLevelEncoding(), c.maxRepetitionLevel) 624 repetitionLevels, pageData, err = decodeLevelsV2(encoding, numValues, pageData, length) 625 } 626 if err != nil { 627 return nil, fmt.Errorf("decoding repetition levels of data page v2: %w", io.ErrUnexpectedEOF) 628 } 629 if repetitionLevels != nil { 630 defer repetitionLevels.unref() 631 } 632 } 633 634 if length := header.DefinitionLevelsByteLength(); length > 0 { 635 if c.maxDefinitionLevel == 0 { 636 pageData, err = skipLevelsV2(pageData, length) 637 } else { 638 encoding := lookupLevelEncoding(header.DefinitionLevelEncoding(), c.maxDefinitionLevel) 639 definitionLevels, pageData, err = decodeLevelsV2(encoding, numValues, pageData, length) 640 } 641 if err != nil { 642 return nil, fmt.Errorf("decoding definition levels of data page v2: %w", io.ErrUnexpectedEOF) 643 } 644 if definitionLevels != nil { 645 defer definitionLevels.unref() 646 } 647 } 648 649 if isCompressed(c.compression) && header.IsCompressed() { 650 if page, err = c.decompress(pageData, size); err != nil { 651 return nil, fmt.Errorf("decompressing data page v2: %w", err) 652 } 653 defer page.unref() 654 pageData = page.data 655 } 656 657 numValues -= int(header.NumNulls()) 658 return c.decodeDataPage(header, numValues, repetitionLevels, definitionLevels, page, pageData, dict) 659 } 660 661 func (c *Column) decodeDataPage(header DataPageHeader, numValues int, repetitionLevels, definitionLevels, page *buffer, data []byte, dict Dictionary) (Page, error) { 662 pageEncoding := LookupEncoding(header.Encoding()) 663 pageType := c.Type() 664 665 if isDictionaryEncoding(pageEncoding) { 666 // In some legacy configurations, the PLAIN_DICTIONARY encoding is used 667 // on data page headers to indicate that the page contains indexes into 668 // the dictionary page, but the page is still encoded using the RLE 669 // encoding in this case, so we convert it to RLE_DICTIONARY. 670 pageEncoding = &RLEDictionary 671 pageType = indexedPageType{newIndexedType(pageType, dict)} 672 } 673 674 var vbuf, obuf *buffer 675 var pageValues []byte 676 var pageOffsets []uint32 677 678 if pageEncoding.CanDecodeInPlace() { 679 vbuf = page 680 pageValues = data 681 } else { 682 vbuf = buffers.get(pageType.EstimateDecodeSize(numValues, data, pageEncoding)) 683 defer vbuf.unref() 684 pageValues = vbuf.data 685 } 686 687 // Page offsets not needed when dictionary-encoded 688 if pageType.Kind() == ByteArray && !isDictionaryEncoding(pageEncoding) { 689 obuf = buffers.get(4 * (numValues + 1)) 690 defer obuf.unref() 691 pageOffsets = unsafecast.BytesToUint32(obuf.data) 692 } 693 694 values := pageType.NewValues(pageValues, pageOffsets) 695 values, err := pageType.Decode(values, data, pageEncoding) 696 if err != nil { 697 return nil, err 698 } 699 700 newPage := pageType.NewPage(c.Index(), numValues, values) 701 switch { 702 case c.maxRepetitionLevel > 0: 703 newPage = newRepeatedPage( 704 newPage, 705 c.maxRepetitionLevel, 706 c.maxDefinitionLevel, 707 repetitionLevels.data, 708 definitionLevels.data, 709 ) 710 case c.maxDefinitionLevel > 0: 711 newPage = newOptionalPage( 712 newPage, 713 c.maxDefinitionLevel, 714 definitionLevels.data, 715 ) 716 } 717 718 return newBufferedPage(newPage, vbuf, obuf, repetitionLevels, definitionLevels), nil 719 } 720 721 func decodeLevelsV1(enc encoding.Encoding, numValues int, data []byte) (*buffer, []byte, error) { 722 if len(data) < 4 { 723 return nil, data, io.ErrUnexpectedEOF 724 } 725 i := 4 726 j := 4 + int(binary.LittleEndian.Uint32(data)) 727 if j > len(data) { 728 return nil, data, io.ErrUnexpectedEOF 729 } 730 levels, err := decodeLevels(enc, numValues, data[i:j]) 731 return levels, data[j:], err 732 } 733 734 func decodeLevelsV2(enc encoding.Encoding, numValues int, data []byte, length int64) (*buffer, []byte, error) { 735 levels, err := decodeLevels(enc, numValues, data[:length]) 736 return levels, data[length:], err 737 } 738 739 func decodeLevels(enc encoding.Encoding, numValues int, data []byte) (levels *buffer, err error) { 740 levels = buffers.get(numValues) 741 levels.data, err = enc.DecodeLevels(levels.data, data) 742 if err != nil { 743 levels.unref() 744 levels = nil 745 } else { 746 switch { 747 case len(levels.data) < numValues: 748 err = fmt.Errorf("decoding level expected %d values but got only %d", numValues, len(levels.data)) 749 case len(levels.data) > numValues: 750 levels.data = levels.data[:numValues] 751 } 752 } 753 return levels, err 754 } 755 756 func skipLevelsV2(data []byte, length int64) ([]byte, error) { 757 if length >= int64(len(data)) { 758 return data, io.ErrUnexpectedEOF 759 } 760 return data[length:], nil 761 } 762 763 // DecodeDictionary decodes a data page from the header and compressed data 764 // passed as arguments. 765 func (c *Column) DecodeDictionary(header DictionaryPageHeader, page []byte) (Dictionary, error) { 766 return c.decodeDictionary(header, &buffer{data: page}, -1) 767 } 768 769 func (c *Column) decodeDictionary(header DictionaryPageHeader, page *buffer, size int32) (Dictionary, error) { 770 pageData := page.data 771 772 if isCompressed(c.compression) { 773 var err error 774 if page, err = c.decompress(pageData, size); err != nil { 775 return nil, fmt.Errorf("decompressing dictionary page: %w", err) 776 } 777 defer page.unref() 778 pageData = page.data 779 } 780 781 pageType := c.Type() 782 pageEncoding := header.Encoding() 783 if pageEncoding == format.PlainDictionary { 784 pageEncoding = format.Plain 785 } 786 787 numValues := int(header.NumValues()) 788 values := pageType.NewValues(nil, nil) 789 values, err := pageType.Decode(values, pageData, LookupEncoding(pageEncoding)) 790 if err != nil { 791 return nil, err 792 } 793 return pageType.NewDictionary(int(c.index), numValues, values), nil 794 } 795 796 var ( 797 _ Node = (*Column)(nil) 798 )