-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
ReturningResultsEntityUpdator.ts
301 lines (277 loc) · 12.5 KB
/
ReturningResultsEntityUpdator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { ObjectLiteral } from "../common/ObjectLiteral"
import { QueryRunner } from "../query-runner/QueryRunner"
import { QueryExpressionMap } from "./QueryExpressionMap"
import { ColumnMetadata } from "../metadata/ColumnMetadata"
import { UpdateResult } from "./result/UpdateResult"
import { InsertResult } from "./result/InsertResult"
import { TypeORMError } from "../error"
/**
* Updates entity with returning results in the entity insert and update operations.
*/
export class ReturningResultsEntityUpdator {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(
protected queryRunner: QueryRunner,
protected expressionMap: QueryExpressionMap,
) {}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Updates entities with a special columns after updation query execution.
*/
async update(
updateResult: UpdateResult,
entities: ObjectLiteral[],
): Promise<void> {
const metadata = this.expressionMap.mainAlias!.metadata
await Promise.all(
entities.map(async (entity, entityIndex) => {
// if database supports returning/output statement then we already should have updating values in the raw data returned by insert query
if (
this.queryRunner.connection.driver.isReturningSqlSupported(
"update",
)
) {
if (
this.queryRunner.connection.driver.options.type ===
"oracle" &&
Array.isArray(updateResult.raw) &&
this.expressionMap.extraReturningColumns.length > 0
) {
updateResult.raw = updateResult.raw.reduce(
(newRaw, rawItem, rawItemIndex) => {
newRaw[
this.expressionMap.extraReturningColumns[
rawItemIndex
].databaseName
] = rawItem[0]
return newRaw
},
{} as ObjectLiteral,
)
}
const result = Array.isArray(updateResult.raw)
? updateResult.raw[entityIndex]
: updateResult.raw
const returningColumns =
this.queryRunner.connection.driver.createGeneratedMap(
metadata,
result,
)
if (returningColumns) {
this.queryRunner.manager.merge(
metadata.target as any,
entity,
returningColumns,
)
updateResult.generatedMaps.push(returningColumns)
}
} else {
// for driver which do not support returning/output statement we need to perform separate query and load what we need
const updationColumns =
this.expressionMap.extraReturningColumns
if (updationColumns.length > 0) {
// get entity id by which we will get needed data
const entityId =
this.expressionMap.mainAlias!.metadata.getEntityIdMap(
entity,
)
if (!entityId)
throw new TypeORMError(
`Cannot update entity because entity id is not set in the entity.`,
)
// execute query to get needed data
const loadedReturningColumns =
(await this.queryRunner.manager
.createQueryBuilder()
.select(
metadata.primaryColumns.map(
(column) =>
metadata.targetName +
"." +
column.propertyPath,
),
)
.addSelect(
updationColumns.map(
(column) =>
metadata.targetName +
"." +
column.propertyPath,
),
)
.from(metadata.target, metadata.targetName)
.where(entityId)
.withDeleted()
.setOption("create-pojo") // use POJO because created object can contain default values, e.g. property = null and those properties might be overridden by merge process
.getOne()) as any
if (loadedReturningColumns) {
this.queryRunner.manager.merge(
metadata.target as any,
entity,
loadedReturningColumns,
)
updateResult.generatedMaps.push(
loadedReturningColumns,
)
}
}
}
}),
)
}
/**
* Updates entities with a special columns after insertion query execution.
*/
async insert(
insertResult: InsertResult,
entities: ObjectLiteral[],
): Promise<void> {
const metadata = this.expressionMap.mainAlias!.metadata
let insertionColumns = metadata.getInsertionReturningColumns()
// to prevent extra select SQL execution for databases not supporting RETURNING
// in the case if we have generated column and it's value returned by underlying driver
// we remove this column from the insertionColumns list
const needToCheckGenerated =
this.queryRunner.connection.driver.isReturningSqlSupported("insert")
insertionColumns = insertionColumns.filter((column) => {
if (!column.isGenerated) return true
return needToCheckGenerated === true
})
const generatedMaps = entities.map((entity, entityIndex) => {
if (
this.queryRunner.connection.driver.options.type === "oracle" &&
Array.isArray(insertResult.raw) &&
this.expressionMap.extraReturningColumns.length > 0
) {
insertResult.raw = insertResult.raw.reduce(
(newRaw, rawItem, rawItemIndex) => {
newRaw[
this.expressionMap.extraReturningColumns[
rawItemIndex
].databaseName
] = rawItem[0]
return newRaw
},
{} as ObjectLiteral,
)
}
// get all values generated by a database for us
const result = Array.isArray(insertResult.raw)
? insertResult.raw[entityIndex]
: insertResult.raw
const generatedMap =
this.queryRunner.connection.driver.createGeneratedMap(
metadata,
result,
entityIndex,
entities.length,
) || {}
if (entityIndex in this.expressionMap.locallyGenerated) {
this.queryRunner.manager.merge(
metadata.target as any,
generatedMap,
this.expressionMap.locallyGenerated[entityIndex],
)
}
this.queryRunner.manager.merge(
metadata.target as any,
entity,
generatedMap,
)
return generatedMap
})
// 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 (
insertionColumns.length > 0 &&
!this.queryRunner.connection.driver.isReturningSqlSupported(
"insert",
)
) {
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 TypeORMError(
`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 might be overridden by merge process
.getMany()
entities.forEach((entity, entityIndex) => {
this.queryRunner.manager.merge(
metadata.target as any,
generatedMaps[entityIndex],
returningResult[entityIndex],
)
this.queryRunner.manager.merge(
metadata.target as any,
entity,
returningResult[entityIndex],
)
})
}
entities.forEach((entity, entityIndex) => {
const entityId = metadata.getEntityIdMap(entity)!
insertResult.identifiers.push(entityId)
insertResult.generatedMaps.push(generatedMaps[entityIndex])
})
}
/**
* Columns we need to be returned from the database when we update entity.
*/
getUpdationReturningColumns(): ColumnMetadata[] {
return this.expressionMap.mainAlias!.metadata.columns.filter(
(column) => {
return (
column.asExpression !== undefined ||
column.isUpdateDate ||
column.isVersion
)
},
)
}
/**
* Columns we need to be returned from the database when we soft delete and restore entity.
*/
getSoftDeletionReturningColumns(): ColumnMetadata[] {
return this.expressionMap.mainAlias!.metadata.columns.filter(
(column) => {
return (
column.asExpression !== undefined ||
column.isUpdateDate ||
column.isVersion ||
column.isDeleteDate
)
},
)
}
}