Class Sequelize

View code

This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:

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.


View code

Instantiate sequelize with name of database, username and password

Example usage

  1. var sequelize = new Sequelize('database', 'username')
  2. // without options
  3. var sequelize = new Sequelize('database', 'username', 'password')
  4. // without password / with blank password
  5. var sequelize = new Sequelize('database', 'username', null, {})
  6. // with password and options
  7. var sequelize = new Sequelize('my_database', 'john', 'doe', {})
  8. // with uri (see below)
  9. var sequelize = new Sequelize('mysql://localhost:3306/database', {})

Params:


new Sequelize(uri, [options={}])

View code

Instantiate sequelize with an URI

Params:

NameTypeDescription
uriStringA full database URI
[options={}]objectSee above for possible options

new Sequelize([options={}])

Instantiate sequelize with an options object

Params:

NameTypeDescription
[options={}]objectSee above for possible options

models

View code

Models are stored here under the name given to sequelize.define


version

Sequelize version number.


Sequelize

View code

A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.

See:


Utils

View code

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.


Promise

A handy reference to the bluebird Promise class


QueryTypes

View code

Available query types for use with sequelize.query


Validator

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.

See:


DataTypes

View code

A reference to the sequelize class holding commonly used data types. The datatypes are used when defining a new model using sequelize.define


Transaction

A reference to the sequelize transaction class. Use this to access isolationLevels and types when creating a transaction

See:


Deferrable

View code

A reference to the deferrable collection. Use this to access the different deferrable options.

See:


Instance

A reference to the sequelize instance class.

See:


Association

A reference to the sequelize association class.

See:


Error

A general error class

See:


ValidationError

Emitted when a validation fails

See:


ValidationErrorItem

Describes a validation error on an instance path

See:


DatabaseError

A base class for all database related errors.

See:


View code

Thrown when a database query times out because of a deadlock

See:


UniqueConstraintError

View code

Thrown when a unique constraint is violated in the database

See:


ExclusionConstraintError

View code

Thrown when an exclusion constraint is violated in the database

See:


ForeignKeyConstraintError

View code

See:


ConnectionError

A base class for all connection related errors.

See:


ConnectionRefusedError

Thrown when a connection to a database is refused

See:


AccessDeniedError

Thrown when a connection to a database is refused due to insufficient access

See:


HostNotFoundError

Thrown when a connection to a database has a hostname that was not found

See:


HostNotReachableError

Thrown when a connection to a database has a hostname that was not reachable

See:


InvalidConnectionError

Thrown when a connection to a database has invalid values for any of the connection parameters

See:


ConnectionTimedOutError

Thrown when a connection to a database times out

See:


InstanceError

Thrown when a some problem occurred with Instance methods (see message for details)

See:


EmptyResultError

Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)

See:


getDialect() -> String

Returns the specified dialect.Returns: The specified dialect.


getQueryInterface() -> QueryInterface

View code

Returns an instance of QueryInterface.

See:

Returns: An instance (singleton) of QueryInterface.


define(modelName, attributes, [options]) -> Model

View code

Define a new model, representing a table in the DB.

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:

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.

For a list of possible data types, see

For more about getters and setters, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters

For more about instance and class methods, see

For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations

See:

Params:

