wocommunity/wonder — pull request #621 by dbliefernicht (2014-12-11 10:04:31+00:00)
Title: H2Plugin seems to initialize sequences with wrong sequence number (off by one)

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:
```sql
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