在 GO 中,此错误“更新或删除表“tablename”违反外键约束的错误名称是什么?

Sai*_*ifi 1 sql postgresql go

嗨,我在 GO 中使用 database/sql 包,我想处理这个错误,最好的方法是什么?

rows, err := transaction.Stmt(MypreparedStmt).Exec(id)
if err!=nil{
    // here I want to check if the error is something with the foreign key so I want something like 
     //if err==something{
           //do something
    //}
}
Run Code Online (Sandbox Code Playgroud)

web*_*rc2 5

好问题!我最好的猜测是这是一个github.com/lib/pq.Error,但您可以通过粘贴fmt.Printf("%T\n", err)错误站点来确认这一点。脱离这个假设,我们可以检查这种类型的属性

type Error struct {
    Severity         string
    Code             ErrorCode
    Message          string
    Detail           string
    Hint             string
    Position         string
    InternalPosition string
    InternalQuery    string
    Where            string
    Schema           string
    Table            string
    Column           string
    DataTypeName     string
    Constraint       string
    File             string
    Line             string
    Routine          string
}
Run Code Online (Sandbox Code Playgroud)

凉爽的!看起来我们有一个ErrorCode成员。然后我们可以检查Postgres 的错误代码列表,在那里我们找到23503 | foreign_key_violation. 把所有这些放在一起,看起来你可以这样做:

const foreignKeyViolationErrorCode = ErrorCode("23503")
if err != nil {
    if pgErr, isPGErr := err.(pq.Error); isPGErr {
        if pgErr.ErrorCode != foreignKeyViolationErrorCode {
            // handle foreign_key_violation errors here
        }
    }
    // handle non-foreign_key_violation errors
}
Run Code Online (Sandbox Code Playgroud)

注意:除了您要处理的错误情况外,“外键违规”标题下可能还有其他错误情况。考虑探索结构的其他字段pq.Error以缩小您感兴趣的特定错误情况。