Chris Hunter-Johnson
Chris Hunter-Johnson

Reputation: 606

How to specify constraint name in TypeOrm for postgresql

I would like to follow SQL naming standards for Primary and Foreign Key names. One such approach is in Naming conventions in SQL. For the Primary key, the name should be in the format PK_. The PrimaryGeneratedColumn decorator should allow you to enter the name. For Foreign Key, the name should be in the format FK__. This could be in the relation decorator.

I cannot see how to achieve this.

Currently the constraints names do not have any semantic meaning - FK_f38670e509f911de73d91cab5bb

Could you let me know if there is another way to achieve this?

Many thanks

Upvotes: 5

Views: 9177

Answers (3)

arifszn
arifszn

Reputation: 81

  • For primary key:
    @PrimaryColumn('uuid', { primaryKeyConstraintName: 'custom' })
    id: string;
    
  • For foreign key:
    @ManyToOne(() => Currency, {})
    @JoinColumn({
    name: 'currencyId',
    referencedColumnName: 'id',
    foreignKeyConstraintName: 'custom',
    })
    currency: Currency;
    
  • For unique key:
    @Unique('custom', ['username'])
    @Column({ length: 200 })
    username: string;
    

Upvotes: 8

Muhammad Bilal
Muhammad Bilal

Reputation: 21

You can use foreignKeyConstraintName to specify constraint name

@JoinColumn([{ name: "user_id", referencedColumnName: "id", foreignKeyConstraintName: "fkey_constraint_name"}])

Upvotes: 2

Suben Saha
Suben Saha

Reputation: 1848

You can use @Unique() constraint as follows:

@Entity()
@Unique('UNIQUE_EMAIL_ADDRESS', ['address'])
export class Email {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'varchar', length: 64 })
  address: string;
}

Upvotes: -2

Related Questions