Skip to content

Removal of support for Connection::lastInsertId($name) broak my code, wrong lastInsertId is returned (from database trigger). #6846

@weerdenburg

Description

@weerdenburg

Since commit b2e0427 my code has been broken.

Because of this change, lastInsertId() returns the last inserted ID from within the latest transaction.

So in my case:
I have a database trigger that creates log records in another table using an INSERT command when a signal is created, and therefore, with this new code, lastInsertId returns a wrong ID. The ID is from my log table, not from my original Entity!

It took me a long time to figure this out and to find a workaround.

I now use my own CustomIdGenerator as a workaround.

 #[ORM\Id]
 #[ORM\GeneratedValue(strategy: 'CUSTOM')]
 #[ORM\CustomIdGenerator(class: SequenceGenerator\Signal::class)]
 #[ORM\Column(type: Types::INTEGER)]
 private ?int $id = null;
<?php

declare(strict_types=1);

namespace App\Entity\SequenceGenerator;

use Doctrine\DBAL\Exception;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Id\AbstractIdGenerator;

class Signal extends AbstractIdGenerator
{
    /**
     * We need to provide the ID before we commit the signal into the database.
     * This is because we are using a database trigger that inserts a row into signal_logs
     * that interfered with the default flow that uses lastInsertId afterward.
     * @see: IdentityGenerator
     *
     * @throws Exception
     */
    public function generateId(EntityManagerInterface $em, object|null $entity): int
    {
        return (int)$em->getConnection()
            ->fetchOne('SELECT NEXTVAL(\'signal_id_seq\')');
    }
}

I wonder if this hard break was intended when you removed the $name parameter.
Because of that $name parameter, the flow worked correctly and returned the intended ID!
Now it doesn't anymore!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions