@mongosh/shell-api 2.1.1 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/lib/abstract-cursor.js +176 -132
  2. package/lib/abstract-cursor.js.map +1 -1
  3. package/lib/aggregate-or-find-cursor.js +102 -51
  4. package/lib/aggregate-or-find-cursor.js.map +1 -1
  5. package/lib/aggregation-cursor.js +59 -13
  6. package/lib/aggregation-cursor.js.map +1 -1
  7. package/lib/bulk.js +248 -197
  8. package/lib/bulk.js.map +1 -1
  9. package/lib/change-stream-cursor.js +145 -101
  10. package/lib/change-stream-cursor.js.map +1 -1
  11. package/lib/collection.d.ts +2 -1
  12. package/lib/collection.js +1185 -1245
  13. package/lib/collection.js.map +1 -1
  14. package/lib/cursor.js +238 -203
  15. package/lib/cursor.js.map +1 -1
  16. package/lib/database.js +1180 -1206
  17. package/lib/database.js.map +1 -1
  18. package/lib/dbquery.js +68 -22
  19. package/lib/dbquery.js.map +1 -1
  20. package/lib/decorators.d.ts +39 -13
  21. package/lib/decorators.js +34 -34
  22. package/lib/decorators.js.map +1 -1
  23. package/lib/explainable-cursor.js +66 -20
  24. package/lib/explainable-cursor.js.map +1 -1
  25. package/lib/explainable.js +214 -179
  26. package/lib/explainable.js.map +1 -1
  27. package/lib/field-level-encryption.js +286 -235
  28. package/lib/field-level-encryption.js.map +1 -1
  29. package/lib/helpers.js.map +1 -1
  30. package/lib/interruptor.js.map +1 -1
  31. package/lib/log-entry.js.map +1 -1
  32. package/lib/mongo-errors.js.map +1 -1
  33. package/lib/mongo.js +581 -547
  34. package/lib/mongo.js.map +1 -1
  35. package/lib/plan-cache.js +108 -64
  36. package/lib/plan-cache.js.map +1 -1
  37. package/lib/replica-set.js +290 -277
  38. package/lib/replica-set.js.map +1 -1
  39. package/lib/result.js +228 -91
  40. package/lib/result.js.map +1 -1
  41. package/lib/run-command-cursor.js +59 -13
  42. package/lib/run-command-cursor.js.map +1 -1
  43. package/lib/session.js +123 -76
  44. package/lib/session.js.map +1 -1
  45. package/lib/shard.js +507 -514
  46. package/lib/shard.js.map +1 -1
  47. package/lib/shell-api.js +313 -268
  48. package/lib/shell-api.js.map +1 -1
  49. package/lib/shell-bson.js.map +1 -1
  50. package/lib/shell-instance-state.js.map +1 -1
  51. package/lib/stream-processor.js +139 -92
  52. package/lib/stream-processor.js.map +1 -1
  53. package/lib/streams.js +158 -110
  54. package/lib/streams.js.map +1 -1
  55. package/package.json +8 -8
package/lib/mongo.js CHANGED
@@ -1,9 +1,41 @@
1
1
  "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
3
+ var useValue = arguments.length > 2;
4
+ for (var i = 0; i < initializers.length; i++) {
5
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
6
+ }
7
+ return useValue ? value : void 0;
8
+ };
9
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
10
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
11
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
12
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
13
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
14
+ var _, done = false;
15
+ for (var i = decorators.length - 1; i >= 0; i--) {
16
+ var context = {};
17
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
18
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
19
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
20
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
21
+ if (kind === "accessor") {
22
+ if (result === void 0) continue;
23
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
24
+ if (_ = accept(result.get)) descriptor.get = _;
25
+ if (_ = accept(result.set)) descriptor.set = _;
26
+ if (_ = accept(result.init)) initializers.unshift(_);
27
+ }
28
+ else if (_ = accept(result)) {
29
+ if (kind === "field") initializers.unshift(_);
30
+ else descriptor[key] = _;
31
+ }
32
+ }
33
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
34
+ done = true;
35
+ };
36
+ var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
37
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
38
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
7
39
  };
