CakePHP:唯一冲突:7错误:重复键值违反唯一约束

CakePHP:唯一冲突:7错误:重复键值违反唯一约束,php,database,postgresql,cakephp,cakephp-3.0,Php,Database,Postgresql,Cakephp,Cakephp 3.0,在尝试删除一组记录,然后插入新记录后,我遇到以下错误: 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_nam

在尝试删除一组记录,然后插入新记录后,我遇到以下错误:

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
知道我为什么会看到这个错误吗

我使用的是CakePHP v3.1和Postgresql 9.4

我试图添加此内容,但没有改变任何内容:

$connection = ConnectionManager::get('default');
$results = $connection->execute('SET CONSTRAINT = routes_pkey DEFERRED');
以下是我在没有找到解决方案的情况下读到的类似问题:

更新 在muistooshort的评论之后,我删除了routes表中的所有记录,并重新运行了代码,代码运行良好。在那之后,我第二次运行它时,它也运行得很好。因此,我认为这支持mu的理论,即db中现有记录(不是我的代码)有问题。我认为现在更好的问题是,DB中到底是什么情况导致了这种情况,以及如何修复它们?

PostgreSQL中的问题非常简单:它本质上是一个
整数
列,其默认值来自。但是序列不知道您对表做了什么,因此如果您在不使用或更新序列的情况下为
serial
指定一个值,那么事情可能会变得混乱

例如:

create table t (
  id serial not null primary key
);
insert into t (id) values (1);
insert into t (id) values (DEFAULT);
将产生唯一性冲突,因为
1
已显式用于
id
,但序列无法知道它已被使用

演示

大概在某个时间某个地方,某个东西添加了一行,其中id=1328,而序列中没有id。或者,您的PK默认值所使用的序列已使用进行了调整,以开始返回表中已有的值

在任何情况下,最简单的方法是使用
setval
调整序列以匹配表的当前内容:

select setval('routes_id_seq', (select max(id) from routes));
该序列应被称为
routes\u id\u seq
,但如果不是,则可以在
psql
中使用
\d routes
来查找其名称

因此,如果我们将前面的示例更新为:

create table t (
  id serial not null primary key
);
insert into t (id) values (1);
select setval('t_id_seq', (select max(id) from t));
insert into t (id) values (DEFAULT);
然后我们将在表中得到
1
2
,而不是
1
和一个错误


Demo

您是否一直在手动分配
id
s或执行其他操作,以使
id
值与提供
id
值的序列不同步?@muistooshort当然不是有意的,但可能是无意中发生的?你能详细说明一下我应该找什么吗?如果一条记录的ID数很低,但数据库中已经有了更高的ID,那么Postgres会被愚弄吗?诸如此类?@muistooshort我想我的问题是我应该在DB中寻找什么症状来确定你的理论是否是问题所在?@muistooshort在问题的底部查看我的更新。
serial
PostgreSQL中的列从序列中获取默认值。如果插入一个带有显式
id
的新行,则将使用该
id
,但序列不知道它,因此当
serial
列请求默认值(例如:)时,它将为您提供该值(当它到达时)。您可以使用重置序列以匹配表中的
id
s。宾果!有一个脚本使用了
COPY
,我们现在知道它不会自动推进序列。这里有更多详细信息:对,
COPY
可以做到这一点,因为这只是向包含
id
值的
INSERT
提供数据的一种奇特方式。很高兴看到你也通过了10公里障碍:)