georgysavva / scany

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

Scanning into a map[string]string{} #98

Closed lknop closed 1 year ago

lknop commented 1 year ago

I am not sure if I am not misreading this line from readme:

Apart from structs, support for maps and Go primitive types as the destination

Is it possible to just read a key/value mapping into a map? Or do I need to scan a slice of structs and map them manually?

sqlQuery := "SELECT key, value from mapping"

var dbMap = map[string]string{}
err := pgxscan.Select(ctx, db, &dbMap, sqlQuery) 

I am getting scany: destination must be a slice, got: map[string]string

georgysavva commented 1 year ago

Hi. Sorry for such a late reply. That documentation line says that you can scan your single row into a map. Since you are calling the Select() method, not Get(), it means that you want to scan multiple rows, so you need to pass a list of maps:

sqlQuery := "SELECT key, value from mapping"

var dbList = []map[string]string{}
err := pgxscan.Select(ctx, db, &dbList, sqlQuery) 
// dbList == [
// {"key": "the key column value from row 1", "value": "the value column  from row 1"},
// {"key": "the key column value from row 2", "value": "the value column  from row 2"},
// ...
// ]

Note that it's not going to build the mapping for you. It just represents each row as a map where keys are column names.

I hope this helps. Let me know if you have other questions.

lknop commented 1 year ago

Thanks, I looked for some time in the source code but I figured that it's not going to build the mapping as you wrote. I resolved the issue by just reading arrays and mapping manually in a loop.