Skip to content

Store UUID as binary type in MySQL #3187

Closed

Description

@igat64

Issue type:

[ ] question
[ ] bug report
[x] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[x ] mysql / mariadb
[ ] oracle
[ ] postgres
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo

TypeORM version:

[x ] latest
[ ] @next
[ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

Given an Entity with primary column that store uuid as a value.

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  ...
}

Generated type in the mysql database is varchar(255).
image

As I know this is not efficient way of storing uuid as varchar. It should be possible to store uuid as a binary type. And mysql 8 has buildin functions like: UUID_TO_BIN/BIN_TO_UUID. These function could be used to convert from the human-readable format (char/varchar) to the compact format (binary) and back.

Is it possible to use uuid values for the primary generated column and store it as binary type under the hood?

Activity

  1. pleerock commented on Jan 8, 2019

    @pleerock
    Member

    We were considering this before, but decided to go simple way because of complexity of implementation and the fact that only mysql 8 support uuid functions.

  2. elovin commented on Nov 20, 2020

    @elovin

    @igat64 you can add a varchar binary key and convert from/to string/Buffer with the event listeners BeforeInsert, BeforeUpdate, AfterUpdate ...

    The only problem I have found so far is that
    this.usersRepository.findOne(id);
    does not work with an id of type Buffer, you have to use a workaround e.g.

     return this.usersRepository.findOne({
                where: {
                    id: uuidBuffer.toBuffer(id)
                }
            });
    
  3. Alia5 commented on Nov 13, 2022

    @Alia5

    To not make this another DenverCoder-like situation

    My workaround, short and simple.
    Probably also related to #7470

    const uuidTransformer {
        to: (uuid: string|undefined) => uuid ? Buffer.from(uuid.replace(/-/g, ''), 'hex') : uuid,
        from: (bin: Buffer) => `${bin.toString('hex', 0, 4)}-${bin.toString('hex', 4, 6)}-${
            bin.toString('hex', 6, 8)}-${bin.toString('hex', 8, 10)}-${bin.toString('hex', 10, 16)}`
    };
    
    @Entity()
    export class Room {
        @PrimaryColumn({
            type: 'binary',
            length: 16,
            generated: false,
            transformer: uuidTransformer,
            default: () => 'UNHEX(REPLACE(UUID(), \'-\', \'\'))' // using maria-db so UUID_TO_BIN does not exist
        })
        public id!: string;
        /// ...
    }

    For sake of completion: with relations:

    Click me!
    @Entity()
    export class Room {
        @PrimaryColumn({
            type: 'binary',
            length: 16,
            generated: false,
            transformer: uuidTransformer,
            default: () => 'UNHEX(REPLACE(UUID(), \'-\', \'\'))'
        })
        public id!: string;
    
        @Column({
            length: 100,
            unique: true
        })
        public name!: string;
    
        @OneToMany(() => Member, (member: Member) => member.room)
        @JoinColumn()
        public members!: Member[];
    }
    
    @Entity()
    export class Member {
        @PrimaryColumn({
            type: 'binary',
            length: 16,
            generated: false,
            transformer: uuidTransformer,
            default: () => 'UNHEX(REPLACE(UUID(), \'-\', \'\'))'
        })
        public id!: string;
    
        @Column({
            length: 100
        })
        public name!: string;
    
        @Column({
            type: 'binary',
            length: 16,
            generated: false,
            transformer: uuidTransformer,
            unique: false
        })
        public roomId!: string;
    
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        @ManyToOne(() => Room, (room: Room) => room.members)
        @JoinColumn()
        public room!: Room;
    }
    
  4. maxbethke commented on Oct 26, 2023

    @maxbethke

    With @Alia5's workaround I run into this problem caused by the default property not setting id before the Entity Manager tries to reload the entity after a .save().

    Any ideas about this?

  5. leonceaklin commented on Nov 21, 2023

    @leonceaklin

    The Workaround by @Alia5 also doesn't work for me when using relationships. For example when I query a many-to-many relationship, the value transformer is not applied. I created a new issue (10365) for this but did not get any answer. I'd like to fix the problem with a PR but don't know where to start. Help appreciated.

  6. hitesh-pathak commented on Jul 15, 2024

    @hitesh-pathak

    To not make this another DenverCoder-like situation

    My workaround, short and simple. Probably also related to #7470

    const uuidTransformer {
        to: (uuid: string|undefined) => uuid ? Buffer.from(uuid.replace(/-/g, ''), 'hex') : uuid,
        from: (bin: Buffer) => `${bin.toString('hex', 0, 4)}-${bin.toString('hex', 4, 6)}-${
            bin.toString('hex', 6, 8)}-${bin.toString('hex', 8, 10)}-${bin.toString('hex', 10, 16)}`
    };
    
    @Entity()
    export class Room {
        @PrimaryColumn({
            type: 'binary',
            length: 16,
            generated: false,
            transformer: uuidTransformer,
            default: () => 'UNHEX(REPLACE(UUID(), \'-\', \'\'))' // using maria-db so UUID_TO_BIN does not exist
        })
        public id!: string;
        /// ...
    }

    For sake of completion: with relations:

    Click me!

    Thanks a lot - this works for me with querybuider and with Many-One and One-Many relations too :D

  7. nalbertcerqueira commented on Sep 26, 2024

    @nalbertcerqueira

    To not make this another DenverCoder-like situation

    My workaround, short and simple. Probably also related to #7470

    const uuidTransformer {
        to: (uuid: string|undefined) => uuid ? Buffer.from(uuid.replace(/-/g, ''), 'hex') : uuid,
        from: (bin: Buffer) => `${bin.toString('hex', 0, 4)}-${bin.toString('hex', 4, 6)}-${
            bin.toString('hex', 6, 8)}-${bin.toString('hex', 8, 10)}-${bin.toString('hex', 10, 16)}`
    };
    
    @Entity()
    export class Room {
        @PrimaryColumn({
            type: 'binary',
            length: 16,
            generated: false,
            transformer: uuidTransformer,
            default: () => 'UNHEX(REPLACE(UUID(), \'-\', \'\'))' // using maria-db so UUID_TO_BIN does not exist
        })
        public id!: string;
        /// ...
    }

    For sake of completion: with relations:

    Click me!

    Thanks a lot man ! This saved me :D

  8. mkfyi commented on Oct 18, 2024

    @mkfyi

    Thanks @Alia5, but we should check in from if bin is actually not null, otherwise the ApplyValueTransformers might fail with this message: TypeError: Cannot read properties of null (reading 'toString').

    uuid-value.transformer.ts

    import { ValueTransformer } from 'typeorm';
    
    class UuidValueTransformer implements ValueTransformer {
      public to(uuid: string | undefined | null): Buffer | null {
        return uuid ? Buffer.from(uuid.replace(/-/g, ''), 'hex') : null;
      }
    
      public from(bin: Buffer | undefined | null): string | null {
        return bin
          ? `${bin.toString('hex', 0, 4)}-${bin.toString('hex', 4, 6)}-${bin.toString(
              'hex',
              6,
              8,
            )}-${bin.toString('hex', 8, 10)}-${bin.toString('hex', 10, 16)}`
          : null;
      }
    }
    
    export const uuidValueTransformer = new UuidValueTransformer();

    I also wrapped the column definitions into own decorators to reduce the amount of the same column definitions when working with multiple entities.

    typeorm.decorators.ts

    import { Column, PrimaryColumn } from 'typeorm';
    import { uuidValueTransformer } from '../database/uuid-value.transformer';
    
    export const PrimaryGeneratedBinaryUuidColumn = (): ReturnType<
      typeof PrimaryColumn
    > =>
      PrimaryColumn({
        type: 'binary',
        length: 16,
        generated: false,
        transformer: uuidValueTransformer,
        default: () => "UNHEX(REPLACE(UUID(), '-', ''))",
      });
    
    export const BinaryUuidColumn = (
      name?: string,
    ): ReturnType<typeof Column> =>
      Column({
        type: 'binary',
        name,
        length: 16,
        generated: false,
        transformer: uuidValueTransformer,
        unique: false,
      });

    So your example would look like:

    @Entity()
    export class Room {
    -  @PrimaryColumn({
    -    type: 'binary',
    -    length: 16,
    -    generated: false,
    -    transformer: uuidTransformer,
    -    default: () => "UNHEX(REPLACE(UUID(), '-', ''))",
    -  })
    +  @PrimaryGeneratedBinaryUuidColumn()
      public id!: string;
    
      @Column({ length: 100, unique: true })
      public name!: string;
    
      @OneToMany(() => Member, (member: Member) => member.room)
      @JoinColumn()
      public members!: Member[];
    }
    
    @Entity()
    export class Member {
    -  @PrimaryColumn({
    -    type: 'binary',
    -    length: 16,
    -    generated: false,
    -    transformer: uuidTransformer,
    -    default: () => "UNHEX(REPLACE(UUID(), '-', ''))",
    -  })
    +  @PrimaryGeneratedBinaryUuidColumn()
      public id!: string;
    
      @Column({ length: 100 })
      public name!: string;
    
    -  @Column({
    -    type: 'binary',
    -    length: 16,
    -    generated: false,
    -    transformer: uuidTransformer,
    -    unique: false,
    -  })
    +  @BinaryUuidColumn()
      public roomId!: string;
    
      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      @ManyToOne(() => Room, (room: Room) => room.members)
      @JoinColumn()
      public room!: Room;
    }
  9. festo commented on Apr 16, 2026

    @festo

    Whoever stumbles upon this, make sure you handle the FindOperators as well.

    if (InstanceChecker.isFindOperator(value)) {
      // Pass through FindOperators (e.g. IsNull()) without transforming
      return value
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions