UNPKG

52.5 kBJavaScriptView Raw
1'use strict';
2
3const url = require('url');
4const path = require('path');
5const retry = require('retry-as-promised');
6const clsBluebird = require('cls-bluebird');
7const _ = require('lodash');
8
9const Utils = require('./utils');
10const Model = require('./model');
11const DataTypes = require('./data-types');
12const Deferrable = require('./deferrable');
13const ModelManager = require('./model-manager');
14const QueryInterface = require('./query-interface');
15const Transaction = require('./transaction');
16const QueryTypes = require('./query-types');
17const TableHints = require('./table-hints');
18const IndexHints = require('./index-hints');
19const sequelizeErrors = require('./errors');
20const Promise = require('./promise');
21const Hooks = require('./hooks');
22const Association = require('./associations/index');
23const Validator = require('./utils/validator-extras').validator;
24const Op = require('./operators');
25const deprecations = require('./utils/deprecations');
26
27/**
28 * This is the main class, the entry point to sequelize.
29 */
30class Sequelize {
31 /**
32 * Instantiate sequelize with name of database, username and password.
33 *
34 * @example
35 * // without password / with blank password
36 * const sequelize = new Sequelize('database', 'username', null, {
37 * dialect: 'mysql'
38 * })
39 *
40 * // with password and options
41 * const sequelize = new Sequelize('my_database', 'john', 'doe', {
42 * dialect: 'postgres'
43 * })
44 *
45 * // with database, username, and password in the options object
46 * const sequelize = new Sequelize({ database, username, password, dialect: 'mssql' });
47 *
48 * // with uri
49 * const sequelize = new Sequelize('mysql://localhost:3306/database', {})
50 *
51 * // option examples
52 * const sequelize = new Sequelize('database', 'username', 'password', {
53 * // the sql dialect of the database
54 * // currently supported: 'mysql', 'sqlite', 'postgres', 'mssql'
55 * dialect: 'mysql',
56 *
57 * // custom host; default: localhost
58 * host: 'my.server.tld',
59 * // for postgres, you can also specify an absolute path to a directory
60 * // containing a UNIX socket to connect over
61 * // host: '/sockets/psql_sockets'.
62 *
63 * // custom port; default: dialect default
64 * port: 12345,
65 *
66 * // custom protocol; default: 'tcp'
67 * // postgres only, useful for Heroku
68 * protocol: null,
69 *
70 * // disable logging or provide a custom logging function; default: console.log
71 * logging: false,
72 *
73 * // you can also pass any dialect options to the underlying dialect library
74 * // - default is empty
75 * // - currently supported: 'mysql', 'postgres', 'mssql'
76 * dialectOptions: {
77 * socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock',
78 * supportBigNumbers: true,
79 * bigNumberStrings: true
80 * },
81 *
82 * // the storage engine for sqlite
83 * // - default ':memory:'
84 * storage: 'path/to/database.sqlite',
85 *
86 * // disable inserting undefined values as NULL
87 * // - default: false
88 * omitNull: true,
89 *
90 * // a flag for using a native library or not.
91 * // in the case of 'pg' -- set this to true will allow SSL support
92 * // - default: false
93 * native: true,
94 *
95 * // Specify options, which are used when sequelize.define is called.
96 * // The following example:
97 * // define: { timestamps: false }
98 * // is basically the same as:
99 * // Model.init(attributes, { timestamps: false });
100 * // sequelize.define(name, attributes, { timestamps: false });
101 * // so defining the timestamps for each model will be not necessary
102 * define: {
103 * underscored: false,
104 * freezeTableName: false,
105 * charset: 'utf8',
106 * dialectOptions: {
107 * collate: 'utf8_general_ci'
108 * },
109 * timestamps: true
110 * },
111 *
112 * // similar for sync: you can define this to always force sync for models
113 * sync: { force: true },
114 *
115 * // pool configuration used to pool database connections
116 * pool: {
117 * max: 5,
118 * idle: 30000,
119 * acquire: 60000,
120 * },
121 *
122 * // isolation level of each transaction
123 * // defaults to dialect default
124 * isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ
125 * })
126 *
127 * @param {string} [database] The name of the database
128 * @param {string} [username=null] The username which is used to authenticate against the database.
129 * @param {string} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.
130 * @param {Object} [options={}] An object with options.
131 * @param {string} [options.host='localhost'] The host of the relational database.
132 * @param {number} [options.port=] The port of the relational database.
133 * @param {string} [options.username=null] The username which is used to authenticate against the database.
134 * @param {string} [options.password=null] The password which is used to authenticate against the database.
135 * @param {string} [options.database=null] The name of the database
136 * @param {string} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.
137 * @param {string} [options.dialectModule=null] If specified, use this dialect library. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'require("pg.js")' here
138 * @param {string} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify '/path/to/pg.js' here
139 * @param {Object} [options.dialectOptions] An object of additional options, which are passed directly to the connection library
140 * @param {string} [options.storage] Only used by sqlite. Defaults to ':memory:'
141 * @param {string} [options.protocol='tcp'] The protocol of the relational database.
142 * @param {Object} [options.define={}] Default options for model definitions. See {@link Model.init}.
143 * @param {Object} [options.query={}] Default options for sequelize.query
144 * @param {string} [options.schema=null] A schema to use
145 * @param {Object} [options.set={}] Default options for sequelize.set
146 * @param {Object} [options.sync={}] Default options for sequelize.sync
147 * @param {string} [options.timezone='+00:00'] The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.
148 * @param {string|boolean} [options.clientMinMessages='warning'] The PostgreSQL `client_min_messages` session parameter. Set to `false` to not override the database's default.
149 * @param {boolean} [options.standardConformingStrings=true] The PostgreSQL `standard_conforming_strings` session parameter. Set to `false` to not set the option. WARNING: Setting this to false may expose vulnerabilities and is not recommended!
150 * @param {Function} [options.logging=console.log] A function that gets executed every time Sequelize would log something.
151 * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
152 * @param {boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
153 * @param {boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres
154 * @param {boolean} [options.replication=false] Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: `host`, `port`, `username`, `password`, `database`
155 * @param {Object} [options.pool] sequelize connection pool configuration
156 * @param {number} [options.pool.max=5] Maximum number of connection in pool
157 * @param {number} [options.pool.min=0] Minimum number of connection in pool
158 * @param {number} [options.pool.idle=10000] The maximum time, in milliseconds, that a connection can be idle before being released.
159 * @param {number} [options.pool.acquire=60000] The maximum time, in milliseconds, that pool will try to get connection before throwing error
160 * @param {number} [options.pool.evict=1000] The time interval, in milliseconds, after which sequelize-pool will remove idle connections.
161 * @param {Function} [options.pool.validate] A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
162 * @param {boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!
163 * @param {string} [options.transactionType='DEFERRED'] Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
164 * @param {string} [options.isolationLevel] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
165 * @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
166 * @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
167 * @param {number} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
168 * @param {boolean} [options.typeValidation=false] Run built-in type validators on insert and update, and select with where clause, e.g. validate that arguments passed to integer fields are integer-like.
169 * @param {Object} [options.operatorsAliases] String based operator alias. Pass object to limit set of aliased operators.
170 * @param {Object} [options.hooks] An object of global hook functions that are called before and after certain lifecycle events. Global hooks will run after any model-specific hooks defined for the same event (See `Sequelize.Model.init()` for a list). Additionally, `beforeConnect()`, `afterConnect()`, `beforeDisconnect()`, and `afterDisconnect()` hooks may be defined here.
171 * @param {boolean} [options.minifyAliases=false] A flag that defines if aliases should be minified (mostly useful to avoid Postgres alias character limit of 64)
172 * @param {boolean} [options.logQueryParameters=false] A flag that defines if show bind patameters in log.
173 */
174 constructor(database, username, password, options) {
175 let config;
176
177 if (arguments.length === 1 && typeof database === 'object') {
178 // new Sequelize({ ... options })
179 options = database;
180 config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
181 } else if (arguments.length === 1 && typeof database === 'string' || arguments.length === 2 && typeof username === 'object') {
182 // new Sequelize(URI, { ... options })
183
184 config = {};
185 options = username || {};
186
187 const urlParts = url.parse(arguments[0], true);
188
189 options.dialect = urlParts.protocol.replace(/:$/, '');
190 options.host = urlParts.hostname;
191
192 if (options.dialect === 'sqlite' && urlParts.pathname && !urlParts.pathname.startsWith('/:memory')) {
193 const storagePath = path.join(options.host, urlParts.pathname);
194 options.storage = path.resolve(options.storage || storagePath);
195 }
196
197 if (urlParts.pathname) {
198 config.database = urlParts.pathname.replace(/^\//, '');
199 }
200
201 if (urlParts.port) {
202 options.port = urlParts.port;
203 }
204
205 if (urlParts.auth) {
206 const authParts = urlParts.auth.split(':');
207
208 config.username = authParts[0];
209
210 if (authParts.length > 1)
211 config.password = authParts.slice(1).join(':');
212 }
213
214 if (urlParts.query) {
215 if (options.dialectOptions)
216 Object.assign(options.dialectOptions, urlParts.query);
217 else
218 options.dialectOptions = urlParts.query;
219 }
220 } else {
221 // new Sequelize(database, username, password, { ... options })
222 options = options || {};
223 config = { database, username, password };
224 }
225
226 Sequelize.runHooks('beforeInit', config, options);
227
228 this.options = Object.assign({
229 dialect: null,
230 dialectModule: null,
231 dialectModulePath: null,
232 host: 'localhost',
233 protocol: 'tcp',
234 define: {},
235 query: {},
236 sync: {},
237 timezone: '+00:00',
238 clientMinMessages: 'warning',
239 standardConformingStrings: true,
240 // eslint-disable-next-line no-console
241 logging: console.log,
242 omitNull: false,
243 native: false,
244 replication: false,
245 ssl: undefined,
246 pool: {},
247 quoteIdentifiers: true,
248 hooks: {},
249 retry: {
250 max: 5,
251 match: [
252 'SQLITE_BUSY: database is locked'
253 ]
254 },
255 transactionType: Transaction.TYPES.DEFERRED,
256 isolationLevel: null,
257 databaseVersion: 0,
258 typeValidation: false,
259 benchmark: false,
260 minifyAliases: false,
261 logQueryParameters: false
262 }, options || {});
263
264 if (!this.options.dialect) {
265 throw new Error('Dialect needs to be explicitly supplied as of v4.0.0');
266 }
267
268 if (this.options.dialect === 'postgresql') {
269 this.options.dialect = 'postgres';
270 }
271
272 if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
273 throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom timezone parameter.');
274 }
275
276 if (this.options.logging === true) {
277 deprecations.noTrueLogging();
278 // eslint-disable-next-line no-console
279 this.options.logging = console.log;
280 }
281
282 this._setupHooks(options.hooks);
283
284 this.config = {
285 database: config.database || this.options.database,
286 username: config.username || this.options.username,
287 password: config.password || this.options.password || null,
288 host: config.host || this.options.host,
289 port: config.port || this.options.port,
290 pool: this.options.pool,
291 protocol: this.options.protocol,
292 native: this.options.native,
293 ssl: this.options.ssl,
294 replication: this.options.replication,
295 dialectModule: this.options.dialectModule,
296 dialectModulePath: this.options.dialectModulePath,
297 keepDefaultTimezone: this.options.keepDefaultTimezone,
298 dialectOptions: this.options.dialectOptions
299 };
300
301 let Dialect;
302 // Requiring the dialect in a switch-case to keep the
303 // require calls static. (Browserify fix)
304 switch (this.getDialect()) {
305 case 'mariadb':
306 Dialect = require('./dialects/mariadb');
307 break;
308 case 'mssql':
309 Dialect = require('./dialects/mssql');
310 break;
311 case 'mysql':
312 Dialect = require('./dialects/mysql');
313 break;
314 case 'postgres':
315 Dialect = require('./dialects/postgres');
316 break;
317 case 'sqlite':
318 Dialect = require('./dialects/sqlite');
319 break;
320 default:
321 throw new Error(`The dialect ${this.getDialect()} is not supported. Supported dialects: mssql, mariadb, mysql, postgres, and sqlite.`);
322 }
323
324 this.dialect = new Dialect(this);
325 this.dialect.QueryGenerator.typeValidation = options.typeValidation;
326
327 if (_.isPlainObject(this.options.operatorsAliases)) {
328 deprecations.noStringOperators();
329 this.dialect.QueryGenerator.setOperatorsAliases(this.options.operatorsAliases);
330 } else if (typeof this.options.operatorsAliases === 'boolean') {
331 deprecations.noBoolOperatorAliases();
332 }
333
334 this.queryInterface = new QueryInterface(this);
335
336 /**
337 * Models are stored here under the name given to `sequelize.define`
338 */
339 this.models = {};
340 this.modelManager = new ModelManager(this);
341 this.connectionManager = this.dialect.connectionManager;
342
343 this.importCache = {};
344
345 Sequelize.runHooks('afterInit', this);
346 }
347
348 /**
349 * Refresh data types and parsers.
350 *
351 * @private
352 */
353 refreshTypes() {
354 this.connectionManager.refreshTypeParser(DataTypes);
355 }
356
357 /**
358 * Returns the specified dialect.
359 *
360 * @returns {string} The specified dialect.
361 */
362 getDialect() {
363 return this.options.dialect;
364 }
365
366 /**
367 * Returns the database name.
368 *
369 * @returns {string} The database name.
370 */
371 getDatabaseName() {
372 return this.config.database;
373 }
374
375 /**
376 * Returns an instance of QueryInterface.
377 *
378 * @returns {QueryInterface} An instance (singleton) of QueryInterface.
379 */
380 getQueryInterface() {
381 this.queryInterface = this.queryInterface || new QueryInterface(this);
382 return this.queryInterface;
383 }
384
385 /**
386 * Define a new model, representing a table in the database.
387 *
388 * The table columns are defined by the object that is given as the second argument. Each key of the object represents a column
389 *
390 * @param {string} modelName The name of the model. The model will be stored in `sequelize.models` under this name
391 * @param {Object} attributes An object, where each attribute is a column of the table. See {@link Model.init}
392 * @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init()
393 *
394 * @see
395 * {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects.
396 * @see <a href="/manual/tutorial/models-definition.html">Model definition</a> Manual related to model definition
397 * @see
398 * {@link DataTypes} For a list of possible data types
399 *
400 * @returns {Model} Newly defined model
401 *
402 * @example
403 * sequelize.define('modelName', {
404 * columnA: {
405 * type: Sequelize.BOOLEAN,
406 * validate: {
407 * is: ["[a-z]",'i'], // will only allow letters
408 * max: 23, // only allow values <= 23
409 * isIn: {
410 * args: [['en', 'zh']],
411 * msg: "Must be English or Chinese"
412 * }
413 * },
414 * field: 'column_a'
415 * },
416 * columnB: Sequelize.STRING,
417 * columnC: 'MY VERY OWN COLUMN TYPE'
418 * });
419 *
420 * sequelize.models.modelName // The model will now be available in models under the name given to define
421 */
422 define(modelName, attributes, options = {}) {
423 options.modelName = modelName;
424 options.sequelize = this;
425
426 const model = class extends Model {};
427
428 model.init(attributes, options);
429
430 return model;
431 }
432
433 /**
434 * Fetch a Model which is already defined
435 *
436 * @param {string} modelName The name of a model defined with Sequelize.define
437 *
438 * @throws Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false)
439 * @returns {Model} Specified model
440 */
441 model(modelName) {
442 if (!this.isDefined(modelName)) {
443 throw new Error(`${modelName} has not been defined`);
444 }
445
446 return this.modelManager.getModel(modelName);
447 }
448
449 /**
450 * Checks whether a model with the given name is defined
451 *
452 * @param {string} modelName The name of a model defined with Sequelize.define
453 *
454 * @returns {boolean} Returns true if model is already defined, otherwise false
455 */
456 isDefined(modelName) {
457 return !!this.modelManager.models.find(model => model.name === modelName);
458 }
459
460 /**
461 * Imports a model defined in another file. Imported models are cached, so multiple
462 * calls to import with the same path will not load the file multiple times.
463 *
464 * @tutorial https://github.com/sequelize/express-example
465 *
466 * @param {string} importPath The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
467 *
468 * @returns {Model} Imported model, returned from cache if was already imported
469 */
470 import(importPath) {
471 // is it a relative path?
472 if (path.normalize(importPath) !== path.resolve(importPath)) {
473 // make path relative to the caller
474 const callerFilename = Utils.stack()[1].getFileName();
475 const callerPath = path.dirname(callerFilename);
476
477 importPath = path.resolve(callerPath, importPath);
478 }
479
480 if (!this.importCache[importPath]) {
481 let defineCall = arguments.length > 1 ? arguments[1] : require(importPath);
482 if (typeof defineCall === 'object') {
483 // ES6 module compatibility
484 defineCall = defineCall.default;
485 }
486 this.importCache[importPath] = defineCall(this, DataTypes);
487 }
488
489 return this.importCache[importPath];
490 }
491
492 /**
493 * Execute a query on the DB, optionally bypassing all the Sequelize goodness.
494 *
495 * By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc.
496 *
497 * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results:
498 *
499 * ```js
500 * sequelize.query('SELECT...').then(([results, metadata]) => {
501 * // Raw query - use then plus array spread
502 * });
503 *
504 * sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => {
505 * // SELECT query - use then
506 * })
507 * ```
508 *
509 * @param {string} sql
510 * @param {Object} [options={}] Query options.
511 * @param {boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
512 * @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
513 * @param {QueryTypes} [options.type='RAW'] The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
514 * @param {boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
515 * @param {boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
516 * @param {Object|Array} [options.replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
517 * @param {Object|Array} [options.bind] Either an object of named bind parameter in the format `_param` or an array of unnamed bind parameter to replace `$1, $2, ...` in your SQL.
518 * @param {boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.
519 * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
520 * @param {new Model()} [options.instance] A sequelize instance used to build the return instance
521 * @param {Model} [options.model] A sequelize model used to build the returned model instances (used to be called callee)
522 * @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
523 * @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
524 * @param {Integer} [options.retry.max] How many times a failing query is automatically retried.
525 * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
526 * @param {boolean} [options.supportsSearchPath] If false do not prepend the query with the search_path (Postgres only)
527 * @param {boolean} [options.mapToModel=false] Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance.
528 * @param {Object} [options.fieldMap] Map returned fields to arbitrary names for `SELECT` query type.
529 *
530 * @returns {Promise}
531 *
532 * @see {@link Model.build} for more information about instance option.
533 */
534
535 query(sql, options) {
536 options = Object.assign({}, this.options.query, options);
537
538 if (options.instance && !options.model) {
539 options.model = options.instance.constructor;
540 }
541
542 if (!options.instance && !options.model) {
543 options.raw = true;
544 }
545
546 // map raw fields to model attributes
547 if (options.mapToModel) {
548 options.fieldMap = _.get(options, 'model.fieldAttributeMap', {});
549 }
550
551 options = _.defaults(options, {
552 // eslint-disable-next-line no-console
553 logging: Object.prototype.hasOwnProperty.call(this.options, 'logging') ? this.options.logging : console.log,
554 searchPath: Object.prototype.hasOwnProperty.call(this.options, 'searchPath') ? this.options.searchPath : 'DEFAULT'
555 });
556
557 if (!options.type) {
558 if (options.model || options.nest || options.plain) {
559 options.type = QueryTypes.SELECT;
560 } else {
561 options.type = QueryTypes.RAW;
562 }
563 }
564
565 //if dialect doesn't support search_path or dialect option
566 //to prepend searchPath is not true delete the searchPath option
567 if (
568 !this.dialect.supports.searchPath ||
569 !this.options.dialectOptions ||
570 !this.options.dialectOptions.prependSearchPath ||
571 options.supportsSearchPath === false
572 ) {
573 delete options.searchPath;
574 } else if (!options.searchPath) {
575 //if user wants to always prepend searchPath (dialectOptions.preprendSearchPath = true)
576 //then set to DEFAULT if none is provided
577 options.searchPath = 'DEFAULT';
578 }
579
580 return Promise.try(() => {
581 if (typeof sql === 'object') {
582 if (sql.values !== undefined) {
583 if (options.replacements !== undefined) {
584 throw new Error('Both `sql.values` and `options.replacements` cannot be set at the same time');
585 }
586 options.replacements = sql.values;
587 }
588
589 if (sql.bind !== undefined) {
590 if (options.bind !== undefined) {
591 throw new Error('Both `sql.bind` and `options.bind` cannot be set at the same time');
592 }
593 options.bind = sql.bind;
594 }
595
596 if (sql.query !== undefined) {
597 sql = sql.query;
598 }
599 }
600
601 sql = sql.trim();
602
603 if (options.replacements && options.bind) {
604 throw new Error('Both `replacements` and `bind` cannot be set at the same time');
605 }
606
607 if (options.replacements) {
608 if (Array.isArray(options.replacements)) {
609 sql = Utils.format([sql].concat(options.replacements), this.options.dialect);
610 } else {
611 sql = Utils.formatNamedParameters(sql, options.replacements, this.options.dialect);
612 }
613 }
614
615 let bindParameters;
616
617 if (options.bind) {
618 [sql, bindParameters] = this.dialect.Query.formatBindParameters(sql, options.bind, this.options.dialect);
619 }
620
621 const checkTransaction = () => {
622 if (options.transaction && options.transaction.finished && !options.completesTransaction) {
623 const error = new Error(`${options.transaction.finished} has been called on this transaction(${options.transaction.id}), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)`);
624 error.sql = sql;
625 throw error;
626 }
627 };
628
629 const retryOptions = Object.assign({}, this.options.retry, options.retry || {});
630
631 return Promise.resolve(retry(() => Promise.try(() => {
632 if (options.transaction === undefined && Sequelize._cls) {
633 options.transaction = Sequelize._cls.get('transaction');
634 }
635
636 checkTransaction();
637
638 return options.transaction
639 ? options.transaction.connection
640 : this.connectionManager.getConnection(options);
641 }).then(connection => {
642 const query = new this.dialect.Query(connection, this, options);
643 return this.runHooks('beforeQuery', options, query)
644 .then(() => checkTransaction())
645 .then(() => query.run(sql, bindParameters))
646 .finally(() => this.runHooks('afterQuery', options, query))
647 .finally(() => {
648 if (!options.transaction) {
649 return this.connectionManager.releaseConnection(connection);
650 }
651 });
652 }), retryOptions));
653 });
654 }
655
656 /**
657 * Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
658 * Only works for MySQL.
659 *
660 * @param {Object} variables Object with multiple variables.
661 * @param {Object} [options] query options.
662 * @param {Transaction} [options.transaction] The transaction that the query should be executed under
663 *
664 * @memberof Sequelize
665 *
666 * @returns {Promise}
667 */
668 set(variables, options) {
669
670 // Prepare options
671 options = Object.assign({}, this.options.set, typeof options === 'object' && options);
672
673 if (this.options.dialect !== 'mysql') {
674 throw new Error('sequelize.set is only supported for mysql');
675 }
676 if (!options.transaction || !(options.transaction instanceof Transaction) ) {
677 throw new TypeError('options.transaction is required');
678 }
679
680 // Override some options, since this isn't a SELECT
681 options.raw = true;
682 options.plain = true;
683 options.type = 'SET';
684
685 // Generate SQL Query
686 const query =
687 `SET ${
688 _.map(variables, (v, k) => `@${k} := ${typeof v === 'string' ? `"${v}"` : v}`).join(', ')}`;
689
690 return this.query(query, options);
691 }
692
693 /**
694 * Escape value.
695 *
696 * @param {string} value string value to escape
697 *
698 * @returns {string}
699 */
700 escape(value) {
701 return this.getQueryInterface().escape(value);
702 }
703
704 /**
705 * Create a new database schema.
706 *
707 * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
708 * not a database table. In mysql and sqlite, this command will do nothing.
709 *
710 * @see
711 * {@link Model.schema}
712 *
713 * @param {string} schema Name of the schema
714 * @param {Object} [options={}] query options
715 * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
716 *
717 * @returns {Promise}
718 */
719 createSchema(schema, options) {
720 return this.getQueryInterface().createSchema(schema, options);
721 }
722
723 /**
724 * Show all defined schemas
725 *
726 * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
727 * not a database table. In mysql and sqlite, this will show all tables.
728 *
729 * @param {Object} [options={}] query options
730 * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
731 *
732 * @returns {Promise}
733 */
734 showAllSchemas(options) {
735 return this.getQueryInterface().showAllSchemas(options);
736 }
737
738 /**
739 * Drop a single schema
740 *
741 * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
742 * not a database table. In mysql and sqlite, this drop a table matching the schema name
743 *
744 * @param {string} schema Name of the schema
745 * @param {Object} [options={}] query options
746 * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
747 *
748 * @returns {Promise}
749 */
750 dropSchema(schema, options) {
751 return this.getQueryInterface().dropSchema(schema, options);
752 }
753
754 /**
755 * Drop all schemas.
756 *
757 * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
758 * not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
759 *
760 * @param {Object} [options={}] query options
761 * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
762 *
763 * @returns {Promise}
764 */
765 dropAllSchemas(options) {
766 return this.getQueryInterface().dropAllSchemas(options);
767 }
768
769 /**
770 * Sync all defined models to the DB.
771 *
772 * @param {Object} [options={}] sync options
773 * @param {boolean} [options.force=false] If force is true, each Model will run `DROP TABLE IF EXISTS`, before it tries to create its own table
774 * @param {RegExp} [options.match] Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code
775 * @param {boolean|Function} [options.logging=console.log] A function that logs sql queries, or false for no logging
776 * @param {string} [options.schema='public'] The schema that the tables should be created in. This can be overridden for each table in sequelize.define
777 * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
778 * @param {boolean} [options.hooks=true] If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called
779 * @param {boolean} [options.alter=false] Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model.
780 *
781 * @returns {Promise}
782 */
783 sync(options) {
784 options = _.clone(options) || {};
785 options.hooks = options.hooks === undefined ? true : !!options.hooks;
786 options = _.defaults(options, this.options.sync, this.options);
787
788 if (options.match) {
789 if (!options.match.test(this.config.database)) {
790 return Promise.reject(new Error(`Database "${this.config.database}" does not match sync match parameter "${options.match}"`));
791 }
792 }
793
794 return Promise.try(() => {
795 if (options.hooks) {
796 return this.runHooks('beforeBulkSync', options);
797 }
798 }).then(() => {
799 if (options.force) {
800 return this.drop(options);
801 }
802 }).then(() => {
803 const models = [];
804
805 // Topologically sort by foreign key constraints to give us an appropriate
806 // creation order
807 this.modelManager.forEachModel(model => {
808 if (model) {
809 models.push(model);
810 } else {
811 // DB should throw an SQL error if referencing non-existent table
812 }
813 });
814
815 // no models defined, just authenticate
816 if (!models.length) return this.authenticate(options);
817
818 return Promise.each(models, model => model.sync(options));
819 }).then(() => {
820 if (options.hooks) {
821 return this.runHooks('afterBulkSync', options);
822 }
823 }).return(this);
824 }
825
826 /**
827 * Truncate all tables defined through the sequelize models.
828 * This is done by calling `Model.truncate()` on each model.
829 *
830 * @param {Object} [options] The options passed to Model.destroy in addition to truncate
831 * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
832 * @returns {Promise}
833 *
834 * @see
835 * {@link Model.truncate} for more information
836 */
837 truncate(options) {
838 const models = [];
839
840 this.modelManager.forEachModel(model => {
841 if (model) {
842 models.push(model);
843 }
844 }, { reverse: false });
845
846 const truncateModel = model => model.truncate(options);
847
848 if (options && options.cascade) {
849 return Promise.each(models, truncateModel);
850 }
851 return Promise.map(models, truncateModel);
852 }
853
854 /**
855 * Drop all tables defined through this sequelize instance.
856 * This is done by calling Model.drop on each model.
857 *
858 * @see
859 * {@link Model.drop} for options
860 *
861 * @param {Object} [options] The options passed to each call to Model.drop
862 * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
863 *
864 * @returns {Promise}
865 */
866 drop(options) {
867 const models = [];
868
869 this.modelManager.forEachModel(model => {
870 if (model) {
871 models.push(model);
872 }
873 }, { reverse: false });
874
875 return Promise.each(models, model => model.drop(options));
876 }
877
878 /**
879 * Test the connection by trying to authenticate. It runs `SELECT 1+1 AS result` query.
880 *
881 * @param {Object} [options={}] query options
882 *
883 * @returns {Promise}
884 */
885 authenticate(options) {
886 options = Object.assign({
887 raw: true,
888 plain: true,
889 type: QueryTypes.SELECT
890 }, options);
891
892 return this.query('SELECT 1+1 AS result', options).return();
893 }
894
895 databaseVersion(options) {
896 return this.getQueryInterface().databaseVersion(options);
897 }
898
899 /**
900 * Get the fn for random based on the dialect
901 *
902 * @returns {Sequelize.fn}
903 */
904 random() {
905 const dia = this.getDialect();
906 if (dia === 'postgres' || dia === 'sqlite') {
907 return this.fn('RANDOM');
908 }
909 return this.fn('RAND');
910 }
911
912 /**
913 * Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
914 * If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings.
915 *
916 * @see
917 * {@link Model.findAll}
918 * @see
919 * {@link Sequelize.define}
920 * @see
921 * {@link Sequelize.col}
922 *
923 * @param {string} fn The function you want to call
924 * @param {any} args All further arguments will be passed as arguments to the function
925 *
926 * @since v2.0.0-dev3
927 * @memberof Sequelize
928 * @returns {Sequelize.fn}
929 *
930 * @example <caption>Convert a user's username to upper case</caption>
931 * instance.update({
932 * username: sequelize.fn('upper', sequelize.col('username'))
933 * });
934 */
935 static fn(fn, ...args) {
936 return new Utils.Fn(fn, args);
937 }
938
939 /**
940 * Creates an object which represents a column in the DB, this allows referencing another column in your query. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped.
941 *
942 * @see
943 * {@link Sequelize#fn}
944 *
945 * @param {string} col The name of the column
946 * @since v2.0.0-dev3
947 * @memberof Sequelize
948 *
949 * @returns {Sequelize.col}
950 */
951 static col(col) {
952 return new Utils.Col(col);
953 }
954
955 /**
956 * Creates an object representing a call to the cast function.
957 *
958 * @param {any} val The value to cast
959 * @param {string} type The type to cast it to
960 * @since v2.0.0-dev3
961 * @memberof Sequelize
962 *
963 * @returns {Sequelize.cast}
964 */
965 static cast(val, type) {
966 return new Utils.Cast(val, type);
967 }
968
969 /**
970 * Creates an object representing a literal, i.e. something that will not be escaped.
971 *
972 * @param {any} val literal value
973 * @since v2.0.0-dev3
974 * @memberof Sequelize
975 *
976 * @returns {Sequelize.literal}
977 */
978 static literal(val) {
979 return new Utils.Literal(val);
980 }
981
982 /**
983 * An AND query
984 *
985 * @see
986 * {@link Model.findAll}
987 *
988 * @param {...string|Object} args Each argument will be joined by AND
989 * @since v2.0.0-dev3
990 * @memberof Sequelize
991 *
992 * @returns {Sequelize.and}
993 */
994 static and(...args) {
995 return { [Op.and]: args };
996 }
997
998 /**
999 * An OR query
1000 *
1001 * @see
1002 * {@link Model.findAll}
1003 *
1004 * @param {...string|Object} args Each argument will be joined by OR
1005 * @since v2.0.0-dev3
1006 * @memberof Sequelize
1007 *
1008 * @returns {Sequelize.or}
1009 */
1010 static or(...args) {
1011 return { [Op.or]: args };
1012 }
1013
1014 /**
1015 * Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type.
1016 *
1017 * @see
1018 * {@link Model.findAll}
1019 *
1020 * @param {string|Object} conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres/sqlite/mysql json syntax.
1021 * @param {string|number|boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
1022 * @memberof Sequelize
1023 *
1024 * @returns {Sequelize.json}
1025 */
1026 static json(conditionsOrPath, value) {
1027 return new Utils.Json(conditionsOrPath, value);
1028 }
1029
1030 /**
1031 * A way of specifying attr = condition.
1032 *
1033 * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` or `Model.rawAttributes.name`). The
1034 * attribute should be defined in your model definition. The attribute can also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.)
1035 *
1036 * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your string to be escaped, use `sequelize.literal`.
1037 *
1038 * @see
1039 * {@link Model.findAll}
1040 *
1041 * @param {Object} attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax
1042 * @param {Symbol} [comparator='Op.eq'] operator
1043 * @param {string|Object} logic The condition. Can be both a simply type, or a further condition (`or`, `and`, `.literal` etc.)
1044 * @since v2.0.0-dev3
1045 */
1046 static where(attr, comparator, logic) {
1047 return new Utils.Where(attr, comparator, logic);
1048 }
1049
1050 /**
1051 * Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction @see {@link Transaction}
1052 *
1053 * If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction will automatically be passed to any query that runs within the callback
1054 *
1055 * @example
1056 * sequelize.transaction().then(transaction => {
1057 * return User.findOne(..., {transaction})
1058 * .then(user => user.update(..., {transaction}))
1059 * .then(() => transaction.commit())
1060 * .catch(() => transaction.rollback());
1061 * })
1062 *
1063 * @example <caption>A syntax for automatically committing or rolling back based on the promise chain resolution is also supported</caption>
1064 *
1065 * sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then()
1066 * return User.findOne(..., {transaction})
1067 * .then(user => user.update(..., {transaction}))
1068 * }).then(() => {
1069 * // Committed
1070 * }).catch(err => {
1071 * // Rolled back
1072 * console.error(err);
1073 * });
1074 *
1075 * @example <caption>To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:</caption>
1076 *
1077 * const cls = require('continuation-local-storage');
1078 * const ns = cls.createNamespace('....');
1079 * const Sequelize = require('sequelize');
1080 * Sequelize.useCLS(ns);
1081 *
1082 * // Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
1083 *
1084 * @param {Object} [options] Transaction options
1085 * @param {string} [options.type='DEFERRED'] See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
1086 * @param {string} [options.isolationLevel] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
1087 * @param {string} [options.deferrable] Sets the constraints to be deferred or immediately checked. See `Sequelize.Deferrable`. PostgreSQL Only
1088 * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
1089 * @param {Function} [autoCallback] The callback is called with the transaction object, and should return a promise. If the promise is resolved, the transaction commits; if the promise rejects, the transaction rolls back
1090 *
1091 * @returns {Promise}
1092 */
1093 transaction(options, autoCallback) {
1094 if (typeof options === 'function') {
1095 autoCallback = options;
1096 options = undefined;
1097 }
1098
1099 const transaction = new Transaction(this, options);
1100
1101 if (!autoCallback) return transaction.prepareEnvironment(false).return(transaction);
1102
1103 // autoCallback provided
1104 return Sequelize._clsRun(() => {
1105 return transaction.prepareEnvironment()
1106 .then(() => autoCallback(transaction))
1107 .tap(() => transaction.commit())
1108 .catch(err => {
1109 // Rollback transaction if not already finished (commit, rollback, etc)
1110 // and reject with original error (ignore any error in rollback)
1111 return Promise.try(() => {
1112 if (!transaction.finished) return transaction.rollback().catch(() => {});
1113 }).throw(err);
1114 });
1115 });
1116 }
1117
1118 /**
1119 * Use CLS with Sequelize.
1120 * CLS namespace provided is stored as `Sequelize._cls`
1121 * and bluebird Promise is patched to use the namespace, using `cls-bluebird` module.
1122 *
1123 * @param {Object} ns CLS namespace
1124 * @returns {Object} Sequelize constructor
1125 */
1126 static useCLS(ns) {
1127 // check `ns` is valid CLS namespace
1128 if (!ns || typeof ns !== 'object' || typeof ns.bind !== 'function' || typeof ns.run !== 'function') throw new Error('Must provide CLS namespace');
1129
1130 // save namespace as `Sequelize._cls`
1131 this._cls = ns;
1132
1133 // patch bluebird to bind all promise callbacks to CLS namespace
1134 clsBluebird(ns, Promise);
1135
1136 // return Sequelize for chaining
1137 return this;
1138 }
1139
1140 /**
1141 * Run function in CLS context.
1142 * If no CLS context in use, just runs the function normally
1143 *
1144 * @private
1145 * @param {Function} fn Function to run
1146 * @returns {*} Return value of function
1147 */
1148 static _clsRun(fn) {
1149 const ns = Sequelize._cls;
1150 if (!ns) return fn();
1151
1152 let res;
1153 ns.run(context => res = fn(context));
1154 return res;
1155 }
1156
1157 log(...args) {
1158 let options;
1159
1160 const last = _.last(args);
1161
1162 if (last && _.isPlainObject(last) && Object.prototype.hasOwnProperty.call(last, 'logging')) {
1163 options = last;
1164
1165 // remove options from set of logged arguments if options.logging is equal to console.log
1166 // eslint-disable-next-line no-console
1167 if (options.logging === console.log) {
1168 args.splice(args.length - 1, 1);
1169 }
1170 } else {
1171 options = this.options;
1172 }
1173
1174 if (options.logging) {
1175 if (options.logging === true) {
1176 deprecations.noTrueLogging();
1177 // eslint-disable-next-line no-console
1178 options.logging = console.log;
1179 }
1180
1181 // second argument is sql-timings, when benchmarking option enabled
1182 // eslint-disable-next-line no-console
1183 if ((this.options.benchmark || options.benchmark) && options.logging === console.log) {
1184 args = [`${args[0]} Elapsed time: ${args[1]}ms`];
1185 }
1186
1187 options.logging(...args);
1188 }
1189 }
1190
1191 /**
1192 * Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected.
1193 *
1194 * Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want
1195 * to garbage collect some of them.
1196 *
1197 * @returns {Promise}
1198 */
1199 close() {
1200 return this.connectionManager.close();
1201 }
1202
1203 normalizeDataType(Type) {
1204 let type = typeof Type === 'function' ? new Type() : Type;
1205 const dialectTypes = this.dialect.DataTypes || {};
1206
1207 if (dialectTypes[type.key]) {
1208 type = dialectTypes[type.key].extend(type);
1209 }
1210
1211 if (type instanceof DataTypes.ARRAY) {
1212 if (!type.type) {
1213 throw new Error('ARRAY is missing type definition for its values.');
1214 }
1215 if (dialectTypes[type.type.key]) {
1216 type.type = dialectTypes[type.type.key].extend(type.type);
1217 }
1218 }
1219
1220 return type;
1221 }
1222
1223 normalizeAttribute(attribute) {
1224 if (!_.isPlainObject(attribute)) {
1225 attribute = { type: attribute };
1226 }
1227
1228 if (!attribute.type) return attribute;
1229
1230 attribute.type = this.normalizeDataType(attribute.type);
1231
1232 if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) {
1233 if (typeof attribute.defaultValue === 'function' && (
1234 attribute.defaultValue === DataTypes.NOW ||
1235 attribute.defaultValue === DataTypes.UUIDV1 ||
1236 attribute.defaultValue === DataTypes.UUIDV4
1237 )) {
1238 attribute.defaultValue = new attribute.defaultValue();
1239 }
1240 }
1241
1242 if (attribute.type instanceof DataTypes.ENUM) {
1243 // The ENUM is a special case where the type is an object containing the values
1244 if (attribute.values) {
1245 attribute.type.values = attribute.type.options.values = attribute.values;
1246 } else {
1247 attribute.values = attribute.type.values;
1248 }
1249
1250 if (!attribute.values.length) {
1251 throw new Error('Values for ENUM have not been defined.');
1252 }
1253 }
1254
1255 return attribute;
1256 }
1257}
1258
1259// Aliases
1260Sequelize.prototype.fn = Sequelize.fn;
1261Sequelize.prototype.col = Sequelize.col;
1262Sequelize.prototype.cast = Sequelize.cast;
1263Sequelize.prototype.literal = Sequelize.literal;
1264Sequelize.prototype.and = Sequelize.and;
1265Sequelize.prototype.or = Sequelize.or;
1266Sequelize.prototype.json = Sequelize.json;
1267Sequelize.prototype.where = Sequelize.where;
1268Sequelize.prototype.validate = Sequelize.prototype.authenticate;
1269
1270/**
1271 * Sequelize version number.
1272 */
1273Sequelize.version = require('../package.json').version;
1274
1275Sequelize.options = { hooks: {} };
1276
1277/**
1278 * @private
1279 */
1280Sequelize.Utils = Utils;
1281
1282/**
1283 * Operators symbols to be used for querying data
1284 * @see {@link Operators}
1285 */
1286Sequelize.Op = Op;
1287
1288/**
1289 * A handy reference to the bluebird Promise class
1290 */
1291Sequelize.Promise = Promise;
1292
1293/**
1294 * Available table hints to be used for querying data in mssql for table hints
1295 * @see {@link TableHints}
1296 */
1297Sequelize.TableHints = TableHints;
1298
1299/**
1300 * Available index hints to be used for querying data in mysql for index hints
1301 * @see {@link IndexHints}
1302 */
1303Sequelize.IndexHints = IndexHints;
1304
1305/**
1306 * A reference to the sequelize transaction class. Use this to access isolationLevels and types when creating a transaction
1307 * @see {@link Transaction}
1308 * @see {@link Sequelize.transaction}
1309 */
1310Sequelize.Transaction = Transaction;
1311
1312/**
1313 * A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
1314 * @see {@link Sequelize}
1315 */
1316Sequelize.prototype.Sequelize = Sequelize;
1317
1318/**
1319 * Available query types for use with `sequelize.query`
1320 * @see {@link QueryTypes}
1321 */
1322Sequelize.prototype.QueryTypes = Sequelize.QueryTypes = QueryTypes;
1323
1324/**
1325 * Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed both on the instance, and on the constructor.
1326 * @see https://github.com/chriso/validator.js
1327 */
1328Sequelize.prototype.Validator = Sequelize.Validator = Validator;
1329
1330Sequelize.Model = Model;
1331
1332Sequelize.DataTypes = DataTypes;
1333for (const dataType in DataTypes) {
1334 Sequelize[dataType] = DataTypes[dataType];
1335}
1336
1337/**
1338 * A reference to the deferrable collection. Use this to access the different deferrable options.
1339 * @see {@link Transaction.Deferrable}
1340 * @see {@link Sequelize#transaction}
1341 */
1342Sequelize.Deferrable = Deferrable;
1343
1344/**
1345 * A reference to the sequelize association class.
1346 * @see {@link Association}
1347 */
1348Sequelize.prototype.Association = Sequelize.Association = Association;
1349
1350/**
1351 * Provide alternative version of `inflection` module to be used by `Utils.pluralize` etc.
1352 * @param {Object} _inflection - `inflection` module
1353 */
1354Sequelize.useInflection = Utils.useInflection;
1355
1356/**
1357 * Allow hooks to be defined on Sequelize + on sequelize instance as universal hooks to run on all models
1358 * and on Sequelize/sequelize methods e.g. Sequelize(), Sequelize#define()
1359 */
1360Hooks.applyTo(Sequelize);
1361Hooks.applyTo(Sequelize.prototype);
1362
1363/**
1364 * Expose various errors available
1365 */
1366
1367// expose alias to BaseError
1368Sequelize.Error = sequelizeErrors.BaseError;
1369
1370for (const error of Object.keys(sequelizeErrors)) {
1371 Sequelize[error] = sequelizeErrors[error];
1372}
1373
1374module.exports = Sequelize;
1375module.exports.Sequelize = Sequelize;
1376module.exports.default = Sequelize;