ERROR: duplicate key value violates unique constraint "pg_class_relname_nsp_index"
- Dominant language
- Go
- Stars
- 786
- Forks
- 61
- Avg merge
- 4d 11h
- Merged PRs (30d)
- 2
Description
```
ERROR: duplicate key value violates unique constraint "pg_class_relname_nsp_index"
DETAIL: Key (relname, relnamespace)=(devices_schema_version_id_seq, 2200) already exists.
STATEMENT: CREATE TABLE IF NOT EXISTS "devices_schema_version" ("id" SERIAL NOT NULL PRIMARY KEY, "version" BIGINT UNIQUE, "created_at" TIMESTAMPTZ, "updated_at" TIMESTAMPTZ);
```
This issue was found by starting two concurrent services, both running an auto-migration as part of its startup in which they were making sure that the `devices_schema_version` table existed, however: Postgres has a known bug with its `CREATE TABLE IF NOT EXIST` implementation that may cause the above cited error.
The remedy is to acquire a lock using `LOCK TABLE pg_catalog.pg_namespace IN SHARE ROW EXCLUSIVE MODE;` within the same transaction according to [source 1](https://stackoverflow.com/a/29908840/15919263) and [source 2](https://www.postgresql.org/message-id/CA+TgmoZAdYVtwBfp1FL2sMZbiHCWT4UPrzRLNnX1Nb30Ku3-gg@mail.gmail.com).
Perhaps this issue should have been written in https://github.com/go-rel/postgres instead?
Contributor guide
Research direction
No file or test is named. Start by locating the auto-migration path used during service startup, then reproduce two concurrent PostgreSQL migrations; done means both services can ensure devices_schema_version exists without the duplicate pg_class_relname_nsp_index error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- go, postgresql
- Domain
- backend, databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100