我有一个表的唯一约束偶尔PostgreSQL的“重复键值违反唯一约束”从根本错误插入
CREATE UNIQUE INDEX "bd_hash_index" ON "public"."bodies" USING btree ("hash");
我也有一个围棋程序,需要一个通道上的“身体”的价值观,过滤掉通过哈希重复,并且只将非重复项插入到数据库中。 像这样:
import (
"crypto/md5"
"database/sql"
"encoding/hex"
"log"
"strings"
"time"
)
type Process struct {
DB *sql.DB
BodiesHash map[string]bool
Channel chan BodyIterface
Logger *log.Logger
}
func (pr *Process) Run() {
bodyInsert, err := pr.DB.Prepare("INSERT INTO bodies (hash, type, source, body, created_timestamp) VALUES ($1, $2, $3, $4, $5)")
if err != nil {
pr.Logger.Println(err)
return
}
defer bodyInsert.Close()
hash := md5.New()
for p := range pr.Channel {
nowUnix := time.Now().Unix()
bodyString := strings.Join([]string{
p.GetType(),
p.GetSource(),
p.GetBodyString(),
}, ":")
hash.Write([]byte(bodyString))
bodyHash := hex.EncodeToString(hash.Sum(nil))
hash.Reset()
if _, ok := pr.BodiesHash[bodyHash]; !ok {
pr.BodiesHash[bodyHash] = true
_, err = bodyInsert.Exec(
bodyHash,
p.GetType(),
p.GetSource(),
p.GetBodyString(),
nowUnix,
)
if err != nil {
pr.Logger.Println(err, bodyString, bodyHash)
}
}
}
}
但周期性我得到的错误
"pq: duplicate key value violates unique constraint "bd_hash_index""
在我的日志文件。我无法想象它是如何可能的,因为我在插入之前检查哈希的唯一性。 我确信当我呼叫go processDebugBody.Run()
时,主体表是空的。
通道与缓冲通道创建:
processDebugBody.Channel = make(chan BodyIterface, 1000)
你确定你没有重复哈希? –
我相信,当我打电话'去processDebugBody.Run()'表'体'是空的。 – user2024300
该表可能为空,但插入的记录可能具有重复散列。你检查过了吗? –