8
40
  var __importDefault = (this && this.__importDefault) || function (mod) {
9
41
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -23,597 +55,599 @@ const error_codes_1 = require("./error-codes");
23
55
  const field_level_encryption_1 = require("./field-level-encryption");
24
56
  const error_codes_2 = require("./error-codes");
25
57
  const log_entry_1 = require("./log-entry");
26
- let Mongo = class Mongo extends decorators_1.ShellApiClass {
27
- constructor(instanceState, uri, fleOptions, otherOptions, sp) {
28
- var _a, _b, _c;
29
- super();
30
- this.__serviceProvider = null;
31
- this._databases = Object.create(null);
32
- this._explicitEncryptionOnly = false;
33
- this._readPreferenceWasExplicitlyRequested = false;
34
- this._cachedDatabaseNames = [];
35
- this._instanceState = instanceState;
36
- if (sp) {
37
- this.__serviceProvider = sp;
38
- }
39
- if (typeof uri === 'object' &&
40
- uri !== null &&
41
- typeof uri._uri === 'string') {
42
- uri = uri._uri;
43
- }
44
- else if (typeof uri !== 'string') {
45
- uri = (_b = (_a = sp === null || sp === void 0 ? void 0 : sp.getURI) === null || _a === void 0 ? void 0 : _a.call(sp)) !== null && _b !== void 0 ? _b : 'mongodb://localhost/';
46
- }
47
- this._connectionInfo = (0, arg_parser_1.generateConnectionInfoFromCliArgs)({
48
- connectionSpecifier: uri,
49
- });
50
- this._readPreferenceWasExplicitlyRequested = /\breadPreference=/i.test(this._uri);
51
- if (fleOptions) {
52
- if (fleOptions.explicitEncryptionOnly !== undefined) {
53
- if (fleOptions.schemaMap !== undefined) {
54
- throw new errors_1.MongoshInvalidInputError('explicitEncryptionOnly and schemaMap are mutually exclusive', errors_1.CommonErrors.InvalidArgument);
55
- }
56
- fleOptions = { ...fleOptions };
57
- this._explicitEncryptionOnly = !!fleOptions.explicitEncryptionOnly;
58
- delete fleOptions.explicitEncryptionOnly;
58
+ let Mongo = (() => {
59
+ let _classDecorators = [decorators_1.shellApiClassDefault, (0, decorators_1.classPlatforms)(['CLI'])];
60
+ let _classDescriptor;
61
+ let _classExtraInitializers = [];
62
+ let _classThis;
63
+ let _classSuper = decorators_1.ShellApiClass;
64
+ let _instanceExtraInitializers = [];
65
+ let _getDB_decorators;
66
+ let _getCollection_decorators;
67
+ let _getDBs_decorators;
68
+ let _getDBNames_decorators;
69
+ let _show_decorators;
70
+ let _setReadPref_decorators;
71
+ let _setReadConcern_decorators;
72
+ let _setWriteConcern_decorators;
73
+ let _startSession_decorators;
74
+ let _setSlaveOk_decorators;
75
+ let _setSecondaryOk_decorators;
76
+ let _watch_decorators;
77
+ let _getClientEncryption_decorators;
78
+ let _getKeyVault_decorators;
79
+ let _convertShardKeyToHashed_decorators;
80
+ var Mongo = _classThis = class extends _classSuper {
81
+ constructor(instanceState, uri, fleOptions, otherOptions, sp) {
82
+ var _a, _b, _c;
83
+ super();
84
+ this.__serviceProvider = (__runInitializers(this, _instanceExtraInitializers), null);
85
+ this._databases = Object.create(null);
86
+ this._explicitEncryptionOnly = false;
87
+ this._readPreferenceWasExplicitlyRequested = false;
88
+ this._cachedDatabaseNames = [];
89
+ this._instanceState = instanceState;
90
+ if (sp) {
91
+ this.__serviceProvider = sp;
59
92
  }
60
- this._connectionInfo.driverOptions.autoEncryption =
61
- (0, helpers_1.processFLEOptions)(fleOptions);
62
- }
63
- else {
64
- const spFleOptions = (_c = sp === null || sp === void 0 ? void 0 : sp.getFleOptions) === null || _c === void 0 ? void 0 : _c.call(sp);
65
- if (spFleOptions) {
66
- this._connectionInfo.driverOptions.autoEncryption = spFleOptions;
93
+ if (typeof uri === 'object' &&
94
+ uri !== null &&
95
+ typeof uri._uri === 'string') {
96
+ uri = uri._uri;
67
97
  }
68
- }
69
- if (otherOptions === null || otherOptions === void 0 ? void 0 : otherOptions.api) {
70
- if (typeof otherOptions.api === 'string') {
71
- this._connectionInfo.driverOptions.serverApi = {
72
- version: otherOptions.api,
73
- };
98
+ else if (typeof uri !== 'string') {
99
+ uri = (_b = (_a = sp === null || sp === void 0 ? void 0 : sp.getURI) === null || _a === void 0 ? void 0 : _a.call(sp)) !== null && _b !== void 0 ? _b : 'mongodb://localhost/';
100
+ }
101
+ this._connectionInfo = (0, arg_parser_1.generateConnectionInfoFromCliArgs)({
102
+ connectionSpecifier: uri,
103
+ });
104
+ this._readPreferenceWasExplicitlyRequested = /\breadPreference=/i.test(this._uri);
105
+ if (fleOptions) {
106
+ if (fleOptions.explicitEncryptionOnly !== undefined) {
107
+ if (fleOptions.schemaMap !== undefined) {
108
+ throw new errors_1.MongoshInvalidInputError('explicitEncryptionOnly and schemaMap are mutually exclusive', errors_1.CommonErrors.InvalidArgument);
109
+ }
110
+ fleOptions = { ...fleOptions };
111
+ this._explicitEncryptionOnly = !!fleOptions.explicitEncryptionOnly;
112
+ delete fleOptions.explicitEncryptionOnly;
113
+ }
114
+ this._connectionInfo.driverOptions.autoEncryption =
115
+ (0, helpers_1.processFLEOptions)(fleOptions);
74
116
  }
75
117
  else {
76
- this._connectionInfo.driverOptions.serverApi = otherOptions.api;
118
+ const spFleOptions = (_c = sp === null || sp === void 0 ? void 0 : sp.getFleOptions) === null || _c === void 0 ? void 0 : _c.call(sp);
119
+ if (spFleOptions) {
120
+ this._connectionInfo.driverOptions.autoEncryption = spFleOptions;
121
+ }
122
+ }
123
+ if (otherOptions === null || otherOptions === void 0 ? void 0 : otherOptions.api) {
124
+ if (typeof otherOptions.api === 'string') {
125
+ this._connectionInfo.driverOptions.serverApi = {
126
+ version: otherOptions.api,
127
+ };
128
+ }
129
+ else {
130
+ this._connectionInfo.driverOptions.serverApi = otherOptions.api;
131
+ }
77
132
  }
78
133
  }
79
- }
80
- get _uri() {
81
- return this._connectionInfo.connectionString;
82
- }
83
- get _fleOptions() {
84
- return this._connectionInfo.driverOptions.autoEncryption;
85
- }
86
- get _serviceProvider() {
87
- if (this.__serviceProvider === null) {
88
- throw new errors_1.MongoshInternalError('No ServiceProvider available for this mongo', error_codes_2.ShellApiErrors.NotConnected);
134
+ get _uri() {
135
+ return this._connectionInfo.connectionString;
89
136
  }
90
- return this.__serviceProvider;
91
- }
92
- set _serviceProvider(sp) {
93
- this.__serviceProvider = sp;
94
- }
95
- async _displayBatchSize() {
96
- var _a;
97
- return ((_a = this._instanceState.displayBatchSizeFromDBQuery) !== null && _a !== void 0 ? _a : (await this._instanceState.shellApi.config.get('displayBatchSize')));
98
- }
99
- [enums_1.asPrintable]() {
100
- return (0, history_1.redactURICredentials)(this._uri);
101
- }
102
- _emitMongoApiCall(methodName, methodArguments = {}) {
103
- this._instanceState.emitApiCallWithArgs({
104
- method: methodName,
105
- class: 'Mongo',
106
- uri: this._uri,
107
- arguments: methodArguments,
108
- });
109
- }
110
- async connect(username, password) {
111
- var _a, _b, _c, _d;
112
- if (username || password) {
113
- this._connectionInfo = (0, arg_parser_1.mapCliToDriver)({
114
- username,
115
- password,
116
- }, this._connectionInfo);
117
- }
118
- const driverOptions = { ...this._connectionInfo.driverOptions };
119
- if (this._explicitEncryptionOnly) {
120
- delete driverOptions.autoEncryption;
121
- }
122
- else if (driverOptions.autoEncryption) {
123
- driverOptions.autoEncryption.extraOptions = {
124
- ...driverOptions.autoEncryption.extraOptions,
125
- ...(await ((_b = (_a = this._instanceState.evaluationListener) === null || _a === void 0 ? void 0 : _a.getCryptLibraryOptions) === null || _b === void 0 ? void 0 : _b.call(_a))),
126
- };
127
- }
128
- const parentProvider = this._instanceState.initialServiceProvider;
129
- try {
130
- this.__serviceProvider = await parentProvider.getNewConnection(this._uri, driverOptions);
131
- }
132
- catch (e) {
133
- if ((e === null || e === void 0 ? void 0 : e.name) === 'MongoServerSelectionError' &&
134
- ((_d = (_c = parentProvider.getRawClient()) === null || _c === void 0 ? void 0 : _c.options) === null || _d === void 0 ? void 0 : _d.tls) &&
135
- !/\b(ssl|tls)=/.exec(this._uri)) {
136
- e.message += ' (is ?tls=true missing from the connection string?)';
137
- }
138
- throw e;
137
+ get _fleOptions() {
138
+ return this._connectionInfo.driverOptions.autoEncryption;
139
139
  }
140
- }
141
- _getDb(name) {
142
- (0, helpers_1.assertArgsDefinedType)([name], ['string']);
143
- if (!(0, helpers_1.isValidDatabaseName)(name)) {
144
- throw new errors_1.MongoshInvalidInputError(`Invalid database name: ${name}`, errors_1.CommonErrors.InvalidArgument);
140
+ get _serviceProvider() {
141
+ if (this.__serviceProvider === null) {
142
+ throw new errors_1.MongoshInternalError('No ServiceProvider available for this mongo', error_codes_2.ShellApiErrors.NotConnected);
143
+ }
144
+ return this.__serviceProvider;
145
145
  }
146
- if (!(name in this._databases)) {
147
- this._databases[name] = new database_1.default(this, name);
146
+ set _serviceProvider(sp) {
147
+ this.__serviceProvider = sp;
148
148
  }
149
- return this._databases[name];
150
- }
151
- getDB(db) {
152
- (0, helpers_1.assertArgsDefinedType)([db], ['string'], 'Mongo.getDB');
153
- this._instanceState.messageBus.emit('mongosh:getDB', { db });
154
- return this._getDb(db);
155
- }
156
- getCollection(name) {
157
- var _a, _b;
158
- (0, helpers_1.assertArgsDefinedType)([name], ['string']);
159
- const { db, coll } = (_b = (_a = /^(?<db>[^.]+)\.(?<coll>.+)$/.exec(name)) === null || _a === void 0 ? void 0 : _a.groups) !== null && _b !== void 0 ? _b : {};
160
- if (!db || !coll) {
161
- throw new errors_1.MongoshInvalidInputError('Collection must be of the format <db>.<collection>', errors_1.CommonErrors.InvalidArgument);
162
- }
163
- return this._getDb(db).getCollection(coll);
164
- }
165
- getURI() {
166
- return this._uri;
167
- }
168
- use(db) {
169
- var _a;
170
- (0, helpers_1.assertArgsDefinedType)([db], ['string'], 'Mongo.use');
171
- this._instanceState.messageBus.emit('mongosh:use', { db });
172
- let previousDbName;
173
- let previousDbMongo;
174
- try {
175
- const previousDb = this._instanceState.context.db;
176
- previousDbName = (_a = previousDb === null || previousDb === void 0 ? void 0 : previousDb.getName) === null || _a === void 0 ? void 0 : _a.call(previousDb);
177
- previousDbMongo = previousDb === null || previousDb === void 0 ? void 0 : previousDb._mongo;
178
- }
179
- catch (e) {
180
- if ((e === null || e === void 0 ? void 0 : e.code) !== error_codes_2.ShellApiErrors.NotConnected) {
149
+ async _displayBatchSize() {
150
+ var _a;
151
+ return ((_a = this._instanceState.displayBatchSizeFromDBQuery) !== null && _a !== void 0 ? _a : (await this._instanceState.shellApi.config.get('displayBatchSize')));
152
+ }
153
+ [enums_1.asPrintable]() {
154
+ return (0, history_1.redactURICredentials)(this._uri);
155
+ }
156
+ _emitMongoApiCall(methodName, methodArguments = {}) {
157
+ this._instanceState.emitApiCallWithArgs({
158
+ method: methodName,
159
+ class: 'Mongo',
160
+ uri: this._uri,
161
+ arguments: methodArguments,
162
+ });
163
+ }
164
+ async connect(username, password) {
165
+ var _a, _b, _c, _d;
166
+ if (username || password) {
167
+ this._connectionInfo = (0, arg_parser_1.mapCliToDriver)({
168
+ username,
169
+ password,
170
+ }, this._connectionInfo);
171
+ }
172
+ const driverOptions = { ...this._connectionInfo.driverOptions };
173
+ if (this._explicitEncryptionOnly) {
174
+ delete driverOptions.autoEncryption;
175
+ }
176
+ else if (driverOptions.autoEncryption) {
177
+ driverOptions.autoEncryption.extraOptions = {
178
+ ...driverOptions.autoEncryption.extraOptions,
179
+ ...(await ((_b = (_a = this._instanceState.evaluationListener) === null || _a === void 0 ? void 0 : _a.getCryptLibraryOptions) === null || _b === void 0 ? void 0 : _b.call(_a))),
180
+ };
181
+ }
182
+ const parentProvider = this._instanceState.initialServiceProvider;
183
+ try {
184
+ this.__serviceProvider = await parentProvider.getNewConnection(this._uri, driverOptions);
185
+ }
186
+ catch (e) {
187
+ if ((e === null || e === void 0 ? void 0 : e.name) === 'MongoServerSelectionError' &&
188
+ ((_d = (_c = parentProvider.getRawClient()) === null || _c === void 0 ? void 0 : _c.options) === null || _d === void 0 ? void 0 : _d.tls) &&
189
+ !/\b(ssl|tls)=/.exec(this._uri)) {
190
+ e.message += ' (is ?tls=true missing from the connection string?)';
191
+ }
181
192
  throw e;
182
193
  }
183
194
  }
184
- this._instanceState.context.db = this._getDb(db);
185
- if (db === previousDbName && previousDbMongo === this) {
186
- return `already on db ${db}`;
195
+ _getDb(name) {
196
+ (0, helpers_1.assertArgsDefinedType)([name], ['string']);
197
+ if (!(0, helpers_1.isValidDatabaseName)(name)) {
198
+ throw new errors_1.MongoshInvalidInputError(`Invalid database name: ${name}`, errors_1.CommonErrors.InvalidArgument);
199
+ }
200
+ if (!(name in this._databases)) {
201
+ this._databases[name] = new database_1.default(this, name);
202
+ }
203
+ return this._databases[name];
204
+ }
205
+ getDB(db) {
206
+ (0, helpers_1.assertArgsDefinedType)([db], ['string'], 'Mongo.getDB');
207
+ this._instanceState.messageBus.emit('mongosh:getDB', { db });
208
+ return this._getDb(db);
209
+ }
210
+ getCollection(name) {
211
+ var _a, _b;
212
+ (0, helpers_1.assertArgsDefinedType)([name], ['string']);
213
+ const { db, coll } = (_b = (_a = /^(?<db>[^.]+)\.(?<coll>.+)$/.exec(name)) === null || _a === void 0 ? void 0 : _a.groups) !== null && _b !== void 0 ? _b : {};
214
+ if (!db || !coll) {
215
+ throw new errors_1.MongoshInvalidInputError('Collection must be of the format <db>.<collection>', errors_1.CommonErrors.InvalidArgument);
216
+ }
217
+ return this._getDb(db).getCollection(coll);
187
218
  }
188
- return `switched to db ${db}`;
189
- }
190
- async _listDatabases(opts = {}) {
191
- const result = await this._serviceProvider.listDatabases('admin', {
192
- ...this._getExplicitlyRequestedReadPref(),
193
- ...opts,
194
- });
195
- if (!('databases' in result)) {
196
- const err = new errors_1.MongoshRuntimeError('Got invalid result from "listDatabases"', errors_1.CommonErrors.CommandFailed);
197
- this._instanceState.messageBus.emit('mongosh:error', err, 'shell-api');
198
- throw err;
199
- }
200
- this._cachedDatabaseNames = result.databases.map((db) => db.name);
201
- return result;
202
- }
203
- async _getDatabaseNamesForCompletion() {
204
- return await Promise.race([
205
- (async () => {
206
- return (await this._listDatabases({ readPreference: 'primaryPreferred' })).databases.map((db) => db.name);
207
- })(),
208
- (async () => {
209
- await new Promise((resolve) => setTimeout(resolve, 200).unref());
210
- return this._cachedDatabaseNames;
211
- })(),
212
- ]);
213
- }
214
- async getDBs(options = {}) {
215
- this._emitMongoApiCall('getDBs', { options });
216
- return await this._listDatabases(options);
217
- }
218
- async getDBNames(options = {}) {
219
- this._emitMongoApiCall('getDBNames', { options });
220
- return (await this._listDatabases(options)).databases.map((db) => db.name);
221
- }
222
- async show(cmd, arg, tracked = true) {
223
- var _a, _b, _c;
224
- const db = this._instanceState.currentDb;
225
- tracked &&
226
- this._instanceState.messageBus.emit('mongosh:show', {
227
- method: `show ${cmd}`,
219
+ getURI() {
220
+ return this._uri;
221
+ }
222
+ use(db) {
223
+ var _a;
224
+ (0, helpers_1.assertArgsDefinedType)([db], ['string'], 'Mongo.use');
225
+ this._instanceState.messageBus.emit('mongosh:use', { db });
226
+ let previousDbName;
227
+ let previousDbMongo;
228
+ try {
229
+ const previousDb = this._instanceState.context.db;
230
+ previousDbName = (_a = previousDb === null || previousDb === void 0 ? void 0 : previousDb.getName) === null || _a === void 0 ? void 0 : _a.call(previousDb);
231
+ previousDbMongo = previousDb === null || previousDb === void 0 ? void 0 : previousDb._mongo;
232
+ }
233
+ catch (e) {
234
+ if ((e === null || e === void 0 ? void 0 : e.code) !== error_codes_2.ShellApiErrors.NotConnected) {
235
+ throw e;
236
+ }
237
+ }
238
+ this._instanceState.context.db = this._getDb(db);
239
+ if (db === previousDbName && previousDbMongo === this) {
240
+ return `already on db ${db}`;
241
+ }
242
+ return `switched to db ${db}`;
243
+ }
244
+ async _listDatabases(opts = {}) {
245
+ const result = await this._serviceProvider.listDatabases('admin', {
246
+ ...this._getExplicitlyRequestedReadPref(),
247
+ ...opts,
228
248
  });
229
- switch (cmd) {
230
- case 'databases':
231
- case 'dbs':
232
- const result = (await this._listDatabases({
233
- readPreference: 'primaryPreferred',
234
- promoteLongs: true,
235
- })).databases;
236
- return new result_1.CommandResult('ShowDatabasesResult', result);
237
- case 'collections':
238
- case 'tables':
239
- const collectionNames = await db._getCollectionNamesWithTypes({
240
- readPreference: 'primaryPreferred',
241
- promoteLongs: true,
249
+ if (!('databases' in result)) {
250
+ const err = new errors_1.MongoshRuntimeError('Got invalid result from "listDatabases"', errors_1.CommonErrors.CommandFailed);
251
+ this._instanceState.messageBus.emit('mongosh:error', err, 'shell-api');
252
+ throw err;
253
+ }
254
+ this._cachedDatabaseNames = result.databases.map((db) => db.name);
255
+ return result;
256
+ }
257
+ async _getDatabaseNamesForCompletion() {
258
+ return await Promise.race([
259
+ (async () => {
260
+ return (await this._listDatabases({ readPreference: 'primaryPreferred' })).databases.map((db) => db.name);
261
+ })(),
262
+ (async () => {
263
+ await new Promise((resolve) => setTimeout(resolve, 200).unref());
264
+ return this._cachedDatabaseNames;
265
+ })(),
266
+ ]);
267
+ }
268
+ async getDBs(options = {}) {
269
+ this._emitMongoApiCall('getDBs', { options });
270
+ return await this._listDatabases(options);
271
+ }
272
+ async getDBNames(options = {}) {
273
+ this._emitMongoApiCall('getDBNames', { options });
274
+ return (await this._listDatabases(options)).databases.map((db) => db.name);
275
+ }
276
+ async show(cmd, arg, tracked = true) {
277
+ var _a, _b, _c;
278
+ const db = this._instanceState.currentDb;
279
+ tracked &&
280
+ this._instanceState.messageBus.emit('mongosh:show', {
281
+ method: `show ${cmd}`,
242
282
  });
243
- return new result_1.CommandResult('ShowCollectionsResult', collectionNames);
244
- case 'profile':
245
- const sysprof = db.getCollection('system.profile');
246
- const profiles = {
247
- count: await sysprof.countDocuments({}),
248
- };
249
- if (profiles.count !== 0) {
250
- profiles.result = await (await sysprof.find({ millis: { $gt: 0 } }))
251
- .sort({ $natural: -1 })
252
- .limit(5)
253
- .toArray();
254
- }
255
- return new result_1.CommandResult('ShowProfileResult', profiles);
256
- case 'users':
257
- const users = await db.getUsers();
258
- return new result_1.CommandResult('ShowResult', users.users);
259
- case 'roles':
260
- const roles = await db.getRoles({ showBuiltinRoles: true });
261
- return new result_1.CommandResult('ShowResult', roles.roles);
262
- case 'log':
263
- const log = await db.adminCommand({ getLog: arg || 'global' });
264
- return new result_1.CommandResult('ShowResult', log.log);
265
- case 'logs':
266
- const logs = await db.adminCommand({ getLog: '*' });
267
- return new result_1.CommandResult('ShowResult', logs.names);
268
- case 'startupWarnings': {
269
- let result;
270
- try {
271
- result = (await db.adminCommand({
272
- getLog: 'startupWarnings',
273
- }));
274
- if (!result) {
275
- throw new errors_1.MongoshCommandFailed('adminCommand getLog unexpectedly returned no result');
283
+ switch (cmd) {
284
+ case 'databases':
285
+ case 'dbs':
286
+ const result = (await this._listDatabases({
287
+ readPreference: 'primaryPreferred',
288
+ promoteLongs: true,
289
+ })).databases;
290
+ return new result_1.CommandResult('ShowDatabasesResult', result);
291
+ case 'collections':
292
+ case 'tables':
293
+ const collectionNames = await db._getCollectionNamesWithTypes({
294
+ readPreference: 'primaryPreferred',
295
+ promoteLongs: true,
296
+ });
297
+ return new result_1.CommandResult('ShowCollectionsResult', collectionNames);
298
+ case 'profile':
299
+ const sysprof = db.getCollection('system.profile');
300
+ const profiles = {
301
+ count: await sysprof.countDocuments({}),
302
+ };
303
+ if (profiles.count !== 0) {
304
+ profiles.result = await (await sysprof.find({ millis: { $gt: 0 } }))
305
+ .sort({ $natural: -1 })
306
+ .limit(5)
307
+ .toArray();
276
308
  }
277
- }
278
- catch (error) {
279
- this._instanceState.messageBus.emit('mongosh:error', error, 'shell-api');
280
- return new result_1.CommandResult('ShowBannerResult', null);
281
- }
282
- if (!result.log || !result.log.length) {
283
- return new result_1.CommandResult('ShowBannerResult', null);
284
- }
285
- const lines = result.log.map((logLine) => {
309
+ return new result_1.CommandResult('ShowProfileResult', profiles);
310
+ case 'users':
311
+ const users = await db.getUsers();
312
+ return new result_1.CommandResult('ShowResult', users.users);
313
+ case 'roles':
314
+ const roles = await db.getRoles({ showBuiltinRoles: true });
315
+ return new result_1.CommandResult('ShowResult', roles.roles);
316
+ case 'log':
317
+ const log = await db.adminCommand({ getLog: arg || 'global' });
318
+ return new result_1.CommandResult('ShowResult', log.log);
319
+ case 'logs':
320
+ const logs = await db.adminCommand({ getLog: '*' });
321
+ return new result_1.CommandResult('ShowResult', logs.names);
322
+ case 'startupWarnings': {
323
+ let result;
286
324
  try {
287
- const entry = (0, log_entry_1.parseAnyLogEntry)(logLine);
288
- return `${entry.timestamp}: ${entry.message}`;
325
+ result = (await db.adminCommand({
326
+ getLog: 'startupWarnings',
327
+ }));
328
+ if (!result) {
329
+ throw new errors_1.MongoshCommandFailed('adminCommand getLog unexpectedly returned no result');
330
+ }
289
331
  }
290
- catch (e) {
291
- return `Unexpected log line format: ${logLine}`;
332
+ catch (error) {
333
+ this._instanceState.messageBus.emit('mongosh:error', error, 'shell-api');
334
+ return new result_1.CommandResult('ShowBannerResult', null);
292
335
  }
293
- });
294
- return new result_1.CommandResult('ShowBannerResult', {
295
- header: 'The server generated these startup warnings when booting',
296
- content: lines.join('\n'),
297
- });
298
- }
299
- case 'automationNotices': {
300
- let helloResult;
301
- try {
302
- helloResult = await db.hello();
336
+ if (!result.log || !result.log.length) {
337
+ return new result_1.CommandResult('ShowBannerResult', null);
338
+ }
339
+ const lines = result.log.map((logLine) => {
340
+ try {
341
+ const entry = (0, log_entry_1.parseAnyLogEntry)(logLine);
342
+ return `${entry.timestamp}: ${entry.message}`;
343
+ }
344
+ catch (e) {
345
+ return `Unexpected log line format: ${logLine}`;
346
+ }
347
+ });
348
+ return new result_1.CommandResult('ShowBannerResult', {
349
+ header: 'The server generated these startup warnings when booting',
350
+ content: lines.join('\n'),
351
+ });
303
352
  }
304
- catch (error) {
305
- this._instanceState.messageBus.emit('mongosh:error', error, 'shell-api');
353
+ case 'automationNotices': {
354
+ let helloResult;
355
+ try {
356
+ helloResult = await db.hello();
357
+ }
358
+ catch (error) {
359
+ this._instanceState.messageBus.emit('mongosh:error', error, 'shell-api');
360
+ return new result_1.CommandResult('ShowBannerResult', null);
361
+ }
362
+ if (helloResult.automationServiceDescriptor) {
363
+ return new result_1.CommandResult('ShowBannerResult', {
364
+ content: `This server is managed by automation service '${helloResult.automationServiceDescriptor}'.\n` +
365
+ 'Many administrative actions are inappropriate, and may be automatically reverted.',
366
+ });
367
+ }
306
368
  return new result_1.CommandResult('ShowBannerResult', null);
307
369
  }
308
- if (helloResult.automationServiceDescriptor) {
370
+ case 'nonGenuineMongoDBCheck': {
371
+ const isGenuine = (_c = (_b = (_a = this._instanceState.connectionInfo) === null || _a === void 0 ? void 0 : _a.extraInfo) === null || _b === void 0 ? void 0 : _b.is_genuine) !== null && _c !== void 0 ? _c : true;
372
+ if (isGenuine) {
373
+ return new result_1.CommandResult('ShowBannerResult', null);
374
+ }
309
375
  return new result_1.CommandResult('ShowBannerResult', {
310
- content: `This server is managed by automation service '${helloResult.automationServiceDescriptor}'.\n` +
311
- 'Many administrative actions are inappropriate, and may be automatically reverted.',
376
+ header: 'Warning: Non-Genuine MongoDB Detected',
377
+ content: [
378
+ 'This server or service appears to be an emulation of MongoDB rather than an official MongoDB product.',
379
+ 'Some documented MongoDB features may work differently, be entirely missing or incomplete, or have unexpected performance characteristics.',
380
+ 'To learn more please visit: https://dochub.mongodb.org/core/non-genuine-mongodb-server-warning.',
381
+ ].join('\n'),
312
382
  });
313
383
  }
314
- return new result_1.CommandResult('ShowBannerResult', null);
384
+ default:
385
+ const err = new errors_1.MongoshInvalidInputError(`'${cmd}' is not a valid argument for "show".`, errors_1.CommonErrors.InvalidArgument);
386
+ this._instanceState.messageBus.emit('mongosh:error', err, 'shell-api');
387
+ throw err;
315
388
  }
316
- case 'nonGenuineMongoDBCheck': {
317
- const isGenuine = (_c = (_b = (_a = this._instanceState.connectionInfo) === null || _a === void 0 ? void 0 : _a.extraInfo) === null || _b === void 0 ? void 0 : _b.is_genuine) !== null && _c !== void 0 ? _c : true;
318
- if (isGenuine) {
319
- return new result_1.CommandResult('ShowBannerResult', null);
320
- }
321
- return new result_1.CommandResult('ShowBannerResult', {
322
- header: 'Warning: Non-Genuine MongoDB Detected',
323
- content: [
324
- 'This server or service appears to be an emulation of MongoDB rather than an official MongoDB product.',
325
- 'Some documented MongoDB features may work differently, be entirely missing or incomplete, or have unexpected performance characteristics.',
326
- 'To learn more please visit: https://dochub.mongodb.org/core/non-genuine-mongodb-server-warning.',
327
- ].join('\n'),
328
- });
329
- }
330
- default:
331
- const err = new errors_1.MongoshInvalidInputError(`'${cmd}' is not a valid argument for "show".`, errors_1.CommonErrors.InvalidArgument);
332
- this._instanceState.messageBus.emit('mongosh:error', err, 'shell-api');
333
- throw err;
334
389
  }
335
- }
336
- async close(force) {
337
- const index = this._instanceState.mongos.indexOf(this);
338
- if (index === -1) {
339
- process.emitWarning(new errors_1.MongoshInternalError(`Closing untracked Mongo instance ${this[enums_1.asPrintable]()}`));
390
+ async close(force) {
391
+ const index = this._instanceState.mongos.indexOf(this);
392
+ if (index === -1) {
393
+ process.emitWarning(new errors_1.MongoshInternalError(`Closing untracked Mongo instance ${this[enums_1.asPrintable]()}`));
394
+ }
395
+ else {
396
+ this._instanceState.mongos.splice(index, 1);
397
+ }
398
+ await this._serviceProvider.close(force);
340
399
  }
341
- else {
342
- this._instanceState.mongos.splice(index, 1);
400
+ async _suspend() {
401
+ return await this._serviceProvider.suspend();
343
402
  }
344
- await this._serviceProvider.close(force);
345
- }
346
- async _suspend() {
347
- return await this._serviceProvider.suspend();
348
- }
349
- getReadPrefMode() {
350
- return this._serviceProvider.getReadPreference().mode;
351
- }
352
- getReadPrefTagSet() {
353
- return this._serviceProvider.getReadPreference().tags;
354
- }
355
- getReadPref() {
356
- return this._serviceProvider.getReadPreference();
357
- }
358
- _getExplicitlyRequestedReadPref() {
359
- return this._readPreferenceWasExplicitlyRequested
360
- ? { readPreference: this.getReadPref() }
361
- : undefined;
362
- }
363
- getReadConcern() {
364
- try {
365
- const rc = this._serviceProvider.getReadConcern();
366
- return rc ? rc.level : undefined;
403
+ getReadPrefMode() {
404
+ return this._serviceProvider.getReadPreference().mode;
367
405
  }
368
- catch (_a) {
369
- throw new errors_1.MongoshInternalError('Error retrieving ReadConcern.');
406
+ getReadPrefTagSet() {
407
+ return this._serviceProvider.getReadPreference().tags;
370
408
  }
371
- }
372
- getWriteConcern() {
373
- try {
374
- return this._serviceProvider.getWriteConcern();
409
+ getReadPref() {
410
+ return this._serviceProvider.getReadPreference();
375
411
  }
376
- catch (_a) {
377
- throw new errors_1.MongoshInternalError('Error retrieving WriteConcern.');
412
+ _getExplicitlyRequestedReadPref() {
413
+ return this._readPreferenceWasExplicitlyRequested
414
+ ? { readPreference: this.getReadPref() }
415
+ : undefined;
378
416
  }
379
- }
380
- async setReadPref(mode, tagSet, hedgeOptions) {
381
- await this._serviceProvider.resetConnectionOptions({
382
- readPreference: this._serviceProvider.readPreferenceFromOptions({
383
- readPreference: mode,
384
- readPreferenceTags: tagSet,
385
- hedge: hedgeOptions,
386
- }),
387
- });
388
- this._readPreferenceWasExplicitlyRequested = true;
389
- }
390
- async setReadConcern(level) {
391
- await this._serviceProvider.resetConnectionOptions({
392
- readConcern: { level: level },
393
- });
394
- }
395
- async setWriteConcern(concernOrWValue, wtimeoutMSValue, jValue) {
396
- const options = {};
397
- let concern;
398
- if (typeof concernOrWValue === 'object') {
399
- if (wtimeoutMSValue !== undefined || jValue !== undefined) {
400
- throw new errors_1.MongoshInvalidInputError('If concern is given as an object no other arguments must be specified', errors_1.CommonErrors.InvalidArgument);
401
- }
402
- concern = concernOrWValue;
403
- }
404
- else {
405
- concern = {};
406
- if (typeof concernOrWValue !== 'string' &&
407
- typeof concernOrWValue !== 'number') {
408
- throw new errors_1.MongoshInvalidInputError(`w value must be a number or string, got: ${typeof concernOrWValue}`, errors_1.CommonErrors.InvalidArgument);
409
- }
410
- else if (typeof concernOrWValue === 'number' && concernOrWValue < 0) {
411
- throw new errors_1.MongoshInvalidInputError(`w value must be equal to or greather than 0, got: ${concernOrWValue}`, errors_1.CommonErrors.InvalidArgument);
412
- }
413
- concern.w = concernOrWValue;
414
- if (wtimeoutMSValue !== undefined) {
415
- if (typeof wtimeoutMSValue !== 'number') {
416
- throw new errors_1.MongoshInvalidInputError(`wtimeoutMS value must be a number, got: ${typeof wtimeoutMSValue}`, errors_1.CommonErrors.InvalidArgument);
417
- }
418
- else if (wtimeoutMSValue < 0) {
419
- throw new errors_1.MongoshInvalidInputError(`wtimeoutMS must be equal to or greather than 0, got: ${wtimeoutMSValue}`, errors_1.CommonErrors.InvalidArgument);
420
- }
421
- concern.wtimeout = wtimeoutMSValue;
417
+ getReadConcern() {
418
+ try {
419
+ const rc = this._serviceProvider.getReadConcern();
420
+ return rc ? rc.level : undefined;
422
421
  }
423
- if (jValue !== undefined) {
424
- if (typeof jValue !== 'boolean') {
425
- throw new errors_1.MongoshInvalidInputError(`j value must be a boolean, got: ${typeof jValue}`, errors_1.CommonErrors.InvalidArgument);
426
- }
427
- concern.j = jValue;
422
+ catch (_a) {
423
+ throw new errors_1.MongoshInternalError('Error retrieving ReadConcern.');
428
424
  }
429
425
  }
430
- if (concern.w !== undefined) {
431
- options.w = concern.w;
426
+ getWriteConcern() {
427
+ try {
428
+ return this._serviceProvider.getWriteConcern();
429
+ }
430
+ catch (_a) {
431
+ throw new errors_1.MongoshInternalError('Error retrieving WriteConcern.');
432
+ }
432
433
  }
433
- if (concern.wtimeout !== undefined) {
434
- options.wtimeoutMS = concern.wtimeout;
434
+ async setReadPref(mode, tagSet, hedgeOptions) {
435
+ await this._serviceProvider.resetConnectionOptions({
436
+ readPreference: this._serviceProvider.readPreferenceFromOptions({
437
+ readPreference: mode,
438
+ readPreferenceTags: tagSet,
439
+ hedge: hedgeOptions,
440
+ }),
441
+ });
442
+ this._readPreferenceWasExplicitlyRequested = true;
435
443
  }
436
- if (concern.j !== undefined) {
437
- options.journal = concern.j;
444
+ async setReadConcern(level) {
445
+ await this._serviceProvider.resetConnectionOptions({
446
+ readConcern: { level: level },
447
+ });
438
448
  }
439
- if (concern.fsync !== undefined) {
440
- options.journal = !!concern.fsync;
449
+ async setWriteConcern(concernOrWValue, wtimeoutMSValue, jValue) {
450
+ const options = {};
451
+ let concern;
452
+ if (typeof concernOrWValue === 'object') {
453
+ if (wtimeoutMSValue !== undefined || jValue !== undefined) {
454
+ throw new errors_1.MongoshInvalidInputError('If concern is given as an object no other arguments must be specified', errors_1.CommonErrors.InvalidArgument);
455
+ }
456
+ concern = concernOrWValue;
457
+ }
458
+ else {
459
+ concern = {};
460
+ if (typeof concernOrWValue !== 'string' &&
461
+ typeof concernOrWValue !== 'number') {
462
+ throw new errors_1.MongoshInvalidInputError(`w value must be a number or string, got: ${typeof concernOrWValue}`, errors_1.CommonErrors.InvalidArgument);
463
+ }
464
+ else if (typeof concernOrWValue === 'number' && concernOrWValue < 0) {
465
+ throw new errors_1.MongoshInvalidInputError(`w value must be equal to or greather than 0, got: ${concernOrWValue}`, errors_1.CommonErrors.InvalidArgument);
466
+ }
467
+ concern.w = concernOrWValue;
468
+ if (wtimeoutMSValue !== undefined) {
469
+ if (typeof wtimeoutMSValue !== 'number') {
470
+ throw new errors_1.MongoshInvalidInputError(`wtimeoutMS value must be a number, got: ${typeof wtimeoutMSValue}`, errors_1.CommonErrors.InvalidArgument);
471
+ }
472
+ else if (wtimeoutMSValue < 0) {
473
+ throw new errors_1.MongoshInvalidInputError(`wtimeoutMS must be equal to or greather than 0, got: ${wtimeoutMSValue}`, errors_1.CommonErrors.InvalidArgument);
474
+ }
475
+ concern.wtimeout = wtimeoutMSValue;
476
+ }
477
+ if (jValue !== undefined) {
478
+ if (typeof jValue !== 'boolean') {
479
+ throw new errors_1.MongoshInvalidInputError(`j value must be a boolean, got: ${typeof jValue}`, errors_1.CommonErrors.InvalidArgument);
480
+ }
481
+ concern.j = jValue;
482
+ }
483
+ }
484
+ if (concern.w !== undefined) {
485
+ options.w = concern.w;
486
+ }
487
+ if (concern.wtimeout !== undefined) {
488
+ options.wtimeoutMS = concern.wtimeout;
489
+ }
490
+ if (concern.j !== undefined) {
491
+ options.journal = concern.j;
492
+ }
493
+ if (concern.fsync !== undefined) {
494
+ options.journal = !!concern.fsync;
495
+ }
496
+ await this._serviceProvider.resetConnectionOptions(options);
497
+ }
498
+ startSession(options = {}) {
499
+ const allTransactionOptions = [
500
+ 'readConcern',
501
+ 'writeConcern',
502
+ 'readPreference',
503
+ 'maxCommitTimeMS',
504
+ ];
505
+ function assertAllTransactionOptionsUsed(_options) {
506
+ }
507
+ assertAllTransactionOptionsUsed('');
508
+ const defaultTransactionOptions = {};
509
+ for (const key of allTransactionOptions) {
510
+ if (typeof options[key] !== 'undefined') {
511
+ defaultTransactionOptions[key] = options[key];
512
+ }
513
+ }
514
+ const allSessionOptions = ['causalConsistency', 'snapshot'];
515
+ function assertAllSessionOptionsUsed(_options) { }
516
+ assertAllSessionOptionsUsed('');
517
+ const driverOptions = {};
518
+ if (Object.keys(defaultTransactionOptions).length > 0) {
519
+ driverOptions.defaultTransactionOptions = defaultTransactionOptions;
520
+ }
521
+ for (const key of allSessionOptions) {
522
+ if (typeof options[key] !== 'undefined') {
523
+ driverOptions[key] = options[key];
524
+ }
525
+ }
526
+ return new session_1.default(this, driverOptions, this._serviceProvider.startSession(driverOptions));
441
527
  }
442
- await this._serviceProvider.resetConnectionOptions(options);
443
- }
444
- startSession(options = {}) {
445
- const allTransactionOptions = [
446
- 'readConcern',
447
- 'writeConcern',
448
- 'readPreference',
449
- 'maxCommitTimeMS',
450
- ];
451
- function assertAllTransactionOptionsUsed(_options) {
452
- }
453
- assertAllTransactionOptionsUsed('');
454
- const defaultTransactionOptions = {};
455
- for (const key of allTransactionOptions) {
456
- if (typeof options[key] !== 'undefined') {
457
- defaultTransactionOptions[key] = options[key];
458
- }
459
- }
460
- const allSessionOptions = ['causalConsistency', 'snapshot'];
461
- function assertAllSessionOptionsUsed(_options) { }
462
- assertAllSessionOptionsUsed('');
463
- const driverOptions = {};
464
- if (Object.keys(defaultTransactionOptions).length > 0) {
465
- driverOptions.defaultTransactionOptions = defaultTransactionOptions;
466
- }
467
- for (const key of allSessionOptions) {
468
- if (typeof options[key] !== 'undefined') {
469
- driverOptions[key] = options[key];
470
- }
471
- }
472
- return new session_1.default(this, driverOptions, this._serviceProvider.startSession(driverOptions));
473
- }
474
- setCausalConsistency() {
475
- throw new errors_1.MongoshUnimplementedError('It is not possible to set causal consistency for an entire connection due to the driver, use startSession({causalConsistency: <>}) instead.', errors_1.CommonErrors.NotImplemented, (0, error_codes_1.blockedByDriverMetadata)('Mongo.setCausalConsistency'));
476
- }
477
- isCausalConsistency() {
478
- throw new errors_1.MongoshUnimplementedError('Causal consistency for drivers is set via Mongo.startSession and can be checked via session.getOptions. The default value is true', errors_1.CommonErrors.NotImplemented, (0, error_codes_1.blockedByDriverMetadata)('Mongo.isCausalConsistency'));
479
- }
480
- setSlaveOk() {
481
- throw new errors_1.MongoshDeprecatedError('Setting slaveOk is deprecated, use setReadPref instead.');
482
- }
483
- async setSecondaryOk() {
484
- await this._instanceState.printDeprecationWarning('.setSecondaryOk() is deprecated. Use .setReadPref("primaryPreferred") instead');
485
- const currentReadPref = this.getReadPrefMode();
486
- if (currentReadPref === 'primary') {
487
- await this._instanceState.shellApi.print('Setting read preference from "primary" to "primaryPreferred"');
488
- await this.setReadPref('primaryPreferred');
528
+ setCausalConsistency() {
529
+ throw new errors_1.MongoshUnimplementedError('It is not possible to set causal consistency for an entire connection due to the driver, use startSession({causalConsistency: <>}) instead.', errors_1.CommonErrors.NotImplemented, (0, error_codes_1.blockedByDriverMetadata)('Mongo.setCausalConsistency'));
489
530
  }
490
- else {
491
- await this._instanceState.shellApi.print(`Leaving read preference unchanged (is already "${currentReadPref}")`);
531
+ isCausalConsistency() {
532
+ throw new errors_1.MongoshUnimplementedError('Causal consistency for drivers is set via Mongo.startSession and can be checked via session.getOptions. The default value is true', errors_1.CommonErrors.NotImplemented, (0, error_codes_1.blockedByDriverMetadata)('Mongo.isCausalConsistency'));
492
533
  }
493
- }
494
- async watch(pipeline = [], options = {}) {
495
- if (!Array.isArray(pipeline)) {
496
- options = pipeline;
497
- pipeline = [];
498
- }
499
- this._emitMongoApiCall('watch', { pipeline, options });
500
- const cursor = new change_stream_cursor_1.default(this._serviceProvider.watch(pipeline, options), (0, history_1.redactURICredentials)(this._uri), this);
501
- if (!options.resumeAfter &&
502
- !options.startAfter &&
503
- !options.startAtOperationTime) {
504
- await cursor.tryNext();
505
- }
506
- this._instanceState.currentCursor = cursor;
507
- return cursor;
508
- }
509
- getClientEncryption() {
510
- if (!this._fleOptions) {
511
- throw new errors_1.MongoshInvalidInputError('Cannot call getClientEncryption() without field-level encryption options', error_codes_2.ShellApiErrors.NotUsingFLE);
534
+ setSlaveOk() {
535
+ throw new errors_1.MongoshDeprecatedError('Setting slaveOk is deprecated, use setReadPref instead.');
512
536
  }
513
- if (!this._clientEncryption) {
514
- this._clientEncryption = new field_level_encryption_1.ClientEncryption(this);
537
+ async setSecondaryOk() {
538
+ await this._instanceState.printDeprecationWarning('.setSecondaryOk() is deprecated. Use .setReadPref("primaryPreferred") instead');
539
+ const currentReadPref = this.getReadPrefMode();
540
+ if (currentReadPref === 'primary') {
541
+ await this._instanceState.shellApi.print('Setting read preference from "primary" to "primaryPreferred"');
542
+ await this.setReadPref('primaryPreferred');
543
+ }
544
+ else {
545
+ await this._instanceState.shellApi.print(`Leaving read preference unchanged (is already "${currentReadPref}")`);
546
+ }
515
547
  }
516
- return this._clientEncryption;
517
- }
518
- async getKeyVault() {
519
- if (!this._keyVault) {
520
- this._keyVault = new field_level_encryption_1.KeyVault(this.getClientEncryption());
521
- await this._keyVault._init();
548
+ async watch(pipeline = [], options = {}) {
549
+ if (!Array.isArray(pipeline)) {
550
+ options = pipeline;
551
+ pipeline = [];
552
+ }
553
+ this._emitMongoApiCall('watch', { pipeline, options });
554
+ const cursor = new change_stream_cursor_1.default(this._serviceProvider.watch(pipeline, options), (0, history_1.redactURICredentials)(this._uri), this);
555
+ if (!options.resumeAfter &&
556
+ !options.startAfter &&
557
+ !options.startAtOperationTime) {
558
+ await cursor.tryNext();
559
+ }
560
+ this._instanceState.currentCursor = cursor;
561
+ return cursor;
522
562
  }
523
- return this._keyVault;
524
- }
525
- async convertShardKeyToHashed(value) {
526
- const pipeline = [
527
- { $limit: 1 },
528
- { $project: { _id: { $toHashedIndexKey: { $literal: value } } } },
529
- ];
530
- let result;
531
- for (const approach of [
532
- () => this.getDB('_fakeDbForMongoshCSKTH').aggregate([
533
- { $documents: [{}] },
534
- ...pipeline,
535
- ]),
536
- () => this.getDB('admin').aggregate([{ $documents: [{}] }, ...pipeline]),
537
- () => this.getDB('admin').getCollection('system.version').aggregate(pipeline),
538
- () => this.getDB('local')
539
- .getCollection('oplog.rs')
540
- .aggregate([{ $collStats: {} }, ...pipeline]),
541
- ]) {
542
- try {
543
- result = await (await approach()).next();
563
+ getClientEncryption() {
564
+ if (!this._fleOptions) {
565
+ throw new errors_1.MongoshInvalidInputError('Cannot call getClientEncryption() without field-level encryption options', error_codes_2.ShellApiErrors.NotUsingFLE);
544
566
  }
545
- catch (_a) {
546
- continue;
567
+ if (!this._clientEncryption) {
568
+ this._clientEncryption = new field_level_encryption_1.ClientEncryption(this);
547
569
  }
548
- if (result)
549
- break;
570
+ return this._clientEncryption;
550
571
  }
551
- if (!result) {
552
- throw new errors_1.MongoshRuntimeError('Could not find a suitable way to run convertShardKeyToHashed() -- tried $documents and aggregating on admin.system.version and local.oplog.rs', errors_1.CommonErrors.CommandFailed);
572
+ async getKeyVault() {
573
+ if (!this._keyVault) {
574
+ this._keyVault = new field_level_encryption_1.KeyVault(this.getClientEncryption());
575
+ await this._keyVault._init();
576
+ }
577
+ return this._keyVault;
578
+ }
579
+ async convertShardKeyToHashed(value) {
580
+ const pipeline = [
581
+ { $limit: 1 },
582
+ { $project: { _id: { $toHashedIndexKey: { $literal: value } } } },
583
+ ];
584
+ let result;
585
+ for (const approach of [
586
+ () => this.getDB('_fakeDbForMongoshCSKTH').aggregate([
587
+ { $documents: [{}] },
588
+ ...pipeline,
589
+ ]),
590
+ () => this.getDB('admin').aggregate([{ $documents: [{}] }, ...pipeline]),
591
+ () => this.getDB('admin').getCollection('system.version').aggregate(pipeline),
592
+ () => this.getDB('local')
593
+ .getCollection('oplog.rs')
594
+ .aggregate([{ $collStats: {} }, ...pipeline]),
595
+ ]) {
596
+ try {
597
+ result = await (await approach()).next();
598
+ }
599
+ catch (_a) {
600
+ continue;
601
+ }
602
+ if (result)
603
+ break;
604
+ }
605
+ if (!result) {
606
+ throw new errors_1.MongoshRuntimeError('Could not find a suitable way to run convertShardKeyToHashed() -- tried $documents and aggregating on admin.system.version and local.oplog.rs', errors_1.CommonErrors.CommandFailed);
607
+ }
608
+ return result._id;
553
609
  }
554
- return result._id;
555
- }
556
- };
557
- __decorate([
558
- (0, decorators_1.returnType)('Database')
559
- ], Mongo.prototype, "getDB", null);
560
- __decorate([
561
- (0, decorators_1.returnType)('Collection')
562
- ], Mongo.prototype, "getCollection", null);
563
- __decorate([
564
- decorators_1.returnsPromise,
565
- (0, decorators_1.apiVersions)([1])
566
- ], Mongo.prototype, "getDBs", null);
567
- __decorate([
568
- decorators_1.returnsPromise,
569
- (0, decorators_1.apiVersions)([1])
570
- ], Mongo.prototype, "getDBNames", null);
571
- __decorate([
572
- decorators_1.returnsPromise,
573
- (0, decorators_1.apiVersions)([1])
574
- ], Mongo.prototype, "show", null);
575
- __decorate([
576
- decorators_1.returnsPromise
577
- ], Mongo.prototype, "setReadPref", null);
578
- __decorate([
579
- decorators_1.returnsPromise
580
- ], Mongo.prototype, "setReadConcern", null);
581
- __decorate([
582
- decorators_1.returnsPromise
583
- ], Mongo.prototype, "setWriteConcern", null);
584
- __decorate([
585
- (0, decorators_1.topologies)([enums_1.Topologies.ReplSet])
586
- ], Mongo.prototype, "startSession", null);
587
- __decorate([
588
- decorators_1.deprecated
589
- ], Mongo.prototype, "setSlaveOk", null);
590
- __decorate([
591
- decorators_1.deprecated,
592
- decorators_1.returnsPromise
593
- ], Mongo.prototype, "setSecondaryOk", null);
594
- __decorate([
595
- (0, decorators_1.serverVersions)(['3.1.0', enums_1.ServerVersions.latest]),
596
- (0, decorators_1.topologies)([enums_1.Topologies.ReplSet, enums_1.Topologies.Sharded]),
597
- (0, decorators_1.apiVersions)([1]),
598
- decorators_1.returnsPromise
599
- ], Mongo.prototype, "watch", null);
600
- __decorate([
601
- (0, decorators_1.platforms)(['CLI']),
602
- (0, decorators_1.serverVersions)(['4.2.0', enums_1.ServerVersions.latest]),
603
- (0, decorators_1.returnType)('ClientEncryption')
604
- ], Mongo.prototype, "getClientEncryption", null);
605
- __decorate([
606
- (0, decorators_1.platforms)(['CLI']),
607
- (0, decorators_1.serverVersions)(['4.2.0', enums_1.ServerVersions.latest]),
608
- (0, decorators_1.returnType)('KeyVault'),
609
- decorators_1.returnsPromise
610
- ], Mongo.prototype, "getKeyVault", null);
611
- __decorate([
612
- decorators_1.returnsPromise
613
- ], Mongo.prototype, "convertShardKeyToHashed", null);
614
- Mongo = __decorate([
615
- decorators_1.shellApiClassDefault,
616
- (0, decorators_1.classPlatforms)(['CLI'])
617
- ], Mongo);
610
+ };
611
+ __setFunctionName(_classThis, "Mongo");
612
+ (() => {
613
+ var _a;
614
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create((_a = _classSuper[Symbol.metadata]) !== null && _a !== void 0 ? _a : null) : void 0;
615
+ _getDB_decorators = [(0, decorators_1.returnType)('Database')];
616
+ _getCollection_decorators = [(0, decorators_1.returnType)('Collection')];
617
+ _getDBs_decorators = [decorators_1.returnsPromise, (0, decorators_1.apiVersions)([1])];
618
+ _getDBNames_decorators = [decorators_1.returnsPromise, (0, decorators_1.apiVersions)([1])];
619
+ _show_decorators = [decorators_1.returnsPromise, (0, decorators_1.apiVersions)([1])];
620
+ _setReadPref_decorators = [decorators_1.returnsPromise];
621
+ _setReadConcern_decorators = [decorators_1.returnsPromise];
622
+ _setWriteConcern_decorators = [decorators_1.returnsPromise];
623
+ _startSession_decorators = [(0, decorators_1.topologies)([enums_1.Topologies.ReplSet])];
624
+ _setSlaveOk_decorators = [decorators_1.deprecated];
625
+ _setSecondaryOk_decorators = [decorators_1.deprecated, decorators_1.returnsPromise];
626
+ _watch_decorators = [(0, decorators_1.serverVersions)(['3.1.0', enums_1.ServerVersions.latest]), (0, decorators_1.topologies)([enums_1.Topologies.ReplSet, enums_1.Topologies.Sharded]), (0, decorators_1.apiVersions)([1]), decorators_1.returnsPromise];
627
+ _getClientEncryption_decorators = [(0, decorators_1.platforms)(['CLI']), (0, decorators_1.serverVersions)(['4.2.0', enums_1.ServerVersions.latest]), (0, decorators_1.returnType)('ClientEncryption')];
628
+ _getKeyVault_decorators = [(0, decorators_1.platforms)(['CLI']), (0, decorators_1.serverVersions)(['4.2.0', enums_1.ServerVersions.latest]), (0, decorators_1.returnType)('KeyVault'), decorators_1.returnsPromise];
629
+ _convertShardKeyToHashed_decorators = [decorators_1.returnsPromise];
630
+ __esDecorate(_classThis, null, _getDB_decorators, { kind: "method", name: "getDB", static: false, private: false, access: { has: obj => "getDB" in obj, get: obj => obj.getDB }, metadata: _metadata }, null, _instanceExtraInitializers);
631
+ __esDecorate(_classThis, null, _getCollection_decorators, { kind: "method", name: "getCollection", static: false, private: false, access: { has: obj => "getCollection" in obj, get: obj => obj.getCollection }, metadata: _metadata }, null, _instanceExtraInitializers);
632
+ __esDecorate(_classThis, null, _getDBs_decorators, { kind: "method", name: "getDBs", static: false, private: false, access: { has: obj => "getDBs" in obj, get: obj => obj.getDBs }, metadata: _metadata }, null, _instanceExtraInitializers);
633
+ __esDecorate(_classThis, null, _getDBNames_decorators, { kind: "method", name: "getDBNames", static: false, private: false, access: { has: obj => "getDBNames" in obj, get: obj => obj.getDBNames }, metadata: _metadata }, null, _instanceExtraInitializers);
634
+ __esDecorate(_classThis, null, _show_decorators, { kind: "method", name: "show", static: false, private: false, access: { has: obj => "show" in obj, get: obj => obj.show }, metadata: _metadata }, null, _instanceExtraInitializers);
635
+ __esDecorate(_classThis, null, _setReadPref_decorators, { kind: "method", name: "setReadPref", static: false, private: false, access: { has: obj => "setReadPref" in obj, get: obj => obj.setReadPref }, metadata: _metadata }, null, _instanceExtraInitializers);
636
+ __esDecorate(_classThis, null, _setReadConcern_decorators, { kind: "method", name: "setReadConcern", static: false, private: false, access: { has: obj => "setReadConcern" in obj, get: obj => obj.setReadConcern }, metadata: _metadata }, null, _instanceExtraInitializers);
637
+ __esDecorate(_classThis, null, _setWriteConcern_decorators, { kind: "method", name: "setWriteConcern", static: false, private: false, access: { has: obj => "setWriteConcern" in obj, get: obj => obj.setWriteConcern }, metadata: _metadata }, null, _instanceExtraInitializers);
638
+ __esDecorate(_classThis, null, _startSession_decorators, { kind: "method", name: "startSession", static: false, private: false, access: { has: obj => "startSession" in obj, get: obj => obj.startSession }, metadata: _metadata }, null, _instanceExtraInitializers);
639
+ __esDecorate(_classThis, null, _setSlaveOk_decorators, { kind: "method", name: "setSlaveOk", static: false, private: false, access: { has: obj => "setSlaveOk" in obj, get: obj => obj.setSlaveOk }, metadata: _metadata }, null, _instanceExtraInitializers);
640
+ __esDecorate(_classThis, null, _setSecondaryOk_decorators, { kind: "method", name: "setSecondaryOk", static: false, private: false, access: { has: obj => "setSecondaryOk" in obj, get: obj => obj.setSecondaryOk }, metadata: _metadata }, null, _instanceExtraInitializers);
641
+ __esDecorate(_classThis, null, _watch_decorators, { kind: "method", name: "watch", static: false, private: false, access: { has: obj => "watch" in obj, get: obj => obj.watch }, metadata: _metadata }, null, _instanceExtraInitializers);
642
+ __esDecorate(_classThis, null, _getClientEncryption_decorators, { kind: "method", name: "getClientEncryption", static: false, private: false, access: { has: obj => "getClientEncryption" in obj, get: obj => obj.getClientEncryption }, metadata: _metadata }, null, _instanceExtraInitializers);
643
+ __esDecorate(_classThis, null, _getKeyVault_decorators, { kind: "method", name: "getKeyVault", static: false, private: false, access: { has: obj => "getKeyVault" in obj, get: obj => obj.getKeyVault }, metadata: _metadata }, null, _instanceExtraInitializers);
644
+ __esDecorate(_classThis, null, _convertShardKeyToHashed_decorators, { kind: "method", name: "convertShardKeyToHashed", static: false, private: false, access: { has: obj => "convertShardKeyToHashed" in obj, get: obj => obj.convertShardKeyToHashed }, metadata: _metadata }, null, _instanceExtraInitializers);
645
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
646
+ Mongo = _classThis = _classDescriptor.value;
647
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
648
+ __runInitializers(_classThis, _classExtraInitializers);
649
+ })();
650
+ return Mongo = _classThis;
651
+ })();
618
652
  exports.default = Mongo;
619
653
  //# sourceMappingURL=mongo.js.map