typescript 时间戳类型列具有缺省空值的TypeORM会生成无限迁移

yquaqz18  于 2022-12-30  发布在  TypeScript
关注(0)|答案(1)|浏览(241)

我在NestJs项目中的一个实体中使用TypeORM定义了以下列:

@CreateDateColumn({
    nullable: true,
    type: 'timestamp',
    default: () => 'NULL',
    })
public succeededAt?: Date;

这将生成看起来正确的迁移:

export class migration123 implements MigrationInterface {
   name = 'migration123';

   public async up(queryRunner: QueryRunner): Promise\<void\> {
      await queryRunner.query(
         `CREATE TABLE [...], "succeededAt" TIMESTAMP DEFAULT NULL, [...]`
   );
   \[...\]
}

但是在运行迁移之后,如果我尝试使用TypeORM CLI生成新的迁移,它仍然检测到一些差异:

[...]
public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "mercadopago_payment_request" ALTER COLUMN "succeededAt" SET DEFAULT null`);
[...]

我猜Postgres会检测到默认值作为全局默认值(如果没有另外声明,每列都有null作为默认值),并且不会为它添加任何特殊规则。然后TypeORM看不到规则,并试图再次添加它。
有什么办法防止这种情况发生吗?
我尝试删除默认值:

@CreateDateColumn({
    nullable: true,
    type: 'timestamp',
    })
public succeededAt?: Date;

但这会生成一个默认值为now()的迁移:

export class migration123 implements MigrationInterface {
   name = 'migration123';

   public async up(queryRunner: QueryRunner): Promise\<void\> {
      await queryRunner.query(
         `CREATE TABLE [...], "succeededAt" TIMESTAMP DEFAULT now(), [...]`
   );
   \[...\]
}

这就是我为什么要特别声明null作为默认值的原因。

cbjzeqam

cbjzeqam1#

我的问题是由于@CreateDateColumn装饰器。
我能够用常规的日期列实现正确的行为:

@Column({ nullable: true, type: 'timestamp' })
  @IsDate()
  public succeededAt: Date | null;

相关问题