vitess.io/vitess@v0.16.2/go/vt/vtgate/vindexes/binarymd5.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package vindexes 18 19 import ( 20 "bytes" 21 "context" 22 "crypto/md5" 23 24 "vitess.io/vitess/go/sqltypes" 25 "vitess.io/vitess/go/vt/key" 26 ) 27 28 var ( 29 _ SingleColumn = (*BinaryMD5)(nil) 30 _ Hashing = (*BinaryMD5)(nil) 31 ) 32 33 // BinaryMD5 is a vindex that hashes binary bits to a keyspace id. 34 type BinaryMD5 struct { 35 name string 36 } 37 38 // NewBinaryMD5 creates a new BinaryMD5. 39 func NewBinaryMD5(name string, _ map[string]string) (Vindex, error) { 40 return &BinaryMD5{name: name}, nil 41 } 42 43 // String returns the name of the vindex. 44 func (vind *BinaryMD5) String() string { 45 return vind.name 46 } 47 48 // Cost returns the cost as 1. 49 func (vind *BinaryMD5) Cost() int { 50 return 1 51 } 52 53 // IsUnique returns true since the Vindex is unique. 54 func (vind *BinaryMD5) IsUnique() bool { 55 return true 56 } 57 58 // NeedsVCursor satisfies the Vindex interface. 59 func (vind *BinaryMD5) NeedsVCursor() bool { 60 return false 61 } 62 63 // Verify returns true if ids maps to ksids. 64 func (vind *BinaryMD5) Verify(ctx context.Context, vcursor VCursor, ids []sqltypes.Value, ksids [][]byte) ([]bool, error) { 65 out := make([]bool, 0, len(ids)) 66 for i, id := range ids { 67 ksid, err := vind.Hash(id) 68 if err != nil { 69 return nil, err 70 } 71 out = append(out, bytes.Equal(ksid, ksids[i])) 72 } 73 return out, nil 74 } 75 76 // Map can map ids to key.Destination objects. 77 func (vind *BinaryMD5) Map(ctx context.Context, vcursor VCursor, ids []sqltypes.Value) ([]key.Destination, error) { 78 out := make([]key.Destination, 0, len(ids)) 79 for _, id := range ids { 80 ksid, err := vind.Hash(id) 81 if err != nil { 82 return out, err 83 } 84 out = append(out, key.DestinationKeyspaceID(ksid)) 85 } 86 return out, nil 87 } 88 89 func (vind *BinaryMD5) Hash(id sqltypes.Value) ([]byte, error) { 90 idBytes, err := id.ToBytes() 91 if err != nil { 92 return nil, err 93 } 94 return vMD5Hash(idBytes), nil 95 } 96 97 func vMD5Hash(source []byte) []byte { 98 sum := md5.Sum(source) 99 return sum[:] 100 } 101 102 func init() { 103 Register("binary_md5", NewBinaryMD5) 104 }