In a previous question, I was wondering why I was getting an Integrity Error from SA when merging an instance with an ID for the first time into the database (injecting fixture data).
However, I learned to account for the problem by calling with the highest index I’m injecting:
select setval('my_items_id_seq', {id});
However, this didn’t solve the underlying problem, which is what I’m struggling with now. Why doesn’t merge call nextval() on the sequence when inserting a new row?
If your object already has its PK attribute set, then the ID sequence will not be used and therefore not incremented because there is no reason for the database to perform an implicit
insert into mytable (id, ...) values ((select nextval from mytable_id_seq), ...).Are you sure you need to be doing a
mergeinstead of anaddto yoursession? If you are really inserting, I would think that is more of anaddoperation. If you are simply reusing an object that is still in memory, but added earlier and possibly changed in the database now, thenmergeis appropriate.