sequelize.js 52 KB

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