NameTypeDescription
modelNameStringThe name of the model. The model will be stored in sequelize.models under this name
attributesObjectAn 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:
attributes.columnString | DataType | ObjectThe description of a database column
attributes.column.typeString | DataTypeA string or a data type
[attributes.column.allowNull=true]BooleanIf false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved.
[attributes.column.defaultValue=null]AnyA literal default value, a JavaScript function, or an SQL function (see sequelize.fn)
[attributes.column.unique=false]String | BooleanIf 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
[attributes.column.primaryKey=false]Boolean
[attributes.column.field=null]StringIf set, sequelize will map the attribute name to a different name in the database
[attributes.column.autoIncrement=false]Boolean
[attributes.column.comment=null]String
[attributes.column.references=null]String | ModelAn object with reference configurations
[attributes.column.references.model]String | ModelIf this column references another table, provide it here as a Model, or a string
[attributes.column.references.key='id']StringThe column of the foreign table that this column references
[attributes.column.onUpdate]StringWhat should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
[attributes.column.onDelete]StringWhat should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
[attributes.column.get]FunctionProvide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values.
[attributes.column.set]FunctionProvide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values.
[attributes.validate]ObjectAn 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.
[options]ObjectThese options are merged with the default define options provided to the Sequelize constructor
[options.defaultScope={}]ObjectDefine the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll
[options.scopes]ObjectMore 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
[options.omitNull]BooleanDon't persist null values. This means that all columns with null values will not be saved
[options.timestamps=true]BooleanAdds createdAt and updatedAt timestamps to the model.
[options.paranoid=false]BooleanCalling destroy will not delete the model, but instead set a timestamp if this is true. Needs timestamps=true to work
[options.underscored=false]BooleanConverts all camelCased columns to underscored if true
[options.underscoredAll=false]BooleanConverts camelCased model names to underscored table names if true
[options.freezeTableName=false]BooleanIf freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the model name will be pluralized
[options.name]ObjectAn object with two attributes, singular and plural, which are used when this model is associated to others.
[options.name.singular=inflection.singularize(modelName)]String
[options.name.plural=inflection.pluralize(modelName)]String
[options.indexes]Array.<Object>
[options.indexes[].name]StringThe name of the index. Defaults to model name + + fields concatenated
[options.indexes[].type]StringIndex type. Only used by mysql. One of UNIQUE, FULLTEXT and SPATIAL
[options.indexes[].method]StringThe method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, and postgres additionally supports GIST and GIN.
[options.indexes[].unique=false]BooleanShould the index by unique? Can also be triggered by setting type to UNIQUE
[options.indexes[].concurrently=false]BooleanPostgreSQL will build the index without taking any write locks. Postgres only
[options.indexes[].fields]Array.<String | Object>An array of the fields to index. Each field can either be a string containing the name of the field, a sequelize object (e.g sequelize.fn), or an object with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the direction the column should be sorted in), collate (the collation (sort order) for the column)
[options.createdAt]String | BooleanOverride the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting.
[options.updatedAt]String | BooleanOverride the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting.
[options.deletedAt]String | BooleanOverride the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting.
[options.tableName]StringDefaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim
[options.getterMethods]ObjectProvide 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
[options.setterMethods]ObjectProvide 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
[options.instanceMethods]ObjectProvide functions that are added to each instance (DAO). If you override methods provided by sequelize, you can access the original method using this.constructor.super.prototype, e.g. this.constructor.super_.prototype.toJSON.apply(this, arguments)
[options.classMethods]ObjectProvide functions that are added to the model (Model). If you override methods provided by sequelize, you can access the original method using this.constructor.prototype, e.g. this.constructor.prototype.find.apply(this, arguments)
[options.schema='public']String
[options.engine]String
[options.charset]String
[options.comment]String
[options.collate]String
[options.initialAutoIncrement]StringSet the initial AUTO_INCREMENT value for the table in MySQL.
[options.hooks]ObjectAn object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, validationFailed, 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.
[options.validate]ObjectAn object of model wide validations. Validations have access to all model values via this. If the validator function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional error.

model(modelName) -> Model

Fetch a Model which is already defined

Params:

NameTypeDescription
modelNameStringThe name of a model defined with Sequelize.define

isDefined(modelName) -> Boolean

View code

Checks whether a model with the given name is defined

Params:

NameTypeDescription
modelNameStringThe name of a model defined with Sequelize.define

import(path) -> Model

Imports a model defined in another file

Imported models are cached, so multiple calls to import with the same path will not load the file multiple times

See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import

Params:

NameTypeDescription
pathStringThe 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

View code

Execute a query on the DB, with the possibility to bypass all the sequelize goodness.

By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use .spread to access the results.

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:

  1. sequelize.query('SELECT...').spread(function (results, metadata) {
  2. // Raw query - use spread
  3. });
  4. sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(function (results) {
  5. // SELECT query - use then
  6. })

See:

Params:

NameTypeDescription
sqlString
[options={}]ObjectQuery options.
[options.raw]BooleanIf true, sequelize will not try to format the results of the query, or build an instance of a model from the result
[options.transaction=null]TransactionThe transaction that the query should be executed under
[options.type='RAW']StringThe 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.
[options.nest=false]BooleanIf true, transforms objects with . separated property names into nested objects using 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
[options.plain=false]BooleanSets the query type to SELECT and return a single row
[options.replacements]Object | ArrayEither an object of named parameter replacements in the format or an array of unnamed replacements to replace ? in your SQL.
[options.bind]Object | ArrayEither an object of named bind parameter in the format $param or an array of unnamed bind parameter to replace $1, $2, … in your SQL.
[options.useMaster=false]BooleanForce the query to use the write pool, regardless of the query type.
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.instance]InstanceA sequelize instance used to build the return instance
[options.model]ModelA sequelize model used to build the returned model instances (used to be called callee)
[options.retry]ObjectSet of flags that control when a query is automatically retried.
[options.retry.match]ArrayOnly retry a query if the error matches one of these strings.
[options.retry.max]IntegerHow many times a failing query is automatically retried.
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)
[options.supportsSearchPath]BooleanIf false do not prepend the query with the search_path (Postgres only)
[options.mapToModel=false]ObjectMap returned fields to model's fields if options.model or options.instance is present. Mapping will occur before building the model instance.
[options.fieldMap]ObjectMap returned fields to arbitrary names for SELECT query type.

set(variables, options) -> Promise

Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.Only works for MySQL.

Params:


escape(value) -> String

View code

Escape value.

Params:

NameTypeDescription
valueString

createSchema(schema, options={}) -> Promise

