Back to Sequelize

Class Sequelize

static/v2/api/sequelize/index.html

latest33.1 KB
Original Source

Class Sequelize

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

var Sequelize = require('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.


new Sequelize(database, [username=null], [password=null], [options={}])

View code Instantiate sequelize with name of database, username and password

Example usage

// without password and options
var sequelize = new Sequelize('database', 'username')

// without options
var sequelize = new Sequelize('database', 'username', 'password')

// without password / with blank password
var sequelize = new Sequelize('database', 'username', null, {})

// with password and options
var sequelize = new Sequelize('my_database', 'john', 'doe', {})

// with uri (see below)
var sequelize = new Sequelize('mysql://localhost:3306/database', {})

Params:

NameTypeDescription
databaseStringThe name of the database
[username=null]StringThe username which is used to authenticate against the database.
[password=null]StringThe password which is used to authenticate against the database.
[options={}]ObjectAn object with options.
[options.dialect='mysql']StringThe dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb
[options.dialectModulePath=null]StringIf 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
[options.dialectOptions]ObjectAn object of additional options, which are passed directly to the connection library
[options.storage]StringOnly used by sqlite. Defaults to ':memory:'
[options.host='localhost']StringThe host of the relational database.
[options.port=]IntegerThe port of the relational database.
[options.protocol='tcp']StringThe protocol of the relational database.
[options.define={}]ObjectDefault options for model definitions. See sequelize.define for options
[options.query={}]ObjectDefault options for sequelize.query
[options.set={}]ObjectDefault options for sequelize.set
[options.sync={}]ObjectDefault options for sequelize.sync
[options.timezone='+00:00']StringThe 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.
[options.logging=console.log]FunctionA function that gets executed everytime Sequelize would log something.
[options.omitNull=false]BooleanA flag that defines if null values should be passed to SQL queries or not.
[options.queue=true]BooleanQueue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all queries will be executed immediately.
[options.maxConcurrentQueries=50]IntegerThe maximum number of queries that should be executed at once if queue is true.
[options.native=false]BooleanA flag that defines if native library shall be used or not. Currently only has an effect for postgres
[options.replication=false]BooleanUse 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
[options.pool={}]ObjectShould sequelize use a connection pool. Default is true
[options.pool.maxConnections]Integer
[options.pool.minConnections]Integer
[options.pool.maxIdleTime]IntegerThe maximum time, in milliseconds, that a connection can be idle before being released
[options.pool.validateConnection]FunctionA function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
[options.quoteIdentifiers=true]BooleanSet to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them.

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

View code Instantiate sequlize with an URI

Params:

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

models

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


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.

See:


Promise

View code A modified version of bluebird promises, that allows listening for sql events

See:


Validator

View code 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:


Transaction

View code A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction

See:


Instance

View code A reference to the sequelize instance class.

See:


Error

View code A general error class

See:


ValidationError

View code Emitted when a validation fails

See:


ValidationErrorItem

View code Describes a validation error on an instance path

See:


DatabaseError

View code A base class for all database related errors.

See:


TimeoutError

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:


ForeignKeyConstraintError

View code Thrown when a foreign key constraint is violated in the database

See:


getDialect() -> String

View code Returns the specified dialect.

Returns: The specified dialect.


getQueryInterface() -> QueryInterface

View code Returns an instance of QueryInterface.

See:

Returns: An instance (singleton) of QueryInterface.


getMigrator([options={}], [force=false]) -> Migrator

View code Returns an instance (singleton) of Migrator.

See:

Params:

NameTypeDescription
[options={}]ObjectSee Migrator for options
[force=false]BooleanA flag that defines if the migrator should get instantiated or not.

Returns: An instance of Migrator.


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:

sequelize.define('modelName', {
    columnA: {
        type: Sequelize.BOOLEAN,
        validate: {
          is: ["[a-z]",'i'], // will only allow letters
          max: 23, // only allow values <= 23
          isIn: {
            args: [['en', 'zh']],
            msg: "Must be English or Chinese"
          }
        },
        field: 'column_a'
        // Other attributes here
    },
    columnB: Sequelize.STRING,
    columnC: 'MY VERY OWN COLUMN TYPE'
})

sequelize.models.modelName // The model will now be available in models under the name given to define

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 http://sequelizejs.com/docs/latest/models#data-types

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

For more about instance and class methods, see http://sequelizejs.com/docs/latest/models#expansion-of-models

For more about validation, see http://sequelizejs.com/docs/latest/models#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.columnStringDataType
attributes.column.typeStringDataType
[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]StringBoolean
[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]StringModel
[attributes.column.referencesKey='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 persits 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 deletedAt 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 tablenames 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 dao 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<StringObject>
[options.createdAt]StringBoolean
[options.updatedAt]StringBoolean
[options.deletedAt]StringBoolean
[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.hooks]ObjectAn 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.
[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 asumed to be async, and is called with a callback that accepts an optional error.

model(modelName) -> Model

View code Fetch a DAO factory 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

View code 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/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

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

query(sql, [callee], [options={}], [replacements]) -> Promise

View code Execute a query on the DB, with the posibility to bypass all the sequelize goodness.

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.

See:

Params:

NameTypeDescription
sqlString
[callee]InstanceIf callee is provided, the returned data will be put into the callee
[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='SELECT']StringThe 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
[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' }}
[replacements]ObjectArray

set(variables, options) -> Promise

View code 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:

NameTypeDescription
variablesObjectObject with multiple variables.
optionsObjectQuery options.
options.transactionTransactionThe transaction that the query should be executed under

createSchema(schema) -> Promise

View code Create a new database schema.

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

showAllSchemas() -> Promise

View code Show all defined schemas

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


dropSchema(schema) -> Promise

View code Drop a single schema

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

Params:

NameTypeDescription
schemaStringName of the schema

dropAllSchemas() -> Promise

View code Drop all schemas

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


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

View code Sync all defined DAOs 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]Booleanfunction
[options.schema='public']StringThe schema that the tables should be created in. This can be overriden for each table in sequelize.define

drop(options) -> Promise

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

See:

Params:

NameTypeDescription
optionsobjectThe options passed to each call to Model.drop

authenticate() -> Promise

View code Test the connection by trying to authenticate

Aliases: 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

instance.updateAttributes({
  username: self.sequelize.fn('upper', self.sequelize.col('username'))
})

See:

Params:

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

col(col) -> Sequelize.col

View code 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

View code 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

View code An AND query

See:

Params:

NameTypeDescription
argsStringObject

or(args) -> Sequelize.or

View code An OR query

See:

Params:

NameTypeDescription
argsStringObject

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

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

See:

Params:

NameTypeDescription
conditionsStringObject
[value]StringNumber

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

View code 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). The 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.)

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:

NameTypeDescription
attrObjectThe 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
[comparator='=']string
logicStringObject

Aliases: condition


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

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

sequelize.transaction().then(function (t) {
  return User.find(..., { transaction: t}).then(function (user) {
    return user.updateAttributes(..., { transaction: t});
  })
  .then(t.commit.bind(t))
  .catch(t.rollback.bind(t));
})

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

sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then()
  return User.find(..., { transaction: t}).then(function (user) {
    return user.updateAttributes(..., { transaction: t});
  });
}).then(function () {
  // Commited
}).catch(function (err) {
  // Rolled back
  console.error(err);
});

See:

Params:

NameTypeDescription
[options={}]Object
[options.autocommit=true]Boolean
[options.isolationLevel='REPEATABLEStringREAD'] See Sequelize.Transaction.ISOLATION_LEVELS for possible options

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 JSDoc and dox