-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
rename.ts
67 lines (57 loc) · 2.1 KB
/
rename.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
import type { Document } from '../bson';
import { Collection } from '../collection';
import { MongoServerError } from '../error';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import { type Callback, checkCollectionName } from '../utils';
import type { CommandOperationOptions } from './command';
import { Aspect, defineAspects } from './operation';
import { RunAdminCommandOperation } from './run_command';
/** @public */
export interface RenameOptions extends CommandOperationOptions {
/** Drop the target name collection if it previously exists. */
dropTarget?: boolean;
/** Unclear */
new_collection?: boolean;
}
/** @internal */
export class RenameOperation extends RunAdminCommandOperation {
override options: RenameOptions;
collection: Collection;
newName: string;
constructor(collection: Collection, newName: string, options: RenameOptions) {
// Check the collection name
checkCollectionName(newName);
// Build the command
const renameCollection = collection.namespace;
const toCollection = collection.s.namespace.withCollection(newName).toString();
const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false;
const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget };
super(collection, cmd, options);
this.options = options;
this.collection = collection;
this.newName = newName;
}
override executeCallback(
server: Server,
session: ClientSession | undefined,
callback: Callback<Collection>
): void {
const coll = this.collection;
super.executeCallback(server, session, (err, doc) => {
if (err) return callback(err);
// We have an error
if (doc?.errmsg) {
return callback(new MongoServerError(doc));
}
let newColl: Collection<Document>;
try {
newColl = new Collection(coll.s.db, this.newName, coll.s.options);
} catch (err) {
return callback(err);
}
return callback(undefined, newColl);
});
}
}
defineAspects(RenameOperation, [Aspect.WRITE_OPERATION]);