sequelize.js 51 KB

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