Skip to content

How to force just update/insert #5348

Closed as not planned
Closed as not planned

Description

@meuevento

Issue type:

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

Database system/driver:

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

TypeORM version:

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

I have a routine where I perform various loop inserts and updates. It is too heavy due to entity's .save () performing a select on dependencies after insert / update.

Would you have any parameters to send that would run .save () without select later?
Its that my entity will be outdated, but it would get faster.

Activity

  1. deemaagog commented on Jan 15, 2020

    @deemaagog

    Why not just use update/insert methods instead of save?

  2. meuevento commented on Jan 15, 2020

    @meuevento
    Author

    they also execute select after insert

  3. boenrobot commented on Jan 19, 2020

    @boenrobot

    I'm facing a similar issue. Doing a save() with reload: false is the only way to do insert/update only, but the problem there is that you don't have access to the inserted row ID (for insert) or the number of matched and affected rows (for update), and I need the insert ID.

  4. ochanje210 commented on Jan 28, 2020

    @ochanje210

    having the same issue regarding performance..

  5. coyoteecd commented on Feb 16, 2021

    @coyoteecd
    Contributor

    This question has been answered here: #2870 (comment)

    @imnotjames @pleerock We have the same issue with the SELECT after INSERT which has been discussed many times over different issues. We are using Aurora Data API driver with mysql.

    I do not mind overriding insert/update in our custom repositories to use updateEntity(false). What is troubling in this case is that the inserted IDs are not set back into the entity. You might say, well, that's what updateEntity(false) says it does. However, the consequence is that there is really no way you can run a "fast and efficient INSERT query" with TypeORM, other than going down to raw "query" level.

    Aurora Data API driver (and likely mysql as well) returns the insertId in the raw insert result. It's just that TypeORM decides to throw it away because entity update is false.

    Looking at the code, InsertQueryBuilder uses ReturningResultsEntityUpdator to process the raw insert result and generate the identifiers map. This is NOT done if updateEntity is false:

    // load returning results and set them to the entity if entity updation is enabled
    if (this.expressionMap.updateEntity === true && this.expressionMap.mainAlias!.hasMetadata) {
    // console.time(".updating entity");
    await returningResultsEntityUpdator.insert(insertResult, valueSets);
    // console.timeEnd(".updating entity");
    }

    But if I leave updateEntity true, then since MySQL and Aurora Data API drivers do not support RETURNING queries, I get the unnecessary select statement after each insert :(. This sucks. Basically what I need is to run ReturningResultsEntityUpdator.insert without doing the additional query, so omitting this code:

    // for postgres and mssql we use returning/output statement to get values of inserted default and generated values
    // for other drivers we have to re-select this data from the database
    if (this.queryRunner.connection.driver.isReturningSqlSupported() === false && insertionColumns.length > 0) {
    const entityIds = entities.map((entity) => {
    const entityId = metadata.getEntityIdMap(entity)!;
    // We have to check for an empty `entityId` - if we don't, the query against the database
    // effectively drops the `where` clause entirely and the first record will be returned -
    // not what we want at all.
    if (!entityId)
    throw new Error(`Cannot update entity because entity id is not set in the entity.`);
    return entityId;
    });
    // to select just inserted entities we need a criteria to select by.
    // for newly inserted entities in drivers which do not support returning statement
    // row identifier can only be an increment column
    // (since its the only thing that can be generated by those databases)
    // or (and) other primary key which is defined by a user and inserted value has it
    const returningResult: any = await this.queryRunner.manager
    .createQueryBuilder()
    .select(metadata.primaryColumns.map(column => metadata.targetName + "." + column.propertyPath))
    .addSelect(insertionColumns.map(column => metadata.targetName + "." + column.propertyPath))
    .from(metadata.target, metadata.targetName)
    .where(entityIds)
    .setOption("create-pojo") // use POJO because created object can contain default values, e.g. property = null and those properties maight be overridden by merge process
    .getMany();
    entities.forEach((entity, entityIndex) => {
    this.queryRunner.manager.merge(metadata.target as any, generatedMaps[entityIndex], returningResult[entityIndex]);
    });
    }

    I checked and the generatedMap is filled correctly based on the raw result. A quick hack would be to modify the AuroraDataApiDriver to return true on isReturningSqlSupported(), but this flag also allows you to specify .returning() etc. which is not correct.

    Proposal

    • (optional) introduce an EntityUpdateMode param to updateEntity, so we can do:
    entityManager
      .createQueryBuilder()
      .insert()
      .into("user")
      .values(users)
      .updateEntity(EntityUpdateMode.IdentityOnly)
      .execute();
    

    Possible values would be None (false mapped to it) and All (true mapped to it). This is necessary to maintain backwards compatibility. Maybe it helps with clarity as well.

    • modify InsertQueryBuilder so it calls ReturningResultsEntityUpdator.insert when update mode != None, passing the update mode to the insert call. The updator would then only execute the additional SELECT when full update is requested.

    This way, the InsertResult gets populated with the correct identifiers array and the entity ID is updated as well.


    Note: I am willing to submit a PR with the above changes, in fact I'll probably do them anyway in a fork because it's blocking us. Would love some feedback to avoid wasting time though.

    Edit: you can view an example implementation here: https://github.com/coyoteecd/typeorm/commits/fix-aurora-data-api-select-after-insert

  6. 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