postgres_exporter/pkg/pgdbconv/dbconv.go
Will Rouesnel 6fcfe4041a
WIP
2020-02-26 02:03:50 +11:00

75 lines
1.7 KiB
Go

// package dbconv defines functions to intelligently convert to and from postgres specific datatypes for metric
// purposes
package pgdbconv
import (
"fmt"
"github.com/prometheus/common/log"
"math"
"strconv"
"time"
)
// DBToFloat64 converts database.sql types to float64s for Prometheus consumption. Null types are mapped to NaN. string and []byte
// types are mapped as NaN and !ok
func DBToFloat64(t interface{}) (float64, bool) {
switch v := t.(type) {
case int64:
return float64(v), true
case float64:
return v, true
case time.Time:
return float64(v.Unix()), true
case []byte:
// Try and convert to string and then parse to a float64
strV := string(v)
result, err := strconv.ParseFloat(strV, 64)
if err != nil {
log.Infoln("Could not parse []byte:", err)
return math.NaN(), false
}
return result, true
case string:
result, err := strconv.ParseFloat(v, 64)
if err != nil {
log.Infoln("Could not parse string:", err)
return math.NaN(), false
}
return result, true
case bool:
if v {
return 1.0, true
}
return 0.0, true
case nil:
return math.NaN(), true
default:
return math.NaN(), false
}
}
// DBToString converts database.sql to string for Prometheus labels. Null types are mapped to empty strings.
func DBToString(t interface{}) (string, bool) {
switch v := t.(type) {
case int64:
return fmt.Sprintf("%v", v), true
case float64:
return fmt.Sprintf("%v", v), true
case time.Time:
return fmt.Sprintf("%v", v.Unix()), true
case nil:
return "", true
case []byte:
// Try and convert to string
return string(v), true
case string:
return v, true
case bool:
if v {
return "true", true
}
return "false", true
default:
return "", false
}
}