github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/store/types/tuple.go (about) 1 // Copyright 2019 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // This file incorporates work covered by the following copyright and 16 // permission notice: 17 // 18 // Copyright 2016 Attic Labs, Inc. All rights reserved. 19 // Licensed under the Apache License, version 2.0: 20 // http://www.apache.org/licenses/LICENSE-2.0 21 22 package types 23 24 import ( 25 "bytes" 26 "context" 27 "errors" 28 "fmt" 29 "io" 30 "strings" 31 "sync" 32 33 "github.com/dolthub/dolt/go/store/d" 34 ) 35 36 var _ LesserValuable = TupleValueSlice(nil) 37 38 type TupleValueSlice []Value 39 40 func (tvs TupleValueSlice) Kind() NomsKind { 41 return TupleKind 42 } 43 44 func (tvs TupleValueSlice) Less(nbf *NomsBinFormat, other LesserValuable) (bool, error) { 45 switch typedOther := other.(type) { 46 case Tuple: 47 val, err := NewTuple(nbf, tvs...) 48 49 if err != nil { 50 return false, err 51 } 52 53 return typedOther.Less(nbf, val) 54 55 case TupleValueSlice: 56 myLen := len(tvs) 57 otherLen := len(typedOther) 58 largerLen := myLen 59 if otherLen > largerLen { 60 largerLen = otherLen 61 } 62 63 var val Value 64 var otherVal Value 65 for i := 0; i < largerLen; i++ { 66 if i < myLen { 67 val = tvs[i] 68 } 69 70 if i < otherLen { 71 otherVal = typedOther[i] 72 } 73 74 if val == nil { 75 return true, nil 76 } else if otherVal == nil { 77 return false, nil 78 } 79 80 if !val.Equals(otherVal) { 81 return val.Less(nbf, otherVal) 82 } 83 } 84 85 return false, nil 86 default: 87 return TupleKind < other.Kind(), nil 88 } 89 } 90 91 func (tvs TupleValueSlice) Value(ctx context.Context) (Value, error) { 92 panic("not implemented") 93 } 94 95 func EmptyTuple(nbf *NomsBinFormat) Tuple { 96 t, err := NewTuple(nbf) 97 d.PanicIfError(err) 98 99 return t 100 } 101 102 func newTupleIterator() interface{} { 103 return &TupleIterator{} 104 } 105 106 type tupleItrPair struct { 107 thisItr *TupleIterator 108 otherItr *TupleIterator 109 } 110 111 func newTupleIteratorPair() interface{} { 112 return &tupleItrPair{&TupleIterator{}, &TupleIterator{}} 113 } 114 115 var TupleItrPool = &sync.Pool{New: newTupleIterator} 116 var tupItrPairPool = &sync.Pool{New: newTupleIteratorPair} 117 118 type TupleIterator struct { 119 dec *valueDecoder 120 count uint64 121 pos uint64 122 nbf *NomsBinFormat 123 } 124 125 func (itr *TupleIterator) Next() (uint64, Value, error) { 126 if itr.pos < itr.count { 127 valPos := itr.pos 128 val, err := itr.dec.readValue(itr.nbf) 129 130 if err != nil { 131 return 0, nil, err 132 } 133 134 itr.pos++ 135 return valPos, val, nil 136 } 137 138 return itr.count, nil, nil 139 } 140 141 func (itr *TupleIterator) NextUint64() (pos uint64, val uint64, err error) { 142 if itr.pos < itr.count { 143 k := itr.dec.ReadKind() 144 145 if k != UintKind { 146 return 0, 0, errors.New("NextUint64 called when the next value is not a Uint64") 147 } 148 149 valPos := itr.pos 150 val := itr.dec.ReadUint() 151 itr.pos++ 152 153 return valPos, val, nil 154 } 155 156 return itr.count, 0, io.EOF 157 } 158 159 func (itr *TupleIterator) CodecReader() (CodecReader, uint64) { 160 return itr.dec, itr.count - itr.pos 161 } 162 163 func (itr *TupleIterator) Skip() error { 164 if itr.pos < itr.count { 165 err := itr.dec.SkipValue(itr.nbf) 166 167 if err != nil { 168 return err 169 } 170 171 itr.pos++ 172 } 173 174 return nil 175 } 176 177 func (itr *TupleIterator) HasMore() bool { 178 return itr.pos < itr.count 179 } 180 181 func (itr *TupleIterator) Len() uint64 { 182 return itr.count 183 } 184 185 func (itr *TupleIterator) Pos() uint64 { 186 return itr.pos 187 } 188 189 func (itr *TupleIterator) InitForTuple(t Tuple) error { 190 return itr.InitForTupleAt(t, 0) 191 } 192 193 func (itr *TupleIterator) InitForTupleAt(t Tuple, pos uint64) error { 194 if itr.dec == nil { 195 dec := t.decoder() 196 itr.dec = &dec 197 } else { 198 itr.dec.buff = t.buff 199 itr.dec.offset = 0 200 itr.dec.vrw = t.vrw 201 } 202 203 itr.dec.skipKind() 204 count := itr.dec.readCount() 205 206 for i := uint64(0); i < pos; i++ { 207 err := itr.dec.SkipValue(t.format()) 208 209 if err != nil { 210 return err 211 } 212 } 213 214 itr.count = count 215 itr.pos = pos 216 itr.nbf = t.format() 217 return nil 218 } 219 220 type Tuple struct { 221 valueImpl 222 } 223 224 // readTuple reads the data provided by a decoder and moves the decoder forward. 225 func readTuple(nbf *NomsBinFormat, dec *valueDecoder) (Tuple, error) { 226 start := dec.pos() 227 k := dec.PeekKind() 228 229 if k == NullKind { 230 dec.skipKind() 231 return EmptyTuple(nbf), nil 232 } 233 234 if k != TupleKind { 235 return Tuple{}, errors.New("current value is not a tuple") 236 } 237 238 err := skipTuple(nbf, dec) 239 240 if err != nil { 241 return Tuple{}, err 242 } 243 244 end := dec.pos() 245 return Tuple{valueImpl{dec.vrw, nbf, dec.byteSlice(start, end), nil}}, nil 246 } 247 248 func skipTuple(nbf *NomsBinFormat, dec *valueDecoder) error { 249 dec.skipKind() 250 count := dec.readCount() 251 for i := uint64(0); i < count; i++ { 252 err := dec.SkipValue(nbf) 253 254 if err != nil { 255 return err 256 } 257 } 258 return nil 259 } 260 261 func walkTuple(nbf *NomsBinFormat, r *refWalker, cb RefCallback) error { 262 r.skipKind() 263 count := r.readCount() 264 for i := uint64(0); i < count; i++ { 265 err := r.walkValue(nbf, cb) 266 267 if err != nil { 268 return err 269 } 270 } 271 return nil 272 } 273 274 func NewTuple(nbf *NomsBinFormat, values ...Value) (Tuple, error) { 275 var vrw ValueReadWriter 276 w := newBinaryNomsWriter() 277 err := TupleKind.writeTo(&w, nbf) 278 279 if err != nil { 280 return EmptyTuple(nbf), err 281 } 282 283 numVals := len(values) 284 w.writeCount(uint64(numVals)) 285 for i := 0; i < numVals; i++ { 286 if vrw == nil { 287 vrw = values[i].(valueReadWriter).valueReadWriter() 288 } 289 err := values[i].writeTo(&w, nbf) 290 291 if err != nil { 292 return EmptyTuple(nbf), err 293 } 294 } 295 296 return Tuple{valueImpl{vrw, nbf, w.data(), nil}}, nil 297 } 298 299 // CopyOf creates a copy of a tuple. This is necessary in cases where keeping a reference to the original tuple is 300 // preventing larger objects from being collected. 301 func (t Tuple) CopyOf(vrw ValueReadWriter) Tuple { 302 buff := make([]byte, len(t.buff)) 303 offsets := make([]uint32, len(t.offsets)) 304 305 copy(buff, t.buff) 306 copy(offsets, t.offsets) 307 308 return Tuple{ 309 valueImpl{ 310 buff: buff, 311 offsets: offsets, 312 vrw: vrw, 313 nbf: t.nbf, 314 }, 315 } 316 } 317 318 func (t Tuple) Empty() bool { 319 return t.Len() == 0 320 } 321 322 func (t Tuple) Format() *NomsBinFormat { 323 return t.format() 324 } 325 326 // Value interface 327 func (t Tuple) Value(ctx context.Context) (Value, error) { 328 return t, nil 329 } 330 331 func (t Tuple) WalkValues(ctx context.Context, cb ValueCallback) error { 332 dec, count := t.decoderSkipToFields() 333 for i := uint64(0); i < count; i++ { 334 v, err := dec.readValue(t.format()) 335 336 if err != nil { 337 return err 338 } 339 340 err = cb(v) 341 342 if err != nil { 343 return err 344 } 345 } 346 347 return nil 348 } 349 350 // PrefixEquals returns whether the given Tuple and calling Tuple have equivalent values up to the given count. Useful 351 // for testing Tuple equality for partial keys. If the Tuples are not of the same length, and one Tuple's length is less 352 // than the given count, then this returns false. If the Tuples are of the same length and they're both less than the 353 // given count, then this function is equivalent to Equals. 354 func (t Tuple) PrefixEquals(ctx context.Context, other Tuple, prefixCount uint64) (bool, error) { 355 tDec, tCount := t.decoderSkipToFields() 356 otherDec, otherCount := other.decoderSkipToFields() 357 if tCount == otherCount && tCount < prefixCount { 358 return t.Equals(other), nil 359 } else if tCount != otherCount && (tCount < prefixCount || otherCount < prefixCount) { 360 return false, nil 361 } 362 for i := uint64(0); i < prefixCount; i++ { 363 val, err := tDec.readValue(t.format()) 364 if err != nil { 365 return false, err 366 } 367 otherVal, err := otherDec.readValue(t.format()) 368 if err != nil { 369 return false, err 370 } 371 if !val.Equals(otherVal) { 372 return false, nil 373 } 374 } 375 return true, nil 376 } 377 378 func (t Tuple) Compare(other Tuple) int { 379 return bytes.Compare(t.buff, other.buff) 380 } 381 382 var tupleType = newType(CompoundDesc{UnionKind, nil}) 383 384 func (t Tuple) typeOf() (*Type, error) { 385 return tupleType, nil 386 } 387 388 func (t Tuple) decoderSkipToFields() (valueDecoder, uint64) { 389 dec := t.decoder() 390 dec.skipKind() 391 count := dec.readCount() 392 return dec, count 393 } 394 395 // Len is the number of fields in the struct. 396 func (t Tuple) Len() uint64 { 397 if len(t.buff) == 0 { 398 return 0 399 } 400 _, count := t.decoderSkipToFields() 401 return count 402 } 403 404 func (t Tuple) isPrimitive() bool { 405 return false 406 } 407 408 func (t Tuple) Iterator() (*TupleIterator, error) { 409 return t.IteratorAt(0) 410 } 411 412 func (t Tuple) IteratorAt(pos uint64) (*TupleIterator, error) { 413 itr := &TupleIterator{} 414 err := itr.InitForTupleAt(t, pos) 415 416 if err != nil { 417 return nil, err 418 } 419 420 return itr, nil 421 } 422 423 func (t Tuple) AsSlice() (TupleValueSlice, error) { 424 dec, count := t.decoderSkipToFields() 425 426 sl := make(TupleValueSlice, count) 427 for pos := uint64(0); pos < count; pos++ { 428 val, err := dec.readValue(t.nbf) 429 430 if err != nil { 431 return nil, err 432 } 433 434 sl[pos] = val 435 } 436 437 return sl, nil 438 } 439 440 // IterFields iterates over the fields, calling cb for every field in the tuple until cb returns false 441 func (t Tuple) IterFields(cb func(index uint64, value Value) (stop bool, err error)) error { 442 itr := TupleItrPool.Get().(*TupleIterator) 443 defer TupleItrPool.Put(itr) 444 445 err := itr.InitForTuple(t) 446 447 if err != nil { 448 return err 449 } 450 451 for itr.HasMore() { 452 i, curr, err := itr.Next() 453 454 if err != nil { 455 return err 456 } 457 458 stop, err := cb(i, curr) 459 460 if err != nil { 461 return err 462 } 463 464 if stop { 465 break 466 } 467 } 468 469 return nil 470 } 471 472 // Get returns the value of a field in the tuple. If the tuple does not a have a field at the index then this panics 473 func (t Tuple) Get(n uint64) (Value, error) { 474 dec, count := t.decoderSkipToFields() 475 476 if n >= count { 477 d.Chk.Fail(fmt.Sprintf(`tuple index "%d" out of range`, n)) 478 } 479 480 for i := uint64(0); i < n; i++ { 481 err := dec.SkipValue(t.format()) 482 483 if err != nil { 484 return nil, err 485 } 486 } 487 488 return dec.readValue(t.format()) 489 } 490 491 // Set returns a new tuple where the field at index n is set to value. Attempting to use Set on an index that is outside 492 // of the bounds will cause a panic. Use Append to add additional values, not Set. 493 func (t Tuple) Set(n uint64, v Value) (Tuple, error) { 494 prolog, head, tail, count, found, err := t.splitFieldsAt(n) 495 496 if err != nil { 497 return EmptyTuple(t.nbf), err 498 } 499 500 if !found { 501 d.Panic("Cannot set tuple value at index %d as it is outside the range [0,%d]", n, count-1) 502 } 503 504 w := binaryNomsWriter{make([]byte, len(t.buff)), 0} 505 w.writeRaw(prolog) 506 507 w.writeCount(count) 508 w.writeRaw(head) 509 err = v.writeTo(&w, t.format()) 510 511 if err != nil { 512 return EmptyTuple(t.nbf), err 513 } 514 w.writeRaw(tail) 515 516 return Tuple{valueImpl{t.vrw, t.format(), w.data(), nil}}, nil 517 } 518 519 func (t Tuple) Append(v Value) (Tuple, error) { 520 dec := t.decoder() 521 dec.skipKind() 522 prolog := dec.buff[:dec.offset] 523 count := dec.readCount() 524 fieldsOffset := dec.offset 525 526 w := binaryNomsWriter{make([]byte, len(t.buff)), 0} 527 w.writeRaw(prolog) 528 w.writeCount(count + 1) 529 w.writeRaw(dec.buff[fieldsOffset:]) 530 err := v.writeTo(&w, t.format()) 531 532 if err != nil { 533 return EmptyTuple(t.nbf), err 534 } 535 536 return Tuple{valueImpl{t.vrw, t.format(), w.data(), nil}}, nil 537 } 538 539 // splitFieldsAt splits the buffer into two parts. The fields coming before the field we are looking for 540 // and the fields coming after it. 541 func (t Tuple) splitFieldsAt(n uint64) (prolog, head, tail []byte, count uint64, found bool, err error) { 542 dec := t.decoder() 543 dec.skipKind() 544 prolog = dec.buff[:dec.offset] 545 count = dec.readCount() 546 547 if n >= count { 548 return nil, nil, nil, count, false, nil 549 } 550 551 found = true 552 fieldsOffset := dec.offset 553 554 for i := uint64(0); i < n; i++ { 555 err := dec.SkipValue(t.format()) 556 557 if err != nil { 558 return nil, nil, nil, 0, false, err 559 } 560 } 561 562 head = dec.buff[fieldsOffset:dec.offset] 563 564 if n != count-1 { 565 err := dec.SkipValue(t.format()) 566 567 if err != nil { 568 return nil, nil, nil, 0, false, err 569 } 570 571 tail = dec.buff[dec.offset:len(dec.buff)] 572 } 573 574 return 575 } 576 577 func (t Tuple) TupleLess(nbf *NomsBinFormat, otherTuple Tuple) (bool, error) { 578 itrs := tupItrPairPool.Get().(*tupleItrPair) 579 defer tupItrPairPool.Put(itrs) 580 581 itr := itrs.thisItr 582 err := itr.InitForTuple(t) 583 584 if err != nil { 585 return false, err 586 } 587 588 otherItr := itrs.otherItr 589 err = otherItr.InitForTuple(otherTuple) 590 591 if err != nil { 592 return false, err 593 } 594 595 smallerCount := itr.count 596 if otherItr.count < smallerCount { 597 smallerCount = otherItr.count 598 } 599 600 dec := itr.dec 601 otherDec := otherItr.dec 602 for i := uint64(0); i < smallerCount; i++ { 603 kind := dec.ReadKind() 604 otherKind := otherDec.ReadKind() 605 606 if kind != otherKind { 607 return kind < otherKind, nil 608 } 609 610 var res int 611 switch kind { 612 case NullKind: 613 continue 614 615 case BoolKind: 616 res = int(dec.buff[dec.offset]) - int(otherDec.buff[otherDec.offset]) 617 dec.offset += 1 618 otherDec.offset += 1 619 620 case StringKind: 621 size, otherSize := uint32(dec.readCount()), uint32(otherDec.readCount()) 622 start, otherStart := dec.offset, otherDec.offset 623 dec.offset += size 624 otherDec.offset += otherSize 625 res = bytes.Compare(dec.buff[start:dec.offset], otherDec.buff[otherStart:otherDec.offset]) 626 627 case InlineBlobKind: 628 size, otherSize := uint32(dec.readUint16()), uint32(otherDec.readUint16()) 629 start, otherStart := dec.offset, otherDec.offset 630 dec.offset += size 631 otherDec.offset += otherSize 632 res = bytes.Compare(dec.buff[start:dec.offset], otherDec.buff[otherStart:otherDec.offset]) 633 634 case UUIDKind: 635 start, otherStart := dec.offset, otherDec.offset 636 dec.offset += uuidNumBytes 637 otherDec.offset += uuidNumBytes 638 res = bytes.Compare(dec.buff[start:dec.offset], otherDec.buff[otherStart:otherDec.offset]) 639 640 case IntKind: 641 n := dec.ReadInt() 642 otherN := otherDec.ReadInt() 643 644 if n == otherN { 645 continue 646 } else { 647 return n < otherN, nil 648 } 649 650 case UintKind: 651 n := dec.ReadUint() 652 otherN := otherDec.ReadUint() 653 654 if n == otherN { 655 continue 656 } else { 657 return n < otherN, nil 658 } 659 660 case DecimalKind: 661 d, err := dec.ReadDecimal() 662 663 if err != nil { 664 return false, err 665 } 666 667 otherD, err := otherDec.ReadDecimal() 668 669 if err != nil { 670 return false, err 671 } 672 673 res = d.Cmp(otherD) 674 675 case FloatKind: 676 f := dec.ReadFloat(nbf) 677 otherF := otherDec.ReadFloat(nbf) 678 res = int(f - otherF) 679 680 if f == otherF { 681 continue 682 } else { 683 return f < otherF, nil 684 } 685 686 case TimestampKind: 687 tm, err := dec.ReadTimestamp() 688 689 if err != nil { 690 return false, err 691 } 692 693 otherTm, err := otherDec.ReadTimestamp() 694 695 if err != nil { 696 return false, err 697 } 698 699 if tm.Equal(otherTm) { 700 continue 701 } else { 702 return tm.Before(otherTm), nil 703 } 704 705 case BlobKind: 706 // readValue expects the Kind to still be there, so we put it back by decrementing the offset 707 dec.offset-- 708 otherDec.offset-- 709 v, err := dec.readValue(nbf) 710 if err != nil { 711 return false, err 712 } 713 otherV, err := otherDec.readValue(nbf) 714 if err != nil { 715 return false, err 716 } 717 if v.Equals(otherV) { 718 continue 719 } else { 720 return v.Less(nbf, otherV) 721 } 722 723 default: 724 v, err := dec.readValue(nbf) 725 726 if err != nil { 727 return false, err 728 } 729 730 otherV, err := otherDec.readValue(nbf) 731 732 if err != nil { 733 return false, err 734 } 735 736 if v.Equals(otherV) { 737 continue 738 } else { 739 return v.Less(nbf, otherV) 740 } 741 } 742 743 if res != 0 { 744 return res < 0, nil 745 } 746 } 747 748 return itr.Len() < otherItr.Len(), nil 749 } 750 751 func (t Tuple) Less(nbf *NomsBinFormat, other LesserValuable) (bool, error) { 752 otherTuple, ok := other.(Tuple) 753 if !ok { 754 return TupleKind < other.Kind(), nil 755 } 756 757 return t.TupleLess(nbf, otherTuple) 758 } 759 760 func (t Tuple) StartsWith(otherTuple Tuple) bool { 761 tplDec, _ := t.decoderSkipToFields() 762 otherDec, _ := otherTuple.decoderSkipToFields() 763 return bytes.HasPrefix(tplDec.buff[tplDec.offset:], otherDec.buff[otherDec.offset:]) 764 } 765 766 func (t Tuple) Contains(v Value) (bool, error) { 767 itr := TupleItrPool.Get().(*TupleIterator) 768 defer TupleItrPool.Put(itr) 769 770 err := itr.InitForTuple(t) 771 if err != nil { 772 return false, err 773 } 774 775 for itr.HasMore() { 776 _, tupleVal, err := itr.Next() 777 if err != nil { 778 return false, err 779 } 780 if tupleVal.Equals(v) { 781 return true, nil 782 } 783 } 784 return false, nil 785 } 786 787 func (t Tuple) readFrom(nbf *NomsBinFormat, b *binaryNomsReader) (Value, error) { 788 panic("unreachable") 789 } 790 791 func (t Tuple) skip(nbf *NomsBinFormat, b *binaryNomsReader) { 792 panic("unreachable") 793 } 794 795 func (t Tuple) String() string { 796 b := strings.Builder{} 797 798 iter := TupleItrPool.Get().(*TupleIterator) 799 defer TupleItrPool.Put(iter) 800 801 err := iter.InitForTuple(t) 802 if err != nil { 803 b.WriteString(err.Error()) 804 return b.String() 805 } 806 807 b.WriteString("Tuple(") 808 809 seenOne := false 810 for { 811 _, v, err := iter.Next() 812 if v == nil { 813 break 814 } 815 if err != nil { 816 b.WriteString(err.Error()) 817 return b.String() 818 } 819 820 if seenOne { 821 b.WriteString(", ") 822 } 823 seenOne = true 824 825 b.WriteString(v.HumanReadableString()) 826 } 827 b.WriteString(")") 828 return b.String() 829 } 830 831 func (t Tuple) HumanReadableString() string { 832 return t.String() 833 }