不要怂,就是干,撸起袖子干!

Commit 0dd07ac1 by Mick Hansen

Merge pull request #3702 from sequelize/feature/deferrable-constraints

Deferrable constraints for PostgreSQL
2 parents 341b0172 c79e5302
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
- [FIXED] `include.attributes = []` will no longer force the inclusion of the primary key, making it possible to write aggregates with includes. - [FIXED] `include.attributes = []` will no longer force the inclusion of the primary key, making it possible to write aggregates with includes.
- [CHANGED] The `references` property of model attributes has been transformed to an object: `{type: Sequelize.INTEGER, references: { model: SomeModel, key: 'some_key' }}`. The former format (`references` and `referecesKey`) still exists but is deprecated and will be removed in 4.0. - [CHANGED] The `references` property of model attributes has been transformed to an object: `{type: Sequelize.INTEGER, references: { model: SomeModel, key: 'some_key' }}`. The former format (`references` and `referecesKey`) still exists but is deprecated and will be removed in 4.0.
- [ADDED] It is now possible to defer constraints in PostgreSQL by added a property `deferrable` to the `references` object of a field.
# 3.0.0 # 3.0.0
......
<a name="mixin"></a> <a name="mixin"></a>
# Mixin Mixin # Mixin Mixin
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/associations/mixin.js#L95) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/associations/mixin.js#L95)
Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany functions Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany functions
on a model (the source), and providing another model as the first argument to the function (the target). on a model (the source), and providing another model as the first argument to the function (the target).
...@@ -89,7 +89,7 @@ you should either disable some constraints, or rethink your associations complet ...@@ -89,7 +89,7 @@ you should either disable some constraints, or rethink your associations complet
<a name="hasone"></a> <a name="hasone"></a>
## `hasOne(target, [options])` ## `hasOne(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/associations/mixin.js#L145) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/associations/mixin.js#L145)
Creates an association between this (the source) and the provided target. The foreign key is added on the target. Creates an association between this (the source) and the provided target. The foreign key is added on the target.
Example: `User.hasOne(Profile)`. This will add userId to the profile table. Example: `User.hasOne(Profile)`. This will add userId to the profile table.
...@@ -121,7 +121,7 @@ All methods return a promise ...@@ -121,7 +121,7 @@ All methods return a promise
<a name="belongsto"></a> <a name="belongsto"></a>
## `belongsTo(target, [options])` ## `belongsTo(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/associations/mixin.js#L170) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/associations/mixin.js#L170)
Creates an association between this (the source) and the provided target. The foreign key is added on the source. Creates an association between this (the source) and the provided target. The foreign key is added on the source.
Example: `Profile.belongsTo(User)`. This will add userId to the profile table. Example: `Profile.belongsTo(User)`. This will add userId to the profile table.
...@@ -153,7 +153,7 @@ All methods return a promise ...@@ -153,7 +153,7 @@ All methods return a promise
<a name="hasmany"></a> <a name="hasmany"></a>
## `hasMany(target, [options])` ## `hasMany(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/associations/mixin.js#L245) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/associations/mixin.js#L245)
Create an association that is either 1:m or n:m. Create an association that is either 1:m or n:m.
```js ```js
...@@ -236,7 +236,7 @@ user.getProjects().success(function (projects) { ...@@ -236,7 +236,7 @@ user.getProjects().success(function (projects) {
<a name="belongstomany"></a> <a name="belongstomany"></a>
## `belongsToMany(target, [options])` ## `belongsToMany(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/associations/mixin.js#L339) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/associations/mixin.js#L339)
Create an N:M association with a join table Create an N:M association with a join table
```js ```js
......
<a name="datatypes"></a> <a name="datatypes"></a>
# Class DataTypes # Class DataTypes
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L37) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L37)
A convenience class holding commonly used data types. The datatypes are used when definining a new model using `Sequelize.define`, like this: A convenience class holding commonly used data types. The datatypes are used when definining a new model using `Sequelize.define`, like this:
```js ```js
sequelize.define('model', { sequelize.define('model', {
...@@ -33,7 +33,7 @@ sequelize.define('model', { ...@@ -33,7 +33,7 @@ sequelize.define('model', {
<a name="string"></a> <a name="string"></a>
## `STRING()` ## `STRING()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L55) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L55)
A variable length string. Default length 255 A variable length string. Default length 255
Available properties: `BINARY` Available properties: `BINARY`
...@@ -43,7 +43,7 @@ Available properties: `BINARY` ...@@ -43,7 +43,7 @@ Available properties: `BINARY`
<a name="char"></a> <a name="char"></a>
## `CHAR()` ## `CHAR()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L88) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L88)
A fixed length string. Default length 255 A fixed length string. Default length 255
Available properties: `BINARY` Available properties: `BINARY`
...@@ -53,14 +53,14 @@ Available properties: `BINARY` ...@@ -53,14 +53,14 @@ Available properties: `BINARY`
<a name="text"></a> <a name="text"></a>
## `TEXT()` ## `TEXT()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L109) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L109)
An unlimited length text column An unlimited length text column
*** ***
<a name="integer"></a> <a name="integer"></a>
## `INTEGER()` ## `INTEGER()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L169) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L169)
A 32 bit integer. A 32 bit integer.
Available properties: `UNSIGNED`, `ZEROFILL` Available properties: `UNSIGNED`, `ZEROFILL`
...@@ -70,7 +70,7 @@ Available properties: `UNSIGNED`, `ZEROFILL` ...@@ -70,7 +70,7 @@ Available properties: `UNSIGNED`, `ZEROFILL`
<a name="bigint"></a> <a name="bigint"></a>
## `BIGINT()` ## `BIGINT()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L188) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L188)
A 64 bit integer. A 64 bit integer.
Available properties: `UNSIGNED`, `ZEROFILL` Available properties: `UNSIGNED`, `ZEROFILL`
...@@ -80,7 +80,7 @@ Available properties: `UNSIGNED`, `ZEROFILL` ...@@ -80,7 +80,7 @@ Available properties: `UNSIGNED`, `ZEROFILL`
<a name="float"></a> <a name="float"></a>
## `FLOAT()` ## `FLOAT()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L206) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L206)
Floating point number (4-byte precision). Accepts one or two arguments for precision Floating point number (4-byte precision). Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL` Available properties: `UNSIGNED`, `ZEROFILL`
...@@ -90,7 +90,7 @@ Available properties: `UNSIGNED`, `ZEROFILL` ...@@ -90,7 +90,7 @@ Available properties: `UNSIGNED`, `ZEROFILL`
<a name="real"></a> <a name="real"></a>
## `REAL()` ## `REAL()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L225) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L225)
Floating point number (4-byte precision). Accepts one or two arguments for precision Floating point number (4-byte precision). Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL` Available properties: `UNSIGNED`, `ZEROFILL`
...@@ -100,7 +100,7 @@ Available properties: `UNSIGNED`, `ZEROFILL` ...@@ -100,7 +100,7 @@ Available properties: `UNSIGNED`, `ZEROFILL`
<a name="double"></a> <a name="double"></a>
## `DOUBLE()` ## `DOUBLE()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L244) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L244)
Floating point number (8-byte precision). Accepts one or two arguments for precision Floating point number (8-byte precision). Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL` Available properties: `UNSIGNED`, `ZEROFILL`
...@@ -110,7 +110,7 @@ Available properties: `UNSIGNED`, `ZEROFILL` ...@@ -110,7 +110,7 @@ Available properties: `UNSIGNED`, `ZEROFILL`
<a name="decimal"></a> <a name="decimal"></a>
## `DECIMAL()` ## `DECIMAL()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L263) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L263)
Decimal number. Accepts one or two arguments for precision Decimal number. Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL` Available properties: `UNSIGNED`, `ZEROFILL`
...@@ -120,63 +120,63 @@ Available properties: `UNSIGNED`, `ZEROFILL` ...@@ -120,63 +120,63 @@ Available properties: `UNSIGNED`, `ZEROFILL`
<a name="boolean"></a> <a name="boolean"></a>
## `BOOLEAN()` ## `BOOLEAN()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L286) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L286)
A boolean / tinyint column, depending on dialect A boolean / tinyint column, depending on dialect
*** ***
<a name="time"></a> <a name="time"></a>
## `TIME()` ## `TIME()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L302) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L302)
A time column A time column
*** ***
<a name="date"></a> <a name="date"></a>
## `DATE()` ## `DATE()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L317) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L317)
A datetime column A datetime column
*** ***
<a name="dateonly"></a> <a name="dateonly"></a>
## `DATEONLY()` ## `DATEONLY()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L333) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L333)
A date only column A date only column
*** ***
<a name="hstore"></a> <a name="hstore"></a>
## `HSTORE()` ## `HSTORE()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L349) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L349)
A key / value column. Only available in postgres. A key / value column. Only available in postgres.
*** ***
<a name="json"></a> <a name="json"></a>
## `JSON()` ## `JSON()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L361) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L361)
A JSON string column. Only available in postgres. A JSON string column. Only available in postgres.
*** ***
<a name="jsonb"></a> <a name="jsonb"></a>
## `JSONB()` ## `JSONB()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L373) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L373)
A pre-processed JSON data column. Only available in postgres. A pre-processed JSON data column. Only available in postgres.
*** ***
<a name="now"></a> <a name="now"></a>
## `NOW()` ## `NOW()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L385) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L385)
A default value of the current timestamp A default value of the current timestamp
*** ***
<a name="blob"></a> <a name="blob"></a>
## `BLOB()` ## `BLOB()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L399) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L399)
Binary storage. Available lengths: `tiny`, `medium`, `long` Binary storage. Available lengths: `tiny`, `medium`, `long`
...@@ -184,7 +184,7 @@ Binary storage. Available lengths: `tiny`, `medium`, `long` ...@@ -184,7 +184,7 @@ Binary storage. Available lengths: `tiny`, `medium`, `long`
<a name="range"></a> <a name="range"></a>
## `RANGE()` ## `RANGE()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L429) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L429)
Range types are data types representing a range of values of some element type (called the range's subtype). Range types are data types representing a range of values of some element type (called the range's subtype).
Only available in postgres. Only available in postgres.
See {@link http://www.postgresql.org/docs/9.4/static/rangetypes.html|Postgres documentation} for more details See {@link http://www.postgresql.org/docs/9.4/static/rangetypes.html|Postgres documentation} for more details
...@@ -193,28 +193,28 @@ See {@link http://www.postgresql.org/docs/9.4/static/rangetypes.html|Postgres do ...@@ -193,28 +193,28 @@ See {@link http://www.postgresql.org/docs/9.4/static/rangetypes.html|Postgres do
<a name="uuid"></a> <a name="uuid"></a>
## `UUID()` ## `UUID()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L458) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L458)
A column storing a unique univeral identifier. Use with `UUIDV1` or `UUIDV4` for default values. A column storing a unique univeral identifier. Use with `UUIDV1` or `UUIDV4` for default values.
*** ***
<a name="uuidv1"></a> <a name="uuidv1"></a>
## `UUIDV1()` ## `UUIDV1()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L471) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L471)
A default unique universal identifier generated following the UUID v1 standard A default unique universal identifier generated following the UUID v1 standard
*** ***
<a name="uuidv4"></a> <a name="uuidv4"></a>
## `UUIDV4()` ## `UUIDV4()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L484) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L484)
A default unique universal identifier generated following the UUID v2 standard A default unique universal identifier generated following the UUID v2 standard
*** ***
<a name="virtual"></a> <a name="virtual"></a>
## `VIRTUAL()` ## `VIRTUAL()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L519) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L519)
A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB. A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.
You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example: You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:
...@@ -244,7 +244,7 @@ __Aliases:__ NONE ...@@ -244,7 +244,7 @@ __Aliases:__ NONE
<a name="enum"></a> <a name="enum"></a>
## `ENUM()` ## `ENUM()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L532) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L532)
An enumeration. `DataTypes.ENUM('value', 'another value')`. An enumeration. `DataTypes.ENUM('value', 'another value')`.
...@@ -252,7 +252,7 @@ An enumeration. `DataTypes.ENUM('value', 'another value')`. ...@@ -252,7 +252,7 @@ An enumeration. `DataTypes.ENUM('value', 'another value')`.
<a name="array"></a> <a name="array"></a>
## `ARRAY()` ## `ARRAY()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/data-types.js#L549) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/data-types.js#L549)
An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in postgres. An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in postgres.
*** ***
......
<a name="deferrable"></a>
## `Deferrable()` -> `object`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/deferrable.js#L39)
A collection of properties related to deferrable constraints. It can be used to
make foreign key constraints deferrable and to set the constaints within a
transaction. This is only supported in PostgreSQL.
The foreign keys can be configured like this. It will create a foreign key
that will check the constraints immediately when the data was inserted.
```js
sequelize.define('Model', {
foreign_id: {
type: Sequelize.INTEGER,
references: {
model: OtherModel,
key: 'id',
deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
}
}
});
```
The constraints can be configured in a transaction like this. It will
trigger a query once the transaction has been started and set the constraints
to be checked at the very end of the transaction.
```js
sequelize.transaction({
deferrable: Sequelize.Deferrable.SET_DEFERRED
});
```
***
<a name="initially_deferred"></a>
## `INITIALLY_DEFERRED()`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/deferrable.js#L59)
A property that will defer constraints checks to the end of transactions.
***
<a name="initially_immediate"></a>
## `INITIALLY_IMMEDIATE()`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/deferrable.js#L76)
A property that will trigger the constraint checks immediately
***
<a name="not"></a>
## `NOT()`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/deferrable.js#L95)
A property that will set the constraints to not deferred. This is
the default in PostgreSQL and it make it impossible to dynamically
defer the constraints within a transaction.
***
<a name="set_deferred"></a>
## `SET_DEFERRED(constraints)`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/deferrable.js#L114)
A property that will trigger an additional query at the beginning of a
transaction which sets the constraints to deferred.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| constraints | Array | An array of constraint names. Will defer all constraints by default. |
***
<a name="set_immediate"></a>
## `SET_IMMEDIATE(constraints)`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/deferrable.js#L135)
A property that will trigger an additional query at the beginning of a
transaction which sets the constraints to immediately.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| constraints | Array | An array of constraint names. Will defer all constraints by default. |
***
_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 <a href="irc://irc.freenode.net/#sequelizejs">IRC</a>, 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](http://usejsdoc.org) and [dox](https://github.com/tj/dox)_
\ No newline at end of file
<a name="errors"></a> <a name="errors"></a>
# Class Errors # Class Errors
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L11) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L11)
Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor. Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor.
All sequelize errors inherit from the base JS error object. All sequelize errors inherit from the base JS error object.
...@@ -9,7 +9,7 @@ All sequelize errors inherit from the base JS error object. ...@@ -9,7 +9,7 @@ All sequelize errors inherit from the base JS error object.
<a name="baseerror"></a> <a name="baseerror"></a>
## `new BaseError()` ## `new BaseError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L20) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L20)
The Base Error all Sequelize Errors inherit from. The Base Error all Sequelize Errors inherit from.
__Aliases:__ Error __Aliases:__ Error
...@@ -18,7 +18,7 @@ __Aliases:__ Error ...@@ -18,7 +18,7 @@ __Aliases:__ Error
<a name="validationerror"></a> <a name="validationerror"></a>
## `new ValidationError(message, [errors])` ## `new ValidationError(message, [errors])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L41) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L41)
Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property, Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
which is an array with 1 or more ValidationErrorItems, one for each validation that failed. which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
...@@ -37,14 +37,14 @@ __Extends:__ BaseError ...@@ -37,14 +37,14 @@ __Extends:__ BaseError
<a name="errors"></a> <a name="errors"></a>
## `errors` ## `errors`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L49) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L49)
An array of ValidationErrorItems An array of ValidationErrorItems
*** ***
<a name="get"></a> <a name="get"></a>
## `get(path)` ## `get(path)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L70) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L70)
Gets all validation error items for the path / field specified. Gets all validation error items for the path / field specified.
...@@ -59,7 +59,7 @@ Gets all validation error items for the path / field specified. ...@@ -59,7 +59,7 @@ Gets all validation error items for the path / field specified.
<a name="databaseerror"></a> <a name="databaseerror"></a>
## `new DatabaseError()` ## `new DatabaseError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L84) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L84)
A base class for all database related errors. A base class for all database related errors.
__Extends:__ BaseError __Extends:__ BaseError
...@@ -68,49 +68,49 @@ __Extends:__ BaseError ...@@ -68,49 +68,49 @@ __Extends:__ BaseError
<a name="parent"></a> <a name="parent"></a>
## `parent` ## `parent`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L92) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L92)
The database specific error which triggered this one The database specific error which triggered this one
*** ***
<a name="sql"></a> <a name="sql"></a>
## `sql` ## `sql`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L98) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L98)
The SQL that triggered the error The SQL that triggered the error
*** ***
<a name="message"></a> <a name="message"></a>
## `message()` ## `message()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L104) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L104)
The message from the DB. The message from the DB.
*** ***
<a name="fields"></a> <a name="fields"></a>
## `fields()` ## `fields()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L109) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L109)
The fields of the unique constraint The fields of the unique constraint
*** ***
<a name="value"></a> <a name="value"></a>
## `value()` ## `value()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L114) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L114)
The value(s) which triggered the error The value(s) which triggered the error
*** ***
<a name="index"></a> <a name="index"></a>
## `index()` ## `index()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L119) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L119)
The name of the index that triggered the error The name of the index that triggered the error
*** ***
<a name="timeouterror"></a> <a name="timeouterror"></a>
## `new TimeoutError()` ## `new TimeoutError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L127) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L127)
Thrown when a database query times out because of a deadlock Thrown when a database query times out because of a deadlock
__Extends:__ DatabaseError __Extends:__ DatabaseError
...@@ -119,7 +119,7 @@ __Extends:__ DatabaseError ...@@ -119,7 +119,7 @@ __Extends:__ DatabaseError
<a name="uniqueconstrainterror"></a> <a name="uniqueconstrainterror"></a>
## `new UniqueConstraintError()` ## `new UniqueConstraintError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L138) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L138)
Thrown when a unique constraint is violated in the database Thrown when a unique constraint is violated in the database
__Extends:__ DatabaseError __Extends:__ DatabaseError
...@@ -128,7 +128,7 @@ __Extends:__ DatabaseError ...@@ -128,7 +128,7 @@ __Extends:__ DatabaseError
<a name="foreignkeyconstrainterror"></a> <a name="foreignkeyconstrainterror"></a>
## `new ForeignKeyConstraintError()` ## `new ForeignKeyConstraintError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L157) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L157)
Thrown when a foreign key constraint is violated in the database Thrown when a foreign key constraint is violated in the database
__Extends:__ DatabaseError __Extends:__ DatabaseError
...@@ -137,7 +137,7 @@ __Extends:__ DatabaseError ...@@ -137,7 +137,7 @@ __Extends:__ DatabaseError
<a name="exclusionconstrainterror"></a> <a name="exclusionconstrainterror"></a>
## `new ExclusionConstraintError()` ## `new ExclusionConstraintError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L177) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L177)
Thrown when an exclusion constraint is violated in the database Thrown when an exclusion constraint is violated in the database
__Extends:__ DatabaseError __Extends:__ DatabaseError
...@@ -146,7 +146,7 @@ __Extends:__ DatabaseError ...@@ -146,7 +146,7 @@ __Extends:__ DatabaseError
<a name="validationerroritem"></a> <a name="validationerroritem"></a>
## `new ValidationErrorItem(message, type, path, value)` ## `new ValidationErrorItem(message, type, path, value)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L201) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L201)
Validation Error Item Validation Error Item
Instances of this class are included in the `ValidationError.errors` property. Instances of this class are included in the `ValidationError.errors` property.
...@@ -165,7 +165,7 @@ Instances of this class are included in the `ValidationError.errors` property. ...@@ -165,7 +165,7 @@ Instances of this class are included in the `ValidationError.errors` property.
<a name="connectionerror"></a> <a name="connectionerror"></a>
## `new ConnectionError()` ## `new ConnectionError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L213) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L213)
A base class for all connection related errors. A base class for all connection related errors.
__Extends:__ BaseError __Extends:__ BaseError
...@@ -174,14 +174,14 @@ __Extends:__ BaseError ...@@ -174,14 +174,14 @@ __Extends:__ BaseError
<a name="parent"></a> <a name="parent"></a>
## `parent` ## `parent`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L220) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L220)
The connection specific error which triggered this one The connection specific error which triggered this one
*** ***
<a name="connectionrefusederror"></a> <a name="connectionrefusederror"></a>
## `new ConnectionRefusedError()` ## `new ConnectionRefusedError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L230) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L230)
Thrown when a connection to a database is refused Thrown when a connection to a database is refused
__Extends:__ ConnectionError __Extends:__ ConnectionError
...@@ -190,7 +190,7 @@ __Extends:__ ConnectionError ...@@ -190,7 +190,7 @@ __Extends:__ ConnectionError
<a name="accessdeniederror"></a> <a name="accessdeniederror"></a>
## `new AccessDeniedError()` ## `new AccessDeniedError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L241) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L241)
Thrown when a connection to a database is refused due to insufficient privileges Thrown when a connection to a database is refused due to insufficient privileges
__Extends:__ ConnectionError __Extends:__ ConnectionError
...@@ -199,7 +199,7 @@ __Extends:__ ConnectionError ...@@ -199,7 +199,7 @@ __Extends:__ ConnectionError
<a name="hostnotfounderror"></a> <a name="hostnotfounderror"></a>
## `new HostNotFoundError()` ## `new HostNotFoundError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L252) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L252)
Thrown when a connection to a database has a hostname that was not found Thrown when a connection to a database has a hostname that was not found
__Extends:__ ConnectionError __Extends:__ ConnectionError
...@@ -208,7 +208,7 @@ __Extends:__ ConnectionError ...@@ -208,7 +208,7 @@ __Extends:__ ConnectionError
<a name="hostnotreachableerror"></a> <a name="hostnotreachableerror"></a>
## `new HostNotReachableError()` ## `new HostNotReachableError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L263) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L263)
Thrown when a connection to a database has a hostname that was not reachable Thrown when a connection to a database has a hostname that was not reachable
__Extends:__ ConnectionError __Extends:__ ConnectionError
...@@ -217,7 +217,7 @@ __Extends:__ ConnectionError ...@@ -217,7 +217,7 @@ __Extends:__ ConnectionError
<a name="invalidconnectionerror"></a> <a name="invalidconnectionerror"></a>
## `new InvalidConnectionError()` ## `new InvalidConnectionError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L274) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L274)
Thrown when a connection to a database has invalid values for any of the connection parameters Thrown when a connection to a database has invalid values for any of the connection parameters
__Extends:__ ConnectionError __Extends:__ ConnectionError
...@@ -226,7 +226,7 @@ __Extends:__ ConnectionError ...@@ -226,7 +226,7 @@ __Extends:__ ConnectionError
<a name="connectiontimedouterror"></a> <a name="connectiontimedouterror"></a>
## `new ConnectionTimedOutError()` ## `new ConnectionTimedOutError()`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/errors.js#L285) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/errors.js#L285)
Thrown when a connection to a database times out Thrown when a connection to a database times out
__Extends:__ ConnectionError __Extends:__ ConnectionError
......
<a name="hooks"></a> <a name="hooks"></a>
# Mixin Hooks # Mixin Hooks
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L39) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L39)
Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation. Hooks can be added to you models in three ways: Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation. Hooks can be added to you models in three ways:
1. By specifying them as options in `sequelize.define` 1. By specifying them as options in `sequelize.define`
...@@ -38,7 +38,7 @@ Model.afterBulkUpdate(function () {}) ...@@ -38,7 +38,7 @@ Model.afterBulkUpdate(function () {})
<a name="addhook"></a> <a name="addhook"></a>
## `addHook(hooktype, [name], fn)` ## `addHook(hooktype, [name], fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L152) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L152)
Add a hook to the model Add a hook to the model
...@@ -56,7 +56,7 @@ __Aliases:__ hook ...@@ -56,7 +56,7 @@ __Aliases:__ hook
<a name="hashook"></a> <a name="hashook"></a>
## `hasHook(hookType)` ## `hasHook(hookType)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L172) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L172)
Check whether the mode has any hooks of this type Check whether the mode has any hooks of this type
...@@ -72,7 +72,7 @@ __Aliases:__ hasHooks ...@@ -72,7 +72,7 @@ __Aliases:__ hasHooks
<a name="beforevalidate"></a> <a name="beforevalidate"></a>
## `beforeValidate(name, fn)` ## `beforeValidate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L185) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L185)
A hook that is run before validation A hook that is run before validation
**Params:** **Params:**
...@@ -87,7 +87,7 @@ A hook that is run before validation ...@@ -87,7 +87,7 @@ A hook that is run before validation
<a name="aftervalidate"></a> <a name="aftervalidate"></a>
## `afterValidate(name, fn)` ## `afterValidate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L192) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L192)
A hook that is run after validation A hook that is run after validation
**Params:** **Params:**
...@@ -102,7 +102,7 @@ A hook that is run after validation ...@@ -102,7 +102,7 @@ A hook that is run after validation
<a name="beforecreate"></a> <a name="beforecreate"></a>
## `beforeCreate(name, fn)` ## `beforeCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L199) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L199)
A hook that is run before creating a single instance A hook that is run before creating a single instance
**Params:** **Params:**
...@@ -117,7 +117,7 @@ A hook that is run before creating a single instance ...@@ -117,7 +117,7 @@ A hook that is run before creating a single instance
<a name="aftercreate"></a> <a name="aftercreate"></a>
## `afterCreate(name, fn)` ## `afterCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L206) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L206)
A hook that is run after creating a single instance A hook that is run after creating a single instance
**Params:** **Params:**
...@@ -132,7 +132,7 @@ A hook that is run after creating a single instance ...@@ -132,7 +132,7 @@ A hook that is run after creating a single instance
<a name="beforedestroy"></a> <a name="beforedestroy"></a>
## `beforeDestroy(name, fn)` ## `beforeDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L215) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L215)
A hook that is run before destroying a single instance A hook that is run before destroying a single instance
**Params:** **Params:**
...@@ -148,7 +148,7 @@ __Aliases:__ beforeDelete ...@@ -148,7 +148,7 @@ __Aliases:__ beforeDelete
<a name="afterdestroy"></a> <a name="afterdestroy"></a>
## `afterDestroy(name, fn)` ## `afterDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L224) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L224)
A hook that is run after destroying a single instance A hook that is run after destroying a single instance
**Params:** **Params:**
...@@ -164,7 +164,7 @@ __Aliases:__ afterDelete ...@@ -164,7 +164,7 @@ __Aliases:__ afterDelete
<a name="beforeupdate"></a> <a name="beforeupdate"></a>
## `beforeUpdate(name, fn)` ## `beforeUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L231) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L231)
A hook that is run before updating a single instance A hook that is run before updating a single instance
**Params:** **Params:**
...@@ -179,7 +179,7 @@ A hook that is run before updating a single instance ...@@ -179,7 +179,7 @@ A hook that is run before updating a single instance
<a name="afterupdate"></a> <a name="afterupdate"></a>
## `afterUpdate(name, fn)` ## `afterUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L238) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L238)
A hook that is run after updating a single instance A hook that is run after updating a single instance
**Params:** **Params:**
...@@ -194,7 +194,7 @@ A hook that is run after updating a single instance ...@@ -194,7 +194,7 @@ A hook that is run after updating a single instance
<a name="beforebulkcreate"></a> <a name="beforebulkcreate"></a>
## `beforeBulkCreate(name, fn)` ## `beforeBulkCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L245) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L245)
A hook that is run before creating instances in bulk A hook that is run before creating instances in bulk
**Params:** **Params:**
...@@ -209,7 +209,7 @@ A hook that is run before creating instances in bulk ...@@ -209,7 +209,7 @@ A hook that is run before creating instances in bulk
<a name="afterbulkcreate"></a> <a name="afterbulkcreate"></a>
## `afterBulkCreate(name, fn)` ## `afterBulkCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L252) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L252)
A hook that is run after creating instances in bulk A hook that is run after creating instances in bulk
**Params:** **Params:**
...@@ -224,7 +224,7 @@ A hook that is run after creating instances in bulk ...@@ -224,7 +224,7 @@ A hook that is run after creating instances in bulk
<a name="beforebulkdestroy"></a> <a name="beforebulkdestroy"></a>
## `beforeBulkDestroy(name, fn)` ## `beforeBulkDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L261) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L261)
A hook that is run before destroying instances in bulk A hook that is run before destroying instances in bulk
**Params:** **Params:**
...@@ -240,7 +240,7 @@ __Aliases:__ beforeBulkDelete ...@@ -240,7 +240,7 @@ __Aliases:__ beforeBulkDelete
<a name="afterbulkdestroy"></a> <a name="afterbulkdestroy"></a>
## `afterBulkDestroy(name, fn)` ## `afterBulkDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L270) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L270)
A hook that is run after destroying instances in bulk A hook that is run after destroying instances in bulk
**Params:** **Params:**
...@@ -256,7 +256,7 @@ __Aliases:__ afterBulkDelete ...@@ -256,7 +256,7 @@ __Aliases:__ afterBulkDelete
<a name="beforebulkupdate"></a> <a name="beforebulkupdate"></a>
## `beforeBulkUpdate(name, fn)` ## `beforeBulkUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L277) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L277)
A hook that is run after updating instances in bulk A hook that is run after updating instances in bulk
**Params:** **Params:**
...@@ -271,7 +271,7 @@ A hook that is run after updating instances in bulk ...@@ -271,7 +271,7 @@ A hook that is run after updating instances in bulk
<a name="afterbulkupdate"></a> <a name="afterbulkupdate"></a>
## `afterBulkUpdate(name, fn)` ## `afterBulkUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L284) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L284)
A hook that is run after updating instances in bulk A hook that is run after updating instances in bulk
**Params:** **Params:**
...@@ -286,7 +286,7 @@ A hook that is run after updating instances in bulk ...@@ -286,7 +286,7 @@ A hook that is run after updating instances in bulk
<a name="beforefind"></a> <a name="beforefind"></a>
## `beforeFind(name, fn)` ## `beforeFind(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L291) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L291)
A hook that is run before a find (select) query A hook that is run before a find (select) query
**Params:** **Params:**
...@@ -301,7 +301,7 @@ A hook that is run before a find (select) query ...@@ -301,7 +301,7 @@ A hook that is run before a find (select) query
<a name="beforefindafterexpandincludeall"></a> <a name="beforefindafterexpandincludeall"></a>
## `beforeFindAfterExpandIncludeAll(name, fn)` ## `beforeFindAfterExpandIncludeAll(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L298) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L298)
A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
**Params:** **Params:**
...@@ -316,7 +316,7 @@ A hook that is run before a find (select) query, after any { include: {all: ...} ...@@ -316,7 +316,7 @@ A hook that is run before a find (select) query, after any { include: {all: ...}
<a name="beforefindafteroptions"></a> <a name="beforefindafteroptions"></a>
## `beforeFindAfterOptions(name, fn)` ## `beforeFindAfterOptions(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L305) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L305)
A hook that is run before a find (select) query, after all option parsing is complete A hook that is run before a find (select) query, after all option parsing is complete
**Params:** **Params:**
...@@ -331,7 +331,7 @@ A hook that is run before a find (select) query, after all option parsing is com ...@@ -331,7 +331,7 @@ A hook that is run before a find (select) query, after all option parsing is com
<a name="afterfind"></a> <a name="afterfind"></a>
## `afterFind(name, fn)` ## `afterFind(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L312) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L312)
A hook that is run after a find (select) query A hook that is run after a find (select) query
**Params:** **Params:**
...@@ -346,7 +346,7 @@ A hook that is run after a find (select) query ...@@ -346,7 +346,7 @@ A hook that is run after a find (select) query
<a name="beforedefine"></a> <a name="beforedefine"></a>
## `beforeDefine(name, fn)` ## `beforeDefine(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L319) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L319)
A hook that is run before a define call A hook that is run before a define call
**Params:** **Params:**
...@@ -361,7 +361,7 @@ A hook that is run before a define call ...@@ -361,7 +361,7 @@ A hook that is run before a define call
<a name="afterdefine"></a> <a name="afterdefine"></a>
## `afterDefine(name, fn)` ## `afterDefine(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L326) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L326)
A hook that is run after a define call A hook that is run after a define call
**Params:** **Params:**
...@@ -376,7 +376,7 @@ A hook that is run after a define call ...@@ -376,7 +376,7 @@ A hook that is run after a define call
<a name="beforeinit"></a> <a name="beforeinit"></a>
## `beforeInit(name, fn)` ## `beforeInit(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L333) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L333)
A hook that is run before Sequelize() call A hook that is run before Sequelize() call
**Params:** **Params:**
...@@ -391,7 +391,7 @@ A hook that is run before Sequelize() call ...@@ -391,7 +391,7 @@ A hook that is run before Sequelize() call
<a name="afterinit"></a> <a name="afterinit"></a>
## `afterInit` ## `afterInit`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/hooks.js#L341) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/hooks.js#L341)
A hook that is run after Sequelize() call A hook that is run after Sequelize() call
**Params:** **Params:**
......
<a name="instance"></a> <a name="instance"></a>
# Class Instance # Class Instance
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L41) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L34)
This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not
instantiate the Instance class directly, instead you access it using the finder and creation methods on the model. instantiate the Instance class directly, instead you access it using the finder and creation methods on the model.
...@@ -26,14 +26,14 @@ Accessing properties directly or using `get` is preferred for regular use, `getD ...@@ -26,14 +26,14 @@ Accessing properties directly or using `get` is preferred for regular use, `getD
<a name="isnewrecord"></a> <a name="isnewrecord"></a>
## `isNewRecord` -> `Boolean` ## `isNewRecord` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L54) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L47)
Returns true if this instance has not yet been persisted to the database Returns true if this instance has not yet been persisted to the database
*** ***
<a name="model"></a> <a name="model"></a>
## `Model()` -> `Model` ## `Model()` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L63) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L56)
Returns the Model the instance was created from. Returns the Model the instance was created from.
**See:** **See:**
...@@ -45,7 +45,7 @@ Returns the Model the instance was created from. ...@@ -45,7 +45,7 @@ Returns the Model the instance was created from.
<a name="sequelize"></a> <a name="sequelize"></a>
## `sequelize()` -> `Sequelize` ## `sequelize()` -> `Sequelize`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L72) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L65)
A reference to the sequelize instance A reference to the sequelize instance
**See:** **See:**
...@@ -55,50 +55,17 @@ A reference to the sequelize instance ...@@ -55,50 +55,17 @@ A reference to the sequelize instance
*** ***
<a name="isdeleted"></a> <a name="where"></a>
## `isDeleted()` -> `Boolean` ## `where()` -> `Object`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L85) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L75)
If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set. Otherwise, always returns false. Get an object representing the query for this instance, use with `options.where`
***
<a name="values"></a>
## `values()` -> `Object`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L98)
Get the values of this Instance. Proxies to `this.get`
**Deprecated** .values is deprecated. Please use .get() instead.
**See:**
* [Instance#get](api/instance#get)
***
<a name="isdirty"></a>
## `isDirty()` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L112)
A getter for `this.changed()`. Returns true if any keys have changed.
**See:**
* [Instance#changed](api/instance#changed)
***
<a name="primarykeyvalues"></a>
## `primaryKeyValues()` -> `Object`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L124)
Get the values of the primary keys of this instance.
*** ***
<a name="getdatavalue"></a> <a name="getdatavalue"></a>
## `getDataValue(key)` -> `any` ## `getDataValue(key)` -> `any`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L160) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L99)
Get the value of the underlying data value Get the value of the underlying data value
...@@ -113,7 +80,7 @@ Get the value of the underlying data value ...@@ -113,7 +80,7 @@ Get the value of the underlying data value
<a name="setdatavalue"></a> <a name="setdatavalue"></a>
## `setDataValue(key, value)` ## `setDataValue(key, value)`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L170) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L109)
Update the underlying data value Update the underlying data value
...@@ -129,7 +96,7 @@ Update the underlying data value ...@@ -129,7 +96,7 @@ Update the underlying data value
<a name="get"></a> <a name="get"></a>
## `get([key], [options])` -> `Object|any` ## `get([key], [options])` -> `Object|any`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L189) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L128)
If no key is given, returns all values of the instance, also invoking virtual getters. If no key is given, returns all values of the instance, also invoking virtual getters.
If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key. If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
...@@ -148,7 +115,7 @@ If key is given and a field or virtual getter is present for the key it will cal ...@@ -148,7 +115,7 @@ If key is given and a field or virtual getter is present for the key it will cal
<a name="set"></a> <a name="set"></a>
## `set(key, value, [options])` ## `set(key, value, [options])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L271) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L210)
Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`). Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`).
In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function
will be called instead. To bypass the setter, you can pass `raw: true` in the options object. will be called instead. To bypass the setter, you can pass `raw: true` in the options object.
...@@ -186,7 +153,7 @@ __Aliases:__ setAttributes ...@@ -186,7 +153,7 @@ __Aliases:__ setAttributes
<a name="changed"></a> <a name="changed"></a>
## `changed([key])` -> `Boolean|Array` ## `changed([key])` -> `Boolean|Array`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L412) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L351)
If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`. If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`.
If changed is called without an argument, it will return an array of keys that have changed. If changed is called without an argument, it will return an array of keys that have changed.
...@@ -205,7 +172,7 @@ If changed is called without an argument and no keys have changed, it will retur ...@@ -205,7 +172,7 @@ If changed is called without an argument and no keys have changed, it will retur
<a name="previous"></a> <a name="previous"></a>
## `previous(key)` -> `any` ## `previous(key)` -> `any`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L433) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L372)
Returns the previous value for key from `_previousDataValues`. Returns the previous value for key from `_previousDataValues`.
**Params:** **Params:**
...@@ -219,7 +186,7 @@ Returns the previous value for key from `_previousDataValues`. ...@@ -219,7 +186,7 @@ Returns the previous value for key from `_previousDataValues`.
<a name="save"></a> <a name="save"></a>
## `save([options])` -> `Promise.<this|Errors.ValidationError>` ## `save([options])` -> `Promise.<this|Errors.ValidationError>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L494) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L433)
Validate this instance, and if the validation passes, persist it to the database. Validate this instance, and if the validation passes, persist it to the database.
On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`. On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`.
...@@ -234,6 +201,7 @@ This error will have a property for each of the fields for which validation fail ...@@ -234,6 +201,7 @@ This error will have a property for each of the fields for which validation fail
| [options.fields] | Object | An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved. | | [options.fields] | Object | An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved. |
| [options.silent=false] | Boolean | If true, the updatedAt timestamp will not be updated. | | [options.silent=false] | Boolean | If true, the updatedAt timestamp will not be updated. |
| [options.validate=true] | Boolean | If false, validations won't be run. | | [options.validate=true] | Boolean | If false, validations won't be run. |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -241,7 +209,7 @@ This error will have a property for each of the fields for which validation fail ...@@ -241,7 +209,7 @@ This error will have a property for each of the fields for which validation fail
<a name="reload"></a> <a name="reload"></a>
## `reload([options])` -> `Promise.<this>` ## `reload([options])` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L742) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L676)
Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object. Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method, This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
all references to the Instance are updated with the new data and no new objects are created. all references to the Instance are updated with the new data and no new objects are created.
...@@ -257,13 +225,14 @@ all references to the Instance are updated with the new data and no new objects ...@@ -257,13 +225,14 @@ all references to the Instance are updated with the new data and no new objects
| Name | Type | Description | | Name | Type | Description |
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| [options] | Object | Options that are passed on to `Model.find` | | [options] | Object | Options that are passed on to `Model.find` |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="validate"></a> <a name="validate"></a>
## `validate([options])` -> `Promise.<Errors.ValidationError|undefined>` ## `validate([options])` -> `Promise.<Errors.ValidationError|undefined>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L769) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L705)
Validate the attribute of this instance according to validation rules set in the model definition. Validate the attribute of this instance according to validation rules set in the model definition.
Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries. Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.
...@@ -286,7 +255,7 @@ Emits null if and only if validation successful; otherwise an Error instance con ...@@ -286,7 +255,7 @@ Emits null if and only if validation successful; otherwise an Error instance con
<a name="update"></a> <a name="update"></a>
## `update(updates, options)` -> `Promise.<this>` ## `update(updates, options)` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L788) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L724)
This is the same as calling `set` and then calling `save`. This is the same as calling `set` and then calling `save`.
...@@ -309,7 +278,7 @@ __Aliases:__ updateAttributes ...@@ -309,7 +278,7 @@ __Aliases:__ updateAttributes
<a name="destroy"></a> <a name="destroy"></a>
## `destroy([options={}])` -> `Promise.<undefined>` ## `destroy([options={}])` -> `Promise.<undefined>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L820) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L757)
Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time. Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.
...@@ -319,6 +288,7 @@ Destroy the row corresponding to this instance. Depending on your setting for pa ...@@ -319,6 +288,7 @@ Destroy the row corresponding to this instance. Depending on your setting for pa
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| [options={}] | Object | | | [options={}] | Object | |
| [options.force=false] | Boolean | If set to true, paranoid models will actually be deleted | | [options.force=false] | Boolean | If set to true, paranoid models will actually be deleted |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -326,7 +296,7 @@ Destroy the row corresponding to this instance. Depending on your setting for pa ...@@ -326,7 +296,7 @@ Destroy the row corresponding to this instance. Depending on your setting for pa
<a name="restore"></a> <a name="restore"></a>
## `restore([options={}])` -> `Promise.<undefined>` ## `restore([options={}])` -> `Promise.<undefined>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L863) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L801)
Restore the row corresponding to this instance. Only available for paranoid models. Restore the row corresponding to this instance. Only available for paranoid models.
...@@ -335,6 +305,7 @@ Restore the row corresponding to this instance. Only available for paranoid mode ...@@ -335,6 +305,7 @@ Restore the row corresponding to this instance. Only available for paranoid mode
| Name | Type | Description | | Name | Type | Description |
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| [options={}] | Object | | | [options={}] | Object | |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -342,7 +313,7 @@ Restore the row corresponding to this instance. Only available for paranoid mode ...@@ -342,7 +313,7 @@ Restore the row corresponding to this instance. Only available for paranoid mode
<a name="increment"></a> <a name="increment"></a>
## `increment(fields, [options])` -> `Promise.<this>` ## `increment(fields, [options])` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L909) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L848)
Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
```sql ```sql
SET column = column + X SET column = column + X
...@@ -369,6 +340,7 @@ instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42 ...@@ -369,6 +340,7 @@ instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42
| fields | String &#124; Array &#124; Object | If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given. | | fields | String &#124; Array &#124; Object | If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given. |
| [options] | Object | | | [options] | Object | |
| [options.by=1] | Integer | The number to increment by | | [options.by=1] | Integer | The number to increment by |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -376,7 +348,7 @@ instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42 ...@@ -376,7 +348,7 @@ instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42
<a name="decrement"></a> <a name="decrement"></a>
## `decrement(fields, [options])` -> `Promise` ## `decrement(fields, [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L998) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L921)
Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
```sql ```sql
SET column = column - X SET column = column - X
...@@ -403,6 +375,7 @@ instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42 ...@@ -403,6 +375,7 @@ instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42
| fields | String &#124; Array &#124; Object | If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given | | fields | String &#124; Array &#124; Object | If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given |
| [options] | Object | | | [options] | Object | |
| [options.by=1] | Integer | The number to decrement by | | [options.by=1] | Integer | The number to decrement by |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -410,7 +383,7 @@ instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42 ...@@ -410,7 +383,7 @@ instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42
<a name="equals"></a> <a name="equals"></a>
## `equals(other)` -> `Boolean` ## `equals(other)` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L1034) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L943)
Check whether all values of this and `other` Instance are the same Check whether all values of this and `other` Instance are the same
...@@ -425,7 +398,7 @@ Check whether all values of this and `other` Instance are the same ...@@ -425,7 +398,7 @@ Check whether all values of this and `other` Instance are the same
<a name="equalsoneof"></a> <a name="equalsoneof"></a>
## `equalsOneOf(others)` -> `Boolean` ## `equalsOneOf(others)` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L1054) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L963)
Check if this is eqaul to one of `others` by calling equals Check if this is eqaul to one of `others` by calling equals
...@@ -440,7 +413,7 @@ Check if this is eqaul to one of `others` by calling equals ...@@ -440,7 +413,7 @@ Check if this is eqaul to one of `others` by calling equals
<a name="tojson"></a> <a name="tojson"></a>
## `toJSON()` -> `object` ## `toJSON()` -> `object`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/instance.js#L1072) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/instance.js#L981)
Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters. Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters.
......
<a name="model"></a> <a name="model"></a>
# Class Model # Class Model
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L24) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L24)
A Model represents a table in the database. Sometimes you might also see it refererred to as model, or simply as factory. A Model represents a table in the database. Sometimes you might also see it refererred to as model, or simply as factory.
This class should _not_ be instantiated directly, it is created using `sequelize.define`, and already created models can be loaded using `sequelize.import` This class should _not_ be instantiated directly, it is created using `sequelize.define`, and already created models can be loaded using `sequelize.import`
...@@ -12,7 +12,7 @@ This class should _not_ be instantiated directly, it is created using `sequelize ...@@ -12,7 +12,7 @@ This class should _not_ be instantiated directly, it is created using `sequelize
<a name="removeattribute"></a> <a name="removeattribute"></a>
## `removeAttribute([attribute])` ## `removeAttribute([attribute])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L398) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L404)
Remove attribute from model definition Remove attribute from model definition
**Params:** **Params:**
...@@ -26,7 +26,7 @@ Remove attribute from model definition ...@@ -26,7 +26,7 @@ Remove attribute from model definition
<a name="sync"></a> <a name="sync"></a>
## `sync()` -> `Promise.<this>` ## `sync()` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L408) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L414)
Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this) Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
**See:** **See:**
...@@ -38,7 +38,7 @@ Sync this Model to the DB, that is create the table. Upon success, the callback ...@@ -38,7 +38,7 @@ Sync this Model to the DB, that is create the table. Upon success, the callback
<a name="drop"></a> <a name="drop"></a>
## `drop([options])` -> `Promise` ## `drop([options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L444) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L451)
Drop the table represented by this Model Drop the table represented by this Model
**Params:** **Params:**
...@@ -47,13 +47,14 @@ Drop the table represented by this Model ...@@ -47,13 +47,14 @@ Drop the table represented by this Model
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| [options] | Object | | | [options] | Object | |
| [options.cascade=false] | Boolean | Also drop all objects depending on this table, such as views. Only works in postgres | | [options.cascade=false] | Boolean | Also drop all objects depending on this table, such as views. Only works in postgres |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="schema"></a> <a name="schema"></a>
## `schema(schema, [options])` -> `hi` ## `schema(schema, [options])` -> `hi`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L461) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L469)
Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - `"schema"."tableName"`, Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - `"schema"."tableName"`,
while the schema will be prepended to the table name for mysql and sqlite - `'schema.tablename'`. while the schema will be prepended to the table name for mysql and sqlite - `'schema.tablename'`.
...@@ -65,13 +66,14 @@ while the schema will be prepended to the table name for mysql and sqlite - `'sc ...@@ -65,13 +66,14 @@ while the schema will be prepended to the table name for mysql and sqlite - `'sc
| schema | String | The name of the schema | | schema | String | The name of the schema |
| [options] | Object | | | [options] | Object | |
| [options.schemaDelimiter='.'] | String | The character(s) that separates the schema name from the table name | | [options.schemaDelimiter='.'] | String | The character(s) that separates the schema name from the table name |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="gettablename"></a> <a name="gettablename"></a>
## `getTableName(options)` -> `String|Object` ## `getTableName([options])` -> `String|Object`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L484) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L493)
Get the tablename of the model, taking schema into account. The method will return The name as a string if the model has no schema, Get the tablename of the model, taking schema into account. The method will return The name as a string if the model has no schema,
or an object with `tableName`, `schema` and `delimiter` properties. or an object with `tableName`, `schema` and `delimiter` properties.
...@@ -80,21 +82,22 @@ or an object with `tableName`, `schema` and `delimiter` properties. ...@@ -80,21 +82,22 @@ or an object with `tableName`, `schema` and `delimiter` properties.
| Name | Type | Description | | Name | Type | Description |
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| options | Object | The hash of options from any query. You can use one model to access tables with matching schemas by overriding `getTableName` and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2) | | [options] | Object | The hash of options from any query. You can use one model to access tables with matching schemas by overriding `getTableName` and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2) |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="unscoped"></a> <a name="unscoped"></a>
## `unscoped()` -> `Model` ## `unscoped()` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L491) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L500)
*** ***
<a name="scope"></a> <a name="scope"></a>
## `scope(options*)` -> `Model` ## `scope(options*)` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L541) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L550)
Apply a scope created in `define` to the model. First let's look at how to create scopes: Apply a scope created in `define` to the model. First let's look at how to create scopes:
```js ```js
var Model = sequelize.define('model', attributes, { var Model = sequelize.define('model', attributes, {
...@@ -150,7 +153,7 @@ __Returns:__ A reference to the model, with the scope(s) applied. Calling scope ...@@ -150,7 +153,7 @@ __Returns:__ A reference to the model, with the scope(s) applied. Calling scope
<a name="findall"></a> <a name="findall"></a>
## `findAll([options])` -> `Promise.<Array.<Instance>>` ## `findAll([options])` -> `Promise.<Array.<Instance>>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L690) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L701)
Search for multiple instances. Search for multiple instances.
__Simple search using AND and =__ __Simple search using AND and =__
...@@ -238,15 +241,40 @@ The success listener is called with an array of instances if the query succeeds. ...@@ -238,15 +241,40 @@ The success listener is called with an array of instances if the query succeeds.
| [options.offset] | Number | | | [options.offset] | Number | |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
| [options.lock] | String &#124; Object | Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. See [transaction.LOCK for an example](api/transaction#lock) | | [options.lock] | String &#124; Object | Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. See [transaction.LOCK for an example](api/transaction#lock) |
| [options.raw] | Boolean | Return raw result. See sequelize.query for more information. | | [options.raw] | Boolean | Return raw result. See sequelize.query for more information. |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.having] | Object | |
__Aliases:__ all __Aliases:__ all
*** ***
<a name="findbyid"></a>
## `findById([options], ')` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L779)
Search for a single instance by its primary key. This applies LIMIT 1, so the listener will always be called with a single instance.
**See:**
* [Model#findAll](api/model#findall)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Number &#124; String &#124; Buffer | A hash of options to describe the scope of the search, or a number to search by id. |
| ' | Object | [options] |
| [options.transaction] | Transaction | |
__Aliases:__ findByPrimary
***
<a name="findone"></a> <a name="findone"></a>
## `findOne([options], [queryOptions])` -> `Promise.<Instance>` ## `findOne([options])` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L772) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L813)
Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance.
...@@ -259,9 +287,8 @@ Search for a single instance. This applies LIMIT 1, so the listener will always ...@@ -259,9 +287,8 @@ Search for a single instance. This applies LIMIT 1, so the listener will always
| Name | Type | Description | | Name | Type | Description |
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| [options] | Object &#124; Number | A hash of options to describe the scope of the search, or a number to search by id. | | [options] | Object | A hash of options to describe the scope of the search |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
| [queryOptions] | Object | |
__Aliases:__ find __Aliases:__ find
...@@ -269,7 +296,7 @@ __Aliases:__ find ...@@ -269,7 +296,7 @@ __Aliases:__ find
<a name="aggregate"></a> <a name="aggregate"></a>
## `aggregate(field, aggregateFunction, [options])` -> `Promise.<options.dataType|object>` ## `aggregate(field, aggregateFunction, [options])` -> `Promise.<options.dataType|object>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L813) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L842)
Run an aggregation method on the specified field Run an aggregation method on the specified field
...@@ -281,6 +308,7 @@ Run an aggregation method on the specified field ...@@ -281,6 +308,7 @@ Run an aggregation method on the specified field
| aggregateFunction | String | The function to use for aggregation, e.g. sum, max etc. | | aggregateFunction | String | The function to use for aggregation, e.g. sum, max etc. |
| [options] | Object | Query options. See sequelize.query for full options | | [options] | Object | Query options. See sequelize.query for full options |
| [options.where] | Object | A hash of search attributes. | | [options.where] | Object | A hash of search attributes. |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.dataType] | DataType &#124; String | The type of the result. If `field` is a field in this Model, the default will be the type of that field, otherwise defaults to float. | | [options.dataType] | DataType &#124; String | The type of the result. If `field` is a field in this Model, the default will be the type of that field, otherwise defaults to float. |
| [options.distinct] | boolean | Applies DISTINCT to the field being aggregated over | | [options.distinct] | boolean | Applies DISTINCT to the field being aggregated over |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -292,7 +320,7 @@ __Returns:__ Returns the aggregate result cast to `options.dataType`, unless `op ...@@ -292,7 +320,7 @@ __Returns:__ Returns the aggregate result cast to `options.dataType`, unless `op
<a name="count"></a> <a name="count"></a>
## `count([options])` -> `Promise.<Integer>` ## `count([options])` -> `Promise.<Integer>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L852) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L882)
Count the number of records matching the provided where clause. Count the number of records matching the provided where clause.
If you provide an `include` option, the number of matching associations will be counted instead. If you provide an `include` option, the number of matching associations will be counted instead.
...@@ -307,14 +335,15 @@ If you provide an `include` option, the number of matching associations will be ...@@ -307,14 +335,15 @@ If you provide an `include` option, the number of matching associations will be
| [options.include] | Object | Include options. See `find` for details | | [options.include] | Object | Include options. See `find` for details |
| [options.distinct] | boolean | Apply COUNT(DISTINCT(col)) | | [options.distinct] | boolean | Apply COUNT(DISTINCT(col)) |
| [options.attributes] | Object | Used in conjustion with `group` | | [options.attributes] | Object | Used in conjustion with `group` |
| [options.group] | Object | For creating complex counts. Will return multiple rows as needed. | | [options.group] | Object | For creating complex counts. Will return multiple rows as needed. |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="findandcount"></a> <a name="findandcount"></a>
## `findAndCount([findOptions], [queryOptions])` -> `Promise.<Object>` ## `findAndCount([findOptions])` -> `Promise.<Object>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L894) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L923)
Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very usefull for paging Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very usefull for paging
```js ```js
...@@ -337,8 +366,7 @@ In the above example, `result.rows` will contain rows 13 through 24, while `resu ...@@ -337,8 +366,7 @@ In the above example, `result.rows` will contain rows 13 through 24, while `resu
| Name | Type | Description | | Name | Type | Description |
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| [findOptions] | Object | See findAll | | [findOptions] | Object | See findAll |
| [queryOptions] | Object | See Sequelize.query |
__Aliases:__ findAndCountAll __Aliases:__ findAndCountAll
...@@ -346,7 +374,7 @@ __Aliases:__ findAndCountAll ...@@ -346,7 +374,7 @@ __Aliases:__ findAndCountAll
<a name="max"></a> <a name="max"></a>
## `max(field, [options])` -> `Promise.<Any>` ## `max(field, [options])` -> `Promise.<Any>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L950) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L979)
Find the maximum value of field Find the maximum value of field
...@@ -367,7 +395,7 @@ Find the maximum value of field ...@@ -367,7 +395,7 @@ Find the maximum value of field
<a name="min"></a> <a name="min"></a>
## `min(field, [options])` -> `Promise.<Any>` ## `min(field, [options])` -> `Promise.<Any>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L963) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L992)
Find the minimum value of field Find the minimum value of field
...@@ -388,7 +416,7 @@ Find the minimum value of field ...@@ -388,7 +416,7 @@ Find the minimum value of field
<a name="sum"></a> <a name="sum"></a>
## `sum(field, [options])` -> `Promise.<Number>` ## `sum(field, [options])` -> `Promise.<Number>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L976) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1005)
Find the sum of field Find the sum of field
...@@ -409,7 +437,7 @@ Find the sum of field ...@@ -409,7 +437,7 @@ Find the sum of field
<a name="build"></a> <a name="build"></a>
## `build(values, [options])` -> `Instance` ## `build(values, [options])` -> `Instance`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L992) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1020)
Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
...@@ -421,7 +449,6 @@ Builds a new model instance. Values is an object of key value pairs, must be def ...@@ -421,7 +449,6 @@ Builds a new model instance. Values is an object of key value pairs, must be def
| [options] | Object | | | [options] | Object | |
| [options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. | | [options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. |
| [options.isNewRecord=true] | Boolean | | | [options.isNewRecord=true] | Boolean | |
| [options.isDirty=true] | Boolean | |
| [options.include] | Array | an array of include options - Used to build prefetched/included model instances. See `set` | | [options.include] | Array | an array of include options - Used to build prefetched/included model instances. See `set` |
...@@ -429,7 +456,7 @@ Builds a new model instance. Values is an object of key value pairs, must be def ...@@ -429,7 +456,7 @@ Builds a new model instance. Values is an object of key value pairs, must be def
<a name="create"></a> <a name="create"></a>
## `create(values, [options])` -> `Promise.<Instance>` ## `create(values, [options])` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1062) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1088)
Builds a new model instance and calls save on it. Builds a new model instance and calls save on it.
...@@ -447,18 +474,18 @@ Builds a new model instance and calls save on it. ...@@ -447,18 +474,18 @@ Builds a new model instance and calls save on it.
| [options] | Object | | | [options] | Object | |
| [options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. | | [options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. |
| [options.isNewRecord=true] | Boolean | | | [options.isNewRecord=true] | Boolean | |
| [options.isDirty=true] | Boolean | |
| [options.fields] | Array | If set, only columns matching those in fields will be saved | | [options.fields] | Array | If set, only columns matching those in fields will be saved |
| [options.include] | Array | an array of include options - Used to build prefetched/included model instances | | [options.include] | Array | an array of include options - Used to build prefetched/included model instances |
| [options.onDuplicate] | String | | | [options.onDuplicate] | String | |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="findorinitialize"></a> <a name="findorinitialize"></a>
## `findOrInitialize` -> `Promise.<Instance>` ## `findOrInitialize` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1092) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1113)
Find a row that matches the query, or build (but don't save) the row if none is found. Find a row that matches the query, or build (but don't save) the row if none is found.
The successfull result of the promise will be (instance, initialized) - Make sure to use .spread() The successfull result of the promise will be (instance, initialized) - Make sure to use .spread()
...@@ -470,19 +497,20 @@ The successfull result of the promise will be (instance, initialized) - Make sur ...@@ -470,19 +497,20 @@ The successfull result of the promise will be (instance, initialized) - Make sur
| options | Object | | | options | Object | |
| options.where | Object | A hash of search attributes. | | options.where | Object | A hash of search attributes. |
| [options.defaults] | Object | Default values to use if building a new instance | | [options.defaults] | Object | Default values to use if building a new instance |
| [options.transaction] | Object | Transaction to run query under | | [options.transaction] | Object | Transaction to run query under |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
__Aliases:__ findOrBuild __Aliases:__ findOrBuild
*** ***
<a name="findorcreate"></a> <a name="findorcreate"></a>
## `findOrCreate(options, [queryOptions])` -> `Promise.<Instance, created>` ## `findOrCreate(options)` -> `Promise.<Instance, created>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1136) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1155)
Find a row that matches the query, or build and save the row if none is found Find a row that matches the query, or build and save the row if none is found
The successfull result of the promise will be (instance, created) - Make sure to use .spread() The successfull result of the promise will be (instance, created) - Make sure to use .spread()
If no transaction is passed in the `queryOptions` object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call. If no transaction is passed in the `options` object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call.
However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has comitted. In this case, an instance of sequelize.TimeoutError will be thrown instead. However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has comitted. In this case, an instance of sequelize.TimeoutError will be thrown instead.
If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally. If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.
...@@ -494,14 +522,14 @@ If a transaction is created, a savepoint will be created instead, and any unique ...@@ -494,14 +522,14 @@ If a transaction is created, a savepoint will be created instead, and any unique
| options | Object | | | options | Object | |
| options.where | Object | where A hash of search attributes. | | options.where | Object | where A hash of search attributes. |
| [options.defaults] | Object | Default values to use if creating a new instance | | [options.defaults] | Object | Default values to use if creating a new instance |
| [queryOptions] | Object | Options passed to the find and create calls | | [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="upsert"></a> <a name="upsert"></a>
## `upsert(values, [options])` -> `Promise.<created>` ## `upsert(values, [options])` -> `Promise.<created>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1227) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1244)
Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated. Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
**Implementation details:** **Implementation details:**
...@@ -520,7 +548,8 @@ Insert or update a single row. An update will be executed if a row which matches ...@@ -520,7 +548,8 @@ Insert or update a single row. An update will be executed if a row which matches
| values | Object | | | values | Object | |
| [options] | Object | | | [options] | Object | |
| [options.validate=true] | Boolean | Run validations before the row is inserted | | [options.validate=true] | Boolean | Run validations before the row is inserted |
| [options.fields=Object.keys(this.attributes)] | Array | The fields to insert / update. Defaults to all fields | | [options.fields=Object.keys(this.attributes)] | Array | The fields to insert / update. Defaults to all fields |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
__Returns:__ Returns a boolean indicating whether the row was created or updated. __Returns:__ Returns a boolean indicating whether the row was created or updated.
__Aliases:__ insertOrUpdate __Aliases:__ insertOrUpdate
...@@ -529,7 +558,7 @@ __Aliases:__ insertOrUpdate ...@@ -529,7 +558,7 @@ __Aliases:__ insertOrUpdate
<a name="bulkcreate"></a> <a name="bulkcreate"></a>
## `bulkCreate(records, [options])` -> `Promise.<Array.<Instance>>` ## `bulkCreate(records, [options])` -> `Promise.<Array.<Instance>>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1281) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1299)
Create and insert multiple instances in bulk. Create and insert multiple instances in bulk.
The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. This is because MySQL The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. This is because MySQL
...@@ -550,13 +579,14 @@ To obtain Instances for the newly created values, you will need to query for the ...@@ -550,13 +579,14 @@ To obtain Instances for the newly created values, you will need to query for the
| [options.ignoreDuplicates=false] | Boolean | Ignore duplicate values for primary keys? (not supported by postgres) | | [options.ignoreDuplicates=false] | Boolean | Ignore duplicate values for primary keys? (not supported by postgres) |
| [options.updateOnDuplicate] | Array | Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated. | | [options.updateOnDuplicate] | Array | Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="destroy"></a> <a name="destroy"></a>
## `destroy(options)` -> `Promise.<undefined>` ## `destroy(options)` -> `Promise.<undefined>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1459) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1450)
Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled. Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
...@@ -573,13 +603,14 @@ Delete multiple instances, or set their deletedAt timestamp to the current time ...@@ -573,13 +603,14 @@ Delete multiple instances, or set their deletedAt timestamp to the current time
| [options.truncate=false] | Boolean | If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored | | [options.truncate=false] | Boolean | If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored |
| [options.cascade=false] | Boolean | Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE. | | [options.cascade=false] | Boolean | Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
*** ***
<a name="restore"></a> <a name="restore"></a>
## `restore(options)` -> `Promise.<undefined>` ## `restore(options)` -> `Promise.<undefined>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1535) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1527)
Restore multiple instances if `paranoid` is enabled. Restore multiple instances if `paranoid` is enabled.
...@@ -592,6 +623,7 @@ Restore multiple instances if `paranoid` is enabled. ...@@ -592,6 +623,7 @@ Restore multiple instances if `paranoid` is enabled.
| [options.hooks=true] | Boolean | Run before / after bulk restore hooks? | | [options.hooks=true] | Boolean | Run before / after bulk restore hooks? |
| [options.individualHooks=false] | Boolean | If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row | | [options.individualHooks=false] | Boolean | If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row |
| [options.limit] | Number | How many rows to undelete | | [options.limit] | Number | How many rows to undelete |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -599,7 +631,7 @@ Restore multiple instances if `paranoid` is enabled. ...@@ -599,7 +631,7 @@ Restore multiple instances if `paranoid` is enabled.
<a name="update"></a> <a name="update"></a>
## `update(values, options)` -> `Promise.<Array.<affectedCount, affectedRows>>` ## `update(values, options)` -> `Promise.<Array.<affectedCount, affectedRows>>`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1606) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1600)
Update multiple instances that match the where options. The promise returns an array with one or two elements. The first element is always the number Update multiple instances that match the where options. The promise returns an array with one or two elements. The first element is always the number
of affected rows, while the second element is the actual affected rows (only supported in postgres with `options.returning` true.) of affected rows, while the second element is the actual affected rows (only supported in postgres with `options.returning` true.)
...@@ -614,9 +646,11 @@ of affected rows, while the second element is the actual affected rows (only sup ...@@ -614,9 +646,11 @@ of affected rows, while the second element is the actual affected rows (only sup
| [options.fields] | Array | Fields to update (defaults to all fields) | | [options.fields] | Array | Fields to update (defaults to all fields) |
| [options.validate=true] | Boolean | Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation | | [options.validate=true] | Boolean | Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation |
| [options.hooks=true] | Boolean | Run before / after bulk update hooks? | | [options.hooks=true] | Boolean | Run before / after bulk update hooks? |
| [options.sideEffects=true] | Boolean | Whether or not to update the side effects of any virtual setters. |
| [options.individualHooks=false] | Boolean | Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs. A select is needed, because the row data needs to be passed to the hooks | | [options.individualHooks=false] | Boolean | Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs. A select is needed, because the row data needs to be passed to the hooks |
| [options.returning=false] | Boolean | Return the affected rows (only for postgres) | | [options.returning=false] | Boolean | Return the affected rows (only for postgres) |
| [options.limit] | Number | How many rows to update (only for mysql and mariadb) | | [options.limit] | Number | How many rows to update (only for mysql and mariadb) |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | | | [options.transaction] | Transaction | |
...@@ -624,7 +658,7 @@ of affected rows, while the second element is the actual affected rows (only sup ...@@ -624,7 +658,7 @@ of affected rows, while the second element is the actual affected rows (only sup
<a name="describe"></a> <a name="describe"></a>
## `describe()` -> `Promise` ## `describe()` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/model.js#L1782) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/model.js#L1788)
Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types. Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types.
......
<a name="sequelize"></a> <a name="sequelize"></a>
# Class Sequelize # Class Sequelize
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L34) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L29)
This is the main class, the entry point to sequelize. To use it, you just need to import sequelize: This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
```js ```js
...@@ -14,7 +14,7 @@ In addition to sequelize, the connection library for the dialect you want to use ...@@ -14,7 +14,7 @@ In addition to sequelize, the connection library for the dialect you want to use
<a name="sequelize"></a> <a name="sequelize"></a>
## `new Sequelize(database, [username=null], [password=null], [options={}])` ## `new Sequelize(database, [username=null], [password=null], [options={}])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L89) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L84)
Instantiate sequelize with name of database, username and password Instantiate sequelize with name of database, username and password
#### Example usage #### Example usage
...@@ -74,7 +74,7 @@ var sequelize = new Sequelize('mysql://localhost:3306/database', {}) ...@@ -74,7 +74,7 @@ var sequelize = new Sequelize('mysql://localhost:3306/database', {})
<a name="sequelize"></a> <a name="sequelize"></a>
## `new Sequelize(uri, [options={}])` ## `new Sequelize(uri, [options={}])`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L98) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L93)
Instantiate sequelize with an URI Instantiate sequelize with an URI
**Params:** **Params:**
...@@ -89,14 +89,14 @@ Instantiate sequelize with an URI ...@@ -89,14 +89,14 @@ Instantiate sequelize with an URI
<a name="models"></a> <a name="models"></a>
## `models` ## `models`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L195) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L190)
Models are stored here under the name given to `sequelize.define` Models are stored here under the name given to `sequelize.define`
*** ***
<a name="sequelize"></a> <a name="sequelize"></a>
## `Sequelize` ## `Sequelize`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L222) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L217)
A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc. A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
**See:** **See:**
...@@ -108,7 +108,7 @@ A reference to Sequelize constructor from sequelize. Useful for accessing DataTy ...@@ -108,7 +108,7 @@ A reference to Sequelize constructor from sequelize. Useful for accessing DataTy
<a name="utils"></a> <a name="utils"></a>
## `Utils` ## `Utils`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L229) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L224)
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. 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:** **See:**
...@@ -120,7 +120,7 @@ A reference to sequelize utilities. Most users will not need to use these utils ...@@ -120,7 +120,7 @@ A reference to sequelize utilities. Most users will not need to use these utils
<a name="promise"></a> <a name="promise"></a>
## `Promise` ## `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L236) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L231)
A modified version of bluebird promises, that allows listening for sql events A modified version of bluebird promises, that allows listening for sql events
**See:** **See:**
...@@ -132,14 +132,14 @@ A modified version of bluebird promises, that allows listening for sql events ...@@ -132,14 +132,14 @@ A modified version of bluebird promises, that allows listening for sql events
<a name="querytypes"></a> <a name="querytypes"></a>
## `QueryTypes` ## `QueryTypes`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L242) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L237)
Available query types for use with `sequelize.query` Available query types for use with `sequelize.query`
*** ***
<a name="validator"></a> <a name="validator"></a>
## `Validator` ## `Validator`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L249) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L244)
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. 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:** **See:**
...@@ -151,7 +151,7 @@ Exposes the validator.js object, so you can extend it with custom validation fun ...@@ -151,7 +151,7 @@ Exposes the validator.js object, so you can extend it with custom validation fun
<a name="transaction"></a> <a name="transaction"></a>
## `Transaction` ## `Transaction`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L269) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L264)
A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction
**See:** **See:**
...@@ -162,9 +162,22 @@ A reference to the sequelize transaction class. Use this to access isolationLeve ...@@ -162,9 +162,22 @@ A reference to the sequelize transaction class. Use this to access isolationLeve
*** ***
<a name="deferrable"></a>
## `Deferrable`
[View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L272)
A reference to the deferrable collection. Use this to access the different deferrable options.
**See:**
* [Deferrable](api/deferrable)
* [Sequelize#transaction](api/sequelize#transaction)
***
<a name="instance"></a> <a name="instance"></a>
## `Instance` ## `Instance`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L276) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L279)
A reference to the sequelize instance class. A reference to the sequelize instance class.
**See:** **See:**
...@@ -176,7 +189,7 @@ A reference to the sequelize instance class. ...@@ -176,7 +189,7 @@ A reference to the sequelize instance class.
<a name="error"></a> <a name="error"></a>
## `Error` ## `Error`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L289) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L292)
A general error class A general error class
**See:** **See:**
...@@ -188,7 +201,7 @@ A general error class ...@@ -188,7 +201,7 @@ A general error class
<a name="validationerror"></a> <a name="validationerror"></a>
## `ValidationError` ## `ValidationError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L297) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L300)
Emitted when a validation fails Emitted when a validation fails
**See:** **See:**
...@@ -200,7 +213,7 @@ Emitted when a validation fails ...@@ -200,7 +213,7 @@ Emitted when a validation fails
<a name="validationerroritem"></a> <a name="validationerroritem"></a>
## `ValidationErrorItem` ## `ValidationErrorItem`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L305) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L308)
Describes a validation error on an instance path Describes a validation error on an instance path
**See:** **See:**
...@@ -212,7 +225,7 @@ Describes a validation error on an instance path ...@@ -212,7 +225,7 @@ Describes a validation error on an instance path
<a name="databaseerror"></a> <a name="databaseerror"></a>
## `DatabaseError` ## `DatabaseError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L312) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L315)
A base class for all database related errors. A base class for all database related errors.
**See:** **See:**
...@@ -224,7 +237,7 @@ A base class for all database related errors. ...@@ -224,7 +237,7 @@ A base class for all database related errors.
<a name="timeouterror"></a> <a name="timeouterror"></a>
## `TimeoutError` ## `TimeoutError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L319) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L322)
Thrown when a database query times out because of a deadlock Thrown when a database query times out because of a deadlock
**See:** **See:**
...@@ -236,7 +249,7 @@ Thrown when a database query times out because of a deadlock ...@@ -236,7 +249,7 @@ Thrown when a database query times out because of a deadlock
<a name="uniqueconstrainterror"></a> <a name="uniqueconstrainterror"></a>
## `UniqueConstraintError` ## `UniqueConstraintError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L326) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L329)
Thrown when a unique constraint is violated in the database Thrown when a unique constraint is violated in the database
**See:** **See:**
...@@ -248,7 +261,7 @@ Thrown when a unique constraint is violated in the database ...@@ -248,7 +261,7 @@ Thrown when a unique constraint is violated in the database
<a name="exclusionconstrainterror"></a> <a name="exclusionconstrainterror"></a>
## `ExclusionConstraintError` ## `ExclusionConstraintError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L333) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L336)
Thrown when an exclusion constraint is violated in the database Thrown when an exclusion constraint is violated in the database
**See:** **See:**
...@@ -260,7 +273,7 @@ Thrown when an exclusion constraint is violated in the database ...@@ -260,7 +273,7 @@ Thrown when an exclusion constraint is violated in the database
<a name="foreignkeyconstrainterror"></a> <a name="foreignkeyconstrainterror"></a>
## `ForeignKeyConstraintError` ## `ForeignKeyConstraintError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L340) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L343)
Thrown when a foreign key constraint is violated in the database Thrown when a foreign key constraint is violated in the database
**See:** **See:**
...@@ -272,7 +285,7 @@ Thrown when a foreign key constraint is violated in the database ...@@ -272,7 +285,7 @@ Thrown when a foreign key constraint is violated in the database
<a name="connectionerror"></a> <a name="connectionerror"></a>
## `ConnectionError` ## `ConnectionError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L347) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L350)
A base class for all connection related errors. A base class for all connection related errors.
**See:** **See:**
...@@ -284,7 +297,7 @@ A base class for all connection related errors. ...@@ -284,7 +297,7 @@ A base class for all connection related errors.
<a name="connectionrefusederror"></a> <a name="connectionrefusederror"></a>
## `ConnectionRefusedError` ## `ConnectionRefusedError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L354) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L357)
Thrown when a connection to a database is refused Thrown when a connection to a database is refused
**See:** **See:**
...@@ -296,7 +309,7 @@ Thrown when a connection to a database is refused ...@@ -296,7 +309,7 @@ Thrown when a connection to a database is refused
<a name="accessdeniederror"></a> <a name="accessdeniederror"></a>
## `AccessDeniedError` ## `AccessDeniedError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L361) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L364)
Thrown when a connection to a database is refused due to insufficient access Thrown when a connection to a database is refused due to insufficient access
**See:** **See:**
...@@ -308,7 +321,7 @@ Thrown when a connection to a database is refused due to insufficient access ...@@ -308,7 +321,7 @@ Thrown when a connection to a database is refused due to insufficient access
<a name="hostnotfounderror"></a> <a name="hostnotfounderror"></a>
## `HostNotFoundError` ## `HostNotFoundError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L368) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L371)
Thrown when a connection to a database has a hostname that was not found Thrown when a connection to a database has a hostname that was not found
**See:** **See:**
...@@ -320,7 +333,7 @@ Thrown when a connection to a database has a hostname that was not found ...@@ -320,7 +333,7 @@ Thrown when a connection to a database has a hostname that was not found
<a name="hostnotreachableerror"></a> <a name="hostnotreachableerror"></a>
## `HostNotReachableError` ## `HostNotReachableError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L375) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L378)
Thrown when a connection to a database has a hostname that was not reachable Thrown when a connection to a database has a hostname that was not reachable
**See:** **See:**
...@@ -332,7 +345,7 @@ Thrown when a connection to a database has a hostname that was not reachable ...@@ -332,7 +345,7 @@ Thrown when a connection to a database has a hostname that was not reachable
<a name="invalidconnectionerror"></a> <a name="invalidconnectionerror"></a>
## `InvalidConnectionError` ## `InvalidConnectionError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L382) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L385)
Thrown when a connection to a database has invalid values for any of the connection parameters Thrown when a connection to a database has invalid values for any of the connection parameters
**See:** **See:**
...@@ -344,7 +357,7 @@ Thrown when a connection to a database has invalid values for any of the connect ...@@ -344,7 +357,7 @@ Thrown when a connection to a database has invalid values for any of the connect
<a name="connectiontimedouterror"></a> <a name="connectiontimedouterror"></a>
## `ConnectionTimedOutError` ## `ConnectionTimedOutError`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L389) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L392)
Thrown when a connection to a database times out Thrown when a connection to a database times out
**See:** **See:**
...@@ -356,7 +369,7 @@ Thrown when a connection to a database times out ...@@ -356,7 +369,7 @@ Thrown when a connection to a database times out
<a name="getdialect"></a> <a name="getdialect"></a>
## `getDialect()` -> `String` ## `getDialect()` -> `String`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L397) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L400)
Returns the specified dialect. Returns the specified dialect.
__Returns:__ The specified dialect. __Returns:__ The specified dialect.
...@@ -365,7 +378,7 @@ __Returns:__ The specified dialect. ...@@ -365,7 +378,7 @@ __Returns:__ The specified dialect.
<a name="getqueryinterface"></a> <a name="getqueryinterface"></a>
## `getQueryInterface()` -> `QueryInterface` ## `getQueryInterface()` -> `QueryInterface`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L409) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L412)
Returns an instance of QueryInterface. Returns an instance of QueryInterface.
...@@ -377,31 +390,9 @@ __Returns:__ An instance (singleton) of QueryInterface. ...@@ -377,31 +390,9 @@ __Returns:__ An instance (singleton) of QueryInterface.
*** ***
<a name="getmigrator"></a>
## `getMigrator([options={}], [force=false])` -> `Migrator`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L423)
Returns an instance (singleton) of Migrator.
**See:**
* [Migrator](api/migrator)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options={}] | Object | See Migrator for options |
| [force=false] | Boolean | A flag that defines if the migrator should get instantiated or not. |
__Returns:__ An instance of Migrator.
***
<a name="define"></a> <a name="define"></a>
## `define(modelName, attributes, [options])` -> `Model` ## `define(modelName, attributes, [options])` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L541) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L515)
Define a new model, representing a table in the DB. 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: 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:
...@@ -461,8 +452,9 @@ For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models ...@@ -461,8 +452,9 @@ For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models
| [attributes.column.field=null] | String | If set, sequelize will map the attribute name to a different name in the database | | [attributes.column.field=null] | String | If set, sequelize will map the attribute name to a different name in the database |
| [attributes.column.autoIncrement=false] | Boolean | | | [attributes.column.autoIncrement=false] | Boolean | |
| [attributes.column.comment=null] | String | | | [attributes.column.comment=null] | String | |
| [attributes.column.references] | String &#124; Model | If this column references another table, provide it here as a Model, or a string | | [attributes.column.references=null] | String &#124; Model | An object with reference configurations |
| [attributes.column.referencesKey='id'] | String | The column of the foreign table that this column references | | [attributes.column.references.model] | String &#124; Model | If this column references another table, provide it here as a Model, or a string |
| [attributes.column.references.key='id'] | String | The column of the foreign table that this column references |
| [attributes.column.onUpdate] | String | What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION | | [attributes.column.onUpdate] | String | What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION |
| [attributes.column.onDelete] | String | What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION | | [attributes.column.onDelete] | String | What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION |
| [attributes.column.get] | Function | Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying values. | | [attributes.column.get] | Function | Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying values. |
...@@ -476,7 +468,7 @@ For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models ...@@ -476,7 +468,7 @@ For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models
| [options.paranoid=false] | Boolean | Calling `destroy` will not delete the model, but instead set a `deletedAt` timestamp if this is true. Needs `timestamps=true` to work | | [options.paranoid=false] | Boolean | Calling `destroy` will not delete the model, but instead set a `deletedAt` timestamp if this is true. Needs `timestamps=true` to work |
| [options.underscored=false] | Boolean | Converts all camelCased columns to underscored if true | | [options.underscored=false] | Boolean | Converts all camelCased columns to underscored if true |
| [options.underscoredAll=false] | Boolean | Converts camelCased model names to underscored tablenames if true | | [options.underscoredAll=false] | Boolean | Converts camelCased model names to underscored tablenames if true |
| [options.freezeTableName=false] | Boolean | 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 | | [options.freezeTableName=false] | Boolean | If 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] | Object | An object with two attributes, `singular` and `plural`, which are used when this model is associated to others. | | [options.name] | Object | An 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.singular=inflection.singularize(modelName)] | String | |
| [options.name.plural=inflection.pluralize(modelName)] | String | | | [options.name.plural=inflection.pluralize(modelName)] | String | |
...@@ -509,8 +501,8 @@ For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models ...@@ -509,8 +501,8 @@ For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models
<a name="model"></a> <a name="model"></a>
## `model(modelName)` -> `Model` ## `model(modelName)` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L587) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L561)
Fetch a DAO factory which is already defined Fetch a Model which is already defined
**Params:** **Params:**
...@@ -524,7 +516,7 @@ Fetch a DAO factory which is already defined ...@@ -524,7 +516,7 @@ Fetch a DAO factory which is already defined
<a name="isdefined"></a> <a name="isdefined"></a>
## `isDefined(modelName)` -> `Boolean` ## `isDefined(modelName)` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L601) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L575)
Checks whether a model with the given name is defined Checks whether a model with the given name is defined
...@@ -539,7 +531,7 @@ Checks whether a model with the given name is defined ...@@ -539,7 +531,7 @@ Checks whether a model with the given name is defined
<a name="import"></a> <a name="import"></a>
## `import(path)` -> `Model` ## `import(path)` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L615) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L589)
Imports a model defined in another file 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 Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
...@@ -556,8 +548,8 @@ See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-m ...@@ -556,8 +548,8 @@ See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-m
*** ***
<a name="query"></a> <a name="query"></a>
## `query(sql, [callee], [options={}])` -> `Promise` ## `query(sql, [options={}])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L670) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L646)
Execute a query on the DB, with the posibility to bypass all the sequelize goodness. Execute a query on the DB, with the posibility 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. 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.
...@@ -585,7 +577,6 @@ sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(functio ...@@ -585,7 +577,6 @@ sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(functio
| Name | Type | Description | | Name | Type | Description |
| ---- | ---- | ----------- | | ---- | ---- | ----------- |
| sql | String | | | sql | String | |
| [callee] | Instance &#124; Model | If callee is provided, the returned data will be put into the callee, and `type` will default to SELECT |
| [options={}] | Object | Query options. | | [options={}] | Object | Query options. |
| [options.raw] | Boolean | If true, sequelize will not try to format the results of the query, or build an instance of a model from the result | | [options.raw] | Boolean | If 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] | Transaction | The transaction that the query should be executed under | | [options.transaction=null] | Transaction | The transaction that the query should be executed under |
...@@ -593,14 +584,17 @@ sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(functio ...@@ -593,14 +584,17 @@ sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(functio
| [options.nest=false] | Boolean | 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 | | [options.nest=false] | Boolean | 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 |
| [options.plain=false] | Boolean | Sets the query type to `SELECT` and return a single row | | [options.plain=false] | Boolean | Sets the query type to `SELECT` and return a single row |
| [options.replacements] | Object &#124; Array | Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL. | | [options.replacements] | Object &#124; Array | Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL. |
| [options.useMaster=false] | Boolean | Force the query to use the write pool, regardless of the query type. | | [options.useMaster=false] | Boolean | Force the query to use the write pool, regardless of the query type. |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.instance] | Instance | A sequelize instance used to build the return instance |
| [options.model] | Model | A sequelize model used to build the returned model instances (used to be called callee) |
*** ***
<a name="set"></a> <a name="set"></a>
## `set(variables, options)` -> `Promise` ## `set(variables, options)` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L767) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L740)
Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction. 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. Only works for MySQL.
...@@ -618,7 +612,7 @@ Only works for MySQL. ...@@ -618,7 +612,7 @@ Only works for MySQL.
<a name="escape"></a> <a name="escape"></a>
## `escape(value)` -> `String` ## `escape(value)` -> `String`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L801) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L774)
Escape value. Escape value.
...@@ -633,7 +627,7 @@ Escape value. ...@@ -633,7 +627,7 @@ Escape value.
<a name="createschema"></a> <a name="createschema"></a>
## `createSchema(schema, options={})` -> `Promise` ## `createSchema(schema, options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L817) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L790)
Create a new database schema. Create a new database schema.
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
...@@ -658,7 +652,7 @@ not a database table. In mysql and sqlite, this command will do nothing. ...@@ -658,7 +652,7 @@ not a database table. In mysql and sqlite, this command will do nothing.
<a name="showallschemas"></a> <a name="showallschemas"></a>
## `showAllSchemas(options={})` -> `Promise` ## `showAllSchemas(options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L830) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L803)
Show all defined schemas Show all defined schemas
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
...@@ -676,7 +670,7 @@ not a database table. In mysql and sqlite, this will show all tables. ...@@ -676,7 +670,7 @@ not a database table. In mysql and sqlite, this will show all tables.
<a name="dropschema"></a> <a name="dropschema"></a>
## `dropSchema(schema, options={})` -> `Promise` ## `dropSchema(schema, options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L844) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L817)
Drop a single schema Drop a single schema
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
...@@ -695,7 +689,7 @@ not a database table. In mysql and sqlite, this drop a table matching the schema ...@@ -695,7 +689,7 @@ not a database table. In mysql and sqlite, this drop a table matching the schema
<a name="dropallschemas"></a> <a name="dropallschemas"></a>
## `dropAllSchemas(options={})` -> `Promise` ## `dropAllSchemas(options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L857) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L830)
Drop all schemas Drop all schemas
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
...@@ -713,8 +707,8 @@ not a database table. In mysql and sqlite, this is the equivalent of drop all ta ...@@ -713,8 +707,8 @@ not a database table. In mysql and sqlite, this is the equivalent of drop all ta
<a name="sync"></a> <a name="sync"></a>
## `sync([options={}])` -> `Promise` ## `sync([options={}])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L871) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L844)
Sync all defined DAOs to the DB. Sync all defined models to the DB.
**Params:** **Params:**
...@@ -732,7 +726,7 @@ Sync all defined DAOs to the DB. ...@@ -732,7 +726,7 @@ Sync all defined DAOs to the DB.
<a name="drop"></a> <a name="drop"></a>
## `drop(options)` -> `Promise` ## `drop(options)` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L917) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L890)
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
**See:** **See:**
...@@ -752,7 +746,7 @@ Drop all tables defined through this sequelize instance. This is done by calling ...@@ -752,7 +746,7 @@ Drop all tables defined through this sequelize instance. This is done by calling
<a name="authenticate"></a> <a name="authenticate"></a>
## `authenticate()` -> `Promise` ## `authenticate()` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L939) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L912)
Test the connection by trying to authenticate Test the connection by trying to authenticate
__Aliases:__ validate __Aliases:__ validate
...@@ -761,7 +755,7 @@ __Aliases:__ validate ...@@ -761,7 +755,7 @@ __Aliases:__ validate
<a name="fn "></a> <a name="fn "></a>
## `fn (fn, args)` -> `Sequelize.fn` ## `fn (fn, args)` -> `Sequelize.fn`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L974) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L947)
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. 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. 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.
...@@ -793,7 +787,7 @@ instance.updateAttributes({ ...@@ -793,7 +787,7 @@ instance.updateAttributes({
<a name="col"></a> <a name="col"></a>
## `col(col)` -> `Sequelize.col` ## `col(col)` -> `Sequelize.col`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L987) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L960)
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. 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:** **See:**
...@@ -812,7 +806,7 @@ Creates a object representing a column in the DB. This is often useful in conjun ...@@ -812,7 +806,7 @@ Creates a object representing a column in the DB. This is often useful in conjun
<a name="cast"></a> <a name="cast"></a>
## `cast(val, type)` -> `Sequelize.cast` ## `cast(val, type)` -> `Sequelize.cast`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L1001) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L974)
Creates a object representing a call to the cast function. Creates a object representing a call to the cast function.
...@@ -828,7 +822,7 @@ Creates a object representing a call to the cast function. ...@@ -828,7 +822,7 @@ Creates a object representing a call to the cast function.
<a name="literal"></a> <a name="literal"></a>
## `literal(val)` -> `Sequelize.literal` ## `literal(val)` -> `Sequelize.literal`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L1014) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L987)
Creates a object representing a literal, i.e. something that will not be escaped. Creates a object representing a literal, i.e. something that will not be escaped.
...@@ -844,7 +838,7 @@ __Aliases:__ asIs ...@@ -844,7 +838,7 @@ __Aliases:__ asIs
<a name="and"></a> <a name="and"></a>
## `and(args)` -> `Sequelize.and` ## `and(args)` -> `Sequelize.and`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L1027) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L1000)
An AND query An AND query
**See:** **See:**
...@@ -863,7 +857,7 @@ An AND query ...@@ -863,7 +857,7 @@ An AND query
<a name="or"></a> <a name="or"></a>
## `or(args)` -> `Sequelize.or` ## `or(args)` -> `Sequelize.or`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L1040) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L1013)
An OR query An OR query
**See:** **See:**
...@@ -882,7 +876,7 @@ An OR query ...@@ -882,7 +876,7 @@ An OR query
<a name="json"></a> <a name="json"></a>
## `json(conditions, [value])` -> `Sequelize.json` ## `json(conditions, [value])` -> `Sequelize.json`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L1053) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L1026)
Creates an object representing nested where conditions for postgres's json data-type. Creates an object representing nested where conditions for postgres's json data-type.
**See:** **See:**
...@@ -902,7 +896,7 @@ Creates an object representing nested where conditions for postgres's json data- ...@@ -902,7 +896,7 @@ Creates an object representing nested where conditions for postgres's json data-
<a name="where"></a> <a name="where"></a>
## `where(attr, [comparator='='], logic)` -> `Sequelize.where` ## `where(attr, [comparator='='], logic)` -> `Sequelize.where`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L1075) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L1048)
A way of specifying attr = condition. 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 The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` or `Model.rawAttributes.name`). The
...@@ -930,7 +924,7 @@ __Aliases:__ condition ...@@ -930,7 +924,7 @@ __Aliases:__ condition
<a name="transaction"></a> <a name="transaction"></a>
## `transaction([options={}])` -> `Promise` ## `transaction([options={}])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/sequelize.js#L1127) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/sequelize.js#L1101)
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 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
```js ```js
...@@ -982,8 +976,9 @@ Note, that CLS is enabled for all sequelize instances, and all instances will sh ...@@ -982,8 +976,9 @@ Note, that CLS is enabled for all sequelize instances, and all instances will sh
| [options={}] | Object | | | [options={}] | Object | |
| [options.autocommit=true] | Boolean | | | [options.autocommit=true] | Boolean | |
| [options.isolationLevel='REPEATABLE_READ'] | String | See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options | | [options.isolationLevel='REPEATABLE_READ'] | String | See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options |
| [options.logging=false] | Function | A 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 <a href="irc://irc.freenode.net/#sequelizejs">IRC</a>, 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](http://usejsdoc.org) and [dox](https://github.com/tj/dox)_ _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 <a href="irc://irc.freenode.net/#sequelizejs">IRC</a>, 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](http://usejsdoc.org) and [dox](https://github.com/tj/dox)_
\ No newline at end of file
<a name="transaction"></a> <a name="transaction"></a>
# Class Transaction # Class Transaction
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/transaction.js#L11) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/transaction.js#L18)
The transaction object is used to identify a running transaction. It is created by calling `Sequelize.transaction()`. The transaction object is used to identify a running transaction. It is created by calling `Sequelize.transaction()`.
To run a query under a transaction, you should pass the transaction in the options object. To run a query under a transaction, you should pass the transaction in the options object.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| sequelize | Sequelize | A configured sequelize Instance |
| options | Object | An object with options |
| options.autocommit=true | Boolean | Sets the autocommit property of the transaction. |
| options.isolationLevel=true | String | Sets the isolation level of the transaction. |
| options.deferrable | String | Sets the constraints to be deferred or immediately checked. |
*** ***
<a name="isolation_levels"></a> <a name="isolation_levels"></a>
## `ISOLATION_LEVELS` ## `ISOLATION_LEVELS`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/transaction.js#L46) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/transaction.js#L53)
The possible isolations levels to use when starting a transaction. The possible isolations levels to use when starting a transaction.
Can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`. Can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`. Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`.
...@@ -28,7 +39,7 @@ Default to `REPEATABLE_READ` but you can override the default isolation level by ...@@ -28,7 +39,7 @@ Default to `REPEATABLE_READ` but you can override the default isolation level by
<a name="lock"></a> <a name="lock"></a>
## `LOCK` ## `LOCK`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/transaction.js#L90) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/transaction.js#L97)
Possible options for row locking. Used in conjuction with `find` calls: Possible options for row locking. Used in conjuction with `find` calls:
```js ```js
...@@ -68,7 +79,7 @@ UserModel will be locked but TaskModel won't! ...@@ -68,7 +79,7 @@ UserModel will be locked but TaskModel won't!
<a name="commit"></a> <a name="commit"></a>
## `commit()` -> `this` ## `commit()` -> `this`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/transaction.js#L102) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/transaction.js#L109)
Commit the transaction Commit the transaction
...@@ -76,7 +87,7 @@ Commit the transaction ...@@ -76,7 +87,7 @@ Commit the transaction
<a name="rollback"></a> <a name="rollback"></a>
## `rollback()` -> `this` ## `rollback()` -> `this`
[View code](https://github.com/sequelize/sequelize/blob/716cb2d2aae3a4cd7fdaace13411cf4161e6deb6/lib/transaction.js#L123) [View code](https://github.com/sequelize/sequelize/blob/2dc7a0f610480e045a412d215d7247912158407d/lib/transaction.js#L130)
Rollback (abort) the transaction Rollback (abort) the transaction
......
...@@ -27,7 +27,8 @@ if (program.file) { ...@@ -27,7 +27,8 @@ if (program.file) {
{file:'lib/associations/mixin.js', output: 'associations'}, {file:'lib/associations/mixin.js', output: 'associations'},
{file:'lib/promise.js', output: 'promise'}, {file:'lib/promise.js', output: 'promise'},
{file:'lib/transaction.js', output: 'transaction'}, {file:'lib/transaction.js', output: 'transaction'},
{file:'lib/data-types.js', output: 'datatypes'} {file:'lib/data-types.js', output: 'datatypes'},
{file:'lib/deferrable.js', output: 'deferrable'}
]; ];
} }
......
...@@ -48,7 +48,23 @@ var Foo = sequelize.define('Foo', { ...@@ -48,7 +48,23 @@ var Foo = sequelize.define('Foo', {
hasComment: { type: Sequelize.INTEGER, comment: "I'm a comment!" }, hasComment: { type: Sequelize.INTEGER, comment: "I'm a comment!" },
// You can specify a custom field name via the "field" attribute: // You can specify a custom field name via the "field" attribute:
fieldWithUnderscores: { type: Sequelize.STRING, field: "field_with_underscores" } fieldWithUnderscores: { type: Sequelize.STRING, field: "field_with_underscores" },
// It is possible to create foreign keys:
bar_id: {
type: Sequelize.INTEGER,
references: {
// This is a reference to another model
model: Bar,
// This is the column name of the referenced model
key: 'id',
// This declares when to check the foreign key constraint. PostgreSQL only.
deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
}
}
}) })
``` ```
...@@ -134,6 +150,25 @@ sequelize.define('model', { ...@@ -134,6 +150,25 @@ sequelize.define('model', {
}) })
``` ```
## Deferrable
When you specify a foreign key column it is optionally possible to declare the deferrable
type in PostgreSQL. The following options are available:
```js
// Defer all foreign key constraint check to the end of a transaction
Sequelize.Deferrable.INITIALLY_DEFERRED
// Immediately check the foreign key constraints
Sequelize.Deferrable.INITIALLY_IMMEDIATE
// Don't defer the checks at all
Sequelize.Deferrable.NOT
```
The last option is the default in PostgreSQL and won't allow you to dynamically change
the rule in a transaction. See [the transaction section](docs/transactions/#options) for further information.
## Getters & setters ## Getters & setters
It is possible to define 'object-property' getters and setter functions on your models, these can be used both for 'protecting' properties that map to database fields and for defining 'pseudo' properties. It is possible to define 'object-property' getters and setter functions on your models, these can be used both for 'protecting' properties that map to database fields and for defining 'pseudo' properties.
......
...@@ -24,7 +24,7 @@ return sequelize.transaction(function (t) { ...@@ -24,7 +24,7 @@ return sequelize.transaction(function (t) {
}); });
}).then(function (result) { }).then(function (result) {
// Transaction has been committed // Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback // result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) { }).catch(function (err) {
// Transaction has been rolled back // Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback // err is whatever rejected the promise chain returned to the transaction callback
...@@ -101,7 +101,7 @@ sequelize.transaction(function (t1) { ...@@ -101,7 +101,7 @@ sequelize.transaction(function (t1) {
# Unmanaged transaction (then-callback) # Unmanaged transaction (then-callback)
Unmanaged transactions force you to manually rollback or commit the transaction. If you don't do that, the transaction will hang until it times out. To start an unmanaged transaction, call `sequelize.transaction()` without a callback (you can still pass an options object) and call `then` on the returned promise. Unmanaged transactions force you to manually rollback or commit the transaction. If you don't do that, the transaction will hang until it times out. To start an unmanaged transaction, call `sequelize.transaction()` without a callback (you can still pass an options object) and call `then` on the returned promise.
```js ```js
return sequelize.transaction().then(function (t) { return sequelize.transaction().then(function (t) {
return User.create({ return User.create({
firstName: 'Homer', firstName: 'Homer',
...@@ -110,7 +110,7 @@ return sequelize.transaction().then(function (t) { ...@@ -110,7 +110,7 @@ return sequelize.transaction().then(function (t) {
return user.addSibling({ return user.addSibling({
firstName: 'Lisa', firstName: 'Lisa',
lastName: 'Simpson' lastName: 'Simpson'
}, {transction: t}); }, {transaction: t});
}).then(function () { }).then(function () {
t.commit(); t.commit();
}).catch(function (err) { }).catch(function (err) {
...@@ -119,7 +119,57 @@ return sequelize.transaction().then(function (t) { ...@@ -119,7 +119,57 @@ return sequelize.transaction().then(function (t) {
}); });
``` ```
# Using transactions with other sequelize methods # Options
The `transaction` method can be called with an options object as the first argument, that
allows the configuration of the transaction.
```js
return sequelize.transaction({ /* options */ });
```
The following options (with it's default values) are available:
```js
{
autocommit: true,
isolationLevel: 'REPEATABLE_READ',
deferrable: 'NOT DEFERRABLE' // implicit default of postgres
}
```
The `isolationLevel` can either be set globally when initializing the Sequelize instance or
locally for every transaction:
```js
// globally
new Sequelize('db', 'user', 'pw', {
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});
// locally
sequelize.transaction({
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});
```
The `deferrable` option triggers an additional query after the transaction start
that optionally set the constraint checks to be deferred or immediate. Please note
that this is only supported in PostgreSQL.
```js
sequelize.transaction({
// to defer all constraints:
deferrable: Sequelize.Deferrable.SET_DEFERRED,
// to defer a specific constraint:
deferrable: Sequelize.Deferrable.SET_DEFERRED(['some_constraint']),
// to not defer constraints:
deferrable: Sequelize.Deferrable.SET_IMMEDIATE
})
```
# Usage with other sequelize methods
The `transaction` option goes with most other options, which are usually the first argument of a method. The `transaction` option goes with most other options, which are usually the first argument of a method.
For methods that take values, like `.create`, `.update()`, `.updateAttributes()` etc. `transaction` should be passed to the option in the second argument. For methods that take values, like `.create`, `.update()`, `.updateAttributes()` etc. `transaction` should be passed to the option in the second argument.
......
'use strict';
var util = require('util');
/**
* A collection of properties related to deferrable constraints. It can be used to
* make foreign key constraints deferrable and to set the constaints within a
* transaction. This is only supported in PostgreSQL.
*
* The foreign keys can be configured like this. It will create a foreign key
* that will check the constraints immediately when the data was inserted.
*
* ```js
* sequelize.define('Model', {
* foreign_id: {
* type: Sequelize.INTEGER,
* references: {
* model: OtherModel,
* key: 'id',
* deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
* }
* }
* });
* ```
*
* The constraints can be configured in a transaction like this. It will
* trigger a query once the transaction has been started and set the constraints
* to be checked at the very end of the transaction.
*
* ```js
* sequelize.transaction({
* deferrable: Sequelize.Deferrable.SET_DEFERRED
* });
* ```
*
* @return {object}
*/
var Deferrable = module.exports = {
INITIALLY_DEFERRED: INITIALLY_DEFERRED,
INITIALLY_IMMEDIATE: INITIALLY_IMMEDIATE,
NOT: NOT,
SET_DEFERRED: SET_DEFERRED,
SET_IMMEDIATE: SET_IMMEDIATE
};
function ABSTRACT () {}
ABSTRACT.prototype.toString = function () {
return this.toSql.apply(this, arguments);
};
/**
* A property that will defer constraints checks to the end of transactions.
*
* @property INITIALLY_DEFERRED
*/
function INITIALLY_DEFERRED () {
if (!(this instanceof INITIALLY_DEFERRED)) {
return new INITIALLY_DEFERRED();
}
}
util.inherits(INITIALLY_DEFERRED, ABSTRACT);
INITIALLY_DEFERRED.prototype.toSql = function () {
return 'DEFERRABLE INITIALLY DEFERRED';
};
/**
* A property that will trigger the constraint checks immediately
*
* @property INITIALLY_IMMEDIATE
*/
function INITIALLY_IMMEDIATE () {
if (!(this instanceof INITIALLY_IMMEDIATE)) {
return new INITIALLY_IMMEDIATE();
}
}
util.inherits(INITIALLY_IMMEDIATE, ABSTRACT);
INITIALLY_IMMEDIATE.prototype.toSql = function () {
return 'DEFERRABLE INITIALLY IMMEDIATE';
};
/**
* A property that will set the constraints to not deferred. This is
* the default in PostgreSQL and it make it impossible to dynamically
* defer the constraints within a transaction.
*
* @property NOT
*/
function NOT () {
if (!(this instanceof NOT)) {
return new NOT();
}
}
util.inherits(NOT, ABSTRACT);
NOT.prototype.toSql = function () {
return 'NOT DEFERRABLE';
};
/**
* A property that will trigger an additional query at the beginning of a
* transaction which sets the constraints to deferred.
*
* @param {Array} constraints An array of constraint names. Will defer all constraints by default.
* @property SET_DEFERRED
*/
function SET_DEFERRED (constraints) {
if (!(this instanceof SET_DEFERRED)) {
return new SET_DEFERRED(constraints);
}
this.constraints = constraints;
}
util.inherits(SET_DEFERRED, ABSTRACT);
SET_DEFERRED.prototype.toSql = function (queryGenerator) {
return queryGenerator.setDeferredQuery(this.constraints);
};
/**
* A property that will trigger an additional query at the beginning of a
* transaction which sets the constraints to immediately.
*
* @param {Array} constraints An array of constraint names. Will defer all constraints by default.
* @property SET_IMMEDIATE
*/
function SET_IMMEDIATE (constraints) {
if (!(this instanceof SET_IMMEDIATE)) {
return new SET_IMMEDIATE(constraints);
}
this.constraints = constraints;
}
util.inherits(SET_IMMEDIATE, ABSTRACT);
SET_IMMEDIATE.prototype.toSql = function (queryGenerator) {
return queryGenerator.setImmediateQuery(this.constraints);
};
Object.keys(Deferrable).forEach(function (key) {
var DeferrableType = Deferrable[key];
DeferrableType.toString = function () {
var instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
};
});
...@@ -48,6 +48,7 @@ AbstractDialect.prototype.supports = { ...@@ -48,6 +48,7 @@ AbstractDialect.prototype.supports = {
joinTableDependent: true, joinTableDependent: true,
indexViaAlter: false, indexViaAlter: false,
JSON: false, JSON: false,
deferrableConstraints: false
}; };
module.exports = AbstractDialect; module.exports = AbstractDialect;
...@@ -1476,6 +1476,19 @@ module.exports = (function() { ...@@ -1476,6 +1476,19 @@ module.exports = (function() {
}, },
/** /**
* Returns a query that defers the constraints. Only works for postgres.
*
* @param {Transaction} transaction
* @param {Object} options An object with options.
* @return {String} The generated sql query.
*/
deferConstraintsQuery: function () {},
setConstraintQuery: function () {},
setDeferredQuery: function () {},
setImmediateQuery: function () {},
/**
* Returns a query that commits a transaction. * Returns a query that commits a transaction.
* *
* @param {Object} options An object with options. * @param {Object} options An object with options.
......
...@@ -44,7 +44,8 @@ PostgresDialect.prototype.supports = _.merge(_.cloneDeep(Abstract.prototype.supp ...@@ -44,7 +44,8 @@ PostgresDialect.prototype.supports = _.merge(_.cloneDeep(Abstract.prototype.supp
NUMERIC: true, NUMERIC: true,
ARRAY: true, ARRAY: true,
JSON: true, JSON: true,
JSONB: true JSONB: true,
deferrableConstraints: true
}); });
PostgresDialect.prototype.Query = Query; PostgresDialect.prototype.Query = Query;
......
...@@ -529,11 +529,40 @@ module.exports = (function() { ...@@ -529,11 +529,40 @@ module.exports = (function() {
template += ' ON UPDATE <%= onUpdateAction %>'; template += ' ON UPDATE <%= onUpdateAction %>';
replacements.onUpdateAction = attribute.onUpdate.toUpperCase(); replacements.onUpdateAction = attribute.onUpdate.toUpperCase();
} }
if (attribute.references.deferrable) {
template += ' <%= deferrable %>';
replacements.deferrable = attribute.references.deferrable.toString(this);
}
} }
return Utils._.template(template)(replacements); return Utils._.template(template)(replacements);
}, },
deferConstraintsQuery: function (options) {
return options.deferrable.toString(this);
},
setConstraintQuery: function (columns, type) {
var columnFragment = 'ALL';
if (columns) {
columnFragment = columns.map(function (column) {
return this.quoteIdentifier(column);
}.bind(this)).join(', ');
}
return 'SET CONSTRAINTS ' + columnFragment + ' ' + type;
},
setDeferredQuery: function (columns) {
return this.setConstraintQuery(columns, 'DEFERRED');
},
setImmediateQuery: function (columns) {
return this.setConstraintQuery(columns, 'IMMEDIATE');
},
attributesToSQL: function(attributes, options) { attributesToSQL: function(attributes, options) {
var result = {} var result = {}
, key , key
......
...@@ -880,6 +880,21 @@ module.exports = (function() { ...@@ -880,6 +880,21 @@ module.exports = (function() {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
QueryInterface.prototype.deferConstraints = function (transaction, options) {
options = Utils._.extend({
transaction: transaction,
parent: options.transaction
}, options || {});
var sql = this.QueryGenerator.deferConstraintsQuery(options);
if (sql) {
return this.sequelize.query(sql, options);
}
return Promise.resolve();
};
QueryInterface.prototype.commitTransaction = function(transaction, options) { QueryInterface.prototype.commitTransaction = function(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!'); throw new Error('Unable to commit a transaction without transaction object!');
......
...@@ -5,6 +5,7 @@ var url = require('url') ...@@ -5,6 +5,7 @@ var url = require('url')
, Utils = require('./utils') , Utils = require('./utils')
, Model = require('./model') , Model = require('./model')
, DataTypes = require('./data-types') , DataTypes = require('./data-types')
, Deferrable = require('./deferrable')
, ModelManager = require('./model-manager') , ModelManager = require('./model-manager')
, QueryInterface = require('./query-interface') , QueryInterface = require('./query-interface')
, Transaction = require('./transaction') , Transaction = require('./transaction')
...@@ -263,6 +264,14 @@ module.exports = (function() { ...@@ -263,6 +264,14 @@ module.exports = (function() {
Sequelize.prototype.Transaction = Sequelize.Transaction = Transaction; Sequelize.prototype.Transaction = Sequelize.Transaction = Transaction;
/** /**
* A reference to the deferrable collection. Use this to access the different deferrable options.
* @property Deferrable
* @see {Deferrable}
* @see {Sequelize#transaction}
*/
Sequelize.prototype.Deferrable = Sequelize.Deferrable = Deferrable;
/**
* A reference to the sequelize instance class. * A reference to the sequelize instance class.
* @property Instance * @property Instance
* @see {Instance} * @see {Instance}
......
...@@ -7,6 +7,13 @@ var Utils = require('./utils'); ...@@ -7,6 +7,13 @@ var Utils = require('./utils');
* *
* To run a query under a transaction, you should pass the transaction in the options object. * To run a query under a transaction, you should pass the transaction in the options object.
* @class Transaction * @class Transaction
* @constructor
*
* @param {Sequelize} sequelize A configured sequelize Instance
* @param {Object} options An object with options
* @param {Boolean} options.autocommit=true Sets the autocommit property of the transaction.
* @param {String} options.isolationLevel=true Sets the isolation level of the transaction.
* @param {String} options.deferrable Sets the constraints to be deferred or immediately checked.
*/ */
var Transaction = module.exports = function(sequelize, options) { var Transaction = module.exports = function(sequelize, options) {
this.sequelize = sequelize; this.sequelize = sequelize;
...@@ -150,6 +157,8 @@ Transaction.prototype.prepareEnvironment = function() { ...@@ -150,6 +157,8 @@ Transaction.prototype.prepareEnvironment = function() {
}).then(function () { }).then(function () {
return self.begin(); return self.begin();
}).then(function () { }).then(function () {
return self.setDeferrable();
}).then(function () {
return self.setIsolationLevel(); return self.setIsolationLevel();
}).then(function () { }).then(function () {
return self.setAutocommit(); return self.setAutocommit();
...@@ -163,6 +172,15 @@ Transaction.prototype.begin = function() { ...@@ -163,6 +172,15 @@ Transaction.prototype.begin = function() {
.startTransaction(this, this.options); .startTransaction(this, this.options);
}; };
Transaction.prototype.setDeferrable = function () {
if (this.options.deferrable) {
return this
.sequelize
.getQueryInterface()
.deferConstraints(this, this.options);
}
};
Transaction.prototype.setAutocommit = function() { Transaction.prototype.setAutocommit = function() {
return this return this
.sequelize .sequelize
......
...@@ -406,8 +406,9 @@ var Utils = module.exports = { ...@@ -406,8 +406,9 @@ var Utils = module.exports = {
formatReferences: function (obj) { formatReferences: function (obj) {
if (!_.isPlainObject(obj.references)) { if (!_.isPlainObject(obj.references)) {
deprecate('Non-object references property found. Support for that will be removed in version 4. Expected { references: { model: "value", key: "key" } } instead of { references: "value", referencesKey: "key" }.'); deprecate('Non-object references property found. Support for that will be removed in version 4. Expected { references: { model: "value", key: "key" } } instead of { references: "value", referencesKey: "key" }.');
obj.references = { model: obj.references, key: obj.referencesKey }; obj.references = { model: obj.references, key: obj.referencesKey, deferrable: obj.referencesDeferrable };
obj.referencesKey = undefined; obj.referencesKey = undefined;
obj.referencesDeferrable = undefined;
} }
return obj; return obj;
......
...@@ -36,8 +36,8 @@ pages: ...@@ -36,8 +36,8 @@ pages:
- ['api/promise.md', 'API', 'Promise'] - ['api/promise.md', 'API', 'Promise']
- ['api/transaction.md', 'API', 'Transaction'] - ['api/transaction.md', 'API', 'Transaction']
- ['api/datatypes.md', 'API', 'Datatypes'] - ['api/datatypes.md', 'API', 'Datatypes']
- ['api/deferrable.md', 'API', 'Deferrable']
- ['api/errors.md', 'API', 'Errors'] - ['api/errors.md', 'API', 'Errors']
- ['changelog.md', 'Misc', 'Changelog'] - ['changelog.md', 'Misc', 'Changelog']
- ['imprint.md', 'Misc', 'Imprint'] - ['imprint.md', 'Misc', 'Imprint']
'use strict';
/* jshint -W030 */
/* jshint -W110 */
var _ = require('lodash')
, chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, Sequelize = require(__dirname + '/../../../index')
, config = require(__dirname + '/../../config/config')
;
if (!Support.sequelize.dialect.supports.deferrableConstraints) {
return;
}
describe(Support.getTestDialectTeaser('Sequelize'), function() {
beforeEach(function () {
this.run = function (deferrable, options) {
options = options || {};
var taskTableName = options.taskTableName || 'tasks_' + config.rand();
var transactionOptions = _.extend({ deferrable: Sequelize.Deferrable.SET_DEFERRED }, options);
var userTableName = 'users_' + config.rand();
var User = this.sequelize.define(
'User', { name: Sequelize.STRING }, { tableName: userTableName }
);
var Task = this.sequelize.define(
'Task', {
title: Sequelize.STRING,
user_id: {
allowNull: false,
type: Sequelize.INTEGER,
references: {
model: userTableName,
key: 'id',
deferrable: deferrable
}
}
}, {
tableName: taskTableName
}
);
return User.sync({ force: true }).bind(this).then(function () {
return Task.sync({ force: true });
}).then(function () {
return this.sequelize.transaction(transactionOptions, function (t) {
return Task
.create({ title: 'a task', user_id: -1 }, { transaction: t })
.then(function (task) {
return [task, User.create({}, { transaction: t })];
})
.spread(function (task, user) {
task.user_id = user.id;
return task.save({ transaction: t });
});
});
});
};
});
describe('Deferrable', function () {
describe('NOT', function () {
it('does not allow the violation of the foreign key constraint', function () {
return expect(this.run(Sequelize.Deferrable.NOT)).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
});
});
describe('INITIALLY_IMMEDIATE', function () {
it('allows the violation of the foreign key constraint if the transaction is deferred', function () {
return this
.run(Sequelize.Deferrable.INITIALLY_IMMEDIATE)
.then(function (task) {
expect(task.title).to.equal('a task');
expect(task.user_id).to.equal(1);
});
});
it('does not allow the violation of the foreign key constraint if the transaction is not deffered', function () {
return expect(this.run(Sequelize.Deferrable.INITIALLY_IMMEDIATE, {
deferrable: undefined
})).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
});
it('allows the violation of the foreign key constraint if the transaction deferres only the foreign key constraint', function () {
var taskTableName = 'tasks_' + config.rand();
return this
.run(Sequelize.Deferrable.INITIALLY_IMMEDIATE, {
deferrable: Sequelize.Deferrable.SET_DEFERRED([taskTableName + '_user_id_fkey']),
taskTableName: taskTableName
})
.then(function (task) {
expect(task.title).to.equal('a task');
expect(task.user_id).to.equal(1);
});
});
});
describe('INITIALLY_DEFERRED', function () {
it('allows the violation of the foreign key constraint', function () {
return this
.run(Sequelize.Deferrable.INITIALLY_DEFERRED)
.then(function (task) {
expect(task.title).to.equal('a task');
expect(task.user_id).to.equal(1);
});
});
});
});
});
...@@ -10,10 +10,11 @@ var chai = require('chai') ...@@ -10,10 +10,11 @@ var chai = require('chai')
describe(Support.getTestDialectTeaser('Utils'), function() { describe(Support.getTestDialectTeaser('Utils'), function() {
describe('formatReferences', function () { describe('formatReferences', function () {
([ ([
[{referencesKey: 1}, {references: {model: undefined, key: 1}, referencesKey: undefined}], [{referencesKey: 1}, {references: {model: undefined, key: 1, deferrable: undefined}, referencesKey: undefined, referencesDeferrable: undefined}],
[{references: 'a'}, {references: {model: 'a', key: undefined}, referencesKey: undefined}], [{references: 'a'}, {references: {model: 'a', key: undefined, deferrable: undefined}, referencesKey: undefined, referencesDeferrable: undefined}],
[{references: 'a', referencesKey: 1}, {references: {model: 'a', key: 1}, referencesKey: undefined}], [{references: 'a', referencesKey: 1}, {references: {model: 'a', key: 1, deferrable: undefined}, referencesKey: undefined, referencesDeferrable: undefined}],
[{references: {model: 1}}, {references: {model: 1}}] [{references: {model: 1}}, {references: {model: 1}}],
[{references: 1, referencesKey: 2, referencesDeferrable: 3}, {references: {model: 1, key: 2, deferrable: 3}, referencesKey: undefined, referencesDeferrable: undefined}]
]).forEach(function (test) { ]).forEach(function (test) {
var input = test[0]; var input = test[0];
var output = test[1]; var output = test[1];
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!