Skip to content

Commit

Permalink
feat: add support for insert with alias (#4003) (#8791)
Browse files Browse the repository at this point in the history
  • Loading branch information
zbarbuto committed Mar 26, 2022
1 parent 79b7f5c commit 4b37030
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/query-builder/InsertQueryBuilder.ts
Expand Up @@ -410,6 +410,13 @@ export class InsertQueryBuilder<Entity> extends QueryBuilder<Entity> {

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})`
Expand Down
Expand Up @@ -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) => {
Expand Down

0 comments on commit 4b37030

Please sign in to comment.