-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathupdate.ts
338 lines (298 loc) · 11 KB
/
update.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import type { Document, ObjectId } from '../bson';
import type { Collection } from '../collection';
import { MongoCompatibilityError, MongoInvalidArgumentError, MongoServerError } from '../error';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import {
Callback,
collationNotSupported,
hasAtomicOperators,
maxWireVersion,
MongoDBNamespace
} from '../utils';
import { CollationOptions, CommandOperation, CommandOperationOptions } from './command';
import { Aspect, defineAspects, Hint } from './operation';
/** @public */
export interface UpdateOptions extends CommandOperationOptions {
/** A set of filters specifying to which array elements an update should apply */
arrayFilters?: Document[];
/** If true, allows the write to opt-out of document level validation */
bypassDocumentValidation?: boolean;
/** Specifies a collation */
collation?: CollationOptions;
/** Specify that the update query should only consider plans using the hinted index */
hint?: Hint;
/** When true, creates a new document if no document matches the query */
upsert?: boolean;
/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
let?: Document;
}
/** @public */
export interface UpdateResult {
/** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
acknowledged: boolean;
/** The number of documents that matched the filter */
matchedCount: number;
/** The number of documents that were modified */
modifiedCount: number;
/** The number of documents that were upserted */
upsertedCount: number;
/** The identifier of the inserted document if an upsert took place */
upsertedId: ObjectId;
}
/** @public */
export interface UpdateStatement {
/** The query that matches documents to update. */
q: Document;
/** The modifications to apply. */
u: Document | Document[];
/** If true, perform an insert if no documents match the query. */
upsert?: boolean;
/** If true, updates all documents that meet the query criteria. */
multi?: boolean;
/** Specifies the collation to use for the operation. */
collation?: CollationOptions;
/** An array of filter documents that determines which array elements to modify for an update operation on an array field. */
arrayFilters?: Document[];
/** A document or string that specifies the index to use to support the query predicate. */
hint?: Hint;
}
/** @internal */
export class UpdateOperation extends CommandOperation<Document> {
override options: UpdateOptions & { ordered?: boolean };
statements: UpdateStatement[];
constructor(
ns: MongoDBNamespace,
statements: UpdateStatement[],
options: UpdateOptions & { ordered?: boolean }
) {
super(undefined, options);
this.options = options;
this.ns = ns;
this.statements = statements;
}
override get canRetryWrite(): boolean {
if (super.canRetryWrite === false) {
return false;
}
return this.statements.every(op => op.multi == null || op.multi === false);
}
override execute(
server: Server,
session: ClientSession | undefined,
callback: Callback<Document>
): void {
const options = this.options ?? {};
const ordered = typeof options.ordered === 'boolean' ? options.ordered : true;
const command: Document = {
update: this.ns.collection,
updates: this.statements,
ordered
};
if (typeof options.bypassDocumentValidation === 'boolean') {
command.bypassDocumentValidation = options.bypassDocumentValidation;
}
if (options.let) {
command.let = options.let;
}
// we check for undefined specifically here to allow falsy values
// eslint-disable-next-line no-restricted-syntax
if (options.comment !== undefined) {
command.comment = options.comment;
}
const statementWithCollation = this.statements.find(statement => !!statement.collation);
if (
collationNotSupported(server, options) ||
(statementWithCollation && collationNotSupported(server, statementWithCollation))
) {
callback(new MongoCompatibilityError(`Server ${server.name} does not support collation`));
return;
}
if (maxWireVersion(server) < 8) {
const hintPresent = this.statements.some(o => o.hint);
const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0;
if (hintPresent && unacknowledgedWrite) {
callback(
new MongoCompatibilityError(`Servers < 4.2 do not support hint on unacknowledged update`)
);
return;
}
}
if (this.explain && maxWireVersion(server) < 3) {
callback(
new MongoCompatibilityError(`Server ${server.name} does not support explain on update`)
);
return;
}
if (this.statements.some(statement => !!statement.arrayFilters) && maxWireVersion(server) < 6) {
callback(
new MongoCompatibilityError('Option "arrayFilters" is only supported on MongoDB 3.6+')
);
return;
}
super.executeCommand(server, session, command, callback);
}
}
/** @internal */
export class UpdateOneOperation extends UpdateOperation {
constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) {
super(
collection.s.namespace,
[makeUpdateStatement(filter, update, { ...options, multi: false })],
options
);
if (!hasAtomicOperators(update)) {
throw new MongoInvalidArgumentError('Update document requires atomic operators');
}
}
override execute(
server: Server,
session: ClientSession | undefined,
callback: Callback<UpdateResult | Document>
): void {
super.execute(server, session, (err, res) => {
if (err || !res) return callback(err);
if (this.explain != null) return callback(undefined, res);
if (res.code) return callback(new MongoServerError(res));
if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0]));
callback(undefined, {
acknowledged: this.writeConcern?.w !== 0 ?? true,
modifiedCount: res.nModified != null ? res.nModified : res.n,
upsertedId:
Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
});
});
}
}
/** @internal */
export class UpdateManyOperation extends UpdateOperation {
constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) {
super(
collection.s.namespace,
[makeUpdateStatement(filter, update, { ...options, multi: true })],
options
);
if (!hasAtomicOperators(update)) {
throw new MongoInvalidArgumentError('Update document requires atomic operators');
}
}
override execute(
server: Server,
session: ClientSession | undefined,
callback: Callback<UpdateResult | Document>
): void {
super.execute(server, session, (err, res) => {
if (err || !res) return callback(err);
if (this.explain != null) return callback(undefined, res);
if (res.code) return callback(new MongoServerError(res));
if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0]));
callback(undefined, {
acknowledged: this.writeConcern?.w !== 0 ?? true,
modifiedCount: res.nModified != null ? res.nModified : res.n,
upsertedId:
Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
});
});
}
}
/** @public */
export interface ReplaceOptions extends CommandOperationOptions {
/** If true, allows the write to opt-out of document level validation */
bypassDocumentValidation?: boolean;
/** Specifies a collation */
collation?: CollationOptions;
/** Specify that the update query should only consider plans using the hinted index */
hint?: string | Document;
/** When true, creates a new document if no document matches the query */
upsert?: boolean;
/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
let?: Document;
}
/** @internal */
export class ReplaceOneOperation extends UpdateOperation {
constructor(
collection: Collection,
filter: Document,
replacement: Document,
options: ReplaceOptions
) {
super(
collection.s.namespace,
[makeUpdateStatement(filter, replacement, { ...options, multi: false })],
options
);
if (hasAtomicOperators(replacement)) {
throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators');
}
}
override execute(
server: Server,
session: ClientSession | undefined,
callback: Callback<UpdateResult | Document>
): void {
super.execute(server, session, (err, res) => {
if (err || !res) return callback(err);
if (this.explain != null) return callback(undefined, res);
if (res.code) return callback(new MongoServerError(res));
if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0]));
callback(undefined, {
acknowledged: this.writeConcern?.w !== 0 ?? true,
modifiedCount: res.nModified != null ? res.nModified : res.n,
upsertedId:
Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
});
});
}
}
export function makeUpdateStatement(
filter: Document,
update: Document | Document[],
options: UpdateOptions & { multi?: boolean }
): UpdateStatement {
if (filter == null || typeof filter !== 'object') {
throw new MongoInvalidArgumentError('Selector must be a valid JavaScript object');
}
if (update == null || typeof update !== 'object') {
throw new MongoInvalidArgumentError('Document must be a valid JavaScript object');
}
const op: UpdateStatement = { q: filter, u: update };
if (typeof options.upsert === 'boolean') {
op.upsert = options.upsert;
}
if (options.multi) {
op.multi = options.multi;
}
if (options.hint) {
op.hint = options.hint;
}
if (options.arrayFilters) {
op.arrayFilters = options.arrayFilters;
}
if (options.collation) {
op.collation = options.collation;
}
return op;
}
defineAspects(UpdateOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION, Aspect.SKIP_COLLATION]);
defineAspects(UpdateOneOperation, [
Aspect.RETRYABLE,
Aspect.WRITE_OPERATION,
Aspect.EXPLAINABLE,
Aspect.SKIP_COLLATION
]);
defineAspects(UpdateManyOperation, [
Aspect.WRITE_OPERATION,
Aspect.EXPLAINABLE,
Aspect.SKIP_COLLATION
]);
defineAspects(ReplaceOneOperation, [
Aspect.RETRYABLE,
Aspect.WRITE_OPERATION,
Aspect.SKIP_COLLATION
]);