Skip to content

Inserted record in MySQL not being returned when using a custom primary key column #7470

Closed as not planned

Description

@mnengwa

Error: Cannot update entity because entity id is not set in the entity.

After a successful insert, return the inserted record.

A new record is inserted successfully into the database, but TypeORM throws an error when attempting to retrieve the inserted record.

[Nest] 9084   - 15/03/2021, 11:17:47   [ExceptionsHandler] Cannot update entity because entity id is not set in the entity. +331142ms
Error: Cannot update entity because entity id is not set in the entity.
    at C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\query-builder\ReturningResultsEntityUpdator.js:128:39
    at Array.map (<anonymous>)
    at ReturningResultsEntityUpdator.<anonymous> (C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\query-builder\ReturningResultsEntityUpdator.js:122:46)
    at step (C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\node_modules\tslib\tslib.js:141:27)
    at Object.next (C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\node_modules\tslib\tslib.js:122:57)
    at C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\node_modules\tslib\tslib.js:115:75
    at new Promise (<anonymous>)
    at Object.__awaiter (C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\node_modules\tslib\tslib.js:111:16)
    at ReturningResultsEntityUpdator.insert (C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\query-builder\ReturningResultsEntityUpdator.js:87:24)
    at InsertQueryBuilder.<anonymous> (C:\Users\Mnengwa\workspace\kodisha\kodisha-web-api\node_modules\typeorm\query-builder\InsertQueryBuilder.js:105:76)

Steps to Reproduce

  1. Define an entity
@Entity({ name: 'users' })
export class User {
  @Column({
    type: 'binary',
    length: 16,
    select: false,
    primary: true,
    default: () => `(UUID_TO_BIN(UUID(), 1))`,
  })

  id: string;
  @Index()
  @Column({ type: 'varchar', length: 225, nullable: false })
  name: string;

  @Column({ type: 'varchar', length: 15, unique: true, nullable: false })
  MSISDN: string;

  @Column({ type: 'varchar', length: 225, unique: true, nullable: false })
  email_address: string;

  @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })
  created_at: Date;

  @Column({ type: 'datetime', nullable: true, onUpdate: 'CURRENT_TIMESTAMP' })
  updated_at: Date;
}
  1. Define a service for the entity
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  create(user: DeepPartial<User>): Promise<User> {
    return this.usersRepository
      .createQueryBuilder()
      .insert()
      .values({ ...user})
      .execute();
  }
}
  1. Attempt to insert a record

  2. An error is thrown as shown above

  3. Check the database using SELECT * FROM users;

  4. Observe that a record is inserted but TypeORM was unable to retrieve the record

My Environment

Dependency Version
Operating System Windows 10 pro
Node.js version v14.15.4
Typescript version v4.2.3
TypeORM version v0.2.31

Additional Context

The same issue arises when the ..save() method is used

When I insert a record with a raw SQL query:

create(account: CreateAccountDto): Promise<Account> {
    const values = Object.values(account);
    const columns = Object.keys(account).join(', ');
    const params = Object.keys(account)
      .map((x) => '?')
      .join(', ');

    const result = this.usersRepository.query(
      `INSERT INTO accounts (${columns}) VALUES (${params});`,
      values,
    );

    console.log(result);
    return result;

This is what gets returned:

{
        "fieldCount": 0,
        "affectedRows": 1,
        "insertId": 0,
        "info": "",
        "serverStatus": 2,
        "warningStatus": 0
    }

Lastly are we able to define some sort of getter for such a primary key, in the column decorator?

Relevant Database Driver(s)

  • aurora-data-api
  • aurora-data-api-pg
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time, and I know how to start.
  • Yes, I have the time, but I don't know how to start. I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. tonytoth commented on Mar 23, 2021

    @tonytoth

    Does not work either if you try this way:

    @PrimaryColumn({
            type: 'binary',
            length: 16,
            default: () => `(UUID_TO_BIN(UUID(), 1))`,
        })
        id: string;
    

    But this migth be related to this issue: #3187

  2. juliengbt commented on Jul 7, 2021

    @juliengbt
    Contributor

    @tonytoth Did you find a workaround ?

  3. tonytoth commented on Jul 8, 2021

    @tonytoth

    Unfortunately, no. I had to drop the idea of uuid.

  4. HakamaObi commented on Jan 12, 2022

    @HakamaObi

    Hi.
    i have writen some helper functions that transforms the uuid to the same byte format as mysql 8 does, so you can use a transformer in the entity.
    currently it's in develop but working fine until now
    gist with code

    it must be uuid v1 as in the docs of mysql 8

  5. github-actions commented on Sep 18, 2025

    @github-actions

    TypeORM has returned to active development after recently transitioning to new leadership (see related announcement).

    As part of the new team's efforts to prioritise work on the project moving forward, it is necessary to clean up the backlog of stale issues.

    🧹 This issue is being automatically closed because it has had no activity in the last 6 months.
    If you believe this issue is still relevant, feel free to comment below and the maintainers may reopen it. Thank you for your contribution.

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