postgresql - 插入记录违反了 PostgreSQL 中的两个唯一索引。首先检查哪一个?

标签 postgresql unique-constraint

我有一个 PostgreSQL 表,在不同字段上有两个唯一索引(nicknameemail)。我正在尝试插入一条违反这两个约束的记录。我希望首先检查并报告昵称

我观察到首先检查首先创建的索引,因此我首先在 nickname 上创建索引,它确实有效。但这种行为是指定的吗?我可以依赖它,还是只是偶然?

最佳答案

PostgreSQL 使用RelationGetIndexList获取索引列表,评论说:

/*
 * RelationGetIndexList -- get a list of OIDs of indexes on this relation
[...]
 *
 * The returned list is guaranteed to be sorted in order by OID.  This is
 * needed by the executor, since for index types that we obtain exclusive
 * locks on when updating the index, all backends must lock the indexes in
 * the same order or we will get deadlocks (see ExecOpenIndices()).  Any
 * consistent ordering would do, but ordering by OID is easy.
[...]
 */

OID(对象标识符)是向上计数的 4 字节无符号整数,因此通常较晚的对象将获得更高的 OID。这与您观察到的情况相符。

但是,一旦 OID 范围用完,它们就会绕回并从 FirstNormalObjectId (16384) 重新开始,因此不能保证首先创建的索引具有较低的 OID。

您可以使用如下查询:

SELECT 'indexname'::regclass::oid;

查找每个索引的 OID。

要获取表上所有索引的 OID,请使用

SELECT indexrelid AS oid, indexrelid::regclass
FROM pg_index
WHERE indrelid = 'tablename'::regclass;

关于postgresql - 插入记录违反了 PostgreSQL 中的两个唯一索引。首先检查哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55104384/

相关文章:

c# - 哪个数据集行违反了数据库唯一约束?

nhibernate - 为什么 Fluent NHibernate 会忽略我对组件的唯一约束?

sql - PostgreSQL 8.3 中具有非空和唯一约束的增量字段

sql - 删除临时表时如何避免删除静态表

postgresql - spark 将字符串转换为 TimestampType

postgresql - pg_dump 数据库转储是 'at-that-time' 转储吗?

postgresql - PostgreSQL 如何强制执行 UNIQUE 约束/它使用什么类型的索引?

javascript - 如何使用 Sequelize 建立关系

如果存在外键,则 PostgreSQL 插入

sql - 插入时在空表上持续出现 "unique constraint violation"