db icon indicating copy to clipboard operation
db copied to clipboard

Can't seem to fill slice of anonymous structs

Open andrew-kennedy opened this issue 5 years ago • 4 comments

My scenario is I don't want to first read the whole row into a slice of matching row structs, I'd like to read just one column value so I came up with something like this:

var keycardIDs = []struct {
    uint64 `db:"keycard_id"`
}

err := s.db.SelectFrom(TableSubjectKeycard).
	Columns(ColumnKeycardID).
	Where(ColumnSubjectUUID, subjectUUID).
	All(&keycardIDs)

Currently, this leads to a slice where all structs are zero-valued. It does work if I instead use a slice of maps like []map[string]interface{}. Is there no way to just read one column's values into a slice of matching type?

andrew-kennedy avatar Jul 09 '19 18:07 andrew-kennedy

Please, provide a full reproducer. I'm using anonymous structs in my codebase and it works properly.

VojtechVitek avatar Jul 15 '19 14:07 VojtechVitek

Can I see an example usage? For reference, I'm using the QL driver and am using the latest version of the upper.db package. My QL table is defined as such in my tests:

	CREATE TABLE subject_keycards(
	id string NOT NULL,
	uuid string NOT NULL,
	keycard_id int64 NOT NULL,
	deleted_at time 
	);

And I attempt to fetch from this table as above. Here's a better snippet with more context:

var keycardIDs = []struct {
    uint64 `db:"keycard_id"`
}

err := s.db.SelectFrom("subject_keycards").
	Columns("keycard_id").
	Where("uuid", someV4UUID).
	All(&keycardIDs)

This fails with the anonymous tagged structs and works with a slice of maps, but that's far more cumbersome to work with with all the type assertions it ends up requiring.

andrew-kennedy avatar Jul 15 '19 18:07 andrew-kennedy

Afaik, your snippet doesn't even compile https://play.golang.org/p/IaepXQHNRtf.

Mind sharing full reproducer?

VojtechVitek avatar Jul 15 '19 20:07 VojtechVitek

Have you tried

var keycardIDs []struct {
    ID uint64 `db:"keycard_id"`
}

?

Or how else would you get to the value of the ID variables?

VojtechVitek avatar Jul 15 '19 20:07 VojtechVitek