golang/pq: “pq: 函数 uniq(integer[]) 不存在”

huangapple go评论97阅读模式
英文:

golang/pq : "pq: function uniq(integer[]) does not exist"

问题

这是我的代码(在gin中正常工作):

query :=`
UPDATE posts SET liked_by = array_append(liked_by, $1)
WHERE id = $2
RETURNING liked_by`

return p.DB.Exec(query, userID, post.ID)

我得到的错误信息是:

pq: function uniq(integer[]) does not exist

我的代码在没有使用uniq()函数时可以正常工作。但是数组中会包含重复的值。我想确保我的数组只包含唯一的值。

英文:

Here's my code (works fine with gin)

query :=`
UPDATE posts SET liked_by = uniq(array_append(liked_by, $1))
WHERE id = $2
RETURNING liked_by`

return p.DB.Exec(query, userID, post.ID)

The error I'm getting

pq: function uniq(integer[]) does not exist

My code works fine without uniq(). But the array is taking duplicate values. I wanna make sure my array only contains unique values.

答案1

得分: 1

问题出在你的SQL语句上(不是Go或lib/pq),你可以通过运行以下SQL语句来复现这个问题:

select uniq('1,2,3,4'::integer[])

参考这个问题中的讨论,其中一个最简单的解决方案可能是:

select array_agg(distinct x) from unnest(array_append('1,2,3,4'::integer[], 4)) t(x)

将这个集成到你的代码中,大致如下(未经测试!):

query :=`
UPDATE posts SET 
liked_by = (select array_agg(distinct x) from unnest(array_append(liked_by, $1)) t(x))
WHERE id = $2
RETURNING liked_by
`
英文:

The issue is with your SQL (not Go or lib/pq); you can replicate the problem by running the following SQL:

select uniq('{1,2,3,4}'::integer[])

See this this question for a discussion of potential solutions, one of the simplest is probably:

select array_agg(distinct x) from unnest(array_append('{1,2,3,4}'::integer[], 4)) t(x)

Integrating this into your code gives something like (untested!):

query :=`
UPDATE posts SET 
liked_by = (select array_agg(distinct x) from unnest(array_append(liked_by, $1)) t(x))
WHERE id = $2
RETURNING liked_by
`

huangapple
  • 本文由 发表于 2022年9月26日 10:21:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73849107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定