sql - GO 中这个错误 `update or delete on table "tablename"violates foreign key constraint"的名称是什么?

标签 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
    //}
}

最佳答案

好问题!我最好的猜测是这是一个 github.com/lib/pq.Error , 但您可以通过粘贴 fmt.Printf("%T\n", err) 来确认这一点在错误站点。离开这个假设,我们可以check the properties of this type :

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
}

太棒了!看起来我们有一个 ErrorCode成员。然后我们可以检查 Postgres's error code list ,我们在哪里找到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
}

注意:除了您尝试处理的错误之外,在“外键违规”一栏下可能还有其他错误情况。考虑探索 pq.Error 的其他领域结构以缩小您感兴趣的特定错误案例。

关于sql - GO 中这个错误 `update or delete on table "tablename"violates foreign key constraint"的名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40398706/

相关文章:

python - 为什么 django ORM 比原始 SQL 慢得多

mysql - PHP SQL 分页 LIMIT 子句

postgresql - 如何在postgreSQL上为hstore添加索引?

javascript - Sequelize : Query same join table with different conditions

go - 通过 Golang 记录器写入日志

golang-migrate Close() 不关闭连接

sql - 查找 GROUP BY 查询中的最高 COUNT

MySQL 错误 1005

ruby-on-rails - FactoryGirl .update 实际上并不更新关联对象

go - 等待所有 goroutine 完成并合并结果