postgres_exporter/exporter/dbconv/dbconv.go

64 lines
1.4 KiB
Go

package dbconv
import (
"time"
"strconv"
"github.com/prometheus/common/log"
"math"
"fmt"
)
// 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 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
default:
return "", false
}
}