/lib/sequelize.js

https://github.com/brabeji/sequelize · JavaScript · 792 lines · 297 code · 80 blank · 415 comment · 43 complexity · 34a4e312fd4c54969797cc319ee4c2db MD5 · raw file

  1. 'use strict';
  2. var url = require('url')
  3. , Path = require('path')
  4. , Utils = require('./utils')
  5. , Model = require('./model')
  6. , DataTypes = require('./data-types')
  7. , ModelManager = require('./model-manager')
  8. , QueryInterface = require('./query-interface')
  9. , Transaction = require('./transaction')
  10. , QueryTypes = require('./query-types')
  11. , sequelizeErrors = require('./errors')
  12. , Promise = require('./promise');
  13. /**
  14. * This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
  15. *
  16. * ```js
  17. * var Sequelize = require('sequelize');
  18. * ```
  19. *
  20. * In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
  21. *
  22. * @class Sequelize
  23. */
  24. module.exports = (function() {
  25. /**
  26. * Instantiate sequelize with name of database, username and password
  27. *
  28. * #### Example usage
  29. *
  30. * ```javascript
  31. * // without password and options
  32. * var sequelize = new Sequelize('database', 'username')
  33. *
  34. * // without options
  35. * var sequelize = new Sequelize('database', 'username', 'password')
  36. *
  37. * // without password / with blank password
  38. * var sequelize = new Sequelize('database', 'username', null, {})
  39. *
  40. * // with password and options
  41. * var sequelize = new Sequelize('my_database', 'john', 'doe', {})
  42. *
  43. * // with uri (see below)
  44. * var sequelize = new Sequelize('mysql://localhost:3306/database', {})
  45. * ```
  46. *
  47. * @name Sequelize
  48. * @constructor
  49. *
  50. * @param {String} database The name of the database
  51. * @param {String} [username=null] The username which is used to authenticate against the database.
  52. * @param {String} [password=null] The password which is used to authenticate against the database.
  53. * @param {Object} [options= {}] An object with options.
  54. * @param {String} [options.dialect='mysql'] The dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb
  55. * @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 'pg.js' here
  56. * @param {String} [options.storage] Only used by sqlite. Defaults to ':memory:'
  57. * @param {String} [options.host='localhost'] The host of the relational database.
  58. * @param {Integer} [options.port=] The port of the relational database.
  59. * @param {String} [options.protocol='tcp'] The protocol of the relational database.
  60. * @param {Object} [options.define= {}] Default options for model definitions. See sequelize.define for options
  61. * @param {Object} [options.query= {}] Default options for sequelize.query
  62. * @param {Object} [options.sync= {}] Default options for sequelize.sync
  63. * @param {Function} [options.logging=console.log] A function that gets executed everytime Sequelize would log something.
  64. * @param {Boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
  65. * @param {Boolean} [options.queue=true] Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all queries will be executed immediately.
  66. * @param {int} [options.maxConcurrentQueries=50] The maximum number of queries that should be executed at once if queue is true.
  67. * @param {Boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres
  68. * @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`
  69. * @param {Object} [options.pool= {}] Should sequelize use a connection pool. Default is true
  70. * @param {int} [options.pool.maxConnections]
  71. * @param {int} [options.pool.minConnections]
  72. * @param {int} [options.pool.maxIdleTime] The maximum time, in milliseconds, that a connection can be idle before being released
  73. * @param {function} [options.pool.validateConnection] 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
  74. * @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them.
  75. */
  76. /**
  77. * Instantiate sequlize with an URI
  78. * @name Sequelize
  79. * @constructor
  80. *
  81. * @param {String} uri A full database URI
  82. * @param {object} [options= {}] See above for possible options
  83. */
  84. var Sequelize = function(database, username, password, options) {
  85. var urlParts;
  86. options = options || {};
  87. if (arguments.length === 1 || (arguments.length === 2 && typeof username === 'object')) {
  88. options = username || {};
  89. urlParts = url.parse(arguments[0]);
  90. // SQLite don't have DB in connection url
  91. if (urlParts.pathname) {
  92. database = urlParts.pathname.replace(/^\//, '');
  93. }
  94. options.dialect = urlParts.protocol.replace(/:$/, '');
  95. options.host = urlParts.hostname;
  96. if (urlParts.port) {
  97. options.port = urlParts.port;
  98. }
  99. if (urlParts.auth) {
  100. username = urlParts.auth.split(':')[0];
  101. password = urlParts.auth.split(':')[1];
  102. }
  103. }
  104. this.options = Utils._.extend({
  105. dialect: 'mysql',
  106. dialectModulePath: null,
  107. host: 'localhost',
  108. protocol: 'tcp',
  109. define: {},
  110. query: {},
  111. sync: {},
  112. logging: console.log,
  113. omitNull: false,
  114. native: false,
  115. replication: false,
  116. ssl: undefined,
  117. pool: {},
  118. quoteIdentifiers: true,
  119. language: 'en'
  120. }, options || {});
  121. if (this.options.dialect === 'postgresql') {
  122. this.options.dialect = 'postgres';
  123. }
  124. if (this.options.logging === true) {
  125. console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
  126. this.options.logging = console.log;
  127. }
  128. this.config = {
  129. database: database,
  130. username: username,
  131. password: (((['', null, false].indexOf(password) > -1) || (typeof password === 'undefined')) ? null : password),
  132. host: this.options.host,
  133. port: this.options.port,
  134. pool: this.options.pool,
  135. protocol: this.options.protocol,
  136. queue: this.options.queue,
  137. native: this.options.native,
  138. ssl: this.options.ssl,
  139. replication: this.options.replication,
  140. dialectModulePath: this.options.dialectModulePath,
  141. maxConcurrentQueries: this.options.maxConcurrentQueries,
  142. dialectOptions: this.options.dialectOptions
  143. };
  144. try {
  145. var Dialect = require('./dialects/' + this.getDialect());
  146. this.dialect = new Dialect(this);
  147. } catch (err) {
  148. throw new Error('The dialect ' + this.getDialect() + ' is not supported. ('+err+')');
  149. }
  150. /**
  151. * Models are stored here under the name given to `sequelize.define`
  152. * @property models
  153. */
  154. this.models = {};
  155. this.modelManager = this.daoFactoryManager = new ModelManager(this);
  156. this.connectionManager = this.dialect.connectionManager;
  157. this.importCache = {};
  158. };
  159. /**
  160. * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want to use `Sequelize.Utils._`, which is a reference to the lodash library, if you don't already have it imported in your project.
  161. * @property Utils
  162. * @see {Utils}
  163. */
  164. Sequelize.prototype.Utils = Sequelize.Utils = Utils;
  165. /**
  166. * A modified version of bluebird promises, that allows listening for sql events
  167. * @property Promise
  168. * @see {Promise}
  169. */
  170. Sequelize.prototype.Promise = Sequelize.Promise = Promise;
  171. Sequelize.QueryTypes = QueryTypes;
  172. /**
  173. * 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.
  174. * @property Validator
  175. * @see https://github.com/chriso/validator.js
  176. */
  177. Sequelize.prototype.Validator = Sequelize.Validator = require('validator');
  178. Sequelize.prototype.Model = Sequelize.Model = Model;
  179. for (var dataType in DataTypes) {
  180. Sequelize[dataType] = DataTypes[dataType];
  181. }
  182. Object.defineProperty(Sequelize.prototype, 'connectorManager', {
  183. get: function() {
  184. return this.transactionManager.getConnectorManager();
  185. }
  186. });
  187. /**
  188. * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction
  189. * @property Transaction
  190. * @see {Transaction}
  191. * @see {Sequelize#transaction}
  192. */
  193. Sequelize.prototype.Transaction = Transaction;
  194. /**
  195. * A general error class
  196. * @property Error
  197. */
  198. Sequelize.prototype.Error = Sequelize.Error =
  199. sequelizeErrors.BaseError;
  200. /**
  201. * Emitted when a validation fails
  202. * @property ValidationError
  203. */
  204. Sequelize.prototype.ValidationError = Sequelize.ValidationError =
  205. sequelizeErrors.ValidationError;
  206. /**
  207. * Returns the specified dialect.
  208. *
  209. * @return {String} The specified dialect.
  210. */
  211. Sequelize.prototype.getDialect = function() {
  212. return this.options.dialect;
  213. };
  214. /**
  215. * Returns an instance of QueryInterface.
  216. * @method getQueryInterface
  217. * @return {QueryInterface} An instance (singleton) of QueryInterface.
  218. *
  219. * @see {QueryInterface}
  220. */
  221. Sequelize.prototype.getQueryInterface = function() {
  222. this.queryInterface = this.queryInterface || new QueryInterface(this);
  223. return this.queryInterface;
  224. };
  225. /**
  226. * Returns an instance (singleton) of Migrator.
  227. *
  228. * @see {Migrator}
  229. * @function getMigrator
  230. * @param {Object} [options= {}] See Migrator for options
  231. * @param {Boolean} [force=false] A flag that defines if the migrator should get instantiated or not.
  232. * @return {Migrator} An instance of Migrator.
  233. */
  234. Sequelize.prototype.getMigrator = function(options, force) {
  235. var Migrator = require('./migrator');
  236. if (force) {
  237. this.migrator = new Migrator(this, options);
  238. } else {
  239. this.migrator = this.migrator || new Migrator(this, options);
  240. }
  241. return this.migrator;
  242. };
  243. /**
  244. * Define a new model, representing a table in the DB.
  245. *
  246. * The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
  247. *
  248. * ```js
  249. * sequelize.define('modelName', {
  250. * columnA: {
  251. * type: Sequelize.BOOLEAN,
  252. * validate: {
  253. * is: ["[a-z]",'i'], // will only allow letters
  254. * max: 23, // only allow values <= 23
  255. * isIn: {
  256. * args: [['en', 'zh']],
  257. * msg: "Must be English or Chinese"
  258. * }
  259. * },
  260. * field: 'column_a'
  261. * // Other attributes here
  262. * },
  263. * columnB: Sequelize.STRING,
  264. * columnC: 'MY VERY OWN COLUMN TYPE'
  265. * })
  266. *
  267. * sequelize.models.modelName // The model will now be available in models under the name given to define
  268. * ```
  269. *
  270. *
  271. * As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
  272. *
  273. * For a list of possible data types, see http://sequelizejs.com/docs/latest/models#data-types
  274. *
  275. * For more about getters and setters, see http://sequelizejs.com/docs/latest/models#getters---setters
  276. *
  277. * For more about instance and class methods, see http://sequelizejs.com/docs/latest/models#expansion-of-models
  278. *
  279. * For more about validation, see http://sequelizejs.com/docs/latest/models#validations
  280. *
  281. * @see {DataTypes}
  282. * @see {Hooks}
  283. * @param {String} modelName The name of the model. The model will be stored in `sequelize.models` under this name
  284. * @param {Object} attributes An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below:
  285. * @param {String|DataType|Object} attributes.column The description of a database column
  286. * @param {String|DataType} attributes.column.type A string or a data type
  287. * @param {Boolean} [attributes.column.allowNull=true] If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved.
  288. * @param {Any} [attributes.column.defaultValue=null] A literal default value, a javascript function, or an SQL function (see `sequelize.fn`)
  289. * @param {String|Boolean} [attributes.column.unique=false] If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index
  290. * @param {Boolean} [attributes.column.primaryKey=false]
  291. * @param {String} [attributes.column.field=null] If set, sequelize will map the attribute name to a different name in the database
  292. * @param {Boolean} [attributes.column.autoIncrement=false]
  293. * @param {String} [attributes.column.comment=null]
  294. * @param {String|Model} [attributes.column.references] If this column references another table, provide it here as a Model, or a string
  295. * @param {String} [attributes.column.referencesKey='id'] The column of the foreign table that this column references
  296. * @param {String} [attributes.column.onUpdate] What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
  297. * @param {String} [attributes.column.onDelete] What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
  298. * @param {Function} [attributes.column.get] Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying values.
  299. * @param {Function} [attributes.column.set] Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the underlying values.
  300. * @param {Object} [attributes.validate] An object of validations to execute for this column every time the model is saved. Can be either the name of a validation provided by validator.js, a validation function provided by extending validator.js (see the `DAOValidator` property for more details), or a custom validation function. Custom validation functions are called with the value of the field, and can possibly take a second callback argument, to signal that they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, the callback should be called with the error text.
  301. * @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor
  302. * @param {Object} [options.defaultScope] Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll
  303. * @param {Object} [options.scopes] More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about how scopes are defined, and what you can do with them
  304. * @param {Boolean} [options.omitNull] Don't persits null values. This means that all columns with null values will not be saved
  305. * @param {Boolean} [options.timestamps=true] Adds createdAt and updatedAt timestamps to the model.
  306. * @param {Boolean} [options.paranoid=false] Calling `destroy` will not delete the model, but instead set a `deletedAt` timestamp if this is true. Needs `timestamps=true` to work
  307. * @param {Boolean} [options.underscored=false] Converts all camelCased columns to underscored if true
  308. * @param {Boolean} [options.underscoredAll=false] Converts camelCased model names to underscored tablenames if true
  309. * @param {Boolean} [options.freezeTableName=false] If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the dao name will be pluralized
  310. * @param {String|Boolean} [options.createdAt] Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true
  311. * @param {String|Boolean} [options.updatedAt] Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true
  312. * @param {String|Boolean} [options.deletedAt] Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true
  313. * @param {String} [options.tableName] Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim
  314. * @param {Object} [options.getterMethods] Provide getter functions that work like those defined per column. If you provide a getter method with the same name as a column, it will be used to access the value of that column. If you provide a name that does not match a column, this function will act as a virtual getter, that can fetch multiple other values
  315. * @param {Object} [options.setterMethods] Provide setter functions that work like those defined per column. If you provide a setter method with the same name as a column, it will be used to update the value of that column. If you provide a name that does not match a column, this function will act as a virtual setter, that can act on and set other values, but will not be persisted
  316. * @param {Object} [options.instanceMethods] Provide functions that are added to each instance (DAO)
  317. * @param {Object} [options.classMethods] Provide functions that are added to the model (Model)
  318. * @param {String} [options.schema='public']
  319. * @param {String} [options.engine]
  320. * @param {String} [options.charset]
  321. * @param {String} [options.comment]
  322. * @param {String} [options.collate]
  323. * @param {Object} [options.hooks] An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions.
  324. * @param {Object} [options.validate] An object of model wide validations. Validations have access to all model values via `this`. If the validator function takes an argument, it is asumed to be async, and is called with a callback that accepts an optional error.
  325. *
  326. * @return {Model}
  327. */
  328. Sequelize.prototype.define = function(modelName, attributes, options) {
  329. options = options || {};
  330. var self = this
  331. , globalOptions = this.options;
  332. if (globalOptions.define) {
  333. options = Utils._.extend({}, globalOptions.define, options);
  334. Utils._(['classMethods', 'instanceMethods']).each(function(key) {
  335. if (globalOptions.define[key]) {
  336. options[key] = options[key] || {};
  337. Utils._.defaults(options[key], globalOptions.define[key]);
  338. }
  339. });
  340. }
  341. options.omitNull = globalOptions.omitNull;
  342. options.language = globalOptions.language;
  343. // if you call "define" multiple times for the same modelName, do not clutter the factory
  344. if (this.isDefined(modelName)) {
  345. this.modelManager.removeDAO(this.modelManager.getDAO(modelName));
  346. }
  347. options.sequelize = this;
  348. var factory = new Model(modelName, attributes, options);
  349. this.modelManager.addDAO(factory.init(this.modelManager));
  350. return factory;
  351. };
  352. /**
  353. * Fetch a DAO factory which is already defined
  354. *
  355. * @param {String} modelName The name of a model defined with Sequelize.define
  356. * @throws Will throw an error if the DAO is not define (that is, if sequelize#isDefined returns false)
  357. * @return {Model}
  358. */
  359. Sequelize.prototype.model = function(modelName) {
  360. if (!this.isDefined(modelName)) {
  361. throw new Error(modelName + ' has not been defined');
  362. }
  363. return this.modelManager.getDAO(modelName);
  364. };
  365. /**
  366. * Checks whether a model with the given name is defined
  367. *
  368. * @param {String} modelName The name of a model defined with Sequelize.define
  369. * @return {Boolean}
  370. */
  371. Sequelize.prototype.isDefined = function(modelName) {
  372. var daos = this.modelManager.daos;
  373. return (daos.filter(function(dao) { return dao.name === modelName; }).length !== 0);
  374. };
  375. /**
  376. * Imports a model defined in another file
  377. *
  378. * Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
  379. *
  380. * See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a short example of how to define your models in separate files so that they can be imported by sequelize.import
  381. * @param {String} path 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
  382. * @return {Model}
  383. */
  384. Sequelize.prototype.import = function(path) {
  385. // is it a relative path?
  386. if(Path.normalize(path) !== Path.resolve(path)){
  387. // make path relative to the caller
  388. var callerFilename = Utils.stack()[1].getFileName()
  389. , callerPath = Path.dirname(callerFilename);
  390. path = Path.resolve(callerPath, path);
  391. }
  392. if (!this.importCache[path]) {
  393. var defineCall = (arguments.length > 1 ? arguments[1] : require(path));
  394. this.importCache[path] = defineCall(this, DataTypes);
  395. }
  396. return this.importCache[path];
  397. };
  398. Sequelize.prototype.migrate = function(options) {
  399. return this.getMigrator().migrate(options);
  400. };
  401. /**
  402. * Execute a query on the DB, with the posibility to bypass all the sequelize goodness.
  403. *
  404. * If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.
  405. *
  406. * @method query
  407. * @param {String} sql
  408. * @param {Model} [callee] If callee is provided, the selected data will be used to build an instance of the DAO represented by the factory. Equivalent to calling Model.build with the values provided by the query.
  409. * @param {Object} [options= {}] Query options.
  410. * @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
  411. * @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
  412. * @param [String] [options.type='SELECT'] The type of query you are executing. The query type affects how results are formatted before they are passed back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to SELECT. The type is a string, but `Sequelize.QueryTypes` is provided is convenience shortcuts. Current options are SELECT, BULKUPDATE and BULKDELETE
  413. * @param {Object|Array} [replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
  414. * @return {Promise}
  415. *
  416. * @see {Model#build} for more information about callee.
  417. */
  418. Sequelize.prototype.query = function(sql, callee, options, replacements) {
  419. var self = this;
  420. sql = sql.trim();
  421. if (arguments.length === 4) {
  422. if (Array.isArray(replacements)) {
  423. sql = Utils.format([sql].concat(replacements), this.options.dialect);
  424. }
  425. else {
  426. sql = Utils.formatNamedParameters(sql, replacements, this.options.dialect);
  427. }
  428. } else if (arguments.length === 3) {
  429. options = options;
  430. } else if (arguments.length === 2) {
  431. options = {};
  432. } else {
  433. options = { raw: true };
  434. }
  435. options = Utils._.extend(Utils._.clone(this.options.query), options);
  436. options = Utils._.defaults(options, {
  437. logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log,
  438. type: (sql.toLowerCase().indexOf('select') === 0) ? QueryTypes.SELECT : false
  439. });
  440. return Promise.resolve(
  441. options.transaction ? options.transaction.connection : self.connectionManager.getConnection()
  442. ).then(function (connection) {
  443. var query = new self.dialect.Query(connection, self, callee, options);
  444. return query.run(sql).finally(function() {
  445. if (options.transaction) return;
  446. return self.connectionManager.releaseConnection(connection);
  447. });
  448. });
  449. };
  450. /**
  451. * Create a new database schema.
  452. *
  453. * Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
  454. * not a database table. In mysql and sqlite, this command will do nothing.
  455. *
  456. * @see {Model#schema}
  457. * @param {String} schema Name of the schema
  458. * @return {Promise}
  459. */
  460. Sequelize.prototype.createSchema = function(schema) {
  461. return this.getQueryInterface().createSchema(schema);
  462. };
  463. /**
  464. * Show all defined schemas
  465. *
  466. * Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
  467. * not a database table. In mysql and sqlite, this will show all tables.
  468. * @return {Promise}
  469. */
  470. Sequelize.prototype.showAllSchemas = function() {
  471. return this.getQueryInterface().showAllSchemas();
  472. };
  473. /**
  474. * Drop a single schema
  475. *
  476. * Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
  477. * not a database table. In mysql and sqlite, this drop a table matching the schema name
  478. * @param {String} schema Name of the schema
  479. * @return {Promise}
  480. */
  481. Sequelize.prototype.dropSchema = function(schema) {
  482. return this.getQueryInterface().dropSchema(schema);
  483. };
  484. /**
  485. * Drop all schemas
  486. *
  487. * Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
  488. * not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
  489. * @return {Promise}
  490. */
  491. Sequelize.prototype.dropAllSchemas = function() {
  492. return this.getQueryInterface().dropAllSchemas();
  493. };
  494. /**
  495. * Sync all defined DAOs to the DB.
  496. *
  497. * @param {Object} [options= {}]
  498. * @param {Boolean} [options.force=false] If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table
  499. * @param {Boolean|function} [options.logging=console.log] A function that logs sql queries, or false for no logging
  500. * @param {String} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define
  501. * @return {Promise}
  502. */
  503. Sequelize.prototype.sync = function(options) {
  504. var self = this;
  505. options = Utils._.defaults(options || {}, this.options.sync, this.options);
  506. options.logging = options.logging === undefined ? false : options.logging;
  507. var when;
  508. if (options.force) {
  509. when = this.drop(options);
  510. } else {
  511. when = Promise.resolve();
  512. }
  513. return when.then(function() {
  514. var daos = [];
  515. // Topologically sort by foreign key constraints to give us an appropriate
  516. // creation order
  517. self.modelManager.forEachDAO(function(dao) {
  518. if (dao) {
  519. daos.push(dao);
  520. } else {
  521. // DB should throw an SQL error if referencing inexistant table
  522. }
  523. });
  524. return Promise.reduce(daos, function(total, dao) {
  525. return dao.sync(options);
  526. }, null);
  527. });
  528. };
  529. /**
  530. * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
  531. * @see {Model#drop} for options
  532. *
  533. * @param {object} options The options passed to each call to Model.drop
  534. * @return {Promise}
  535. */
  536. Sequelize.prototype.drop = function(options) {
  537. var daos = [];
  538. this.modelManager.forEachDAO(function(dao) {
  539. if (dao) {
  540. daos.push(dao);
  541. }
  542. }, { reverse: false});
  543. return Promise.reduce(daos, function(total, dao) {
  544. return dao.drop(options);
  545. }, null);
  546. };
  547. /**
  548. * Test the connection by trying to authenticate
  549. *
  550. * @fires success If authentication was successfull
  551. * @error 'Invalid credentials' if the authentication failed (even if the database did not respond at all...)
  552. * @alias validate
  553. * @return {Promise}
  554. */
  555. Sequelize.prototype.authenticate = function() {
  556. return this.query('SELECT 1+1 AS result', null, { raw: true, plain: true }).return().catch(function(err) {
  557. throw new Error(err);
  558. });
  559. };
  560. Sequelize.prototype.validate = Sequelize.prototype.authenticate;
  561. /**
  562. * Creates a 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.
  563. * 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.
  564. *
  565. * Convert a user's username to upper case
  566. * ```js
  567. * instance.updateAttributes({
  568. * username: self.sequelize.fn('upper', self.sequelize.col('username'))
  569. * })
  570. * ```
  571. *
  572. * @see {Model#find}
  573. * @see {Model#findAll}
  574. * @see {Model#define}
  575. * @see {Sequelize#col}
  576. * @method fn
  577. *
  578. * @param {String} fn The function you want to call
  579. * @param {any} args All further arguments will be passed as arguments to the function
  580. *
  581. * @since v2.0.0-dev3
  582. * @return {Sequelize.fn}
  583. */
  584. Sequelize.fn = Sequelize.prototype.fn = function(fn) {
  585. return new Utils.fn(fn, Array.prototype.slice.call(arguments, 1));
  586. };
  587. /**
  588. * Creates a object representing a column in the DB. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped.
  589. * @see {Sequelize#fn}
  590. *
  591. * @method col
  592. * @param {String} col The name of the column
  593. * @since v2.0.0-dev3
  594. * @return {Sequelize.col}
  595. */
  596. Sequelize.col = Sequelize.prototype.col = function(col) {
  597. return new Utils.col(col);
  598. };
  599. /**
  600. * Creates a object representing a call to the cast function.
  601. *
  602. * @method cast
  603. * @param {any} val The value to cast
  604. * @param {String} type The type to cast it to
  605. * @since v2.0.0-dev3
  606. * @return {Sequelize.cast}
  607. */
  608. Sequelize.cast = Sequelize.prototype.cast = function(val, type) {
  609. return new Utils.cast(val, type);
  610. };
  611. /**
  612. * Creates a object representing a literal, i.e. something that will not be escaped.
  613. *
  614. * @method literal
  615. * @param {any} val
  616. * @alias asIs
  617. * @since v2.0.0-dev3
  618. * @return {Sequelize.literal}
  619. */
  620. Sequelize.literal = Sequelize.prototype.literal = function(val) {
  621. return new Utils.literal(val);
  622. };
  623. Sequelize.asIs = Sequelize.prototype.asIs = function(val) {
  624. return new Utils.asIs(val);
  625. };
  626. /**
  627. * An AND query
  628. * @see {Model#find}
  629. *
  630. * @method and
  631. * @param {String|Object} args Each argument will be joined by AND
  632. * @since v2.0.0-dev3
  633. * @return {Sequelize.and}
  634. */
  635. Sequelize.and = Sequelize.prototype.and = function() {
  636. return new Utils.and(Array.prototype.slice.call(arguments));
  637. };
  638. /**
  639. * An OR query
  640. * @see {Model#find}
  641. *
  642. * @method or
  643. * @param {String|Object} args Each argument will be joined by OR
  644. * @since v2.0.0-dev3
  645. * @return {Sequelize.or}
  646. */
  647. Sequelize.or = Sequelize.prototype.or = function() {
  648. return new Utils.or(Array.prototype.slice.call(arguments));
  649. };
  650. /*
  651. * A way of specifying attr = condition. Mostly used internally
  652. * @see {Model#find}
  653. *
  654. * @param {string} attr The attribute
  655. * @param {String|Object} condition The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` etc.)
  656. * @method where
  657. * @alias condition
  658. * @since v2.0.0-dev3
  659. * @return {Sequelize.where}
  660. */
  661. Sequelize.where = Sequelize.prototype.where = function() {
  662. return new Utils.where(Array.prototype.slice.call(arguments));
  663. };
  664. Sequelize.condition = Sequelize.prototype.condition = function() {
  665. return new Utils.condition(Array.prototype.slice.call(arguments));
  666. };
  667. /**
  668. * 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
  669. *
  670. * ```js
  671. * sequelize.transaction().then(function (t) {
  672. * return User.find(..., { transaction: t}).then(function (user) {
  673. * return user.updateAttributes(..., { transaction: t});
  674. * })
  675. * .then(t.commit.bind(t))
  676. * .catch(t.rollback.bind(t));
  677. * })
  678. * ```
  679. *
  680. * @see {Transaction}
  681. * @param {Object} [options= {}]
  682. * @param {Boolean} [options.autocommit=true]
  683. * @param {String} [options.isolationLevel='REPEATABLE READ'] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
  684. * @return {Promise}
  685. * @fires error If there is an uncaught error during the transaction
  686. * @fires success When the transaction has ended (either comitted or rolled back)
  687. */
  688. Sequelize.prototype.transaction = function(options) {
  689. if (Utils._.any(arguments, Utils._.isFunction)) {
  690. throw new Error('DEPRECATION WARNING: This function no longer accepts callbacks. Use sequelize.transaction().then(function (t) {}) instead.');
  691. }
  692. var transaction = new Transaction(this, options);
  693. return transaction.prepareEnvironment().then(function() {
  694. return transaction;
  695. });
  696. };
  697. Sequelize.prototype.log = function() {
  698. var args = [].slice.call(arguments);
  699. if (this.options.logging) {
  700. if (this.options.logging === true) {
  701. console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
  702. this.options.logging = console.log;
  703. }
  704. this.options.logging.apply(null, args);
  705. }
  706. };
  707. return Sequelize;
  708. })();