georgysavva / scany

Library for scanning data from a database into Go structs and more
MIT License
1.24k stars 67 forks source link

Confusing error message for NULLable fields #56

Closed carrothug closed 3 years ago

carrothug commented 3 years ago

Hello!

When (wrongly) trying to scan a NULL value into a non-pointer type, pgxscan gives me an error like so: can't scan into dest[18]: cannot assign NULL to *float64

The context for the call:

type MyStruct struct {
    ...
    ProblemField       float64   // 18th field
    ...
}

// Called with address of a MyStruct
func GetMyStruct(ctx context.Context, dest interface{}, someID uint32) error {
    err := pgxscan.Get(ctx, db, dest,
        sqlQuery, // Query has a outer join hence the NULLable fields
        someID,
    )
    return err
}

I believe the error message should read can't scan into dest[18]: cannot assign NULL to float64 instead since the issue would be solved by having a pointer type. (The same type of error message happens in https://github.com/georgysavva/scany/issues/36.)

Thanks for taking a look!

georgysavva commented 3 years ago

Hello! This error message cannot assign NULL to *float64 comes from pgx library. It says *float64 because for field ProblemField float64 scany takes a reference and passes it as &MyStruct.ProblemField since otherwise, pgx wouldn't be able to mutate it. So pgx does receive *float64 type, not float64.

For NULLable fields you need to define them like ProblemField *float64 and pgx will receive **float64 (double pointer) and if something would go wrong it would return an error like that: cannot assign "something" to **float64, because now pgx indeed received **float64. I hope it helps!

carrothug commented 3 years ago

Ah yes, the getting passed by reference clears up the message meaning. @georgysavva thank you!