Using lastval() instead of currval('sequence_name') for fetching IDs can return wrong ID #7489

Open
opened 2026-01-22 15:52:14 +01:00 by admin · 0 comments
Owner

Originally created by @Brajk19 on GitHub (Mar 21, 2025).

In ORM 2, newly inserted IDs in Postgres were fetched using:

SELECT currval('sequence_name')

However, in Doctrine ORM 3, this has been changed to:

SELECT lastval()

This change introduces an issue when using tools like pg_repack (or triggers in general), which create triggers that make insert into log table while doing table repack. These inserts cause another sequence to increment, meaning that lastval() may return an ID from the wrong sequence.

I understand that this change was made because of issues with Oracle (https://github.com/doctrine/dbal/issues/4687) but i I think it would be useful if this behaviour could be modified.
For Postgres it makes more sense to use currval('sequence_name').

Even having option to define our own generator when using #[ORM\GeneratedValue(strategy: 'IDENTITY')] would be useful.
Currently it depends on type so only IdentityGenerator and BigIntegerIdentityGenerator can be used:
1072ea6db4/src/Mapping/ClassMetadataFactory.php (L556-L558)

Originally created by @Brajk19 on GitHub (Mar 21, 2025). In ORM 2, newly inserted IDs in Postgres were fetched using: ```sql SELECT currval('sequence_name') ``` However, in Doctrine ORM 3, this has been changed to: ```sql SELECT lastval() ``` This change introduces an issue when using tools like [pg_repack](https://github.com/reorg/pg_repack) (or triggers in general), which create triggers that make insert into log table while doing table repack. These inserts cause another sequence to increment, meaning that `lastval()` may return an ID from the wrong sequence. I understand that this change was made because of issues with Oracle (https://github.com/doctrine/dbal/issues/4687) but i I think it would be useful if this behaviour could be modified. For Postgres it makes more sense to use `currval('sequence_name')`. Even having option to define our own generator when using `#[ORM\GeneratedValue(strategy: 'IDENTITY')]` would be useful. Currently it depends on type so only `IdentityGenerator` and `BigIntegerIdentityGenerator` can be used: https://github.com/doctrine/orm/blob/1072ea6db470308ea51eb5827733eff0438c470b/src/Mapping/ClassMetadataFactory.php#L556-L558
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: doctrine/archived-orm#7489