gopgx

pgtype.Numeric to float conversion


I have an app that uses interfaces to get a variable number of columns from a postgresql database. It uses a dynamic struct of type map[string]interface{} for the data type for the query to scan into and it is all working to the point where the data is coming back fine, I can decode the column names into keys on the map and the data is able to be converted to either time.Time (for the time stamps) or pgtype.Numeric for the other fields.

This is great... BUT. I have been totally unable to get the pgtype.Numeric results to convert to float32 or Int results.

I can pull apart the pgtype.Numeric returns and print them out (for example)

Turbine, Timestamp, WindSpeed, WindDir, Power
   t017,2024-02-15 18:20:00 +1100 AEDT,{892 -2 2 false none},{7200 -2 2 false none},{226391 -2 2 false none}

But, try as I might I am totally unable to go from pgtype.Numeric to a base type.

There are directions for using set to make the pgtype.Numeric, but I've tried .Scan, and .Get and straight up casts and have not had any joy at all at getting the number back.

This MUST be easy... but I cannot work it out.

var floatval float32
err := pgNumeric.Scan(&floatval) just returns 0 every time.

What have I missed?


Solution

  • It seems there is an AssignTo method on the pgtype.Numeric:

    var f float64
    err := pgNumeric.AssignTo(&f)
    

    It checks the given input type and fills the variable with it's internal value. Here is a link to the implementation.

    Scan does the parsing of the DB value into the Numeric variable.