【发布时间】:2016-07-27 11:01:23
【问题描述】:
我在尝试删除一堆记录然后插入新记录后遇到以下错误:
Error: SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "routes_pkey" DETAIL: Key (id)=(1328) already exists.
SQL Query:
INSERT INTO routes (agency_id, route_identifier, short_name, long_name, description, route_color, text_color) VALUES (:c0, :c1, :c2, :c3, :c4, :c5, :c6) RETURNING *
这是代码的简化版本:
$routes = TableRegistry::get('Routes');
$routes->deleteAll(['agency_id' => $agency->id]);
# Data to be updated
$patchData = [
'stops' => $stopData,
'static_data_modified' => Time::now()
];
$patchOptions = [
'associated' => ['Stops.Routes']
];
# If: The stops have already been added to the DB
# Then: Remove them from the patch data
if (isset($stopData['_ids'])) {
unset($patchData['stops']);
# Change settings for this implementation type
$patchOptions = [];
$stopCount = count($stopData['_ids']);
}
$agency = $this->Agencies->patchEntity($agency, $patchData, $patchOptions);
$this->Agencies->save($agency);
似乎出于某种原因,Postgres 认为我正在插入具有重复主键的记录。但我无法从我的代码中看出这是如何实现的。
这是我在 SQL 日志末尾看到的内容:
DELETE FROM
routes
WHERE
agency_id = 51
BEGIN
SELECT
1 AS "existing"
FROM
agencies Agencies
WHERE
Agencies.id = 51
LIMIT
1
INSERT INTO routes (
agency_id, route_identifier, short_name,
long_name, description, route_color,
text_color
)
VALUES
(
51, '100001', '1', '', 'Kinnear - Downtown Seattle',
'', ''
) RETURNING *
ROLLBACK
知道为什么我会看到此错误吗?
我正在使用带有 Postgresql 9.4 的 CakePHP v3.1
我尝试添加它,但它没有改变任何东西:
$connection = ConnectionManager::get('default');
$results = $connection->execute('SET CONSTRAINT = routes_pkey DEFERRED');
以下是我读过但没有找到解决方案的类似问题:
- ERROR: duplicate key value violates unique constraint in postgres
- cakephp duplicate key value violates unique constraint
- Error: duplicate key value violates unique constraint
- ERROR: duplicate key value violates unique constraint "xak1fact_dim_relationship"
- postgresql: error duplicate key value violates unique constraint
- https://stackoverflow.com/questions/33416321/postgresql-bdr-error-duplicate-key-value-violates-unique-constraint-bdr-node
更新 根据 muistooshort 的评论,我从路由表中删除了所有记录并重新运行代码,它工作正常。之后我第二次运行它时它也运行良好。所以我认为这支持 mu 的理论,即数据库中的现有记录(不是我的代码)有问题。我认为现在更好的问题是数据库中究竟是什么情况导致了这种情况,我该如何解决?
【问题讨论】:
-
您是否手动分配
ids 或执行其他操作导致id值与提供id值的序列不同步? -
@muistooshort 当然不是故意的,但也许是无意中发生的?你能详细说明我应该寻找什么吗?如果记录的 ID 号较低但数据库中已有较高的 ID,Postgres 会被愚弄吗?类似的东西?
-
@muistooshort 我想我的问题是我应该在数据库中寻找什么症状来确定你的理论是否有问题?
-
@muistooshort 在问题底部查看我的更新。
-
serialPostgreSQL 中的列从序列中获取默认值。如果您插入带有显式id的新行,则将使用id但序列不会知道它,因此当serial列询问时,它将为您提供该值(当它到达时)默认值(例如:sqlfiddle.com/#!15/17534/1)。您可以使用setval重置序列以匹配表中的ids。
标签: php database postgresql cakephp cakephp-3.0