1

I need a string primary column that gets auto-generated when no value is set while still being able to set it myself to whatever value I want. Here's how I handled it on MySQL :

@Entity()
export class Item extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    id: string;
}

Thing is, I just migrated to PostgreSQL and uuid type prevents me from inserting simple string values. I came up with this workaround but I'm wondering if there is a better way to handle it :

import { v4 as uuid } from 'uuid';

@Entity()
export class Item extends BaseEntity {
    @PrimaryColumn()
    id: string;

    save(options?: SaveOptions): Promise<this> {
        if (!this.id) this.id = uuid();
        return super.save(options);
    }
}

ps it doesn't need to be uuid necessarily. Thanks !

Edit: I need this because I'm getting some items from another db and want to keep their ids as the PK. Hence why I can't use uuid type : the ids might not be uuid at all, just strings. I started using uuid solely because @PrimaryGeneratedColumn('increment') wouldn't accept string type

coteArthur
  • 11
  • 3
  • what is making you try to use a uuid column as another string value? in postgresql if you add the extension `CREATE EXTENSION "uuid-ossp";` and use as default value `some-orm.raw('uuid_generate_v4()')` you'll get auto generated uuids in that column by default – M-Raw Jan 13 '22 at 13:58
  • 1
    @M-Raw with the current Postgres version `uuid-ossp` is no longer necessary. `gen_random_uid()` is now a built-in function –  Jan 13 '22 at 14:01
  • You shouldn't store UUIDs as strings (text). Use the `uuid` data type. –  Jan 13 '22 at 14:02
  • @a_horse_with_no_name i didn't know that, thanks for the tip, documentation says its `gen_random_uuid()` – M-Raw Jan 13 '22 at 14:09
  • check edit for clarifications – coteArthur Jan 13 '22 at 14:48
  • Do not allow an external system to dictate your design. What happens when you get the same string for your PK from 2 separate sources? You must accept the duplicate but you cannot accept the duplicate; well you cannot have both. Instead generate your PK as either UUID or via SEQ (v10 or lager generated always a identity). Add a text column `external_identifier` to you table, use that column to track the value from the external db/app/etc. – Belayer Jan 13 '22 at 21:13

1 Answers1

0

My sample entity [typeorm][postgres]

@ObjectType()
@Entity({ name: 'Agreement', schema: 'public' })
@Index('idx_agreementId', ['agreementId'])
// @Index(['agreementId', 'departmentId', 'workplaceId'])
export class Agreement extends CoreEntity {
  @HideField()
  @PrimaryGeneratedColumn('increment')
  @IsInt()
  readonly agreementId: number;

  @Field(() => String, { nullable: false })
  @Generated('uuid')
  @Column({ nullable: false })
  readonly agreementUUID: string;

Every new record have automatically generated value int and UUID