Postgres enum in typeorm

前端 未结 4 1169
南笙
南笙 2021-02-18 18:49

In typeorm, how can I create a postgres enum type Gender as in this raw query

CREATE TYPE public.Gender AS ENUM (
    \'male\', \'female\'
);
ALTER TABL         


        
4条回答
  •  无人共我
    2021-02-18 19:24

    As the accepted answer states, it is now supported in postgres but still buggy: Github issue, the fix will be released in the next RC probably. Meanwhile, I saw on the thread a nice solution which I even liked it more than the actual feature fully working:

    fwiw I've been using string enum with check constraint. It's a lot more flexible than actual postgres enum, which creates whole new data types in postgres index and are really hard to manage (alter table, etc.)

    export function CheckEnum(tableName: string, fieldName: string, enumValue: any) {
      // Hash enum value and put it as part of constraint name so we can
      // force typeorm to generate migration for enum changes.
      const hash = crypto
        .createHash('sha1')
        .update(Object.values(enumValue).join(''))
        .digest('hex')
      return Check(
        // https://til.hashrocket.com/posts/8f87c65a0a-postgresqls-max-identifier-length-is-63-bytes
        `cke_${tableName}_${fieldName}_${hash}`.slice(0, 63),
        `${fieldName} in (${Object.values(enumValue).map(t => `'${t}'`)})`,
      )
    }
    

    And use it like so

    export enum Gender {
      Male = 'male',
      Female = 'female',
      Other = 'other'
    }
    
    @Entity()
    @CheckEnum('person', 'gender', Gender)
    export class Person {
    

提交回复
热议问题