kibae / typeorm-auditing

TypeORM Auditing: Create history tables and manage changes of entity automatically.
https://www.npmjs.com/package/typeorm-auditing
MIT License
25 stars 3 forks source link

Duplicate key value violates unique constraint when using @OneToOne #12

Open alberto-i opened 1 year ago

alberto-i commented 1 year ago

Environment

When an entity has a OneToOne relationship, TypeORM will create a unique index for the foreign key column. The inherited auditing entity also creates this unique index, and after trying to save a second record to the auditing table, we get a "duplicate key value violates unique constraint"

Steps to reproduce:

export abstract class AuditedEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string
}

@Entity()
export class Registration extends AuditedEntity {
  @Column()
  foo: string

  @OneToOne(() => RegistrationApproval, { cascade: true, eager: true })
  @JoinColumn()
  approval: RegistrationApproval
}

@AuditingEntity(Registration)
export class AuditingRegistration extends Registration implements AuditingEntityDefaultColumns {
  readonly _seq: number
  readonly _action: AuditingAction
  readonly _modifiedAt: Date
}

@Entity()
export class RegistrationApproval extends AuditedEntity {
  @Column()
  status: string
}

// Somewhere:
const reg = registrationRepository.create({ foo: 'hello'})
const approval = new RegistrationApproval()
approval.status = 'valid'
reg.approval = approval
const saved = await registrationRepository.save(reg)

saved.foo = 'world'
await registrationRepository.save(reg) // Will throw duplicate key
alberto-i commented 1 year ago

Overriding the join column "fixed" the problem, removing the unique constraint:

@AuditingEntity(Registration)
export class AuditingRegistration extends Registration implements AuditingEntityDefaultColumns {
  readonly _seq: number
  readonly _action: AuditingAction
  readonly _modifiedAt: Date

  @Column({ nullable: true })
  approvalId: string
}

Edit: Actually it didn't:

column "approvalId" specified more than once
Filoz commented 1 year ago

Hi

did you find a solution?

Thank you!