{ "version": 3, "sources": ["../src/sequelize.js"], "sourcesContent": ["'use strict';\n\nconst url = require('url');\nconst path = require('path');\nconst pgConnectionString = require('pg-connection-string');\nconst retry = require('retry-as-promised');\nconst _ = require('lodash');\n\nconst Utils = require('./utils');\nconst Model = require('./model');\nconst DataTypes = require('./data-types');\nconst Deferrable = require('./deferrable');\nconst ModelManager = require('./model-manager');\nconst Transaction = require('./transaction');\nconst QueryTypes = require('./query-types');\nconst TableHints = require('./table-hints');\nconst IndexHints = require('./index-hints');\nconst sequelizeErrors = require('./errors');\nconst Hooks = require('./hooks');\nconst Association = require('./associations/index');\nconst Validator = require('./utils/validator-extras').validator;\nconst Op = require('./operators');\nconst deprecations = require('./utils/deprecations');\nconst { QueryInterface } = require('./dialects/abstract/query-interface');\nconst { BelongsTo } = require('./associations/belongs-to');\nconst HasOne = require('./associations/has-one');\nconst { BelongsToMany } = require('./associations/belongs-to-many');\nconst { HasMany } = require('./associations/has-many');\nconst { withSqliteForeignKeysOff } = require('./dialects/sqlite/sqlite-utils');\nconst { injectReplacements } = require('./utils/sql');\n\n/**\n * This is the main class, the entry point to sequelize.\n */\nclass Sequelize {\n /**\n * Instantiate sequelize with name of database, username and password.\n *\n * @example\n * // without password / with blank password\n * const sequelize = new Sequelize('database', 'username', null, {\n * dialect: 'mysql'\n * })\n *\n * // with password and options\n * const sequelize = new Sequelize('my_database', 'john', 'doe', {\n * dialect: 'postgres'\n * })\n *\n * // with database, username, and password in the options object\n * const sequelize = new Sequelize({ database, username, password, dialect: 'mssql' });\n *\n * // with uri\n * const sequelize = new Sequelize('mysql://localhost:3306/database', {})\n *\n * // option examples\n * const sequelize = new Sequelize('database', 'username', 'password', {\n * // the sql dialect of the database\n * // currently supported: 'mysql', 'sqlite', 'postgres', 'mssql'\n * dialect: 'mysql',\n *\n * // custom host; default: localhost\n * host: 'my.server.tld',\n * // for postgres, you can also specify an absolute path to a directory\n * // containing a UNIX socket to connect over\n * // host: '/sockets/psql_sockets'.\n *\n * // custom port; default: dialect default\n * port: 12345,\n *\n * // custom protocol; default: 'tcp'\n * // postgres only, useful for Heroku\n * protocol: null,\n *\n * // disable logging or provide a custom logging function; default: console.log\n * logging: false,\n *\n * // you can also pass any dialect options to the underlying dialect library\n * // - default is empty\n * // - currently supported: 'mysql', 'postgres', 'mssql'\n * dialectOptions: {\n * socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock',\n * supportBigNumbers: true,\n * bigNumberStrings: true\n * },\n *\n * // the storage engine for sqlite\n * // - default ':memory:'\n * storage: 'path/to/database.sqlite',\n *\n * // disable inserting undefined values as NULL\n * // - default: false\n * omitNull: true,\n *\n * // a flag for using a native library or not.\n * // in the case of 'pg' -- set this to true will allow SSL support\n * // - default: false\n * native: true,\n *\n * // Specify options, which are used when sequelize.define is called.\n * // The following example:\n * // define: { timestamps: false }\n * // is basically the same as:\n * // Model.init(attributes, { timestamps: false });\n * // sequelize.define(name, attributes, { timestamps: false });\n * // so defining the timestamps for each model will be not necessary\n * define: {\n * underscored: false,\n * freezeTableName: false,\n * charset: 'utf8',\n * dialectOptions: {\n * collate: 'utf8_general_ci'\n * },\n * timestamps: true\n * },\n *\n * // similar for sync: you can define this to always force sync for models\n * sync: { force: true },\n *\n * // pool configuration used to pool database connections\n * pool: {\n * max: 5,\n * idle: 30000,\n * acquire: 60000,\n * },\n *\n * // isolation level of each transaction\n * // defaults to dialect default\n * isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ\n * })\n *\n * @param {string} [database] The name of the database\n * @param {string} [username=null] The username which is used to authenticate against the database.\n * @param {string} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.\n * @param {object} [options={}] An object with options.\n * @param {string} [options.host='localhost'] The host of the relational database.\n * @param {number} [options.port] The port of the relational database.\n * @param {string} [options.username=null] The username which is used to authenticate against the database.\n * @param {string} [options.password=null] The password which is used to authenticate against the database.\n * @param {string} [options.database=null] The name of the database.\n * @param {string} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite, db2, mariadb and mssql.\n * @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\n * @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\n * @param {object} [options.dialectOptions] An object of additional options, which are passed directly to the connection library\n * @param {string} [options.storage] Only used by sqlite. Defaults to ':memory:'\n * @param {string} [options.protocol='tcp'] The protocol of the relational database.\n * @param {object} [options.define={}] Default options for model definitions. See {@link Model.init}.\n * @param {object} [options.query={}] Default options for sequelize.query\n * @param {string} [options.schema=null] A schema to use\n * @param {object} [options.set={}] Default options for sequelize.set\n * @param {object} [options.sync={}] Default options for sequelize.sync\n * @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.\n * @param {string|boolean} [options.clientMinMessages='warning'] (Deprecated) The PostgreSQL `client_min_messages` session parameter. Set to `false` to not override the database's default.\n * @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!\n * @param {Function} [options.logging=console.log] A function that gets executed every time Sequelize would log something. Function may receive multiple parameters but only first one is printed by `console.log`. To print all values use `(...msg) => console.log(msg)`\n * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).\n * @param {boolean} [options.omitNull=false] A flag that defines if null values should be passed as values to CREATE/UPDATE SQL queries or not.\n * @param {boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres\n * @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`\n * @param {object} [options.pool] sequelize connection pool configuration\n * @param {number} [options.pool.max=5] Maximum number of connection in pool\n * @param {number} [options.pool.min=0] Minimum number of connection in pool\n * @param {number} [options.pool.idle=10000] The maximum time, in milliseconds, that a connection can be idle before being released.\n * @param {number} [options.pool.acquire=60000] The maximum time, in milliseconds, that pool will try to get connection before throwing error\n * @param {number} [options.pool.evict=1000] The time interval, in milliseconds, after which sequelize-pool will remove idle connections.\n * @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\n * @param {number} [options.pool.maxUses=Infinity] The number of times a connection can be used before discarding it for a replacement, [`used for eventual cluster rebalancing`](https://github.com/sequelize/sequelize-pool).\n * @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!\n * @param {string} [options.transactionType='DEFERRED'] Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.\n * @param {string} [options.isolationLevel] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.\n * @param {object} [options.retry] Set of flags that control when a query is automatically retried. Accepts all options for [`retry-as-promised`](https://github.com/mickhansen/retry-as-promised).\n * @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.\n * @param {number} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.\n * @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.\n * @param {object} [options.operatorsAliases] String based operator alias. Pass object to limit set of aliased operators.\n * @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.\n * @param {boolean} [options.minifyAliases=false] A flag that defines if aliases should be minified (mostly useful to avoid Postgres alias character limit of 64)\n * @param {boolean} [options.logQueryParameters=false] A flag that defines if show bind parameters in log.\n */\n constructor(database, username, password, options) {\n let config;\n\n if (arguments.length === 1 && typeof database === 'object') {\n // new Sequelize({ ... options })\n options = database;\n config = _.pick(options, 'host', 'port', 'database', 'username', 'password');\n } else if (arguments.length === 1 && typeof database === 'string' || arguments.length === 2 && typeof username === 'object') {\n // new Sequelize(URI, { ... options })\n\n config = {};\n options = username || {};\n\n const urlParts = url.parse(arguments[0], true);\n\n options.dialect = urlParts.protocol.replace(/:$/, '');\n options.host = urlParts.hostname;\n\n if (options.dialect === 'sqlite' && urlParts.pathname && !urlParts.pathname.startsWith('/:memory')) {\n const storagePath = path.join(options.host, urlParts.pathname);\n options.storage = path.resolve(options.storage || storagePath);\n }\n\n if (urlParts.pathname) {\n config.database = urlParts.pathname.replace(/^\\//, '');\n }\n\n if (urlParts.port) {\n options.port = urlParts.port;\n }\n\n if (urlParts.auth) {\n const authParts = urlParts.auth.split(':');\n\n config.username = authParts[0];\n\n if (authParts.length > 1)\n config.password = authParts.slice(1).join(':');\n }\n\n if (urlParts.query) {\n // Allow host query argument to override the url host.\n // Enables specifying domain socket hosts which cannot be specified via the typical\n // host part of a url.\n if (urlParts.query.host) {\n options.host = urlParts.query.host;\n }\n\n if (options.dialectOptions) {\n Object.assign(options.dialectOptions, urlParts.query);\n } else {\n options.dialectOptions = urlParts.query;\n if (urlParts.query.options) {\n try {\n const o = JSON.parse(urlParts.query.options);\n options.dialectOptions.options = o;\n } catch (e) {\n // Nothing to do, string is not a valid JSON\n // an thus does not need any further processing\n }\n }\n }\n }\n\n // For postgres, we can use this helper to load certs directly from the\n // connection string.\n if (['postgres', 'postgresql'].includes(options.dialect)) {\n Object.assign(options.dialectOptions, pgConnectionString.parse(arguments[0]));\n }\n } else {\n // new Sequelize(database, username, password, { ... options })\n options = options || {};\n config = { database, username, password };\n }\n\n Sequelize.runHooks('beforeInit', config, options);\n\n this.options = {\n dialect: null,\n dialectModule: null,\n dialectModulePath: null,\n host: 'localhost',\n protocol: 'tcp',\n define: {},\n query: {},\n sync: {},\n timezone: '+00:00',\n standardConformingStrings: true,\n // eslint-disable-next-line no-console\n logging: console.log,\n omitNull: false,\n native: false,\n replication: false,\n ssl: undefined,\n pool: {},\n quoteIdentifiers: true,\n hooks: {},\n retry: {\n max: 5,\n match: [\n 'SQLITE_BUSY: database is locked'\n ]\n },\n transactionType: Transaction.TYPES.DEFERRED,\n isolationLevel: null,\n databaseVersion: 0,\n typeValidation: false,\n benchmark: false,\n minifyAliases: false,\n logQueryParameters: false,\n ...options\n };\n\n if (!this.options.dialect) {\n throw new Error('Dialect needs to be explicitly supplied as of v4.0.0');\n }\n\n if (this.options.dialect === 'postgresql') {\n this.options.dialect = 'postgres';\n }\n\n if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {\n throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom timezone parameter.');\n }\n\n if (this.options.logging === true) {\n deprecations.noTrueLogging();\n // eslint-disable-next-line no-console\n this.options.logging = console.log;\n }\n\n this._setupHooks(options.hooks);\n\n this.config = {\n database: config.database || this.options.database,\n username: config.username || this.options.username,\n password: config.password || this.options.password || null,\n host: config.host || this.options.host,\n port: config.port || this.options.port,\n pool: this.options.pool,\n protocol: this.options.protocol,\n native: this.options.native,\n ssl: this.options.ssl,\n replication: this.options.replication,\n dialectModule: this.options.dialectModule,\n dialectModulePath: this.options.dialectModulePath,\n keepDefaultTimezone: this.options.keepDefaultTimezone,\n dialectOptions: this.options.dialectOptions\n };\n\n let Dialect;\n // Requiring the dialect in a switch-case to keep the\n // require calls static. (Browserify fix)\n switch (this.getDialect()) {\n case 'mariadb':\n Dialect = require('./dialects/mariadb');\n break;\n case 'mssql':\n Dialect = require('./dialects/mssql');\n break;\n case 'mysql':\n Dialect = require('./dialects/mysql');\n break;\n case 'postgres':\n Dialect = require('./dialects/postgres');\n break;\n case 'sqlite':\n Dialect = require('./dialects/sqlite');\n break;\n case 'db2':\n Dialect = require('./dialects/db2');\n break;\n case 'snowflake':\n Dialect = require('./dialects/snowflake');\n break;\n default:\n throw new Error(`The dialect ${this.getDialect()} is not supported. Supported dialects: mssql, mariadb, mysql, postgres, db2 and sqlite.`);\n }\n\n this.dialect = new Dialect(this);\n this.dialect.queryGenerator.typeValidation = options.typeValidation;\n\n if (_.isPlainObject(this.options.operatorsAliases)) {\n deprecations.noStringOperators();\n this.dialect.queryGenerator.setOperatorsAliases(this.options.operatorsAliases);\n } else if (typeof this.options.operatorsAliases === 'boolean') {\n deprecations.noBoolOperatorAliases();\n }\n\n this.queryInterface = this.dialect.queryInterface;\n\n /**\n * Models are stored here under the name given to `sequelize.define`\n */\n this.models = {};\n this.modelManager = new ModelManager(this);\n this.connectionManager = this.dialect.connectionManager;\n\n Sequelize.runHooks('afterInit', this);\n }\n\n /**\n * Refresh data types and parsers.\n *\n * @private\n */\n refreshTypes() {\n this.connectionManager.refreshTypeParser(DataTypes);\n }\n\n /**\n * Returns the specified dialect.\n *\n * @returns {string} The specified dialect.\n */\n getDialect() {\n return this.options.dialect;\n }\n\n /**\n * Returns the database name.\n *\n * @returns {string} The database name.\n */\n getDatabaseName() {\n return this.config.database;\n }\n\n /**\n * Returns an instance of QueryInterface.\n *\n * @returns {QueryInterface} An instance (singleton) of QueryInterface.\n */\n getQueryInterface() {\n return this.queryInterface;\n }\n\n /**\n * Define a new model, representing a table in the database.\n *\n * The table columns are defined by the object that is given as the second argument. Each key of the object represents a column\n *\n * @param {string} modelName The name of the model. The model will be stored in `sequelize.models` under this name\n * @param {object} attributes An object, where each attribute is a column of the table. See {@link Model.init}\n * @param {object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init()\n *\n * @see\n * {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects.\n * @see\n * Model Basics guide\n *\n * @returns {Model} Newly defined model\n *\n * @example\n * sequelize.define('modelName', {\n * columnA: {\n * type: Sequelize.BOOLEAN,\n * validate: {\n * is: [\"[a-z]\",'i'], // will only allow letters\n * max: 23, // only allow values <= 23\n * isIn: {\n * args: [['en', 'zh']],\n * msg: \"Must be English or Chinese\"\n * }\n * },\n * field: 'column_a'\n * },\n * columnB: Sequelize.STRING,\n * columnC: 'MY VERY OWN COLUMN TYPE'\n * });\n *\n * sequelize.models.modelName // The model will now be available in models under the name given to define\n */\n define(modelName, attributes, options = {}) {\n options.modelName = modelName;\n options.sequelize = this;\n\n const model = class extends Model {};\n\n model.init(attributes, options);\n\n return model;\n }\n\n /**\n * Fetch a Model which is already defined\n *\n * @param {string} modelName The name of a model defined with Sequelize.define\n *\n * @throws Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false)\n * @returns {Model} Specified model\n */\n model(modelName) {\n if (!this.isDefined(modelName)) {\n throw new Error(`${modelName} has not been defined`);\n }\n\n return this.modelManager.getModel(modelName);\n }\n\n /**\n * Checks whether a model with the given name is defined\n *\n * @param {string} modelName The name of a model defined with Sequelize.define\n *\n * @returns {boolean} Returns true if model is already defined, otherwise false\n */\n isDefined(modelName) {\n return !!this.modelManager.models.find(model => model.name === modelName);\n }\n\n /**\n * Execute a query on the DB, optionally bypassing all the Sequelize goodness.\n *\n * By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc.\n *\n * 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:\n *\n * ```js\n * const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring\n *\n * const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring\n * ```\n *\n * @param {string} sql\n * @param {object} [options={}] Query options.\n * @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\n * @param {Transaction} [options.transaction=null] The transaction that the query should be executed under\n * @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.\n * @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\n * @param {boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row\n * @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.\n * @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.\n * @param {boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.\n * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.\n * @param {Model} [options.instance] A sequelize model instance whose Model is to be used to build the query result\n * @param {typeof Model} [options.model] A sequelize model used to build the returned model instances\n * @param {object} [options.retry] Set of flags that control when a query is automatically retried. Accepts all options for [`retry-as-promised`](https://github.com/mickhansen/retry-as-promised).\n * @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.\n * @param {Integer} [options.retry.max] How many times a failing query is automatically retried.\n * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)\n * @param {boolean} [options.supportsSearchPath] If false do not prepend the query with the search_path (Postgres only)\n * @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.\n * @param {object} [options.fieldMap] Map returned fields to arbitrary names for `SELECT` query type.\n * @param {boolean} [options.rawErrors=false] Set to `true` to cause errors coming from the underlying connection/database library to be propagated unmodified and unformatted. Else, the default behavior (=false) is to reinterpret errors as sequelize.errors.BaseError objects.\n *\n * @returns {Promise}\n *\n * @see {@link Model.build} for more information about instance option.\n */\n\n async query(sql, options) {\n options = { ...this.options.query, ...options };\n\n if (options.instance && !options.model) {\n options.model = options.instance.constructor;\n }\n\n if (!options.instance && !options.model) {\n options.raw = true;\n }\n\n // map raw fields to model attributes\n if (options.mapToModel) {\n options.fieldMap = _.get(options, 'model.fieldAttributeMap', {});\n }\n\n options = _.defaults(options, {\n // eslint-disable-next-line no-console\n logging: Object.prototype.hasOwnProperty.call(this.options, 'logging') ? this.options.logging : console.log,\n searchPath: Object.prototype.hasOwnProperty.call(this.options, 'searchPath') ? this.options.searchPath : 'DEFAULT'\n });\n\n if (!options.type) {\n if (options.model || options.nest || options.plain) {\n options.type = QueryTypes.SELECT;\n } else {\n options.type = QueryTypes.RAW;\n }\n }\n\n //if dialect doesn't support search_path or dialect option\n //to prepend searchPath is not true delete the searchPath option\n if (\n !this.dialect.supports.searchPath ||\n !this.options.dialectOptions ||\n !this.options.dialectOptions.prependSearchPath ||\n options.supportsSearchPath === false\n ) {\n delete options.searchPath;\n } else if (!options.searchPath) {\n //if user wants to always prepend searchPath (dialectOptions.preprendSearchPath = true)\n //then set to DEFAULT if none is provided\n options.searchPath = 'DEFAULT';\n }\n\n if (typeof sql === 'object') {\n if (sql.values !== undefined) {\n if (options.replacements !== undefined) {\n throw new Error('Both `sql.values` and `options.replacements` cannot be set at the same time');\n }\n options.replacements = sql.values;\n }\n\n if (sql.bind !== undefined) {\n if (options.bind !== undefined) {\n throw new Error('Both `sql.bind` and `options.bind` cannot be set at the same time');\n }\n options.bind = sql.bind;\n }\n\n if (sql.query !== undefined) {\n sql = sql.query;\n }\n }\n\n sql = sql.trim();\n\n if (options.replacements && options.bind) {\n throw new Error('Both `replacements` and `bind` cannot be set at the same time');\n }\n\n if (options.replacements) {\n sql = injectReplacements(sql, this.dialect, options.replacements);\n }\n\n let bindParameters;\n\n if (options.bind) {\n [sql, bindParameters] = this.dialect.Query.formatBindParameters(sql, options.bind, this.options.dialect);\n }\n\n const checkTransaction = () => {\n if (options.transaction && options.transaction.finished && !options.completesTransaction) {\n 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)`);\n error.sql = sql;\n throw error;\n }\n };\n\n const retryOptions = { ...this.options.retry, ...options.retry };\n\n return retry(async () => {\n if (options.transaction === undefined && Sequelize._cls) {\n options.transaction = Sequelize._cls.get('transaction');\n }\n\n checkTransaction();\n\n const connection = await (options.transaction ? options.transaction.connection : this.connectionManager.getConnection(options));\n\n if (this.options.dialect === 'db2' && options.alter) {\n if (options.alter.drop === false) {\n connection.dropTable = false;\n }\n }\n const query = new this.dialect.Query(connection, this, options);\n\n try {\n await this.runHooks('beforeQuery', options, query);\n checkTransaction();\n return await query.run(sql, bindParameters);\n } finally {\n await this.runHooks('afterQuery', options, query);\n if (!options.transaction) {\n this.connectionManager.releaseConnection(connection);\n }\n }\n }, retryOptions);\n }\n\n /**\n * Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.\n * Only works for MySQL or MariaDB.\n *\n * @param {object} variables Object with multiple variables.\n * @param {object} [options] query options.\n * @param {Transaction} [options.transaction] The transaction that the query should be executed under\n *\n * @memberof Sequelize\n *\n * @returns {Promise}\n */\n async set(variables, options) {\n\n // Prepare options\n options = { ...this.options.set, ...typeof options === 'object' && options };\n\n if (!['mysql', 'mariadb'].includes(this.options.dialect)) {\n throw new Error('sequelize.set is only supported for mysql or mariadb');\n }\n if (!options.transaction || !(options.transaction instanceof Transaction) ) {\n throw new TypeError('options.transaction is required');\n }\n\n // Override some options, since this isn't a SELECT\n options.raw = true;\n options.plain = true;\n options.type = 'SET';\n\n // Generate SQL Query\n const query =\n `SET ${\n _.map(variables, (v, k) => `@${k} := ${typeof v === 'string' ? `\"${v}\"` : v}`).join(', ')}`;\n\n return await this.query(query, options);\n }\n\n /**\n * Escape value.\n *\n * @param {string} value string value to escape\n *\n * @returns {string}\n */\n escape(value) {\n return this.dialect.queryGenerator.escape(value);\n }\n\n /**\n * Create a new database schema.\n *\n * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),\n * not a database table. In mysql and sqlite, this command will do nothing.\n *\n * @see\n * {@link Model.schema}\n *\n * @param {string} schema Name of the schema\n * @param {object} [options={}] query options\n * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging\n *\n * @returns {Promise}\n */\n async createSchema(schema, options) {\n return await this.getQueryInterface().createSchema(schema, options);\n }\n\n /**\n * Show all defined schemas\n *\n * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),\n * not a database table. In mysql and sqlite, this will show all tables.\n *\n * @param {object} [options={}] query options\n * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging\n *\n * @returns {Promise}\n */\n async showAllSchemas(options) {\n return await this.getQueryInterface().showAllSchemas(options);\n }\n\n /**\n * Drop a single schema\n *\n * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),\n * not a database table. In mysql and sqlite, this drop a table matching the schema name\n *\n * @param {string} schema Name of the schema\n * @param {object} [options={}] query options\n * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging\n *\n * @returns {Promise}\n */\n async dropSchema(schema, options) {\n return await this.getQueryInterface().dropSchema(schema, options);\n }\n\n /**\n * Drop all schemas.\n *\n * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),\n * not a database table. In mysql and sqlite, this is the equivalent of drop all tables.\n *\n * @param {object} [options={}] query options\n * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging\n *\n * @returns {Promise}\n */\n async dropAllSchemas(options) {\n return await this.getQueryInterface().dropAllSchemas(options);\n }\n\n /**\n * Sync all defined models to the DB.\n *\n * @param {object} [options={}] sync options\n * @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\n * @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\n * @param {boolean|Function} [options.logging=console.log] A function that logs sql queries, or false for no logging\n * @param {string} [options.schema='public'] The schema that the tables should be created in. This can be overridden for each table in sequelize.define\n * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)\n * @param {boolean} [options.hooks=true] If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called\n * @param {boolean|object} [options.alter=false] Alters tables to fit models. Provide an object for additional configuration. Not recommended for production use. If not further configured deletes data in columns that were removed or had their type changed in the model.\n * @param {boolean} [options.alter.drop=true] Prevents any drop statements while altering a table when set to `false`\n *\n * @returns {Promise}\n */\n async sync(options) {\n options = {\n ...this.options,\n ...this.options.sync,\n ...options,\n hooks: options ? options.hooks !== false : true\n };\n\n if (options.match) {\n if (!options.match.test(this.config.database)) {\n throw new Error(`Database \"${this.config.database}\" does not match sync match parameter \"${options.match}\"`);\n }\n }\n\n if (options.hooks) {\n await this.runHooks('beforeBulkSync', options);\n }\n\n if (options.force) {\n await this.drop(options);\n }\n\n // no models defined, just authenticate\n if (this.modelManager.models.length === 0) {\n await this.authenticate(options);\n } else {\n const models = this.modelManager.getModelsTopoSortedByForeignKey();\n if (models == null) {\n return this._syncModelsWithCyclicReferences(options);\n }\n\n // reverse to start with the one model that does not depend on anything\n models.reverse();\n\n // Topologically sort by foreign key constraints to give us an appropriate\n // creation order\n for (const model of models) {\n await model.sync(options);\n }\n }\n\n if (options.hooks) {\n await this.runHooks('afterBulkSync', options);\n }\n\n return this;\n }\n\n /**\n * Used instead of sync() when two models reference each-other, so their foreign keys cannot be created immediately.\n *\n * @param {object} options - sync options\n * @private\n */\n async _syncModelsWithCyclicReferences(options) {\n if (this.dialect.name === 'sqlite') {\n // Optimisation: no need to do this in two passes in SQLite because we can temporarily disable foreign keys\n await withSqliteForeignKeysOff(this, options, async () => {\n for (const model of this.modelManager.models) {\n await model.sync(options);\n }\n });\n\n return;\n }\n\n // create all tables, but don't create foreign key constraints\n for (const model of this.modelManager.models) {\n await model.sync({ ...options, withoutForeignKeyConstraints: true });\n }\n\n // add foreign key constraints\n for (const model of this.modelManager.models) {\n await model.sync({ ...options, force: false, alter: true });\n }\n }\n\n /**\n * Truncate all tables defined through the sequelize models.\n * This is done by calling `Model.truncate()` on each model.\n *\n * @param {object} [options] The options passed to Model.destroy in addition to truncate\n * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging\n * @returns {Promise}\n *\n * @see\n * {@link Model.truncate} for more information\n */\n async truncate(options) {\n const sortedModels = this.modelManager.getModelsTopoSortedByForeignKey();\n const models = sortedModels || this.modelManager.models;\n const hasCyclicDependencies = sortedModels == null;\n\n // we have cyclic dependencies, cascade must be enabled.\n if (hasCyclicDependencies && (!options || !options.cascade)) {\n throw new Error('Sequelize#truncate: Some of your models have cyclic references (foreign keys). You need to use the \"cascade\" option to be able to delete rows from models that have cyclic references.');\n }\n\n // TODO [>=7]: throw if options.cascade is specified but unsupported in the given dialect.\n if (hasCyclicDependencies && this.dialect.name === 'sqlite') {\n // Workaround: SQLite does not support options.cascade, but we can disable its foreign key constraints while we\n // truncate all tables.\n return withSqliteForeignKeysOff(this, options, async () => {\n await Promise.all(models.map(model => model.truncate(options)));\n });\n }\n\n if (options && options.cascade) {\n for (const model of models) await model.truncate(options);\n } else {\n await Promise.all(models.map(model => model.truncate(options)));\n }\n }\n\n /**\n * Drop all tables defined through this sequelize instance.\n * This is done by calling Model.drop on each model.\n *\n * @see\n * {@link Model.drop} for options\n *\n * @param {object} [options] The options passed to each call to Model.drop\n * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging\n *\n * @returns {Promise}\n */\n async drop(options) {\n // if 'cascade' is specified, we don't have to worry about cyclic dependencies.\n if (options && options.cascade) {\n for (const model of this.modelManager.models) {\n await model.drop(options);\n }\n }\n\n const sortedModels = this.modelManager.getModelsTopoSortedByForeignKey();\n\n // no cyclic dependency between models, we can delete them in an order that will not cause an error.\n if (sortedModels) {\n for (const model of sortedModels) {\n await model.drop(options);\n }\n }\n\n if (this.dialect.name === 'sqlite') {\n // Optimisation: no need to do this in two passes in SQLite because we can temporarily disable foreign keys\n await withSqliteForeignKeysOff(this, options, async () => {\n for (const model of this.modelManager.models) {\n await model.drop(options);\n }\n });\n\n return;\n }\n\n // has cyclic dependency: we first remove each foreign key, then delete each model.\n for (const model of this.modelManager.models) {\n const tableName = model.getTableName();\n const foreignKeys = await this.queryInterface.getForeignKeyReferencesForTable(tableName, options);\n\n await Promise.all(foreignKeys.map(foreignKey => {\n return this.queryInterface.removeConstraint(tableName, foreignKey.constraintName, options);\n }));\n }\n\n for (const model of this.modelManager.models) {\n await model.drop(options);\n }\n }\n\n /**\n * Test the connection by trying to authenticate. It runs `SELECT 1+1 AS result` query.\n *\n * @param {object} [options={}] query options\n *\n * @returns {Promise}\n */\n async authenticate(options) {\n options = {\n raw: true,\n plain: true,\n type: QueryTypes.SELECT,\n ...options\n };\n\n await this.query('SELECT 1+1 AS result', options);\n\n return;\n }\n\n async databaseVersion(options) {\n return await this.getQueryInterface().databaseVersion(options);\n }\n\n /**\n * Get the fn for random based on the dialect\n *\n * @returns {Sequelize.fn}\n */\n random() {\n if (['postgres', 'sqlite', 'snowflake'].includes(this.getDialect())) {\n return this.fn('RANDOM');\n }\n return this.fn('RAND');\n }\n\n /**\n * 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.\n * 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.\n *\n * @see\n * {@link Model.findAll}\n * @see\n * {@link Sequelize.define}\n * @see\n * {@link Sequelize.col}\n *\n * @param {string} fn The function you want to call\n * @param {any} args All further arguments will be passed as arguments to the function\n *\n * @since v2.0.0-dev3\n * @memberof Sequelize\n * @returns {Sequelize.fn}\n *\n * @example