github.com/XiaoMi/Gaea@v1.2.5/parser/tidb-types/enum.go (about) 1 // Copyright 2015 PingCAP, 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package types 15 16 import ( 17 "strconv" 18 "strings" 19 20 "github.com/pingcap/errors" 21 ) 22 23 // Enum is for MySQL enum type. 24 type Enum struct { 25 Name string 26 Value uint64 27 } 28 29 // String implements fmt.Stringer interface. 30 func (e Enum) String() string { 31 return e.Name 32 } 33 34 // ToNumber changes enum index to float64 for numeric operation. 35 func (e Enum) ToNumber() float64 { 36 return float64(e.Value) 37 } 38 39 // ParseEnumName creates a Enum with item name. 40 func ParseEnumName(elems []string, name string) (Enum, error) { 41 for i, n := range elems { 42 if strings.EqualFold(n, name) { 43 return Enum{Name: n, Value: uint64(i) + 1}, nil 44 } 45 } 46 47 // name doesn't exist, maybe an integer? 48 if num, err := strconv.ParseUint(name, 0, 64); err == nil { 49 return ParseEnumValue(elems, num) 50 } 51 52 return Enum{}, errors.Errorf("item %s is not in enum %v", name, elems) 53 } 54 55 // ParseEnumValue creates a Enum with special number. 56 func ParseEnumValue(elems []string, number uint64) (Enum, error) { 57 if number == 0 || number > uint64(len(elems)) { 58 return Enum{}, errors.Errorf("number %d overflow enum boundary [1, %d]", number, len(elems)) 59 } 60 61 return Enum{Name: elems[number-1], Value: number}, nil 62 }