Note,that this is a schema in the postgres sense of the word,not a database table. In mysql and sqlite, this command will do nothing.

See:

Params:

NameTypeDescription
schemaStringName of the schema
options={}Object
options.loggingBoolean | functionA function that logs sql queries, or false for no logging

showAllSchemas(options={}) -> Promise

View code

Show all defined schemas

Note,that this is a schema in the ,not a database table. In mysql and sqlite, this will show all tables.

Params:

NameTypeDescription
options={}Object
options.loggingBoolean | functionA function that logs sql queries, or false for no logging

dropSchema(schema, options={}) -> Promise

View code

Drop a single schema

Note,that this is a schema in the ,not a database table. In mysql and sqlite, this drop a table matching the schema name

Params:

NameTypeDescription
schemaStringName of the schema
options={}Object
options.loggingBoolean | functionA function that logs sql queries, or false for no logging

dropAllSchemas(options={}) -> Promise

View code

Drop all schemas

Note,that this is a schema in the ,not a database table. In mysql and sqlite, this is the equivalent of drop all tables.

Params:

NameTypeDescription
options={}Object
options.loggingBoolean | functionA function that logs sql queries, or false for no logging

sync([options={}]) -> Promise

View code

Sync all defined models to the DB.

Params:

NameTypeDescription
[options={}]Object
[options.force=false]BooleanIf force is true, each DAO will do DROP TABLE IF EXISTS …, before it tries to create its own table
[options.match]RegExMatch a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code
[options.logging=console.log]Boolean | functionA function that logs sql queries, or false for no logging
[options.schema='public']StringThe schema that the tables should be created in. This can be overriden for each table in sequelize.define
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)
[options.hooks=true]BooleanIf hooks is true then beforeSync, afterSync, beforBulkSync, afterBulkSync hooks will be called

truncate([options]) -> Promise

Truncate all tables defined through the sequelize models. This is doneby calling Model.truncate() on each model.

See:

Params:

NameTypeDescription
[options]objectThe options passed to Model.destroy in addition to truncate
[options.transaction]Boolean | function
[options.logging]Boolean | functionA function that logs sql queries, or false for no logging

drop(options) -> Promise

Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model

See:

Params:


authenticate() -> Promise

Test the connection by trying to authenticateAliases: validate


fn(fn, args) -> Sequelize.fn

View code

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.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.

Convert a user's username to upper case

See:

Params:

NameTypeDescription
fnStringThe function you want to call
argsanyAll further arguments will be passed as arguments to the function

col(col) -> Sequelize.col

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.

See:

Params:

NameTypeDescription
colStringThe name of the column

cast(val, type) -> Sequelize.cast

Creates a object representing a call to the cast function.

Params:

NameTypeDescription
valanyThe value to cast
typeStringThe type to cast it to

literal(val) -> Sequelize.literal

View code

Creates a object representing a literal, i.e. something that will not be escaped.

Params:

NameTypeDescription
valany

Aliases: asIs


and(args) -> Sequelize.and

An AND query

See:

Params:

NameTypeDescription
argsString | ObjectEach argument will be joined by AND

or(args) -> Sequelize.or

An OR query

See:

Params:

NameTypeDescription
argsString | ObjectEach argument will be joined by OR

json(conditions, [value]) -> Sequelize.json

Creates an object representing nested where conditions for postgres's json data-type.

See:

Params:

NameTypeDescription
conditionsString | ObjectA hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.
[value]String | Number | BooleanAn optional value to compare against. Produces a string of the form "<json path> = '<value>'".

where(attr, [comparator='='], logic) -> Sequelize.where

A way of specifying attr = condition.

The attr can either be an object taken from Model.rawAttributes (for example Model.rawAttributes.id or Model.rawAttributes.name). Theattribute 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.)

For string attributes, use the regular { where: { attr: something }} syntax. If you don't want your string to be escaped, use sequelize.literal.

See:

Params:

Aliases: condition


View code

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

  1. sequelize.transaction().then(function (t) {
  2. return User.find(..., { transaction: t}).then(function (user) {
  3. return user.updateAttributes(..., { transaction: t});
  4. })
  5. .then(t.commit.bind(t))
  6. .catch(t.rollback.bind(t));
  7. })

A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:

If you have enabled, the transaction will automatically be passed to any query that runs within the callback.To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:

  1. var cls = require('continuation-local-storage'),
  2. ns = cls.createNamespace('....');
  3. var Sequelize = require('sequelize');
  4. Sequelize.cls = ns;

Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace

See:

Params:

NameTypeDescription
[options={}]Object
[options.autocommit=true]Boolean
[options.type='DEFERRED']StringSee Sequelize.Transaction.TYPES for possible options. Sqlite only.
[options.isolationLevel='REPEATABLE_READ']StringSee for possible options
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.

This document is automatically generated based on source code comments. Please do not edit it directly, as your changes will be ignored. Please write on IRC, open an issue or a create a pull request if you feel something can be improved. For help on how to write source code documentation see and dox