In my Golang (1.15) application I use sqlx package to work with the PostgreSQL database (PostgreSQL 12.5).
My SQL request has an array_agg function that returns the array of strings or null if it's empty.
I am trying to Scan the results of this SQL request but it raises the next error in my program:
sql: Scan error on column index 3, name "organization_ids": unsupported Scan, storing driver.Value type string into type *[]string
Code snippet:
type Channel struct {
ChannelId *string `db:"channel_id" json:"channelId"`
ChannelName *string `db:"channel_name" json:"channelName"`
OrganizationsIds *[]string `db:"organizations_ids" json:"organizationsIds"`
}
var channel Channel
row := db.QueryRow(`
select
channels.channel_id::text,
channels.channel_name::text,
array_agg(distinct channels_organizations_relationship.organization_id)::text[] organizations_ids
from
channels
left join channels_organizations_relationship on
channels.channel_id = channels_organizations_relationship.channel_id
where
channels.channel_id = $1
group by
channels.channel_id
limit 1;`, *channelId)
if err := row.Scan(&channel.ChannelId, &channel.ChannelName, &channel.OrganizationsIds); err != nil {
fmt.Println(err)
}
return &channel
I also tried to change the data type of the OrganizationsIds field in the Channel struct to *pg.StringArray from the github.com/lib/pq package. In this case, when I Scan, I get the following error in my program:
sql: Scan error on column index 3, name "organizations_ids": unsupported Scan, storing driver.Value type string into type *[]pq.StringArray
My task is to return a list of strings or null/nil to the client for this column.
Can someone explain how to fix this strange behavior?
pq.StringArray's underlying type is a[]stringso one thing you can do is to convert your field topq.StringArrayjust before scanning. i.e. have the field beOrganizationsIds []string, and then when scanning dorow.Scan(..., (*pq.StringArray)(&channel.OrganizationIds)).OrganizationsIds pq.StringArrayand then in scan:row.Scan(..., &channel.OrganizationIds).sql: Scan error on column index 3, name "organizations_ids": pq: parsing array element index 0: cannot convert nil to string. Do you have any ideas on how to fix it?[]*stringor[]sql.NullStringas the target type. Try thepq.Arrayfunction, e.g. haveOrganizationsIds []*stringand scan like thisrow.Scan(..., pq.Array(&channel.OrganizationIds)).{NULL}. It seems like I need to change the request itself. What do you think?