goqu icon indicating copy to clipboard operation
goqu copied to clipboard

ScanStructs with left join query

Open benzolium opened this issue 3 years ago • 1 comments

Problem If I scan results of left join query where there are no joined rows, ScanStructs fails with errors like: converting NULL to string is unsupported.

To Reproduce

type FromTable struct {
	ID uint64 `db:"id"`
}

type TableToLeftJoin struct {
	ID uint64 `db:"id"`
}

type Result struct {
	FromTable `db:"from_table"`
	*TableToLeftJoin `db:"table_to_left_join"`
}

var rs []Result
ds := db.From("from_table").LeftJoin(goqu.T("table_to_left_join"), goqu.On(goqu.V(false)))
err = ds.ScanStructs(&rs)

err is not nil.

Expected behavior rs[0].FromTable should have some filled fields. rs[0].TableToLeftJoin should be nil. err should be nil

Dialect:

  • [x] postgres
  • [ ] mysql
  • [ ] sqlite3

Tested only with postgres, but should affect other dialects too.

Maybe there is a way of achieving the same result but some other way?

benzolium avatar Apr 01 '21 07:04 benzolium

"converting NULL to string is unsupported" is a common error when trying to Scan null results into a struct and is not specific to just the LeftJoin. This has been brought up with Go ORMs in the past, and has normally been rejected in favor of using a pointer or using sql.Null{Type} (NullString, NullInt, etc.), see sql package docs. If you convert your types over, it will not error out anymore. This also helps everyone distinguish the result from just being empty and actually being null.

Please see these other relevant issues: gorm: https://github.com/go-gorm/gorm/issues/3387 go-sql-driver: https://github.com/go-sql-driver/mysql/issues/34#issuecomment-14249039

Furthermore, please note that the author of the library mentions "While goqu may support the scanning of rows into structs it is not intended to be used as an ORM if you are looking for common ORM features like associations, or hooks"

In my opinion its a non-issue, but I'll let @doug-martin review.

juanri0s avatar Oct 10 '21 03:10 juanri0s