Derek
Derek

Reputation: 367

Golang SQL Scanning to Struct strangeness

Please imagine a table as such:

FirstName, LastName, Fee, Opt_Out
String     String    Int   TinyInt(4)

And a struct as such:

type Dude struct {
    Firstname string
    Lastname  string
    Fee       int
    Opt_out   int
}

To keep it short: I am using database/sql to scan into structs with no issue, except when it comes to that TinyInt.

err = rows.Scan(&firstname, &lastname, &fee, &opt_out)

After scanning, and before assigning values to my struct, I

fmt.PrintLn(Opt_out)

and they always return a zero value. If I plug the query directly into the sql server, I get the correct ones and zero's I am expecting.

I have also tried changing the type of "Opt_out" in the struct to string, and attempted to cast via the query itself by doing a

IF(Opt_out=1,"yes","no") 

and a similar thing happens, the query run in sql returns expected results, but golang returns empty values.

I am drawing a blank. Any ideas?

Upvotes: 0

Views: 2780

Answers (1)

Derek
Derek

Reputation: 367

Jeez. Ok, this had nothing to do with the tinyint itself apparently.

The 'fee' column in the database had null values in it, the pre-existing query was set to replace null with empty strings.

IFNULL(fee,'')

It seems that the sql driver 'broke' very quietly on seeing those, and just gave up on processing everything afterwards.

My fix was ammending the query with IFNULL(fee,0) and everything popped back to life.

Thanks RayfenWindspear! I would not have given it the extra mile without your feedback.

Upvotes: 3

Related Questions