Skip to content

Commit

Permalink
feat: Add support for insert with alias typeorm#4003
Browse files Browse the repository at this point in the history
  • Loading branch information
zbarbuto committed Mar 24, 2022
1 parent 68a5c23 commit d5ff3fd
Showing 2 changed files with 82 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/query-builder/InsertQueryBuilder.ts
Original file line number Diff line number Diff line change
@@ -410,6 +410,10 @@ export class InsertQueryBuilder<Entity> extends QueryBuilder<Entity> {

query += `INTO ${tableName}`

if (this.alias && this.connection.driver.options.type === "postgres") {
query += ` AS "${this.alias}"`
}

// add columns expression
if (columnsExpression) {
query += `(${columnsExpression})`
Original file line number Diff line number Diff line change
@@ -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) => {

0 comments on commit d5ff3fd

Please sign in to comment.