github.com/influxdata/influxdb/v2@v2.7.6/influxql/query/cast.go (about)

     1  package query
     2  
     3  import "github.com/influxdata/influxql"
     4  
     5  // castToType will coerce the underlying interface type to another
     6  // interface depending on the type.
     7  func castToType(v interface{}, typ influxql.DataType) interface{} {
     8  	switch typ {
     9  	case influxql.Float:
    10  		if val, ok := castToFloat(v); ok {
    11  			v = val
    12  		}
    13  	case influxql.Integer:
    14  		if val, ok := castToInteger(v); ok {
    15  			v = val
    16  		}
    17  	case influxql.Unsigned:
    18  		if val, ok := castToUnsigned(v); ok {
    19  			v = val
    20  		}
    21  	case influxql.String, influxql.Tag:
    22  		if val, ok := castToString(v); ok {
    23  			v = val
    24  		}
    25  	case influxql.Boolean:
    26  		if val, ok := castToBoolean(v); ok {
    27  			v = val
    28  		}
    29  	}
    30  	return v
    31  }
    32  
    33  func castToFloat(v interface{}) (float64, bool) {
    34  	switch v := v.(type) {
    35  	case float64:
    36  		return v, true
    37  	case int64:
    38  		return float64(v), true
    39  	case uint64:
    40  		return float64(v), true
    41  	default:
    42  		return float64(0), false
    43  	}
    44  }
    45  
    46  func castToInteger(v interface{}) (int64, bool) {
    47  	switch v := v.(type) {
    48  	case float64:
    49  		return int64(v), true
    50  	case int64:
    51  		return v, true
    52  	case uint64:
    53  		return int64(v), true
    54  	default:
    55  		return int64(0), false
    56  	}
    57  }
    58  
    59  func castToUnsigned(v interface{}) (uint64, bool) {
    60  	switch v := v.(type) {
    61  	case float64:
    62  		return uint64(v), true
    63  	case uint64:
    64  		return v, true
    65  	case int64:
    66  		return uint64(v), true
    67  	default:
    68  		return uint64(0), false
    69  	}
    70  }
    71  
    72  func castToString(v interface{}) (string, bool) {
    73  	switch v := v.(type) {
    74  	case string:
    75  		return v, true
    76  	default:
    77  		return "", false
    78  	}
    79  }
    80  
    81  func castToBoolean(v interface{}) (bool, bool) {
    82  	switch v := v.(type) {
    83  	case bool:
    84  		return v, true
    85  	default:
    86  		return false, false
    87  	}
    88  }