Search code examples
javasqlh2

Primary key constraint error while inserting default in `id` column,


My application trying to insert new entity into DB (url=jdbc:h2:mem:db) and I get following error:

Unique index or primary key violation: "PRIMARY KEY ON MY_TABLE(ID) ( /* key:10 */ CAST(10 AS BIGINT), UUID '00000000-0000-0000-0000-000000000000')"; SQL statement:
insert into my_table (id, account_id) values (default, ?) [23505-214]

My table declared as:

CREATE TABLE my_table (
    id                              BIGSERIAL PRIMARY KEY,
    account_id                      UUID NOT NULL
)

Unfortunately I can't provide minimal reproducible example because error happens only when I run big test suite.

It is correlated with other test that also insert in that table. Test are NOT run in parralel.

Am I right that "PRIMARY KEY ON MY_TABLE(ID)" means that this is primary key violation? My table have other uniq constrains so I'm not sure.

EDIT

Here is minimal example to reproduce:

-- create
CREATE TABLE MY_TABLE (
  id BIGSERIAL PRIMARY KEY,
  val BIGINT NOT NULL
);

-- insert
INSERT INTO MY_TABLE(ID, VAL) VALUES (2, 99);

INSERT INTO MY_TABLE(ID, VAL) VALUES (default, 99);
INSERT INTO MY_TABLE(ID, VAL) VALUES (default, 99);
INSERT INTO MY_TABLE(ID, VAL) VALUES (default, 99);


Solution

  • H2 does not allow to insert value of sequential primary key and use default at same time.

    Not sure if this is a bug or feature.

    Cause of problem located in org.h2.mvstore.db.MVPrimaryIndex#add. When row.setKey(lastKey.incrementAndGet()) is executed it doesn't take into account that this value may be already inserted in table manually.