333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var ConnectionIsNotSetError_1 = require("../../error/ConnectionIsNotSetError");
var DriverPackageNotInstalledError_1 = require("../../error/DriverPackageNotInstalledError");
var MongoQueryRunner_1 = require("./MongoQueryRunner");
var PlatformTools_1 = require("../../platform/PlatformTools");
var MongoSchemaBuilder_1 = require("../../schema-builder/MongoSchemaBuilder");
var ObjectUtils_1 = require("../../util/ObjectUtils");
var ApplyValueTransformers_1 = require("../../util/ApplyValueTransformers");
/**
 * Organizes communication with MongoDB.
 */
var MongoDriver = /** @class */ (function () {
    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------
    function MongoDriver(connection) {
        this.connection = connection;
        /**
         * Indicates if replication is enabled.
         */
        this.isReplicated = false;
        /**
         * Indicates if tree tables are supported by this driver.
         */
        this.treeSupport = false;
        /**
         * Mongodb does not need to have column types because they are not used in schema sync.
         */
        this.supportedDataTypes = [];
        /**
         * Gets list of spatial column data types.
         */
        this.spatialTypes = [];
        /**
         * Gets list of column data types that support length by a driver.
         */
        this.withLengthColumnTypes = [];
        /**
         * Gets list of column data types that support precision by a driver.
         */
        this.withPrecisionColumnTypes = [];
        /**
         * Gets list of column data types that support scale by a driver.
         */
        this.withScaleColumnTypes = [];
        /**
         * Mongodb does not need to have a strong defined mapped column types because they are not used in schema sync.
         */
        this.mappedDataTypes = {
            createDate: "int",
            createDateDefault: "",
            updateDate: "int",
            updateDateDefault: "",
            version: "int",
            treeLevel: "int",
            migrationId: "int",
            migrationName: "int",
            migrationTimestamp: "int",
            cacheId: "int",
            cacheIdentifier: "int",
            cacheTime: "int",
            cacheDuration: "int",
            cacheQuery: "int",
            cacheResult: "int",
            metadataType: "int",
            metadataDatabase: "int",
            metadataSchema: "int",
            metadataTable: "int",
            metadataName: "int",
            metadataValue: "int",
        };
        // -------------------------------------------------------------------------
        // Protected Properties
        // -------------------------------------------------------------------------
        /**
         * Valid mongo connection options
         * NOTE: Keep sync with MongoConnectionOptions
         * Sync with http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html
         */
        this.validOptionNames = [
            "poolSize",
            "ssl",
            "sslValidate",
            "sslCA",
            "sslCert",
            "sslKey",
            "sslPass",
            "sslCRL",
            "autoReconnect",
            "noDelay",
            "keepAlive",
            "keepAliveInitialDelay",
            "connectTimeoutMS",
            "family",
            "socketTimeoutMS",
            "reconnectTries",
            "reconnectInterval",
            "ha",
            "haInterval",
            "replicaSet",
            "secondaryAcceptableLatencyMS",
            "acceptableLatencyMS",
            "connectWithNoPrimary",
            "authSource",
            "w",
            "wtimeout",
            "j",
            "forceServerObjectId",
            "serializeFunctions",
            "ignoreUndefined",
            "raw",
            "bufferMaxEntries",
            "readPreference",
            "pkFactory",
            "promiseLibrary",
            "readConcern",
            "maxStalenessSeconds",
            "loggerLevel",
            // Do not overwrite BaseConnectionOptions.logger
            // "logger",
            "promoteValues",
            "promoteBuffers",
            "promoteLongs",
            "domainsEnabled",
            "checkServerIdentity",
            "validateOptions",
            "appname",
            // omit auth - we are building url from username and password
            // "auth"
            "authMechanism",
            "compression",
            "fsync",
            "readPreferenceTags",
            "numberOfRetries",
            "auto_reconnect",
            "minSize",
            "monitorCommands",
            "useNewUrlParser"
        ];
        this.options = connection.options;
        // validate options to make sure everything is correct and driver will be able to establish connection
        this.validateOptions(connection.options);
        // load mongodb package
        this.loadDependencies();
    }
    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------
    /**
     * Performs connection to the database.
     */
    MongoDriver.prototype.connect = function () {
        var _this = this;
        return new Promise(function (ok, fail) {
            _this.mongodb.MongoClient.connect(_this.buildConnectionUrl(), _this.buildConnectionOptions(), function (err, client) {
                if (err)
                    return fail(err);
                _this.queryRunner = new MongoQueryRunner_1.MongoQueryRunner(_this.connection, client);
                ObjectUtils_1.ObjectUtils.assign(_this.queryRunner, { manager: _this.connection.manager });
                ok();
            });
        });
    };
    MongoDriver.prototype.afterConnect = function () {
        return Promise.resolve();
    };
    /**
     * Closes connection with the database.
     */
    MongoDriver.prototype.disconnect = function () {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var _this = this;
            return tslib_1.__generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (ok, fail) {
                        if (!_this.queryRunner)
                            return fail(new ConnectionIsNotSetError_1.ConnectionIsNotSetError("mongodb"));
                        var handler = function (err) { return err ? fail(err) : ok(); };
                        _this.queryRunner.databaseConnection.close(handler);
                        _this.queryRunner = undefined;
                    })];
            });
        });
    };
    /**
     * Creates a schema builder used to build and sync a schema.
     */
    MongoDriver.prototype.createSchemaBuilder = function () {
        return new MongoSchemaBuilder_1.MongoSchemaBuilder(this.connection);
    };
    /**
     * Creates a query runner used to execute database queries.
     */
    MongoDriver.prototype.createQueryRunner = function (mode) {
        if (mode === void 0) { mode = "master"; }
        return this.queryRunner;
    };
    /**
     * Replaces parameters in the given sql with special escaping character
     * and an array of parameter names to be passed to a query.
     */
    MongoDriver.prototype.escapeQueryWithParameters = function (sql, parameters, nativeParameters) {
        throw new Error("This operation is not supported by Mongodb driver.");
    };
    /**
     * Escapes a column name.
     */
    MongoDriver.prototype.escape = function (columnName) {
        return columnName;
    };
    /**
     * Build full table name with database name, schema name and table name.
     * E.g. "myDB"."mySchema"."myTable"
     */
    MongoDriver.prototype.buildTableName = function (tableName, schema, database) {
        return tableName;
    };
    /**
     * Prepares given value to a value to be persisted, based on its column type and metadata.
     */
    MongoDriver.prototype.preparePersistentValue = function (value, columnMetadata) {
        if (columnMetadata.transformer)
            value = ApplyValueTransformers_1.ApplyValueTransformers.transformTo(columnMetadata.transformer, value);
        return value;
    };
    /**
     * Prepares given value to a value to be persisted, based on its column type or metadata.
     */
    MongoDriver.prototype.prepareHydratedValue = function (value, columnMetadata) {
        if (columnMetadata.transformer)
            value = ApplyValueTransformers_1.ApplyValueTransformers.transformFrom(columnMetadata.transformer, value);
        return value;
    };
    /**
     * Creates a database type from a given column metadata.
     */
    MongoDriver.prototype.normalizeType = function (column) {
        throw new Error("MongoDB is schema-less, not supported by this driver.");
    };
    /**
     * Normalizes "default" value of the column.
     */
    MongoDriver.prototype.normalizeDefault = function (columnMetadata) {
        throw new Error("MongoDB is schema-less, not supported by this driver.");
    };
    /**
     * Normalizes "isUnique" value of the column.
     */
    MongoDriver.prototype.normalizeIsUnique = function (column) {
        throw new Error("MongoDB is schema-less, not supported by this driver.");
    };
    /**
     * Calculates column length taking into account the default length values.
     */
    MongoDriver.prototype.getColumnLength = function (column) {
        throw new Error("MongoDB is schema-less, not supported by this driver.");
    };
    /**
     * Normalizes "default" value of the column.
     */
    MongoDriver.prototype.createFullType = function (column) {
        throw new Error("MongoDB is schema-less, not supported by this driver.");
    };
    /**
     * Obtains a new database connection to a master server.
     * Used for replication.
     * If replication is not setup then returns default connection's database connection.
     */
    MongoDriver.prototype.obtainMasterConnection = function () {
        return Promise.resolve();
    };
    /**
     * Obtains a new database connection to a slave server.
     * Used for replication.
     * If replication is not setup then returns master (default) connection's database connection.
     */
    MongoDriver.prototype.obtainSlaveConnection = function () {
        return Promise.resolve();
    };
    /**
     * Creates generated map of values generated or returned by database after INSERT query.
     */
    MongoDriver.prototype.createGeneratedMap = function (metadata, insertedId) {
        return metadata.objectIdColumn.createValueMap(insertedId);
    };
    /**
     * Differentiate columns of this table and columns from the given column metadatas columns
     * and returns only changed.
     */
    MongoDriver.prototype.findChangedColumns = function (tableColumns, columnMetadatas) {
        throw new Error("MongoDB is schema-less, not supported by this driver.");
    };
    /**
     * Returns true if driver supports RETURNING / OUTPUT statement.
     */
    MongoDriver.prototype.isReturningSqlSupported = function () {
        return false;
    };
    /**
     * Returns true if driver supports uuid values generation on its own.
     */
    MongoDriver.prototype.isUUIDGenerationSupported = function () {
        return false;
    };
    /**
     * Creates an escaped parameter.
     */
    MongoDriver.prototype.createParameter = function (parameterName, index) {
        return "";
    };
    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------
    /**
     * Validate driver options to make sure everything is correct and driver will be able to establish connection.
     */
    MongoDriver.prototype.validateOptions = function (options) {
        // if (!options.url) {
        //     if (!options.database)
        //         throw new DriverOptionNotSetError("database");
        // }
    };
    /**
     * Loads all driver dependencies.
     */
    MongoDriver.prototype.loadDependencies = function () {
        try {
            this.mongodb = PlatformTools_1.PlatformTools.load("mongodb"); // try to load native driver dynamically
        }
        catch (e) {
            throw new DriverPackageNotInstalledError_1.DriverPackageNotInstalledError("MongoDB", "mongodb");
        }
    };
    /**
     * Builds connection url that is passed to underlying driver to perform connection to the mongodb database.
     */
    MongoDriver.prototype.buildConnectionUrl = function () {
        if (this.options.url)
            return this.options.url;
        var credentialsUrlPart = (this.options.username && this.options.password)
            ? this.options.username + ":" + this.options.password + "@"
            : "";
        return "mongodb://" + credentialsUrlPart + (this.options.host || "127.0.0.1") + ":" + (this.options.port || "27017") + "/" + this.options.database;
    };
    /**
     * Build connection options from MongoConnectionOptions
     */
    MongoDriver.prototype.buildConnectionOptions = function () {
        var mongoOptions = {};
        for (var index = 0; index < this.validOptionNames.length; index++) {
            var optionName = this.validOptionNames[index];
            if (this.options.extra && optionName in this.options.extra) {
                mongoOptions[optionName] = this.options.extra[optionName];
            }
            else if (optionName in this.options) {
                mongoOptions[optionName] = this.options[optionName];
            }
        }
        return mongoOptions;
    };
    return MongoDriver;
}());
exports.MongoDriver = MongoDriver;
 
//# sourceMappingURL=MongoDriver.js.map