在我的Golang (1.15) 应用程序中,我使用sqlx包来处理PostgreSQL数据库 (PostgreSQL 12.5)。
我的SQL请求有一个array_agg函数,该函数返回字符串数组,如果为空则返回 null。
我正在尝试Scan此 SQL 请求的结果,但它在我的程序中引发了下一个错误:
sql:列索引 3 上扫描错误,名称“organization_ids”:不支持扫描,将 driver.Value 类型字符串存储到类型 *[]string
代码片段:
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
Run Code Online (Sandbox Code Playgroud)
我还尝试将结构OrganizationsIds中字段的数据类型更改为来自github.com/lib/pq包。在这种情况下,当我的程序中出现以下错误:Channel*pg.StringArrayScan
sql:列索引 3 上扫描错误,名称“organizations_ids”:不支持扫描,将 driver.Value 类型字符串存储到类型 *[]pq.StringArray
我的任务是向客户端返回该列的字符串列表或 null/nil。
有人可以解释如何解决这种奇怪的行为吗?
好吧,终于我找到了我的问题的解决方案。
我注意到该array_agg函数返回[null]. 我稍微更改了 SQL 请求以返回而null不是[null]. 我通过以下更改做到了:
array_agg(distinct channels_organizations_relationship.organization_id) filter (where channels_organizations_relationship.organization_id is not null)
Run Code Online (Sandbox Code Playgroud)
在这篇文章中(Postgres returns [null]而不是[] for array_agg of join table ),你可以找到这个问题的许多不同的解决方案。
然后您可以使用以下解决方案之一:
1个选项
我们可以在结构体中使用OrganizationsIds pq.StringArray,然后在扫描时执行此操作 row.Scan(..., &channel.OrganizationIds。
2个选项
我们可以在结构体中使用OrganizationsIds []string,然后在扫描时执行此操作row.Scan(..., (*pq.StringArray)(&channel.OrganizationIds))。