Search code examples
nestjstypeorm

Loading a 'bit' Mysql field from TypeOrm


I want to map a Mysql bit data column against a boolean property with TypeOrm. I'm using the NestJs framework and can't figure out how to do it. As far as I've seen, the Mysql bit datatype is not supported by the framework, but I don't know any way to workaround it. According to this discussion it should be enough to declare a boolean typed field in the entity and do not decorate it with nothing but @Column:

  @Column()
  enable: boolean;

However, with this I get true value in every single instance of the entity. Also tried adding the import 'reflect-metadata'; either in the entity and in app.module.ts, with the same result.

Another choice would be to use the tinyint type:

  @Column({
    type: 'tinyint',
  })
  enable: boolean;

With this, I get this kind of data, where the data field holds the current boolean value stored:

"enable":{"type":"Buffer","data":[1]}

Do I need to make some kind of hack to get this converted into a proper boolean value or is there another cleaner choice to do it?


EDIT 1

Changing the DB column data type to int seems to produce the proper output. However, it's not the most proper solution, since the bit type is the one that best suits here.

Versions being used:

  • "@nestjs/typeorm": "5.1.0"
  • "typeorm": "0.2.13"
  • "reflect-metadata": "0.1.12"
  • Mysql Engine: 5.7.25

EDIT 2

I've tried updating the typeorm related packages to their latest versions, the same keeps happening. Also with Mysql 8.0 engine. Tried also with these decorators:

  @Column()
  @IsBoolean()
  enable: boolean;

I'm in Xubuntu 16.04, BTW.


Solution

  • I resolved this issue with transformer:

    import {ValueTransformer} from 'typeorm';
    class BoolBitTransformer implements ValueTransformer {
      // To db from typeorm
      to(value: boolean | null): Buffer | null {
        if (value === null) {
          return null;
        }
        const res = new Buffer(1);
        res[0] = value ? 1 : 0;
        return res;
      }
      // From db to typeorm
      from(value: Buffer): boolean | null {
        if (value === null) {
          return null;
        }
        return value[0] === 1;
      }
    }
    

    And then used this transformer in bit/boolean columns:

      @Column({
        type: 'bit',
        nullable: false,
        default: () => `"'b'1''"`,
        name: 'can_read',
        transformer: new BoolBitTransformer()
      })
      can_read!: boolean;