Skip to content

Constraint already exists error on second run with synchronize #7738

Closed

Description

@petkovicdanilo

Issue Description

I have following Professor and Student entities (irrelevant information excluded):

@Entity()
class Professor {
    @PrimaryGeneratedColumn()
    id: number;

    //...

    @OneToMany(() => Subject, (subject) => subject.professor)
    subjects: Subject[];

    @OneToMany(() => Subject, (subject) => subject.assistant)
    assistedSubjects: Subject[];

    //...
}
@Entity()
class Subject {
    @PrimaryGeneratedColumn()
    id: number;

    //...

    @ManyToOne(() => Professor, (professor) => professor.subjects)
    professor: Professor;

    @ManyToOne(() => Professor, (professor) => professor.assistedSubjects)
    assistant: Professor;

    //...
}

I have synchronize: true option set. When I run my application with empty database this creates
tables as expected. But on second run I get an error that constraint for relation "subject" already exists.

Expected Behavior

Synchronization works every time, not just at the database tables creation.

Actual Behavior

When I turn on logging: true this is what I get:

...
query: ALTER TABLE "subject" DROP CONSTRAINT "FK_cd1bf0b362daefd2e6a1046aa35"
...
query: ALTER TABLE "subject" ADD CONSTRAINT "FK_cd1bf0b362daefd2e6a1046aa35" FOREIGN KEY ("professorId") REFERENCES "professor"("id") ON DELETE NO ACTION ON UPDATE NO ACTION
query: ALTER TABLE "subject" ADD CONSTRAINT "FK_5a054b9f487cd7b0f04f7ae6197" FOREIGN KEY ("assistantId") REFERENCES "professor"("id") ON DELETE NO ACTION ON UPDATE NO ACTION
query failed: ALTER TABLE "subject" ADD CONSTRAINT "FK_5a054b9f487cd7b0f04f7ae6197" FOREIGN KEY ("assistantId") REFERENCES "professor"("id") ON DELETE NO ACTION ON UPDATE NO ACTION
error: error: constraint "FK_5a054b9f487cd7b0f04f7ae6197" for relation "subject" already exists
    at Parser.parseErrorMessage (<path>/node_modules/pg-protocol/dist/parser.js:287:98)
    at Parser.handlePacket (<path>/node_modules/pg-protocol/dist/parser.js:126:29)
    at Parser.parse (<path>/node_modules/pg-protocol/dist/parser.js:39:38)
    at Socket.<anonymous> (<path>/node_modules/pg-protocol/dist/index.js:11:42)
    at Socket.emit (events.js:376:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
  length: 149,
  severity: 'ERROR',
  code: '42710',
  detail: undefined,
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'tablecmds.c',
  line: '8141',
  routine: 'ATExecAddConstraint'
}
query: ROLLBACK
...

Steps to Reproduce

  1. Create above mentioned entities
  2. Run application with synchronize: true twice

My Environment

I'm using typeorm with NestJS if it is relevant.

Dependency Version
Operating System Fedora 33
Node.js version v14.17.0
Typescript version v4.2.4
TypeORM version v0.2.32

Relevant Database Driver(s)

  • aurora-data-api
  • aurora-data-api-pg
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Am i wrong with how i connect entities or is this a bug?
My guess is that typeorm drops only one relation between entities, even though many relations can exist.

Activity

  1. JasonMan34 commented on Jun 15, 2021

    @JasonMan34
    Contributor

    Make sure you don't have two entities with the same name. That could cause this type of issue

  2. petkovicdanilo commented on Jun 17, 2021

    @petkovicdanilo
    Author

    All of my entities have unique name, so I guess that's not a cause for this problem.

  3. matthew-emw commented on Jun 17, 2021

    @matthew-emw

    we're experiencing something similar in a situation where we have two-tables-that-could-have-been-one... that is, we have an entity SiteLocation that has a property like this:

    @OneToOne(() => Site)
    @JoinColumn()
    SITE: Site;

    This results in a UNIQUE constraint being generated for SITE_ID column on the site_location table. It's that UQ_<etc> constraint that is causing the breakage in our case. Thusly:

    query: ALTER TABLE "site_location" RENAME CONSTRAINT "UQ_84122c12c69c84911b6a8dc2686" TO "UQ_84122c12c69c84911b6a8dc2686"
    query failed: ALTER TABLE "site_location" RENAME CONSTRAINT "UQ_84122c12c69c84911b6a8dc2686" TO "UQ_84122c12c69c84911b6a8dc2686"
    error: error: relation "UQ_84122c12c69c84911b6a8dc2686" already exists
    

    (I acknowledge that the OP has a slightly different-shaped issue, but there seemed to be enough commonality for me to feel that this message was worth writing...)

  4. ubald commented on Jun 22, 2021

    @ubald

    I'm having a similar situation as @matthew-emw where my OneToOnes have their foreign keys being recreated on every run with synchronize: true. I was made aware of that when I switched to a custom naming strategy that doesn't use "random" names and I started to get conflicts.

  5. mleduc-zirtue commented on Aug 13, 2025

    @mleduc-zirtue

    Why is this still open after 4 years? I am having a similar issue. I am using a custom naming strategy as well as defining my primary key column with this decorator: @PrimaryColumn('uuid', { default: () => 'uuid_generate_v7()' }). Trying to debug / fix this is a nightmare.

  6. kwonstone commented on Sep 5, 2025

    @kwonstone

    also seeing this issue as well

  7. gioboa commented on Jan 18, 2026

    @gioboa
    Collaborator

    Closed by #11889

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions