Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make only a single SELECT to get inserted default and generated values of multiple entities #6669

Merged
merged 3 commits into from Sep 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 22 additions & 19 deletions src/query-builder/ReturningResultsEntityUpdator.ts
Expand Up @@ -117,26 +117,29 @@ export class ReturningResultsEntityUpdator {
// 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) {
await Promise.all(entities.map(async (entity, entityIndex) => {
const entityIds = entities.map((entity) => {
const entityId = metadata.getEntityIdMap(entity)!;

// to select just inserted entity 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(entityId)
.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
.getOne();

this.queryRunner.manager.merge(metadata.target as any, generatedMaps[entityIndex], returningResult);
}));
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]);
});
}

entities.forEach((entity, entityIndex) => {
Expand Down
14 changes: 14 additions & 0 deletions test/github-issues/6266/entity/Post.ts
@@ -0,0 +1,14 @@
import { PrimaryGeneratedColumn, Entity, Column, CreateDateColumn } from "../../../../src";

@Entity()
export class Post {

@PrimaryGeneratedColumn()
id?: number;

@Column()
title: string;

@CreateDateColumn()
readonly createdAt?: Date;
}
60 changes: 60 additions & 0 deletions test/github-issues/6266/issue-6266.ts
@@ -0,0 +1,60 @@
import "reflect-metadata";
import {
closeTestingConnections,
createTestingConnections,
reloadTestingDatabases,
} from "../../utils/test-utils";
import { Connection } from "../../../src/connection/Connection";
import { Post } from "./entity/Post";
import sinon from "sinon";
import { SelectQueryBuilder } from "../../../src";
import { assert } from "chai";

describe("github issues > #6266 Many identical selects after insert bunch of items", () => {
let connections: Connection[];
const posts: Post[] = [
{
title: "Post 1",
},
{
title: "Post 2",
},
{
title: "Post 3",
},
{
title: "Post 4",
},
];

before(
async () =>
(connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
enabledDrivers: ["mysql"],
}))
);
beforeEach(() => reloadTestingDatabases(connections));
after(() => closeTestingConnections(connections));

it("should execute a single SELECT to get inserted default and generated values of multiple entities", () =>
Promise.all(
connections.map(async (connection) => {
const selectSpy = sinon.spy(
SelectQueryBuilder.prototype,
"select"
);

await connection
.createQueryBuilder()
.insert()
.into(Post)
.values(posts)
.execute();

assert.strictEqual(selectSpy.calledOnce, true);

selectSpy.restore();
})
));
});