diff --git a/src/query-builder/InsertQueryBuilder.ts b/src/query-builder/InsertQueryBuilder.ts index a1f3c0de2f..1aa5545de9 100644 --- a/src/query-builder/InsertQueryBuilder.ts +++ b/src/query-builder/InsertQueryBuilder.ts @@ -410,6 +410,13 @@ export class InsertQueryBuilder extends QueryBuilder { query += `INTO ${tableName}` + if ( + this.alias !== this.getMainTableName() && + this.connection.driver.options.type === "postgres" + ) { + query += ` AS "${this.alias}"` + } + // add columns expression if (columnsExpression) { query += `(${columnsExpression})` diff --git a/test/functional/query-builder/insert-on-conflict/query-builder-insert-on-conflict.ts b/test/functional/query-builder/insert-on-conflict/query-builder-insert-on-conflict.ts index e445e05d7b..e06017fc53 100644 --- a/test/functional/query-builder/insert-on-conflict/query-builder-insert-on-conflict.ts +++ b/test/functional/query-builder/insert-on-conflict/query-builder-insert-on-conflict.ts @@ -82,6 +82,84 @@ describe("query builder > insertion > on conflict", () => { }), )) + it("should support alias in insert", () => + Promise.all( + connections.map(async (connection) => { + if (connection.driver.options.type !== "postgres") return + + const post1 = new Post() + post1.id = "post#1" + post1.title = "About post" + post1.date = new Date("06 Aug 2020 00:12:01 GMT") + + const post2 = new Post() + post2.id = "post#2" + post2.title = "Again post" + post2.date = new Date("06 Aug 2020 00:12:02 GMT") + + await connection + .createQueryBuilder() + .insert() + .into(Post) + .values([post1, post2]) + .orIgnore() + .execute() + + await connection.manager + .find(Post, { + order: { + id: "ASC", + }, + }) + .should.eventually.be.eql([ + { + id: "post#1", + title: "About post", + date: new Date("06 Aug 2020 00:12:01 GMT"), + }, + { + id: "post#2", + title: "Again post", + date: new Date("06 Aug 2020 00:12:02 GMT"), + }, + ]) + + post1.date = new Date("07 Aug 2020 00:12:03 GMT") + + post2.title = "Edited post" + post2.date = new Date("07 Aug 2020 00:12:04 GMT") + + await connection + .createQueryBuilder(Post, "p") + .insert() + .values([post1, post2]) + .onConflict( + `("id") DO UPDATE SET "title" = excluded.title, "date" = excluded.date WHERE p.title != excluded.title`, + ) + .setParameter("title", post2.title) + .execute() + + await connection.manager + .find(Post, { + order: { + id: "ASC", + }, + }) + .should.eventually.be.eql([ + { + id: "post#1", + title: "About post", + date: new Date("06 Aug 2020 00:12:01 GMT"), + }, + { + id: "post#2", + title: "Edited post", + date: new Date("07 Aug 2020 00:12:04 GMT"), + }, + ]) + }), + )) + it("should perform insertion correctly using orIgnore", () => Promise.all( connections.map(async (connection) => {