Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

H2Plugin seems to initialize sequences with wrong sequence number (off by one) #621

Merged
merged 1 commit into from
Dec 11, 2014

Conversation

dbliefernicht
Copy link
Contributor

Hi everyone,

currently we use H2 in memory for testing scenarios in combination with DBUnit (while using PostgresQL in production). During this we encountered an issue with the way, that H2Plugin seems to initialize primary-key-providing sequences, when entities are already present in the database. Basically when no sequence exists, H2Plugin tries to create a new sequence based on the current PK values by using MAX(pk) as the initial value.
Unfortunately the initial value given to H2 is actually the next value returned by the sequence (i.e. the sequence is initialized with val-1), so the first primary key generation after the initialization will give an existing primary key value instead of a new one.
An example flow (to be tested on the H2 console) simulating this is:

CREATE TABLE X (id int UNIQUE);
INSERT INTO X VALUES (1), (2), (3);

-- this is equivalent to the statements generated by Wonder
CREATE SEQUENCE x_id START WITH (SELECT MAX(id) FROM x);
ALTER TABLE x ALTER COLUMN id SET DEFAULT nextval('x_id');
-- x_id will now be 2 instead and return 3 on nextval('x_id')

-- this statement fails: Unique index or primary key violation
INSERT INTO X VALUES();
-- this statement completes successfully using PK value 4
INSERT INTO X VALUES();

This can be fixed simply by adding one to the initial H2 sequence value and thus complying with the H2 semantics, which is contained in this pull request. Most likely this will only affect testing and not live environments due to H2 deployments with existing records are seldomly encountered there.

Let me know, if this does not conform to any guidelines, code styles or if there are other issues with this patch :-) && Greetings
Dennis

@darkv
Copy link
Member

darkv commented Dec 11, 2014

Thanks for that catch!

darkv added a commit that referenced this pull request Dec 11, 2014
H2Plugin seems to initialize sequences with wrong sequence number (off by one)
@darkv darkv merged commit 59c5cd8 into wocommunity:master Dec 11, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants