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

Commit 688dd002 by Jan Aagaard Meier Committed by GitHub

Change documentation to esdoc (#7490)

* docs: first esdoc steps

* remove: deprecated articles

* fix: a bit of indentation

* add: router with redirects for surge

* fix: small css fixes (hide docs links). fix docs command

* add domain to travis.yml

* chore(package): remove unused packages, add esdoc

* fix: lint

* fix: links in /docs + other small changes

* shields

* remove eslint comments. Add back UnknownConstraintError
1 parent c381625d
Showing with 1297 additions and 7074 deletions
dir: lib
packageJson: package.json
articles:
- Getting started: docs/articles/getting-started.md
branches:
- master
- doclets
{
"title": " Sequelize | The node.js ORM for PostgreSQL, MySQL, SQLite and MSSQL",
"source": "./lib",
"destination": "./esdoc",
"access": ["public"],
"builtinExternal": false,
"unexportIdentifier": true,
"undocumentIdentifier": false,
"includeSource": false,
"coverage": false,
"lint": false,
"plugins": [
{"name": "./docs/esdoc-sequelize.js"}
],
"styles": [
"./docs/style.css"
],
"scripts": [
"./docs/script.js"
],
"manual": {
"globalIndex": true,
"index": "./docs/index.md",
"asset": "./docs/images",
"badge": false,
"installation": [
"./docs/getting-started.md"
],
"tutorial": [
"./docs/models-definition.md",
"./docs/models-usage.md",
"./docs/querying.md",
"./docs/instances.md",
"./docs/associations.md",
"./docs/transactions.md",
"./docs/scopes.md",
"./docs/hooks.md",
"./docs/raw-queries.md",
"./docs/migrations.md"
],
"advanced": [
"./docs/legacy.md"
],
"faq": [
"./docs/whos-using.md",
"./docs/imprint.md"
]
}
}
......@@ -16,3 +16,4 @@ ssce.js
coverage
.vscode/
*.sublime*
esdoc
......@@ -39,4 +39,16 @@ before_script:
- "if [ $POSTGRES_VER ]; then docker run --link ${POSTGRES_VER}:db -e CHECK_PORT=5432 -e CHECK_HOST=db --net sequelize_default giorgos/takis; fi"
script:
- npm run lint
- "if [ $COVERAGE ]; then npm run cover && bash <(curl -s https://codecov.io/bash) -f coverage/lcov.info; else npm run test; fi"
deploy:
provider: surge
project: ./esdoc/
domain: docs.sequelizejs.com
skip_cleanup: true
on:
branch: master
before_deploy:
- npm run docs
......@@ -4,23 +4,14 @@ The sequelize documentation is written in a combination of markdown (articles an
All documentation is located in the `docs` folder.
The documentation is rendered using [mkdocs](http://mkdocs.org) and hosted at [Read the docs](http://sequelize.readthedocs.org). Mkdocs generates static HTML from markdown files. The files in `articles` and `docs` should be edited directly, and the files in `api` are generated from source code comments (more on that later).
The documentation is rendered using [esdoc](http://esdoc.org) and continously deployed to [Surge](http://surge.sh). esdoc generates static HTML from the code comments.
All pages in the documentation are defined in the `pages` section of `mkdocs.yml`. Each page is given as a separate line:
```yml
- ['index.md', 'Home', 'Welcome']
```
All pages in the documentation are defined in the `manual` section of `.esdoc.json`. Each page is given as a separate line:
The first array element is the path of the markdown file, relative to the `docs` dir. The second element is the section the page should be placed in, and the third is the name of the page.
To view the docs locally use `mkdocs serve`. This will start a local server at port 8000. The documentation is automatically regenerated when you edit an `.md` file. However, you'll have to restart the server if you add new pages in the configuration file.
To view the docs locally run `npm run docs` and open the generated HTML in your favorite browser.
## Articles and example based docs
Write markdown, and have fun :)
## API docs
The API documentation is generated from source code comments by a custom script, which outputs markdown into the `docs/api` folder. To regenerate the documentation, run:
```bash
$ npm run docs
```
By default all generation will be regenerated, but you can run the generation for a single file by specifying `--file`.
Change the source-code, and rerun `npm run docs` to see your changes.
......@@ -113,7 +113,7 @@ The generated documentation will be placed in `docs/tmp.md`.
Just commit and send your pull request. Happy hacking and thank you for contributing.
### Coding Guidelines ###
Have a look at our [.jshintrc](https://github.com/sequelize/sequelize/blob/master/.jshintrc) file for the specifics. As part of the test process, all files will be linted, and your PR will **not** be accepted if it does not pass linting.
Have a look at our [.eslintrc](https://github.com/sequelize/sequelize/blob/master/.eslintrc) file for the specifics. As part of the test process, all files will be linted, and your PR will **not** be accepted if it does not pass linting.
#### Spaces ####
......
......@@ -10,9 +10,9 @@
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, SQLite and Microsoft SQL Server. It features solid transaction support, relations, read replication and more.
[Stable (v3) documentation](http://docs.sequelizejs.com/en/v3/)
[Stable (v4) documentation](http://docs.sequelizejs.com)
[Master / unstable (v4-pre) documentation](http://docs.sequelizejs.com/en/latest/)
[v3 documentation](https://sequelize.readthedocs.io/en/v3/)
## Installation
......@@ -40,9 +40,9 @@ If you have any security issue to report, contact project maintainers privately.
## Resources
- [Changelog](https://github.com/sequelize/sequelize/blob/master/changelog.md)
- [Getting Started](http://docs.sequelizejs.com/en/latest/docs/getting-started/)
- [Getting Started](http://docs.sequelizejs.com/en/manual/installation/getting-started.html)
- [Express Example](https://github.com/sequelize/express-example)
- [Documentation](http://docs.sequelizejs.com/en/latest/)
- [Documentation](http://docs.sequelizejs.com)
- [Collaboration and pull requests](https://github.com/sequelize/sequelize/blob/master/CONTRIBUTING.md)
- [Roadmap](https://github.com/sequelize/sequelize/issues/2869)
- [Twitter](https://twitter.com/SequelizeJS): @SequelizeJS
......
301 /en/v3/ https://sequelize.readthedocs.io/en/v3/
301 /en/v3/:foo https://sequelize.readthedocs.io/en/v3/:foo
301 /en/v3/:foo/:bar https://sequelize.readthedocs.io/en/v3/:foo/:bar
301 /en/v3/:foo/:bar/:baz https://sequelize.readthedocs.io/en/v3/:foo/:bar/:baz
301 /en/v3/:foo/:bar/:baz/:quz https://sequelize.readthedocs.io/en/v3/:foo/:bar/:baz/:quz
301 /en/latest /
301 /en/latest/ /
301 /en/latest/docs/getting-started/ /manual/installation/getting-started.html
301 /en/latest/docs/:section/ /manual/tutorial/:section.html
301 /en/latest/api/sequelize/ /class/lib/sequelize.js~Sequelize.html
301 /en/latest/api/model/ /class/lib/model.js~Model.html
301 /en/latest/api/instance/ /class/lib/model.js~Model.html
301 /en/latest/api/associations/ /class/lib/associations/base.js~Association.html
301 /en/latest/api/associations/belongs-to/ /class/lib/associations/belongs-to.js~BelongsTo.html
301 /en/latest/api/associations/belongs-to-many/ /class/lib/associations/belongs-to-.many.js~BelongsToMany.html
301 /en/latest/api/associations/has-one/ /class/lib/associations/has-one.js~HasOne.html
301 /en/latest/api/associations/has-many/ /class/lib/associations/has-many.js~HasMany.html
301 /en/latest/api/transaction/ /class/lib/transaction.js~Transaction.html
301 /en/latest/api/datatypes/ /variable/index.html#static-variable-DataTypes
301 /en/latest/api/deferrable/ /variable/index.html#static-variable-Deferrable
301 /en/latest/api/errors/ /class/lib/errors/index.js~BaseError.html
<a name="belongstomany"></a>
# Mixin BelongsToMany
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L41)
Many-to-many association with a join table.
When the join table has additional attributes, these can be passed in the options object:
```js
UserProject = sequelize.define('user_project', {
role: Sequelize.STRING
});
User.belongsToMany(Project, { through: UserProject });
Project.belongsToMany(User, { through: UserProject });
// through is required!
user.addProject(project, { role: 'manager', transaction: t });
```
All methods allow you to pass either a persisted instance, its primary key, or a mixture:
```js
Project.create({ id: 11 }).then(function (project) {
user.addProjects([project, 12]);
});
```
In the API reference below, replace `Assocation(s)` with the actual name of your association, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
***
<a name="getassociations"></a>
## `getAssociations([options])` -> `Promise.<Array.<Instance>>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L209)
Get everything currently associated with this, using an optional where clause.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.where] | Object | An optional where clause to limit the associated models |
| [options.scope] | String &#124; Boolean | Apply a scope on the related model, or remove its default scope by passing false |
| [options.schema] | String | Apply a schema on the related model |
***
<a name="setassociations"></a>
## `setAssociations([newAssociations], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L219)
Set the associated models by passing an array of instances or their primary keys. Everything that it not in the passed array will be un-associated.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociations] | Array.&lt;Instance &#124; String &#124; Number&gt; | An array of instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations. |
| [options] | Object | Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`. Can also hold additional attributes for the join table |
| [options.validate] | Object | Run validation for the join model |
***
<a name="addassociations"></a>
## `addAssociations([newAssociations], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L229)
Associate several instances with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociations] | Array.&lt;Instance &#124; String &#124; Number&gt; | An array of instances or primary key of instances to associate with this. |
| [options] | Object | Options passed to `through.findAll`, `bulkCreate` and `update`. Can also hold additional attributes for the join table. |
| [options.validate] | Object | Run validation for the join model. |
***
<a name="addassociation"></a>
## `addAssociation([newAssociation], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L239)
Associate one instance with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociation] | Instance &#124; String &#124; Number | An instance or primary key of instance to associate with this. |
| [options] | Object | Options passed to `through.findAll`, `bulkCreate` and `update`. Can also hold additional attributes for the join table. |
| [options.validate] | Object | Run validation for the join model. |
***
<a name="createassociation"></a>
## `createAssociation([values], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L248)
Create a new instance of the associated model and associate it with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [values] | Object | |
| [options] | Object | Options passed to create and add. Can also hold additional attributes for the join table |
***
<a name="removeassociation"></a>
## `removeAssociation([oldAssociated], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L257)
Un-associate the instance.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [oldAssociated] | Instance &#124; String &#124; Number | Can be an Instance or its primary key |
| [options] | Object | Options passed to `through.destroy` |
***
<a name="removeassociations"></a>
## `removeAssociations([oldAssociated], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L266)
Un-associate several instances.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [oldAssociated] | Array.&lt;Instance &#124; String &#124; Number&gt; | Can be an array of instances or their primary keys |
| [options] | Object | Options passed to `through.destroy` |
***
<a name="hasassociation"></a>
## `hasAssociation([instance], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L275)
Check if an instance is associated with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [instance] | Instance &#124; String &#124; Number | Can be an Instance or its primary key |
| [options] | Object | Options passed to getAssociations |
***
<a name="hasassociations"></a>
## `hasAssociations([instances], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L284)
Check if all instances are associated with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [instances] | Array.&lt;Instance &#124; String &#124; Number&gt; | Can be an array of instances or their primary keys |
| [options] | Object | Options passed to getAssociations |
***
<a name="countassociations"></a>
## `countAssociations([options])` -> `Promise.<Int>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to-many.js#L294)
Count everything currently associated with this, using an optional where clause.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.where] | Object | An optional where clause to limit the associated models |
| [options.scope] | String &#124; Boolean | Apply a scope on the related model, or remove its default scope by passing false |
***
_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)_
<a name="belongsto"></a>
# Mixin BelongsTo
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to.js#L17)
One-to-one association
In the API reference below, replace `Assocation` with the actual name of your association, e.g. for `User.belongsTo(Project)` the getter will be `user.getProject()`.
***
<a name="getassociation"></a>
## `getAssociation([options])` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to.js#L83)
Get the associated instance.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.scope] | String &#124; Boolean | Apply a scope on the related model, or remove its default scope by passing false. |
| [options.schema] | String | Apply a schema on the related model |
***
<a name="setassociation"></a>
## `setAssociation([newAssociation], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to.js#L93)
Set the associated model.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociation] | Instance &#124; String &#124; Number | An instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association. |
| [options] | Object | Options passed to `this.save` |
| [options.save=true] | Boolean | Skip saving this after setting the foreign key if false. |
***
<a name="createassociation"></a>
## `createAssociation([values], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/belongs-to.js#L102)
Create a new instance of the associated model and associate it with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [values] | Object | |
| [options] | Object | Options passed to `target.create` and setAssociation. |
***
_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="hasmany"></a>
# Mixin HasMany
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L17)
One-to-many association
In the API reference below, replace `Association(s)` with the actual name of your association, e.g. for `User.hasMany(Project)` the getter will be `user.getProjects()`.
***
<a name="getassociations"></a>
## `getAssociations([options])` -> `Promise.<Array.<Instance>>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L104)
Get everything currently associated with this, using an optional where clause.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.where] | Object | An optional where clause to limit the associated models |
| [options.scope] | String &#124; Boolean | Apply a scope on the related model, or remove its default scope by passing false |
| [options.schema] | String | Apply a schema on the related model |
***
<a name="setassociations"></a>
## `setAssociations([newAssociations], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L114)
Set the associated models by passing an array of instances or their primary keys. Everything that is not in the passed array will be un-associated
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociations] | Array.&lt;Instance &#124; String &#124; Number&gt; | An array of instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations. |
| [options] | Object | Options passed to `target.findAll` and `update`. |
| [options.validate] | Object | Run validation for the join model |
***
<a name="addassociations"></a>
## `addAssociations([newAssociations], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L124)
Associate several instances with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociations] | Array.&lt;Instance &#124; String &#124; Number&gt; | An array of instances or primary key of instances to associate with this. |
| [options] | Object | Options passed to `target.update`. |
| [options.validate] | Object | Run validation for the join model. |
***
<a name="addassociation"></a>
## `addAssociation([newAssociation], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L134)
Associate one instance with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociation] | Instance &#124; String &#124; Number | An instance or primary key of instance to associate with this. |
| [options] | Object | Options passed to `target.update`. |
| [options.validate] | Object | Run validation for the join model. |
***
<a name="createassociation"></a>
## `createAssociation([values], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L143)
Create a new instance of the associated model and associate it with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [values] | Object | |
| [options] | Object | Options passed to `target.create`. |
***
<a name="removeassociation"></a>
## `removeAssociation([oldAssociated], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L152)
Un-associate the instance.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [oldAssociated] | Instance &#124; String &#124; Number | Can be an Instance or its primary key |
| [options] | Object | Options passed to `target.update` |
***
<a name="removeassociations"></a>
## `removeAssociations([oldAssociatedArray], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L161)
Un-associate several instances.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [oldAssociatedArray] | Array.&lt;Instance &#124; String &#124; Number&gt; | Can be an array of instances or their primary keys |
| [options] | Object | Options passed to `through.destroy` |
***
<a name="hasassociation"></a>
## `hasAssociation([instance], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L170)
Check if an instance is associated with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [instance] | Instance &#124; String &#124; Number | Can be an Instance or its primary key |
| [options] | Object | Options passed to getAssociations |
***
<a name="hasassociations"></a>
## `hasAssociations([instances], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L179)
Check if all instances are associated with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [instances] | Array.&lt;Instance &#124; String &#124; Number&gt; | Can be an array of instances or their primary keys |
| [options] | Object | Options passed to getAssociations |
***
<a name="countassociations"></a>
## `countAssociations([options])` -> `Promise.<Int>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-many.js#L189)
Count everything currently associated with this, using an optional where clause.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.where] | Object | An optional where clause to limit the associated models |
| [options.scope] | String &#124; Boolean | Apply a scope on the related model, or remove its default scope by passing false |
***
_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="hasone"></a>
# Mixin HasOne
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-one.js#L17)
One-to-one association
In the API reference below, replace `Association` with the actual name of your association, e.g. for `User.hasOne(Project)` the getter will be `user.getProject()`.
This is almost the same as `belongsTo` with one exception. The foreign key will be defined on the target model.
***
<a name="getassociation"></a>
## `getAssociation([options])` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-one.js#L78)
Get the associated instance.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.scope] | String &#124; Boolean | Apply a scope on the related model, or remove its default scope by passing false |
| [options.schema] | String | Apply a schema on the related model |
***
<a name="setassociation"></a>
## `setAssociation([newAssociation], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-one.js#L87)
Set the associated model.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [newAssociation] | Instance &#124; String &#124; Number | An instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association. |
| [options] | Object | Options passed to getAssociation and `target.save` |
***
<a name="createassociation"></a>
## `createAssociation([values], [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/has-one.js#L96)
Create a new instance of the associated model and associate it with this.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [values] | Object | |
| [options] | Object | Options passed to `target.create` and setAssociation. |
***
_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="associations"></a>
# Mixin Associations
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/mixin.js#L89)
Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).
* hasOne - adds a foreign key to the target and singular association mixins to the source.
* belongsTo - add a foreign key and singular association mixins to the source.
* hasMany - adds a foreign key to target and plural association mixins to the source.
* belongsToMany - creates an N:M association with a join table and adds plural association mixins to the source. The junction table is created with sourceId and targetId.
Creating an association will add a foreign key constraint to the attributes. All associations use `CASCADE` on update and `SET NULL` on delete, except for n:m, which also uses `CASCADE` on delete.
When creating associations, you can provide an alias, via the `as` option. This is useful if the same model is associated twice, or you want your association to be called something other than the name of the target model.
As an example, consider the case where users have many pictures, one of which is their profile picture. All pictures have a `userId`, but in addition the user model also has a `profilePictureId`, to be able to easily load the user's profile picture.
```js
User.hasMany(Picture)
User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false })
user.getPictures() // gets you all pictures
user.getProfilePicture() // gets you only the profile picture
User.findAll({
where: ...,
include: [
{ model: Picture }, // load all pictures
{ model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be the exact same as the one in the association
]
})
```
To get full control over the foreign key column added by sequelize, you can use the `foreignKey` option. It can either be a string, that specifies the name, or and object type definition,
equivalent to those passed to `sequelize.define`.
```js
User.hasMany(Picture, { foreignKey: 'uid' })
```
The foreign key column in Picture will now be called `uid` instead of the default `userId`.
```js
User.hasMany(Picture, {
foreignKey: {
name: 'uid',
allowNull: false
}
})
```
This specifies that the `uid` column cannot be null. In most cases this will already be covered by the foreign key constraints, which sequelize creates automatically, but can be useful in case where the foreign keys are disabled, e.g. due to circular references (see `constraints: false` below).
When fetching associated models, you can limit your query to only load some models. These queries are written in the same way as queries to `find`/`findAll`. To only get pictures in JPG, you can do:
```js
user.getPictures({
where: {
format: 'jpg'
}
})
```
There are several ways to update and add new associations. Continuing with our example of users and pictures:
```js
user.addPicture(p) // Add a single picture
user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be deleted
user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current associations
```
You don't have to pass in a complete object to the association functions, if your associated model has a single primary key:
```js
user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture
```
In the example above we have specified that a user belongs to his profile picture. Conceptually, this might not make sense, but since we want to add the foreign key to the user model this is the way to do it.
Note how we also specified `constraints: false` for profile picture. This is because we add a foreign key from user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys to both, it would create a cyclic dependency, and sequelize would not know which table to create first, since user depends on picture, and picture depends on user. These kinds of problems are detected by sequelize before the models are synced to the database, and you will get an error along the lines of `Error: Cyclic dependency found. 'users' is dependent of itself`. If you encounter this, you should either disable some constraints, or rethink your associations completely.
***
<a name="hasone"></a>
## `hasOne(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/mixin.js#L131)
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.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| target | Model | |
| [options] | object | |
| [options.hooks=false] | boolean | Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks |
| [options.as] | string | The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target |
| [options.foreignKey] | string &#124; object | The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source |
| [options.onDelete='SET&nbsp;NULL &#124; CASCADE'] | string | SET NULL if foreignKey allows nulls, CASCADE if otherwise |
| [options.onUpdate='CASCADE'] | string | |
| [options.constraints=true] | boolean | Should on update and on delete constraints be enabled on the foreign key. |
***
<a name="belongsto"></a>
## `belongsTo(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/mixin.js#L149)
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.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| target | Model | |
| [options] | object | |
| [options.hooks=false] | boolean | Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks |
| [options.as] | string | The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target |
| [options.foreignKey] | string &#124; object | The name of the foreign key in the source table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target |
| [options.targetKey] | string | The name of the field to use as the key for the association in the target table. Defaults to the primary key of the target table |
| [options.onDelete='SET&nbsp;NULL &#124; NO&nbsp;ACTION'] | string | SET NULL if foreignKey allows nulls, NO ACTION if otherwise |
| [options.onUpdate='CASCADE'] | string | |
| [options.constraints=true] | boolean | Should on update and on delete constraints be enabled on the foreign key. |
***
<a name="hasmany"></a>
## `hasMany(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/mixin.js#L166)
Creates a 1:m association between this (the source) and the provided target. The foreign key is added on the target.
Example: `User.hasMany(Profile)`. This will add userId to the profile table.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| target | Model | |
| [options] | object | |
| [options.hooks=false] | boolean | Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks |
| [options.as] | string &#124; object | The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target |
| [options.foreignKey] | string &#124; object | The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source |
| [options.scope] | object | A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M) |
| [options.onDelete='SET&nbsp;NULL &#124; CASCADE'] | string | SET NULL if foreignKey allows nulls, CASCADE if otherwise |
| [options.onUpdate='CASCADE'] | string | |
| [options.constraints=true] | boolean | Should on update and on delete constraints be enabled on the foreign key. |
***
<a name="belongstomany"></a>
## `belongsToMany(target, [options])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/associations/mixin.js#L245)
Create an N:M association with a join table.
```js
User.belongsToMany(Project, { through: 'UserProjects' })
Project.belongsToMany(User, { through: 'UserProjects' })
```
Defining `through` is required. Sequelize would previously attempt to auto generate names but that would not always lead to the most logical setups.
If you define a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before with a join table that stores whether the project has been started yet:
```js
var UserProjects = sequelize.define('UserProjects', {
started: Sequelize.BOOLEAN
})
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
```
```js
jan.addProject(homework, { started: false }) // The homework project is not started yet
jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started
```
If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
```js
p1.UserProjects = {
started: true
}
user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
```
Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
```js
user.getProjects().then(function (projects) {
var p1 = projects[0]
p1.UserProjects.started // Is this project started yet?
})
```
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| target | Model | |
| [options] | object | |
| [options.hooks=false] | boolean | Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks |
| [options.through] | Model &#124; string &#124; object | The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it. |
| [options.through.model] | Model | The model used to join both sides of the N:M association. |
| [options.through.scope] | object | A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model) |
| [options.through.unique=true] | boolean | If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes) |
| [options.as] | string &#124; object | The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target |
| [options.foreignKey] | string &#124; object | The name of the foreign key in the join table (representing the source model) or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source |
| [options.otherKey] | string &#124; object | The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target |
| [options.scope] | object | A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M) |
| [options.timestamps=sequelize.options.timestamps] | boolean | Should the join model have timestamps |
| [options.onDelete='SET&nbsp;NULL &#124; CASCADE'] | string | Cascade if this is a n:m, and set null if it is a 1:m |
| [options.onUpdate='CASCADE'] | string | |
| [options.constraints=true] | boolean | Should on update and on delete constraints be enabled on the foreign key. |
***
_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="datatypes"></a>
# Class DataTypes
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L57)
A convenience class holding commonly used data types. The datatypes are used when defining a new model using `Sequelize.define`, like this:
```js
sequelize.define('model', {
column: DataTypes.INTEGER
})
```
When defining a model you can just as easily pass a string as type, but often using the types defined here is beneficial. For example, using `DataTypes.BLOB`, mean
that that column will be returned as an instance of `Buffer` when being fetched by sequelize.
Some data types have special properties that can be accessed in order to change the data type.
For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`.
The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as well. The available properties are listed under each data type.
To provide a length for the data type, you can invoke it like a function: `INTEGER(2)`
Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not be used to define types. Instead they are used as shorthands for
defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:
```js
sequelize.define('model', {
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV1,
primaryKey: true
}
})
```
There may be times when you want to generate your own UUID conforming to some other algorithm. This is accomplised
using the defaultValue property as well, but instead of specifying one of the supplied UUID types, you return a value
from a function.
```js
sequelize.define('model', {
uuid: {
type: DataTypes.UUID,
defaultValue: function() {
return generateMyId()
},
primaryKey: true
}
})
```
***
<a name="string"></a>
## `STRING()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L109)
A variable length string. Default length 255
Available properties: `BINARY`
***
<a name="char"></a>
## `CHAR()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L151)
A fixed length string. Default length 255
Available properties: `BINARY`
***
<a name="text"></a>
## `TEXT()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L170)
An (un)limited length text column. Available lengths: `tiny`, `medium`, `long`
***
<a name="integer"></a>
## `INTEGER()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L258)
A 32 bit integer.
Available properties: `UNSIGNED`, `ZEROFILL`
***
<a name="bigint"></a>
## `BIGINT()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L283)
A 64 bit integer.
Note: an attribute defined as `BIGINT` will be treated like a `string` due this [feature from node-postgres](https://github.com/brianc/node-postgres/pull/353) to prevent precision loss. To have this attribute as a `number`, this is a possible [workaround](https://github.com/sequelize/sequelize/issues/2383#issuecomment-58006083).
Available properties: `UNSIGNED`, `ZEROFILL`
***
<a name="float"></a>
## `FLOAT()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L307)
Floating point number (4-byte precision). Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL`
***
<a name="real"></a>
## `REAL()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L332)
Floating point number (4-byte precision). Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL`
***
<a name="double"></a>
## `DOUBLE()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L350)
Floating point number (8-byte precision). Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL`
***
<a name="decimal"></a>
## `DECIMAL()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L368)
Decimal number. Accepts one or two arguments for precision
Available properties: `UNSIGNED`, `ZEROFILL`
***
<a name="boolean"></a>
## `BOOLEAN()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L397)
A boolean / tinyint column, depending on dialect
***
<a name="time"></a>
## `TIME()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L416)
A time column
***
<a name="date"></a>
## `DATE()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L427)
A datetime column
***
<a name="dateonly"></a>
## `DATEONLY()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L476)
A date only column
***
<a name="hstore"></a>
## `HSTORE()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L492)
A key / value column. Only available in postgres.
***
<a name="json"></a>
## `JSON()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L507)
A JSON string column. Only available in postgres.
***
<a name="jsonb"></a>
## `JSONB()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L526)
A pre-processed JSON data column. Only available in postgres.
***
<a name="now"></a>
## `NOW()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L538)
A default value of the current timestamp
***
<a name="blob"></a>
## `BLOB()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L548)
Binary storage. Available lengths: `tiny`, `medium`, `long`
***
<a name="range"></a>
## `RANGE()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L603)
Range types are data types representing a range of values of some element type (called the range's subtype).
Only available in postgres.
See {@link http://www.postgresql.org/docs/9.4/static/rangetypes.html|Postgres documentation} for more details
***
<a name="uuid"></a>
## `UUID()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L653)
A column storing a unique universal identifier. Use with `UUIDV1` or `UUIDV4` for default values.
***
<a name="uuidv1"></a>
## `UUIDV1()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L669)
A default unique universal identifier generated following the UUID v1 standard
***
<a name="uuidv4"></a>
## `UUIDV4()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L689)
A default unique universal identifier generated following the UUID v4 standard
***
<a name="virtual"></a>
## `VIRTUAL()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L746)
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:
```js
sequelize.define('user', {
password_hash: DataTypes.STRING,
password: {
type: DataTypes.VIRTUAL,
set: function (val) {
this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
this.setDataValue('password_hash', this.salt + val);
},
validate: {
isLongEnough: function (val) {
if (val.length < 7) {
throw new Error("Please choose a longer password")
}
}
}
}
})
```
In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
VIRTUAL also takes a return type and dependency fields as arguments
If a virtual attribute is present in `attributes` it will automatically pull in the extra fields as well.
Return type is mostly useful for setups that rely on types like GraphQL.
```js
{
active: {
type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
get: function() {
return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
}
}
}
```
__Aliases:__ NONE
***
<a name="enum"></a>
## `ENUM()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L762)
An enumeration. `DataTypes.ENUM('value', 'another value')`.
***
<a name="array"></a>
## `ARRAY()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L786)
An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in postgres.
***
<a name="geometry"></a>
## `GEOMETRY()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L869)
A column storing Geometry information.
Only available in PostgreSQL (with PostGIS) or MySQL.
In MySQL, allowable Geometry types are 'POINT', 'LINESTRING', 'POLYGON'.
When using, GeoJSON is accepted as input and returned as output.
In PostGIS, the GeoJSON is parsed using the PostGIS function `ST_GeomFromGeoJSON`.
In MySQL it is parsed using the function `GeomFromText`.
Therefore, one can just follow the [GeoJSON spec](http://geojson.org/geojson-spec.html) for handling geometry objects. See the following examples:
```js
// Create a new point:
var point = { type: 'Point', coordinates: [39.807222,-76.984722]};
User.create({username: 'username', geometry: point }).then(function(newUser) {
...
});
// Create a new linestring:
var line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] };
User.create({username: 'username', geometry: line }).then(function(newUser) {
...
});
// Create a new polygon:
var polygon = { type: 'Polygon', coordinates: [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
]};
User.create({username: 'username', geometry: polygon }).then(function(newUser) {
...
});
// Create a new point with a custom SRID:
var point = {
type: 'Point',
coordinates: [39.807222,-76.984722],
crs: { type: 'name', properties: { name: 'EPSG:4326'} }
};
User.create({username: 'username', geometry: point }).then(function(newUser) {
...
});
```
***
<a name="geography"></a>
## `GEOGRAPHY()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L894)
A geography datatype represents two dimensional spacial objects in an elliptic coord system.
***
_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)_
<a name="deferrable"></a>
## `Deferrable()` -> `object`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/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 constraints 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/3e5b8772ef75169685fc96024366bca9958fee63/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/3e5b8772ef75169685fc96024366bca9958fee63/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/3e5b8772ef75169685fc96024366bca9958fee63/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/3e5b8772ef75169685fc96024366bca9958fee63/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/3e5b8772ef75169685fc96024366bca9958fee63/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>
# Class Errors
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/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.
All sequelize errors inherit from the base JS error object.
***
<a name="baseerror"></a>
## `new BaseError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L20)
The Base Error all Sequelize Errors inherit from.
__Aliases:__ Error
***
<a name="validationerror"></a>
## `new ValidationError(message, [errors])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L41)
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.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| message | string | Error message |
| [errors] | Array | Array of ValidationErrorItem objects describing the validation errors |
__Extends:__ BaseError
***
<a name="errors"></a>
## `errors`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L49)
An array of ValidationErrorItems
***
<a name="get"></a>
## `get(path)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L70)
Gets all validation error items for the path / field specified.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| path | string | The path to be checked for error items |
***
<a name="databaseerror"></a>
## `new DatabaseError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L84)
A base class for all database related errors.
__Extends:__ BaseError
***
<a name="parent"></a>
## `parent`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L92)
The database specific error which triggered this one
***
<a name="sql"></a>
## `sql`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L98)
The SQL that triggered the error
***
<a name="message"></a>
## `message()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L104)
The message from the DB.
***
<a name="fields"></a>
## `fields()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L109)
The fields of the unique constraint
***
<a name="value"></a>
## `value()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L114)
The value(s) which triggered the error
***
<a name="index"></a>
## `index()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L119)
The name of the index that triggered the error
***
<a name="timeouterror"></a>
## `new TimeoutError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L127)
Thrown when a database query times out because of a deadlock
__Extends:__ DatabaseError
***
<a name="uniqueconstrainterror"></a>
## `new UniqueConstraintError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L138)
Thrown when a unique constraint is violated in the database
__Extends:__ DatabaseError
***
<a name="foreignkeyconstrainterror"></a>
## `new ForeignKeyConstraintError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L157)
Thrown when a foreign key constraint is violated in the database
__Extends:__ DatabaseError
***
<a name="exclusionconstrainterror"></a>
## `new ExclusionConstraintError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L177)
Thrown when an exclusion constraint is violated in the database
__Extends:__ DatabaseError
***
<a name="validationerroritem"></a>
## `new ValidationErrorItem(message, type, path, value)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L201)
Validation Error Item
Instances of this class are included in the `ValidationError.errors` property.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| message | string | An error message |
| type | string | The type of the validation error |
| path | string | The field that triggered the validation error |
| value | string | The value that generated the error |
***
<a name="connectionerror"></a>
## `new ConnectionError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L213)
A base class for all connection related errors.
__Extends:__ BaseError
***
<a name="parent"></a>
## `parent`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L220)
The connection specific error which triggered this one
***
<a name="connectionrefusederror"></a>
## `new ConnectionRefusedError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L230)
Thrown when a connection to a database is refused
__Extends:__ ConnectionError
***
<a name="accessdeniederror"></a>
## `new AccessDeniedError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L241)
Thrown when a connection to a database is refused due to insufficient privileges
__Extends:__ ConnectionError
***
<a name="hostnotfounderror"></a>
## `new HostNotFoundError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L252)
Thrown when a connection to a database has a hostname that was not found
__Extends:__ ConnectionError
***
<a name="hostnotreachableerror"></a>
## `new HostNotReachableError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L263)
Thrown when a connection to a database has a hostname that was not reachable
__Extends:__ ConnectionError
***
<a name="invalidconnectionerror"></a>
## `new InvalidConnectionError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L274)
Thrown when a connection to a database has invalid values for any of the connection parameters
__Extends:__ ConnectionError
***
<a name="connectiontimedouterror"></a>
## `new ConnectionTimedOutError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L285)
Thrown when a connection to a database times out
__Extends:__ ConnectionError
***
<a name="instanceerror"></a>
## `new InstanceError()`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/errors.js#L296)
Thrown when a some problem occurred with Instance methods (see message for details)
__Extends:__ BaseError
***
_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="hooks"></a>
# Mixin Hooks
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/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:
1. By specifying them as options in `sequelize.define`
2. By calling `hook()` with a string and your hook handler function
3. By calling the function with the same name as the hook you want
```js
// Method 1
sequelize.define(name, { attributes }, {
hooks: {
beforeBulkCreate: function () {
// can be a single function
},
beforeValidate: [
function () {},
function() {} // Or an array of several
]
}
})
// Method 2
Model.hook('afterDestroy', function () {})
// Method 3
Model.afterBulkUpdate(function () {})
```
**See:**
* [Sequelize#define](sequelize#define)
***
<a name="addhook"></a>
## `addHook(hooktype, [name], fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L160)
Add a hook to the model
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| hooktype | String | |
| [name] | String | Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future. |
| fn | Function | The hook function |
__Aliases:__ hook
***
<a name="removehook"></a>
## `removeHook(hookType, name)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L179)
Remove hook from the model
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| hookType | String | |
| name | String | |
***
<a name="hashook"></a>
## `hasHook(hookType)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L205)
Check whether the mode has any hooks of this type
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| hookType | String | |
__Aliases:__ hasHooks
***
<a name="beforevalidate"></a>
## `beforeValidate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L218)
A hook that is run before validation
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
***
<a name="aftervalidate"></a>
## `afterValidate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L225)
A hook that is run after validation
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
***
<a name="beforecreate"></a>
## `beforeCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L232)
A hook that is run before creating a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with attributes, options |
***
<a name="aftercreate"></a>
## `afterCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L239)
A hook that is run after creating a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with attributes, options |
***
<a name="beforedestroy"></a>
## `beforeDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L248)
A hook that is run before destroying a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
__Aliases:__ beforeDelete
***
<a name="afterdestroy"></a>
## `afterDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L257)
A hook that is run after destroying a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
__Aliases:__ afterDelete
***
<a name="beforerestore"></a>
## `beforeRestore(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L265)
A hook that is run before restoring a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
***
<a name="afterrestore"></a>
## `afterRestore(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L273)
A hook that is run after restoring a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
***
<a name="beforeupdate"></a>
## `beforeUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L280)
A hook that is run before updating a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
***
<a name="afterupdate"></a>
## `afterUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L287)
A hook that is run after updating a single instance
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance, options |
***
<a name="beforebulkcreate"></a>
## `beforeBulkCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L294)
A hook that is run before creating instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instances, options |
***
<a name="afterbulkcreate"></a>
## `afterBulkCreate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L301)
A hook that is run after creating instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instances, options |
***
<a name="beforebulkdestroy"></a>
## `beforeBulkDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L310)
A hook that is run before destroying instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
__Aliases:__ beforeBulkDelete
***
<a name="afterbulkdestroy"></a>
## `afterBulkDestroy(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L319)
A hook that is run after destroying instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
__Aliases:__ afterBulkDelete
***
<a name="beforebulkrestore"></a>
## `beforeBulkRestore(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L327)
A hook that is run before restoring instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
***
<a name="afterbulkrestore"></a>
## `afterBulkRestore(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L335)
A hook that is run after restoring instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
***
<a name="beforebulkupdate"></a>
## `beforeBulkUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L342)
A hook that is run before updating instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
***
<a name="afterbulkupdate"></a>
## `afterBulkUpdate(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L349)
A hook that is run after updating instances in bulk
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
***
<a name="beforefind"></a>
## `beforeFind(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L356)
A hook that is run before a find (select) query
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
***
<a name="beforefindafterexpandincludeall"></a>
## `beforeFindAfterExpandIncludeAll(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L363)
A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
***
<a name="beforefindafteroptions"></a>
## `beforeFindAfterOptions(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L370)
A hook that is run before a find (select) query, after all option parsing is complete
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options |
***
<a name="afterfind"></a>
## `afterFind(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L377)
A hook that is run after a find (select) query
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with instance(s), options |
***
<a name="beforedefine"></a>
## `beforeDefine(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L384)
A hook that is run before a define call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with attributes, options |
***
<a name="afterdefine"></a>
## `afterDefine(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L391)
A hook that is run after a define call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with factory |
***
<a name="beforeinit"></a>
## `beforeInit(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L398)
A hook that is run before Sequelize() call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with config, options |
***
<a name="afterinit"></a>
## `afterInit(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L405)
A hook that is run after Sequelize() call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with sequelize |
***
<a name="beforesync"></a>
## `beforeSync(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L412)
A hook that is run before Model.sync call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options passed to Model.sync |
***
<a name="aftersync"></a>
## `afterSync(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L419)
A hook that is run after Model.sync call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options passed to Model.sync |
***
<a name="beforebulksync"></a>
## `beforeBulkSync(name, fn)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L426)
A hook that is run before sequelize.sync call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options passed to sequelize.sync |
***
<a name="afterbulksync"></a>
## `afterBulkSync`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/hooks.js#L434)
A hook that is run after sequelize.sync call
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | |
| fn | Function | A callback function that is called with options passed to sequelize.sync |
***
_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="instance"></a>
# Class Instance
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L85)
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.
Instance instances operate with the concept of a `dataValues` property, which stores the actual values represented by the instance.
By default, the values from dataValues can also be accessed directly from the Instance, that is:
```js
instance.field
// is the same as
instance.get('field')
// is the same as
instance.getDataValue('field')
```
However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the value from `dataValues`.
Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters.
**See:**
* [Sequelize#define](sequelize#define)
***
<a name="isnewrecord"></a>
## `isNewRecord` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L98)
Returns true if this instance has not yet been persisted to the database
***
<a name="model"></a>
## `Model()` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L107)
Returns the Model the instance was created from.
**See:**
* [Model](model)
***
<a name="sequelize"></a>
## `sequelize()` -> `Sequelize`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L116)
A reference to the sequelize instance
**See:**
* [Sequelize](sequelize)
***
<a name="where"></a>
## `where()` -> `Object`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L126)
Get an object representing the query for this instance, use with `options.where`
***
<a name="getdatavalue"></a>
## `getDataValue(key)` -> `any`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L150)
Get the value of the underlying data value
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| key | String | |
***
<a name="setdatavalue"></a>
## `setDataValue(key, value)`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L160)
Update the underlying data value
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| key | String | |
| value | any | |
***
<a name="get"></a>
## `get([key], [options])` -> `Object|any`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L179)
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.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [key] | String | |
| [options] | Object | |
| [options.plain=false] | Boolean | If set to true, included instances will be returned as plain objects |
***
<a name="set"></a>
## `set(key, value, [options])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L249)
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
will be called instead. To bypass the setter, you can pass `raw: true` in the options object.
If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be
set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
Set can also be used to build instances for associations, if you have values for those.
When using set with associations you need to make sure the property key matches the alias of the association
while also making sure that the proper include options have been set (from .build() or .find())
If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
**See:**
* [Model#find](model#find)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| key | String &#124; Object | |
| value | any | |
| [options] | Object | |
| [options.raw=false] | Boolean | If set to true, field and virtual setters will be ignored |
| [options.reset=false] | Boolean | Clear all previously set data values |
__Aliases:__ setAttributes
***
<a name="changed"></a>
## `changed([key])` -> `Boolean|Array`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L401)
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 and no keys have changed, it will return `false`.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [key] | String | |
***
<a name="previous"></a>
## `previous([key])` -> `any|Array.<any>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L425)
Returns the previous value for key from `_previousDataValues`.
If called without a key, returns the previous values for all values which have changed
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [key] | String | |
***
<a name="save"></a>
## `save([options])` -> `Promise.<this|Errors.ValidationError>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L493)
Validate this instance, and if the validation passes, persist it to the database. It will only save changed fields, and do nothing if no fields have changed.
On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`.
This error will have a property for each of the fields for which validation failed, with the error message for that field.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.fields] | Array.&lt;string&gt; | 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.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.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.returning] | Boolean | Append RETURNING * to get back auto generated values (Postgres only) |
***
<a name="reload"></a>
## `reload([options])` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L740)
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,
all references to the Instance are updated with the new data and no new objects are created.
**See:**
* [Model#find](model#find)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [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>
## `validate([options])` -> `Promise.<Errors.ValidationError|undefined>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L776)
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.
**See:**
* [InstanceValidator](instancevalidator)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | Options that are passed to the validator |
| [options.skip] | Array | An array of strings. All properties that are in this array will not be validated |
***
<a name="update"></a>
## `update(updates, options)` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L796)
This is the same as calling `set` and then calling `save` but it only saves the
exact values passed to it, making it more atomic and safer.
**See:**
* [Instance#set](instance#set)
* [Instance#save](instance#save)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| updates | Object | See `set` |
| options | Object | See `save` |
__Aliases:__ updateAttributes
***
<a name="destroy"></a>
## `destroy([options={}])` -> `Promise.<undefined>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L835)
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.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options={}] | Object | |
| [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.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.silent=false] | Boolean | If true, the updatedAt timestamp will not be updated. |
***
<a name="restore"></a>
## `restore([options={}])` -> `Promise.<undefined>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L882)
Restore the row corresponding to this instance. Only available for paranoid models.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options={}] | Object | |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.transaction] | Transaction | |
***
<a name="increment"></a>
## `increment(fields, [options])` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L934)
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
SET column = column + X
```
query. To get the correct value after an increment into the Instance you should do a reload.
```js
instance.increment('number') // increment number by 1
instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
// `by` is ignored, since each column has its own value
```
**See:**
* [Instance#reload](instance#reload)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| 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.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.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
***
<a name="decrement"></a>
## `decrement(fields, [options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L997)
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
SET column = column - X
```
query. To get the correct value after an decrement into the Instance you should do a reload.
```js
instance.decrement('number') // decrement number by 1
instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
// `by` is ignored, since each column has its own value
```
**See:**
* [Instance#reload](instance#reload)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| 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.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.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
***
<a name="equals"></a>
## `equals(other)` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L1019)
Check whether all values of this and `other` Instance are the same
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| other | Instance | |
***
<a name="equalsoneof"></a>
## `equalsOneOf(others)` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L1043)
Check if this is equal to one of `others` by calling equals
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| others | Array | |
***
<a name="tojson"></a>
## `toJSON()` -> `object`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L1061)
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.
**See:**
* [Instance#get](instance#get)
***
_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)_
<a name="model"></a>
# Class Model
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L26)
A Model represents a table in the database. Sometimes you might also see it referred 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`
### Mixes:
* Hooks
* Associations
***
<a name="removeattribute"></a>
## `removeAttribute([attribute])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L964)
Remove attribute from model definition
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [attribute] | String | |
***
<a name="sync"></a>
## `sync()` -> `Promise.<this>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L974)
Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
**See:**
* [Sequelize#sync](sequelize#sync)
***
<a name="drop"></a>
## `drop([options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1022)
Drop the table represented by this Model
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [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. |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
***
<a name="schema"></a>
## `schema(schema, [options])` -> `this`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1041)
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'`.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| schema | String | The name of the schema |
| [options] | Object | |
| [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. |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
***
<a name="gettablename"></a>
## `getTableName([options])` -> `String|Object`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1075)
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.
**Params:**
| 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.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
***
<a name="unscoped"></a>
## `unscoped()` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1082)
***
<a name="addscope"></a>
## `addScope(name, scope, [options])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1096)
Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined.
By default this will throw an error if a scope with that name already exists. Pass `override: true` in the options object to silence this error.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| name | String | The name of the scope. Use `defaultScope` to override the default scope |
| scope | Object &#124; Function | |
| [options] | Object | |
| [options.override=false] | Boolean | |
***
<a name="scope"></a>
## `scope(options*)` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1160)
Apply a scope created in `define` to the model. First let's look at how to create scopes:
```js
var Model = sequelize.define('model', attributes, {
defaultScope: {
where: {
username: 'dan'
},
limit: 12
},
scopes: {
isALie: {
where: {
stuff: 'cake'
}
},
complexFunction: function(email, accessLevel) {
return {
where: {
email: {
$like: email
},
accesss_level {
$gte: accessLevel
}
}
}
}
}
})
```
Now, since you defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples:
```js
Model.findAll() // WHERE username = 'dan'
Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
```
To invoke scope functions you can do:
```js
Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
// WHERE email like 'dan@sequelize.com%' AND access_level >= 42
```
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options* | Array &#124; Object &#124; String | The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default. |
__Returns:__ A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
***
<a name="findall"></a>
## `findAll([options])` -> `Promise.<Array.<Instance>>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1327)
Search for multiple instances.
__Simple search using AND and =__
```js
Model.findAll({
where: {
attr1: 42,
attr2: 'cake'
}
})
```
```sql
WHERE attr1 = 42 AND attr2 = 'cake'
```
__Using greater than, less than etc.__
```js
Model.findAll({
where: {
attr1: {
gt: 50
},
attr2: {
lte: 45
},
attr3: {
in: [1,2,3]
},
attr4: {
ne: 5
}
}
})
```
```sql
WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
```
Possible options are: `$ne, $in, $not, $notIn, $gte, $gt, $lte, $lt, $like, $ilike/$iLike, $notLike, $notILike, '..'/$between, '!..'/$notBetween, '&&'/$overlap, '@>'/$contains, '<@'/$contained`
__Queries using OR__
```js
Model.findAll({
where: {
name: 'a project',
$or: [
{id: [1, 2, 3]},
{
$and: [
{id: {gt: 10}},
{id: {lt: 100}}
]
}
]
}
});
```
```sql
WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));
```
The success listener is called with an array of instances if the query succeeds.
**See:**
* [Sequelize#query](sequelize#query)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | A hash of options to describe the scope of the search |
| [options.where] | Object | A hash of attributes to describe your search. See above for examples. |
| [options.attributes] | Array.&lt;String&gt; &#124; Object | A list of the attributes that you want to select, or an object with `include` and `exclude` keys. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to have in the returned instance |
| [options.attributes.include] | Array.&lt;String&gt; | Select all the attributes of the model, plus some additional ones. Useful for aggregations, e.g. `{ attributes: { include: [[sequelize.fn('COUNT', sequelize.col('id')), 'total']] }` |
| [options.attributes.exclude] | Array.&lt;String&gt; | Select all the attributes of the model, except some few. Useful for security purposes e.g. `{ attributes: { exclude: ['password'] } }` |
| [options.paranoid=true] | Boolean | If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned. Only applies if `options.paranoid` is true for the model. |
| [options.include] | Array.&lt;Object &#124; Model &#124; String&gt; | A list of associations to eagerly load using a left join. Supported is either `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }, ...]}` or `{ include: ['Alias', ...]}`. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y). |
| [options.include[].model] | Model | The model you want to eagerly load |
| [options.include[].as] | String | The alias of the relation, in case the model you want to eagerly load is aliased. For `hasOne` / `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural |
| [options.include[].association] | Association | The association you want to eagerly load. (This can be used instead of providing a model/as pair) |
| [options.include[].where] | Object | Where clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set `required: false` |
| [options.include[].or=false] | Boolean | Whether to bind the ON and WHERE clause together by OR instead of AND. |
| [options.include[].on] | Object | Supply your own ON condition for the join. |
| [options.include[].attributes] | Array.&lt;String&gt; | A list of attributes to select from the child model |
| [options.include[].required] | Boolean | If true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if `include.where` is set, false otherwise. |
| [options.include[].separate] | Boolean | If true, runs a separate query to fetch the associated instances, only supported for hasMany associations |
| [options.include[].limit] | Number | Limit the joined rows, only supported with include.separate=true |
| [options.include[].through.where] | Object | Filter on the join model for belongsToMany relations |
| [options.include[].through.attributes] | Array | A list of attributes to select from the join model for belongsToMany relations |
| [options.include[].include] | Array.&lt;Object &#124; Model &#124; String&gt; | Load further nested related models |
| [options.order] | Array &#124; Sequelize.fn &#124; Sequelize.col &#124; Sequelize.literal | Specifies an ordering. Using an array, you can provide several columns / functions to order by. Each element can be further wrapped in a two-element array. The first element is the column / function to order by, the second is the direction. For example: `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not. |
| [options.limit] | Number | |
| [options.offset] | Number | |
| [options.transaction] | Transaction | Transaction to run query under |
| [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](transaction#lock) |
| [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 | |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
__Aliases:__ all
***
<a name="findbyid"></a>
## `findById(id, [options])` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1456)
Search for a single instance by its primary key.
**See:**
* [Model#findAll](model#findall)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| id | Number &#124; String &#124; Buffer | The value of the desired instance's primary key. |
| [options] | Object | |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
__Aliases:__ findByPrimary
***
<a name="findone"></a>
## `findOne([options])` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1487)
Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance.
**See:**
* [Model#findAll](model#findall)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | A hash of options to describe the scope of the search |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
__Aliases:__ find
***
<a name="aggregate"></a>
## `aggregate(field, aggregateFunction, [options])` -> `Promise.<options.dataType|object>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1525)
Run an aggregation method on the specified field
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| field | String | The field to aggregate over. Can be a field name or * |
| aggregateFunction | String | The function to use for aggregation, e.g. sum, max etc. |
| [options] | Object | Query options. See sequelize.query for full options |
| [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.distinct] | boolean | Applies DISTINCT to the field being aggregated over |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.plain] | Boolean | When `true`, the first returned value of `aggregateFunction` is cast to `dataType` and returned. If additional attributes are specified, along with `group` clauses, set `plain` to `false` to return all values of all returned rows. Defaults to `true` |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
__Returns:__ Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in which case the complete data result is returned.
***
<a name="count"></a>
## `count([options])` -> `Promise.<Integer>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1579)
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.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | Object | |
| [options.where] | Object | A hash of search attributes. |
| [options.include] | Object | Include options. See `find` for details |
| [options.distinct] | boolean | Apply COUNT(DISTINCT(col)) on primary key, `Model.aggregate` should be used for other columns |
| [options.attributes] | Object | Used in conjunction with `group` |
| [options.group] | Object | For creating complex counts. Will return multiple rows as needed. |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
***
<a name="findandcount"></a>
## `findAndCount([findOptions])` -> `Promise.<Object>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1638)
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 useful for paging
```js
Model.findAndCountAll({
where: ...,
limit: 12,
offset: 12
}).then(function (result) {
...
})
```
In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return the total number of rows that matched your query.
When you add includes, only those which are required (either because they have a where clause, or because `required` is explicitly set to true on the include) will be added to the count part.
Suppose you want to find all users who have a profile attached:
```js
User.findAndCountAll({
include: [
{ model: Profile, required: true}
],
limit 3
});
```
Because the include for `Profile` has `required` set it will result in an inner join, and only the users who have a profile will be counted. If we remove `required` from the include, both users with and without profiles will be counted
**See:**
* [Model#findAll](model#findall)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [findOptions] | Object | See findAll |
__Aliases:__ findAndCountAll
***
<a name="max"></a>
## `max(field, [options])` -> `Promise.<Any>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1702)
Find the maximum value of field
**See:**
* [Model#aggregate](model#aggregate)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| field | String | |
| [options] | Object | See aggregate |
***
<a name="min"></a>
## `min(field, [options])` -> `Promise.<Any>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1715)
Find the minimum value of field
**See:**
* [Model#aggregate](model#aggregate)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| field | String | |
| [options] | Object | See aggregate |
***
<a name="sum"></a>
## `sum(field, [options])` -> `Promise.<Number>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1728)
Find the sum of field
**See:**
* [Model#aggregate](model#aggregate)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| field | String | |
| [options] | Object | See aggregate |
***
<a name="build"></a>
## `build(values, [options])` -> `Instance`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1743)
Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| values | Object | |
| [options] | Object | |
| [options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. |
| [options.isNewRecord=true] | Boolean | |
| [options.include] | Array | an array of include options - Used to build prefetched/included model instances. See `set` |
***
<a name="create"></a>
## `create(values, [options])` -> `Promise.<Instance>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1815)
Builds a new model instance and calls save on it.
**See:**
* [Instance#build](instance#build)
* [Instance#save](instance#save)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| values | Object | |
| [options] | Object | |
| [options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. |
| [options.isNewRecord=true] | Boolean | |
| [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.onDuplicate] | String | |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
| [options.returning] | Boolean | Append RETURNING * to get back auto generated values (Postgres only) |
| [options.silent=false] | Boolean | If true, the updatedAt timestamp will not be updated. |
***
<a name="findorinitialize"></a>
## `findOrInitialize` -> `Promise.<Instance, initialized>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1841)
Find a row that matches the query, or build (but don't save) the row if none is found.
The successful result of the promise will be (instance, initialized) - Make sure to use .spread()
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | Object | |
| options.where | Object | A hash of search attributes. |
| [options.defaults] | Object | Default values to use if building a new instance |
| [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. |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
__Aliases:__ findOrBuild
***
<a name="findorcreate"></a>
## `findOrCreate(options)` -> `Promise.<Instance, created>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1883)
Find a row that matches the query, or build and save the row if none is found
The successful result of the promise will be (instance, created) - Make sure to use .spread()
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 committed. 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.
**See:**
* [Model#findAll](model#findall)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | Object | |
| options.where | Object | where A hash of search attributes. |
| [options.defaults] | Object | Default values to use if creating a new instance |
| [options.transaction] | Transaction | Transaction to run query under |
***
<a name="findcreatefind"></a>
## `findCreateFind(options)` -> `Promise.<Instance, created>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L1969)
A more performant findOrCreate that will not work under a transaction (at least not in postgres)
Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
**See:**
* [Model#findAll](model#findall)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | Object | |
| options.where | Object | where A hash of search attributes. |
| [options.defaults] | Object | Default values to use if creating a new instance |
***
<a name="upsert"></a>
## `upsert(values, [options])` -> `Promise.<created>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L2018)
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:**
* MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values`
* PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN unique_constraint UPDATE
* SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed regardless of whether the row already existed or not
**Note** that SQLite returns undefined for created, no matter if the row was created or updated. This is because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know whether the row was inserted or not.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| values | Object | |
| [options] | Object | |
| [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.transaction] | Transaction | Transaction to run query under |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
__Returns:__ Returns a boolean indicating whether the row was created or updated.
__Aliases:__ insertOrUpdate
***
<a name="bulkcreate"></a>
## `bulkCreate(records, [options])` -> `Promise.<Array.<Instance>>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L2081)
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
and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records.
To obtain Instances for the newly created values, you will need to query for them again.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| records | Array | List of objects (key/value pairs) to create instances from |
| [options] | Object | |
| [options.fields] | Array | Fields to insert (defaults to all fields) |
| [options.validate=false] | 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 create hooks? |
| [options.individualHooks=false] | Boolean | Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true. |
| [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). By default, all fields are updated. |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.returning=false] | Boolean | Append RETURNING * to get back auto generated values (Postgres only) |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
***
<a name="truncate"></a>
## `truncate([options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L2234)
Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
**See:**
* [Model#destroy](model#destroy)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | object | The options passed to Model.destroy in addition to truncate |
| [options.transaction] | Boolean &#124; function | Transaction to run query under |
| [options.cascade=false] | Boolean &#124; function | Only used in conjunction 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 | Transaction to run query under |
| [options.logging] | Boolean &#124; function | A function that logs sql queries, or false for no logging |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
***
<a name="destroy"></a>
## `destroy(options)` -> `Promise.<Integer>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L2256)
Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | Object | |
| [options.where] | Object | Filter the destroy |
| [options.hooks=true] | Boolean | Run before / after bulk destroy hooks? |
| [options.individualHooks=false] | Boolean | If set to true, destroy will SELECT all records matching the where parameter and will execute before / after destroy hooks on each row |
| [options.limit] | Number | How many rows to delete |
| [options.force=false] | Boolean | Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled) |
| [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 conjunction 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.restartIdentity=false] | Boolean | Only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table. Postgres only. |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
__Returns:__ The number of destroyed rows
***
<a name="restore"></a>
## `restore(options)` -> `Promise.<undefined>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L2338)
Restore multiple instances if `paranoid` is enabled.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | Object | |
| [options.where] | Object | Filter the restore |
| [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.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.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
| [options.transaction] | Transaction | Transaction to run query under |
***
<a name="update"></a>
## `update(values, options)` -> `Promise.<Array.<affectedCount, affectedRows>>`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L2417)
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.)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| values | Object | |
| options | Object | |
| options.where | Object | Options to describe the scope of the search. |
| [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.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.returning=false] | Boolean | Return the affected rows (only for postgres) |
| [options.limit] | Number | How many rows to update (only for mysql) |
| [options.logging=false] | Function | A function that gets executed while running the query to log the sql. |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
| [options.transaction] | Transaction | Transaction to run query under |
| [options.silent=false] | Boolean | If true, the updatedAt timestamp will not be updated. |
***
<a name="describe"></a>
## `describe()` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/model.js#L2613)
Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types.
***
_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)_
<a name="sequelize"></a>
# Class Sequelize
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L31)
This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
```js
var Sequelize = require('sequelize');
```
In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
***
<a name="sequelize"></a>
## `new Sequelize(database, [username=null], [password=null], [options={}])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L91)
Instantiate sequelize with name of database, username and password
#### Example usage
```javascript
// without password and options
var sequelize = new Sequelize('database', 'username')
// without options
var sequelize = new Sequelize('database', 'username', 'password')
// without password / with blank password
var sequelize = new Sequelize('database', 'username', null, {})
// with password and options
var sequelize = new Sequelize('my_database', 'john', 'doe', {})
// with uri (see below)
var sequelize = new Sequelize('mysql://localhost:3306/database', {})
```
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| database | String | The name of the database |
| [username=null] | String | The username which is used to authenticate against the database. |
| [password=null] | String | The password which is used to authenticate against the database. |
| [options={}] | Object | An object with options. |
| [options.dialect='mysql'] | String | The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql. |
| [options.dialectModulePath=null] | String | If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here |
| [options.dialectOptions] | Object | An object of additional options, which are passed directly to the connection library |
| [options.storage] | String | Only used by sqlite. Defaults to ':memory:' |
| [options.host='localhost'] | String | The host of the relational database. |
| [options.port=] | Integer | The port of the relational database. |
| [options.protocol='tcp'] | String | The protocol of the relational database. |
| [options.define={}] | Object | Default options for model definitions. See sequelize.define for options |
| [options.query={}] | Object | Default options for sequelize.query |
| [options.set={}] | Object | Default options for sequelize.set |
| [options.sync={}] | Object | Default options for sequelize.sync |
| [options.timezone='+00:00'] | String | The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes. |
| [options.logging=console.log] | Function | A function that gets executed every time Sequelize would log something. |
| [options.omitNull=false] | Boolean | A flag that defines if null values should be passed to SQL queries or not. |
| [options.native=false] | Boolean | A flag that defines if native library shall be used or not. Currently only has an effect for postgres |
| [options.replication=false] | Boolean | Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: `host`, `port`, `username`, `password`, `database` |
| [options.pool={}] | Object | Should sequelize use a connection pool. Default is true |
| [options.pool.max] | Integer | Maximum number of connections in pool. Default is 5 |
| [options.pool.min] | Integer | Minimum number of connections in pool. Default is 0 |
| [options.pool.idle] | Integer | The maximum time, in milliseconds, that a connection can be idle before being released. Default is 10000 |
| [options.pool.validateConnection] | Function | A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected |
| [options.quoteIdentifiers=true] | Boolean | Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. *WARNING: Setting this to false may expose vulnerabilities and is not reccomended!* |
| [options.transactionType='DEFERRED'] | String | Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only. |
| [options.isolationLevel='REPEATABLE_READ'] | String | Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options. |
| [options.retry] | Object | Set of flags that control when a query is automatically retried. |
| [options.retry.match] | Array | Only retry a query if the error matches one of these strings. |
| [options.retry.max] | Integer | How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error. |
| [options.typeValidation=false] | Boolean | Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like. |
| [options.benchmark=false] | Boolean | Print query execution time in milliseconds when logging SQL. |
***
<a name="sequelize"></a>
## `new Sequelize(uri, [options={}])`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L100)
Instantiate sequelize with an URI
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| uri | String | A full database URI |
| [options={}] | object | See above for possible options |
***
<a name="models"></a>
## `models`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L221)
Models are stored here under the name given to `sequelize.define`
***
<a name="version"></a>
## `version`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L245)
Sequelize version number.
***
<a name="sequelize"></a>
## `Sequelize`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L254)
A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
**See:**
* [Sequelize](sequelize)
***
<a name="utils"></a>
## `Utils`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L260)
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 name="promise"></a>
## `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L266)
A handy reference to the bluebird Promise class
***
<a name="querytypes"></a>
## `QueryTypes`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L272)
Available query types for use with `sequelize.query`
***
<a name="validator"></a>
## `Validator`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L279)
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:**
***
<a name="transaction"></a>
## `Transaction`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L299)
A reference to the sequelize transaction class. Use this to access isolationLevels and types when creating a transaction
**See:**
* [Transaction](transaction)
* [Sequelize#transaction](sequelize#transaction)
***
<a name="deferrable"></a>
## `Deferrable`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L307)
A reference to the deferrable collection. Use this to access the different deferrable options.
**See:**
* [Deferrable](deferrable)
* [Sequelize#transaction](sequelize#transaction)
***
<a name="instance"></a>
## `Instance`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L314)
A reference to the sequelize instance class.
**See:**
* [Instance](instance)
***
<a name="association"></a>
## `Association`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L321)
A reference to the sequelize association class.
**See:**
* [Association](association)
***
<a name="error"></a>
## `Error`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L334)
A general error class
**See:**
* [Errors#BaseError](errors#baseerror)
***
<a name="validationerror"></a>
## `ValidationError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L342)
Emitted when a validation fails
**See:**
* [Errors#ValidationError](errors#validationerror)
***
<a name="validationerroritem"></a>
## `ValidationErrorItem`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L350)
Describes a validation error on an instance path
**See:**
* [Errors#ValidationErrorItem](errors#validationerroritem)
***
<a name="databaseerror"></a>
## `DatabaseError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L357)
A base class for all database related errors.
**See:**
* [Errors#DatabaseError](errors#databaseerror)
***
<a name="timeouterror"></a>
## `TimeoutError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L364)
Thrown when a database query times out because of a deadlock
**See:**
* [Errors#TimeoutError](errors#timeouterror)
***
<a name="uniqueconstrainterror"></a>
## `UniqueConstraintError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L371)
Thrown when a unique constraint is violated in the database
**See:**
* [Errors#UniqueConstraintError](errors#uniqueconstrainterror)
***
<a name="exclusionconstrainterror"></a>
## `ExclusionConstraintError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L378)
Thrown when an exclusion constraint is violated in the database
**See:**
* [Errors#ExclusionConstraintError](errors#exclusionconstrainterror)
***
<a name="foreignkeyconstrainterror"></a>
## `ForeignKeyConstraintError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L385)
Thrown when a foreign key constraint is violated in the database
**See:**
* [Errors#ForeignKeyConstraintError](errors#foreignkeyconstrainterror)
***
<a name="connectionerror"></a>
## `ConnectionError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L392)
A base class for all connection related errors.
**See:**
* [Errors#ConnectionError](errors#connectionerror)
***
<a name="connectionrefusederror"></a>
## `ConnectionRefusedError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L399)
Thrown when a connection to a database is refused
**See:**
* [Errors#ConnectionRefusedError](errors#connectionrefusederror)
***
<a name="accessdeniederror"></a>
## `AccessDeniedError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L406)
Thrown when a connection to a database is refused due to insufficient access
**See:**
* [Errors#AccessDeniedError](errors#accessdeniederror)
***
<a name="hostnotfounderror"></a>
## `HostNotFoundError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L413)
Thrown when a connection to a database has a hostname that was not found
**See:**
* [Errors#HostNotFoundError](errors#hostnotfounderror)
***
<a name="hostnotreachableerror"></a>
## `HostNotReachableError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L420)
Thrown when a connection to a database has a hostname that was not reachable
**See:**
* [Errors#HostNotReachableError](errors#hostnotreachableerror)
***
<a name="invalidconnectionerror"></a>
## `InvalidConnectionError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L427)
Thrown when a connection to a database has invalid values for any of the connection parameters
**See:**
* [Errors#InvalidConnectionError](errors#invalidconnectionerror)
***
<a name="connectiontimedouterror"></a>
## `ConnectionTimedOutError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L434)
Thrown when a connection to a database times out
**See:**
* [Errors#ConnectionTimedOutError](errors#connectiontimedouterror)
***
<a name="instanceerror"></a>
## `InstanceError`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L441)
Thrown when a some problem occurred with Instance methods (see message for details)
**See:**
* [Errors#InstanceError](errors#instanceerror)
***
<a name="getdialect"></a>
## `getDialect()` -> `String`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L454)
Returns the specified dialect.
__Returns:__ The specified dialect.
***
<a name="getqueryinterface"></a>
## `getQueryInterface()` -> `QueryInterface`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L466)
Returns an instance of QueryInterface.
**See:**
* [QueryInterface](queryinterface)
__Returns:__ An instance (singleton) of QueryInterface.
***
<a name="define"></a>
## `define(modelName, attributes, [options])` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L569)
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:
```js
sequelize.define('modelName', {
columnA: {
type: Sequelize.BOOLEAN,
validate: {
is: ["[a-z]",'i'], // will only allow letters
max: 23, // only allow values <= 23
isIn: {
args: [['en', 'zh']],
msg: "Must be English or Chinese"
}
},
field: 'column_a'
// Other attributes here
},
columnB: Sequelize.STRING,
columnC: 'MY VERY OWN COLUMN TYPE'
})
sequelize.models.modelName // The model will now be available in models under the name given to define
```
As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
For a list of possible data types, see [Data Types](http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types).
For more about getters and setters, see [Getters and Setters](http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters).
For more about instance and class methods, see [Expansion of Models](http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models).
For more about validation, see [Validations](http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations).
**See:**
* [DataTypes](datatypes)
* [Hooks](hooks)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| modelName | String | The name of the model. The model will be stored in `sequelize.models` under this name |
| attributes | Object | An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below: |
| attributes.column | String &#124; DataType &#124; Object | The description of a database column |
| attributes.column.type | String &#124; DataType | A string or a data type |
| [attributes.column.allowNull=true] | Boolean | If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved. |
| [attributes.column.defaultValue=null] | Any | A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`) |
| [attributes.column.unique=false] | String &#124; Boolean | If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index |
| [attributes.column.primaryKey=false] | Boolean | |
| [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.comment=null] | String | |
| [attributes.column.references=null] | String &#124; Model | An object with reference configurations |
| [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.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.set] | Function | Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the underlying values. |
| [attributes.validate] | Object | An object of validations to execute for this column every time the model is saved. Can be either the name of a validation provided by validator.js, a validation function provided by extending validator.js (see the `DAOValidator` property for more details), or a custom validation function. Custom validation functions are called with the value of the field, and can possibly take a second callback argument, to signal that they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, the callback should be called with the error text. |
| [options] | Object | These options are merged with the default define options provided to the Sequelize constructor |
| [options.defaultScope={}] | Object | Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll |
| [options.scopes] | Object | More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about how scopes are defined, and what you can do with them |
| [options.omitNull] | Boolean | Don't persist null values. This means that all columns with null values will not be saved |
| [options.timestamps=true] | Boolean | Adds createdAt and updatedAt timestamps to the model. |
| [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.underscoredAll=false] | Boolean | Converts camelCased model names to underscored table names 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 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.singular=inflection.singularize(modelName)] | String | |
| [options.name.plural=inflection.pluralize(modelName)] | String | |
| [options.indexes] | Array.&lt;Object&gt; | |
| [options.indexes[].name] | String | The name of the index. Defaults to model name + _ + fields concatenated |
| [options.indexes[].type] | String | Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL` |
| [options.indexes[].method] | String | The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and postgres, and postgres additionally supports GIST and GIN. |
| [options.indexes[].unique=false] | Boolean | Should the index by unique? Can also be triggered by setting type to `UNIQUE` |
| [options.indexes[].concurrently=false] | Boolean | PostgreSQL will build the index without taking any write locks. Postgres only |
| [options.indexes[].fields] | Array.&lt;String &#124; Object&gt; | An array of the fields to index. Each field can either be a string containing the name of the field, a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute` (field name), `length` (create a prefix index of length chars), `order` (the direction the column should be sorted in), `collate` (the collation (sort order) for the column) |
| [options.createdAt] | String &#124; Boolean | Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting. |
| [options.updatedAt] | String &#124; Boolean | Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting. |
| [options.deletedAt] | String &#124; Boolean | Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting. |
| [options.tableName] | String | Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim |
| [options.getterMethods] | Object | Provide getter functions that work like those defined per column. If you provide a getter method with the same name as a column, it will be used to access the value of that column. If you provide a name that does not match a column, this function will act as a virtual getter, that can fetch multiple other values |
| [options.setterMethods] | Object | Provide setter functions that work like those defined per column. If you provide a setter method with the same name as a column, it will be used to update the value of that column. If you provide a name that does not match a column, this function will act as a virtual setter, that can act on and set other values, but will not be persisted |
| [options.instanceMethods] | Object | Provide functions that are added to each instance (DAO). If you override methods provided by sequelize, you can access the original method using `this.constructor.super_.prototype`, e.g. `this.constructor.super_.prototype.toJSON.apply(this, arguments)` |
| [options.classMethods] | Object | Provide functions that are added to the model (Model). If you override methods provided by sequelize, you can access the original method using `this.constructor.prototype`, e.g. `this.constructor.prototype.find.apply(this, arguments)` |
| [options.schema='public'] | String | |
| [options.engine] | String | |
| [options.charset] | String | |
| [options.comment] | String | |
| [options.collate] | String | |
| [options.rowFormat] | String | Specify the ROW_FORMAT for use with the MySQL InnoDB engine. |
| [options.initialAutoIncrement] | String | Set the initial AUTO_INCREMENT value for the table in MySQL. |
| [options.hooks] | Object | An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions. |
| [options.validate] | Object | An object of model wide validations. Validations have access to all model values via `this`. If the validator function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional error. |
***
<a name="model"></a>
## `model(modelName)` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L615)
Fetch a Model which is already defined
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| modelName | String | The name of a model defined with Sequelize.define |
***
<a name="isdefined"></a>
## `isDefined(modelName)` -> `Boolean`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L629)
Checks whether a model with the given name is defined
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| modelName | String | The name of a model defined with Sequelize.define |
***
<a name="import"></a>
## `import(path)` -> `Model`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L643)
Imports a model defined in another file
Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| path | String | The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file |
***
<a name="query"></a>
## `query(sql, [options={}])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L708)
Execute a query on the DB, with the possibility to bypass all the sequelize goodness.
By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use `.spread` to access the results.
If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results:
```js
sequelize.query('SELECT...').spread(function (results, metadata) {
// Raw query - use spread
});
sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(function (results) {
// SELECT query - use then
})
```
**See:**
* [Model#build](model#build)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| sql | String | |
| [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.transaction=null] | Transaction | The transaction that the query should be executed under |
| [options.type='RAW'] | String | The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts. |
| [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.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.bind] | Object &#124; Array | Either an object of named bind parameter in the format `$param` or an array of unnamed bind parameter to replace `$1, $2, ...` in your SQL. |
| [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) |
| [options.retry] | Object | Set of flags that control when a query is automatically retried. |
| [options.retry.match] | Array | Only retry a query if the error matches one of these strings. |
| [options.retry.max] | Integer | How many times a failing query is automatically retried. |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.supportsSearchPath] | Boolean | If false do not prepend the query with the search_path (Postgres only) |
| [options.mapToModel=false] | Object | Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance. |
| [options.fieldMap] | Object | Map returned fields to arbitrary names for `SELECT` query type. |
***
<a name="set"></a>
## `set(variables, options)` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L841)
Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
Only works for MySQL.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| variables | Object | Object with multiple variables. |
| options | Object | Query options. |
| options.transaction | Transaction | The transaction that the query should be executed under |
***
<a name="escape"></a>
## `escape(value)` -> `String`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L875)
Escape value.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| value | String | |
***
<a name="createschema"></a>
## `createSchema(schema, options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L891)
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),
not a database table. In mysql and sqlite, this command will do nothing.
**See:**
* [Model#schema](model#schema)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| schema | String | Name of the schema |
| options={} | Object | |
| options.logging | Boolean &#124; function | A function that logs sql queries, or false for no logging |
***
<a name="showallschemas"></a>
## `showAllSchemas(options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L904)
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),
not a database table. In mysql and sqlite, this will show all tables.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options={} | Object | |
| options.logging | Boolean &#124; function | A function that logs sql queries, or false for no logging |
***
<a name="dropschema"></a>
## `dropSchema(schema, options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L918)
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),
not a database table. In mysql and sqlite, this drop a table matching the schema name
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| schema | String | Name of the schema |
| options={} | Object | |
| options.logging | Boolean &#124; function | A function that logs sql queries, or false for no logging |
***
<a name="dropallschemas"></a>
## `dropAllSchemas(options={})` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L931)
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),
not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options={} | Object | |
| options.logging | Boolean &#124; function | A function that logs sql queries, or false for no logging |
***
<a name="sync"></a>
## `sync([options={}])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L947)
Sync all defined models to the DB.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options={}] | Object | |
| [options.force=false] | Boolean | If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table |
| [options.match] | RegEx | Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code |
| [options.logging=console.log] | Boolean &#124; function | A function that logs sql queries, or false for no logging |
| [options.schema='public'] | String | The schema that the tables should be created in. This can be overriden for each table in sequelize.define |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.hooks=true] | Boolean | If hooks is true then beforeSync, afterSync, beforBulkSync, afterBulkSync hooks will be called |
| [options.alter=false] | Boolean | Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model. |
***
<a name="truncate"></a>
## `truncate([options])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1003)
Truncate all tables defined through the sequelize models. This is done
by calling Model.truncate() on each model.
**See:**
* [Model#truncate](model#truncate)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options] | object | The options passed to Model.destroy in addition to truncate |
| [options.transaction] | Boolean &#124; function | |
| [options.logging] | Boolean &#124; function | A function that logs sql queries, or false for no logging |
***
<a name="drop"></a>
## `drop(options)` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1025)
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
**See:**
* [Model#drop](model#drop)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | object | The options passed to each call to Model.drop |
| options.logging | Boolean &#124; function | A function that logs sql queries, or false for no logging |
***
<a name="authenticate"></a>
## `authenticate()` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1047)
Test the connection by trying to authenticate
__Aliases:__ validate
***
<a name="fn"></a>
## `fn(fn, args)` -> `Sequelize.fn`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1080)
Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings.
Convert a user's username to upper case
```js
instance.updateAttributes({
username: self.sequelize.fn('upper', self.sequelize.col('username'))
})
```
Alternatively, a condition object can be used as an argument e.g. to get the count of rows for which the predicate evaluates to true. Works on mysql and sqlite.
```js
sequelize.fn('sum', { age: { $gt: 25 }, name: 'Joe' })
```
An explicit cast is required on postgres.
```js
sequelize.fn('sum', sequelize.cast({ age: { $gt: 25 }, name: 'Joe' }, 'int'))
```
**See:**
* [Model#find](model#find)
* [Model#findAll](model#findall)
* [Model#define](model#define)
* [Sequelize#col](sequelize#col)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| fn | String | The function you want to call |
| args | any | All further arguments will be passed as arguments to the function. An argument may be a condition object. |
***
<a name="col"></a>
## `col(col)` -> `Sequelize.col`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1093)
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:**
* [Sequelize#fn](sequelize#fn)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| col | String | The name of the column |
***
<a name="cast"></a>
## `cast(val, type)` -> `Sequelize.cast`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1107)
Creates a object representing a call to the cast function.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| val | any | The value to cast |
| type | String | The type to cast it to |
***
<a name="literal"></a>
## `literal(val)` -> `Sequelize.literal`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1120)
Creates a object representing a literal, i.e. something that will not be escaped.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| val | any | |
__Aliases:__ asIs
***
<a name="and"></a>
## `and(args)` -> `Sequelize.and`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1133)
An AND query
**See:**
* [Model#find](model#find)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| args | String &#124; Object | Each argument will be joined by AND |
***
<a name="or"></a>
## `or(args)` -> `Sequelize.or`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1146)
An OR query
**See:**
* [Model#find](model#find)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| args | String &#124; Object | Each argument will be joined by OR |
***
<a name="json"></a>
## `json(conditions, [value])` -> `Sequelize.json`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1159)
Creates an object representing nested where conditions for postgres's json data-type.
**See:**
* [Model#find](model#find)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| conditions | String &#124; Object | A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax. |
| [value] | String &#124; Number &#124; Boolean | An optional value to compare against. Produces a string of the form "&lt;json path&gt; = '&lt;value&gt;'". |
***
<a name="where"></a>
## `where(attr, [comparator='='], logic)` -> `Sequelize.where`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1181)
A way of specifying attr = condition.
The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` or `Model.rawAttributes.name`). The
attribute should be defined in your model definition. The attribute can also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.)
For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your string to be escaped, use `sequelize.literal`.
**See:**
* [Model#find](model#find)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| attr | Object | The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax |
| [comparator='='] | string | |
| logic | String &#124; Object | The condition. Can be both a simply type, or a further condition (`$or`, `$and`, `.literal` etc.) |
__Aliases:__ condition
***
<a name="transaction"></a>
## `transaction([options={}])` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/sequelize.js#L1235)
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
sequelize.transaction().then(function (t) {
return User.find(..., { transaction: t}).then(function (user) {
return user.updateAttributes(..., { transaction: t});
})
.then(t.commit.bind(t))
.catch(t.rollback.bind(t));
})
```
A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:
```js
sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then()
return User.find(..., { transaction: t}).then(function (user) {
return user.updateAttributes(..., { transaction: t});
});
}).then(function () {
// Committed
}).catch(function (err) {
// Rolled back
console.error(err);
});
```
If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction will automatically be passed to any query that runs within the callback.
To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:
```js
var cls = require('continuation-local-storage'),
ns = cls.createNamespace('....');
var Sequelize = require('sequelize');
Sequelize.cls = ns;
```
Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
**See:**
* [Transaction](transaction)
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options={}] | Object | |
| [options.autocommit=true] | Boolean | |
| [options.type='DEFERRED'] | String | See `Sequelize.Transaction.TYPES` for possible options. Sqlite only. |
| [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)_
<a name="transaction"></a>
# Class Transaction
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/transaction.js#L20)
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.
**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.type=true | String | Sets the type 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="types"></a>
## `TYPES`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/transaction.js#L76)
Types can be set per-transaction by passing `options.type` to `sequelize.transaction`.
Default to `DEFERRED` but you can override the default type by passing `options.transactionType` in `new Sequelize`.
Sqlite only.
The possible types to use when starting a transaction:
```js
{
DEFERRED: "DEFERRED",
IMMEDIATE: "IMMEDIATE",
EXCLUSIVE: "EXCLUSIVE"
}
```
Pass in the desired level as the first argument:
```js
return sequelize.transaction({
type: Sequelize.Transaction.EXCLUSIVE
}, function (t) {
// your transactions
}).then(function(result) {
// transaction has been committed. Do something after the commit if required.
}).catch(function(err) {
// do something with the err.
});
```
***
<a name="isolation_levels"></a>
## `ISOLATION_LEVELS`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/transaction.js#L116)
Isolations levels 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`.
The possible isolations levels to use when starting a transaction:
```js
{
READ_UNCOMMITTED: "READ UNCOMMITTED",
READ_COMMITTED: "READ COMMITTED",
REPEATABLE_READ: "REPEATABLE READ",
SERIALIZABLE: "SERIALIZABLE"
}
```
Pass in the desired level as the first argument:
```js
return sequelize.transaction({
isolationLevel: Sequelize.Transaction.SERIALIZABLE
}, function (t) {
// your transactions
}).then(function(result) {
// transaction has been committed. Do something after the commit if required.
}).catch(function(err) {
// do something with the err.
});
```
***
<a name="lock"></a>
## `LOCK`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/transaction.js#L160)
Possible options for row locking. Used in conjunction with `find` calls:
```js
t1 // is a transaction
t1.LOCK.UPDATE,
t1.LOCK.SHARE,
t1.LOCK.KEY_SHARE, // Postgres 9.3+ only
t1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ only
```
Usage:
```js
t1 // is a transaction
Model.findAll({
where: ...,
transaction: t1,
lock: t1.LOCK...
});
```
Postgres also supports specific locks while eager loading by using OF:
```js
UserModel.findAll({
where: ...,
include: [TaskModel, ...],
transaction: t1,
lock: {
level: t1.LOCK...,
of: UserModel
}
});
```
UserModel will be locked but TaskModel won't!
***
<a name="commit"></a>
## `commit()` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/transaction.js#L172)
Commit the transaction
***
<a name="rollback"></a>
## `rollback()` -> `Promise`
[View code](https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/transaction.js#L200)
Rollback (abort) the transaction
***
_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
<script type="text/javascript">
fromGithub = function (partialId, ext) {
ext = ext || '';
var $partial = $("#" + partialId)
$.get("https://cdn.rawgit.com/sequelize/express-example/master/" + partialId.replace("_", "/") + ext, function (code) {
if (ext === '.js') {
code = hljs.highlight('js', code).value;
}
code = '<div class="highlight"><pre>' + code + '</pre></div>';
$partial.replaceWith(code);
}, 'html');
}
</script>
## Introduction
This article explains the usage of Sequelize with the MVC framework Express.You will learn how and where to define models and how to load them when needed.
## A minimal express application
In order to create a minimal express application, we need to install express first and scaffold a project. We can do this via the following commands:
```bash
$ mkdir example-app
$ cd example-app
$ npm install express express-generator
$ node_modules/.bin/express . -f
$ npm install
$ ./bin/www
```
You should now be able to see a tiny welcome page on `http://localhost:3000`
## Adding Sequelize to the application
Now that we have the express application in place, we can start adding Sequelize to it. What we need for that are the following packages: sequelize, sequelize-cli, sqlite3. Please note, that for the sake of simplicity this tutorial will use SQLite.
```bash
$ npm install --save sequelize@2.0.0-rc1 sequelize-cli sqlite3
```
This will install the respective packages and uses the upcoming major release of sequelize. We can now let the sequelize CLI initialize the project's directory:
```bash
$ node_modules/.bin/sequelize init
```
Running this command will create the folders `config`, `migrations` and `models`.
## Implementing a todo app
As an example application we will create a very basic and simple todo tool, which allows the creation of users and the management of their tasks.
### bin/www
In order to create a maintainable application, we will put all the database logic into the `models` folder. When the application gets fired up, sequelize will sync the models with the database and afterwards start the server. This way we don't clutter the application while making use of sequelize's features.
<div id="bin_www"></div>
<script>$(function () { fromGithub("bin_www") })</script>
### models/index.js
This file has been generated with the sequelize CLI and collects all the models from the `models` directory and associates them if needed.
<div id="models_index"></div>
<script>$(function () { fromGithub("models_index", '.js') })</script>
### models/user.js
All models of our application are located as separate files in the `models` folder. If you want to add a new model, just add it to this folder and everything will work automagically. Also you can use the sequelize CLI's `sequelize model:create`.
**Notice** that the `associate` method receives a parameter `models`, which contains every declared model within the models directory.
<div id="models_user"></div>
<script>$(function () { fromGithub("models_user", '.js') })</script>
### models/task.js
The other needed model is `Task`. It relates to the `User`.
<div id="models_task"></div>
<script>$(function () { fromGithub("models_task", '.js') })</script>
### routes/index.js
The file `routes/index.js` contains the logic for a request against the main homepage. It loads the models module and uses it to load all the users and tasks from the database.
<div id="routes_index"></div>
<script>$(function () { fromGithub("routes_index", '.js') })</script>
This will allow us to iterate over the users in the view file. We will skip the rest of the route files for this article.
### views/index.jade
As we passed the users to the view and include the tasks for each user, we can access the data in the view's template file. Besides listing the users and tasks, there are also forms for creating new instances.
<div id="views_index"></div>
<script>$(function () { fromGithub("views_index", '.jade') })</script>
## What's next?
This article shows a basic approach of how to integrate Sequelize into an ExpressJS application. It allows the very easy management of models by adding new files to a specific folder. Starting the application will automatically sync the schema with the database.
If you don't want to have automatic schema synchronization and instead want migrations, just add a respective step to your deployment script. When you use the CLI for the model generation, you will gain the migration scripts for free as well.
You can find the complete application code [on Github](https://github.com/sequelize/express-example). Feel free to add pull requests to it.
Besides the use of Sequelize as model backend in your ExpressJS application, you might also want to turn your server into a restful API. If that is the case, check out [the repository on Github](https://github.com/sequelize/sequelize-restful)
\ No newline at end of file
## Introduction
This article explains the basic concepts of Sequelize. You will learn how to use the supported dialects, which types of database setup approaches are available, and how common scenarios can be achieved.
## Premise
We will skip the very basic things and directly dive into the Sequelize related stuff. Here is a list of things that have to be in place before you can start:
* Node.JS at v0.8 or higher
* One of the supported databases / SQLite bindings
* The credentials for the respective database
* A basic understanding of how databases are working
* Optional but recommended: Coffee :)
## A word about promises
Read about promises [here](http://bluebirdjs.com/docs/why-promises.html).
## Setting up a project
Now that your computer is prepared and your coffee sits next to your keyboard,
we can finally get started. First things first: create a directory and initialize it with NPM!
```bash
$ mkdir my-project
$ cd my-project
$ npm init
```
NPM will ask you a couple of questions. Answer them or just hit the return key until it's satisfied.
Once done, you can install Sequelize and the connector for your database of choice.
```bash
$ npm install --save sequelize
$ npm install --save pg # for postgres
$ npm install --save mysql2 # for mysql
$ npm install --save sqlite3 # for sqlite
```
## Connecting to the database
Open the created directory in your favorite text editor and add a new file called `app.js` with the following content:
```js
var Sequelize = require('sequelize')
, sequelize = new Sequelize('database_name', 'username', 'password', {
dialect: "mysql", // or 'sqlite', 'postgres', 'mssql'
port: 3306 // or 5432 (for postgres)
});
sequelize
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
```
## Managing the schema of your database
Sequelize supports two types of schema management. You can either define so-called migrations, which are programmatically changing your database's structure, or you can let Sequelize create the tables for you.
While the first possibility of using `migrations` takes more time to setup, it's most likely the way to go if you want to deploy your application on many different server environments. This is because migrations are consistently changing your database according to the current state of the schema.
However, the automated way of using Sequelize's function `sequelize.sync` will probably be a good choice on your local machine or if you just want to quickly spin up a prototype.
As this article is for beginners, we will skip migrations for now and take a closer look at the automated way.
### Defining a model
In order to let Sequelize create schemas in the database, you need to describe what kind of data you want to store. This can be done with `sequelize.define`:
```js
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
});
```
This will define a user model that has a username and password. Furthermore, Sequelize will automatically add the columns `id`, `createdAt` and `updatedAt`. `createdAt` and `updatedAt` are controlled by Sequelize - when you `create` a model through Sequelize, `createdAt` will be set, and whenever you call `updateAttributes` / `save` on a model, `updatedAt` will be set.
### Synchronizing the schema
As we want to store data in the database, we need to create a representation of the model:
```js
sequelize
.sync({ force: true })
.then(function(err) {
console.log('It worked!');
}, function (err) {
console.log('An error occurred while creating the table:', err);
});
```
Once executed, the database will contain a table `Users` (note the plural) with the columns:
* id - INT(11)
* username - VARCHAR(255)
* password - VARCHAR(255)
* createdAt - DATETIME
* updatedAt - DATETIME
Please note, that `{ force: true }` will drop the `Users` table and re-create it.
### Configuration
You might not need the timestamps or you might not want the plural of the model's name as table name, right? Luckily there are configuration possibilities for that:
```js
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
tableName: 'my_user_table', // this will define the table's name
timestamps: false // this will deactivate the timestamp columns
})
```
And just in case you want to customize the timestamp field names, you can do it like this:
```js
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
updatedAt: 'last_update',
createdAt: 'date_of_creation'
})
```
Furthermore you can introduce a `deletedAt` timestamp so models are not actually deleted when you call `destroy`. Adding a `deletedAt` timestamp is called making the model 'paranoid':
```js
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
paranoid: true
});
```
## Creating and persisting instances
Sequelize allows the creation of instances in two ways. You can either `build` an object and `save` it afterwards. Or you can directly `create` an instance in the database:
```js
var user = User.build({
username: 'john-doe',
password: generatePasswordHash('i-am-so-great')
})
user.save().then(function() {
/* ... */
})
```
This persists the instance in a two step way. If you want to do everything at once, use the following approach:
```js
User.create({
username: 'john-doe',
password: generatePasswordHash('i-am-so-great')
}).then(function(user) {
/* ... */
})
```
## Reading data from the database
Every defined model has finder methods, with which you can read the database. Searching for a single item can be done with `Model.find`. Retrieval of multiple items needs the use of `Model.findAll`.
```js
User
.find({ where: { username: 'john-doe' } })
.then(function(err, johnDoe) {
if (!johnDoe) {
console.log('No user with the username "john-doe" has been found.');
} else {
console.log('Hello ' + johnDoe.username + '!');
console.log('All attributes of john:', johnDoe.get());
}
});
```
Please note that, if no user with the name "john-doe" has been found, there won't be any errors. This is intended, as there are no internal or authentication errors.
## Defining associations
A very common use case is the definition of associations between two or even more models. Once declared, Sequelize will know how to query the database to get or set associated data. Furthermore it will be able to automatically create the respective foreign key columns for you.
Before taking a closer look at the code, it is critical to understand some details about the three different association types.
### One to one
An association between one source and one target is called "one to one" or 1:1 association. It consists of a source that **has one** target and a target that **belongs to** a source.
Sequelize expects a foreign key in the target's schema. That means that there has to be an attribute respectively a column in the target's table.
```js
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasOne(Target)
Target.belongsTo(Source)
sequelize
.sync({ force: true })
.then(function() {
// Even if we didn't define any foreign key or something else,
// instances of Target will have a column SourceId!
});
```
### One to many
An association between one source and many target is called "one to many" or 1:N association. It consists of a source that **has many** targets and some targets which **belong to** a source.
Sequelize expects a foreign key in the target's schema. That means that there has to be an attribute respectively a column in the target's table.
```js
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasMany(Target)
Target.belongsTo(Source)
sequelize
.sync({ force: true })
.then(function() {
// Even if we didn't define any foreign key or something else,
// instances of Target will have a column SourceId!
})
```
### Many to many
An association between many sources and many targets is called "many to many" or N:M association. It consists of sources which **have many** targets and some targets which **have many** sources.
Sequelize expects a junction table which contains a foreign key to the source table and a foreign key to the target table. A row in the table connects a source with a target.
```js
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasMany(Target)
Target.hasMany(Source)
sequelize
.sync({ force: true })
.then(function() {
// Even if we didn't define any foreign key or something else,
// Sequelize will create a table SourcesTargets.
})
```
### Getting/Setting associations
Defining associations is nice, but won't give you any advantage if you cannot read or set associations. Of course Sequelize will add respective functions to your models. Depending on the type of association you will find different methods:
```js
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {});
Source.hasOne(Target);
Target.belongsTo(Source);
sequelize.Promise.all([
Source.create({}),
Target.create({})
]).spread(function (source, target) {
// Set the association
return source.setTarget(target).return(source);
}).then(function(source) {
// Get the association
return source.getTarget();
}).then(function(_target) {
console.log(_target.get({
plain: true
}))
/*
{
id: 1,
createdAt: Sun Dec 08 2013 11:46:42 GMT+0100 (CET),
updatedAt: Sun Dec 08 2013 11:46:42 GMT+0100 (CET),
SourceId: 1
}
*/
});
```
### Clearing associations
Assuming we already defined the models (as in the previous code example) and synced the schema with the database, we can clear the associations like this:
```js
source.setTarget(null).then(function() {
return source.getTarget();
}).then(function(target) {
console.log(target);
});
```
### Adding / removing associations
For 1:N and N:M associations it makes sense to not only set the associations, but also to add or remove associations. Furthermore checking for an association can be handy.
```js
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {});
Source.hasMany(Target);
Target.belongsTo(Source);
return sequelize.Promise.all([
Source.create({}),
Target.create({});
Target.create({}),
]).bind({}).spread(function (source, target1, target2) {
// Set the association
this.source = source;
this.target1 = target1;
this.target2 = target2;
return source.setTargets([target1, target2]);
}).then(function() {
// Get the association
return this.source.getTargets();
}).then(function(targets) {
console.log(targets.length) // = 2
// Remove an association
return this.source.removeTarget(this.target1);
}).then(function() {
return source.getTargets();
}).then(function(targets) {
console.log(targets.length) // = 1
// Check for an association
return this.source.hasTarget(this.target1);
}).then(function(hasTarget) {
console.log(hasTarget) // false
// Adding an association
return this.source.addTarget(this.target1);
}).then(function() {
return this.source.getTargets();
}).then(function(targets) {
console.log(targets.length) // = 2
return this.source.hasTarget(this.target1);
}).then(function(hasTarget) {
console.log(hasTarget) // true
});
```
## A combined example
Now that you know the basics of Sequelize, you might want to see everything in a single program:
```js
var Sequelize = require('sequelize')
, sequelize = new Sequelize('database_name', 'username', 'password')
, User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
});
sequelize.sync({ force: true }).then(function() {
return User.create({ username: 'john', password: '1111' });
}).then(function(user1) {
return User.find({ username: 'john' })
}).then(function(user2) {
console.log(user2.get()); // Get returns a JSON representation of the user
});
```
## What's next?
As there are some more advanced features in Sequelize which are a bit inappropriate for this article, you can check the following resources for further advice:
* [Migrations][0]
* [Data types][1]
* [Configuration of the model][2]
* [Validations][3]
* [Finders][4]
* [Associations][5]
[0]: /docs/latest/migrations
[1]: /docs/latest/models#data-types
[2]: /docs/latest/models#configuration
[3]: /docs/latest/models#validations
[4]: /docs/latest/models#finders
[5]: /docs/latest/associations
## Introduction
This section covers the use of Sequelize on Heroku. It will explain how to get started with Heroku and what is necessary to setup a proper environment. We will use MySQL on the development machine and PostgreSQL on the remote servers.
## Getting started with Heroku
Before we can roll out any software on the Heroku cluster, we need to sign up and have to connect our development environment. Here are the most basic steps:
* [Sign up][0] for a Heroku account.
* [Install][1] the Heroku Toolbelt. This tool will let you create applications and is a handy way to configure them on the command line.
* Use the new binary to login. Run the following command on command line:`heroku login`
And that's it. You should now be able to do things like `heroku apps`. This should list all applications you've currently created on the Heroku cluster. If you've just created a new account, this should show you an empty list. [You can get further information about the registration process here][2].
## A minimal express application
In order to create a minimal express application, we need to install express first. We can do this via the following commands:
```bash
$ mkdir example-app
$ cd example-app
$ npm install express
$ node_modules/.bin/express . -f
$ npm install
$ node app.js
```
So now we have a default express application. If you point your browser to `http://localhost:8080`, you will see a tiny page welcoming you.
Next step: Deploy the application to Heroku.
## Deployment to Heroku
First of all, we need to add the right version of Node.JS and NPM to the `package.json`. The file should look similar to this:
```js
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.1.1",
"jade": "*"
},
"engines": {
"node": "0.8.x",
"npm": "1.1.x"
}
}
```
Now we can create a Heroku application and deploy to it:
```bash
$ echo "web: node app.js" > Procfile
$ echo "node_modules" > .gitignore
$ git init
$ git add .
$ git commit -m "initial commit"
$ heroku create
$ git push heroku master
$ heroku ps:scale web=1
$ heroku open
```
You should now see a browser with the same application as on your local machine.
## Spawning a database on Heroku
In order to get a database on Heroku we can use their CLI. Just run the following command and take a closer look at it's output:
```bash
$ heroku addons:add heroku-postgresql:dev
```
This will result in something like this:
```bash
Adding heroku-postgresql:dev on fast-dusk-7858... done, v5 (free)
Attached as HEROKU_POSTGRESQL_BRONZE_URL
Database has been created and is available
! This database is empty. If upgrading, you can transfer
! data from another database with pgbackups:restore.
Use `heroku addons:docs heroku-postgresql:dev` to view documentation.
```
What we will need is the color (sounds strange right?) of the database. In this case we just created a `bronze` one. That means, that we will have an environment variable `HEROKU_POSTGRESQL_BRONZE_URL` containing the URI of the database.
If you are interested in the URI, you can just run this command:
```bash
$ heroku config:get HEROKU_POSTGRESQL_BRONZE_URL
$ # => postgres://pfforbjhkrletg:aic5oO6Cran1g3hk6mJa5QqNZB@ec2-23-21-91-97.compute-1.amazonaws.com:5432/dek11b2j1g3mfb
```
## Adding Sequelize to the application
The following commands will install `sequelize`, the needed PostgreSQL library as well as the MySQL bindings. Also we will create a folder `models`, that will contain the model definitions.
```bash
$ npm install --save sequelize pg mysql
$ mkdir models
```
### app.js
In order to create a maintainable application, we will put all the database logic into the `models` folder. The application's main file will then just sync the models with the database and run the server. This way we don't clutter the application.
```js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, db = require('./models');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
db.sequelize.sync().then(function() {
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
```
### models/index.js
The idea of this file is to configure a connection to the database and to collect all model definitions. Once everything is in place we will store the stuff in a singleton. This will make it possible to load the file whenever we need database access without running into issues with duplicated database access.
This file will also differ between the local machine and the Heroku server.
```js
if (!global.hasOwnProperty('db')) {
var Sequelize = require('sequelize')
, sequelize = null
if (process.env.HEROKU_POSTGRESQL_BRONZE_URL) {
// the application is executed on Heroku ... use the postgres database
sequelize = new Sequelize(process.env.HEROKU_POSTGRESQL_BRONZE_URL, {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: true //false
})
} else {
// the application is executed on the local machine ... use mysql
sequelize = new Sequelize('example-app-db', 'root', null)
}
global.db = {
Sequelize: Sequelize,
sequelize: sequelize,
User: sequelize.import(__dirname + '/user') 
// add your other models here
}
/*
Associations can be defined here. E.g. like this:
global.db.User.hasMany(global.db.SomethingElse)
*/
}
module.exports = global.db
```
### models/user.js
All the other models of our application will be located as separate files in the `models` folder. We will use the `import`-method of Sequelize to load those files.
```js
module.exports = function(sequelize, DataTypes) {
return sequelize.define("User", {
username: DataTypes.STRING
})
}
```
## Running Migrations
To run migrations on Heroku you must have the following entry in your config/config.json file:
```js
"production": {
"use_env_variable": "DATABASE_URL"
}
```
Which also means you must make sure your Heroku environment has [a promoted database.][3] Then from the command line run
```bash
$ heroku run bash
$ sequelize -m
```
## tl;dr
This article explains a straight-forward but maintainable approach for hosting an express application on Heroku. If you don't want to read all the stuff mentioned, just execute the following stuff and have fun.
```bash
$ mkdir example-app
$ cd example-app
$ npm install express
$ node_modules/.bin/express . -f
$ npm install
$ curl -s https://gist.github.com/sdepold/ced7d2a4a847f38901ef/raw/459c923dd0a14841c932bb95ff3be8a8170bd563/package.json > package.json
$ echo "web: node app.js" > Procfile
$ echo "node_modules" > .gitignore
$ npm install --save sequelize pg mysql
$ mkdir models
$ git init
$ git add .
$ git commit -m "initial commit"
$ heroku create
$ git push heroku master
$ heroku ps:scale web=1
$ heroku addons:add heroku-postgresql:dev
$ curl -s https://gist.github.com/sdepold/ced7d2a4a847f38901ef/raw/6db41e130a8b901cd0843bf52390b7cb11db5f15/app.js > app.js
$ curl -s https://gist.github.com/sdepold/ced7d2a4a847f38901ef/raw/26c5a94d74db4a242464b02aa8e0ae4b3bac6880/models-index.js > models/index.js
$ curl -s https://gist.github.com/sdepold/ced7d2a4a847f38901ef/raw/3b37b0e5d459b2e4b3833a63a018b600a1001795/models-user.js > models/user.js
$ clear
$ # Now run the following command and change HEROKU_POSTGRESQL_BRONZE_URL in
$ # the file "models/index.js" to its result:
$ heroku config|grep HEROKU_POSTGRESQL|cut -d : -f 1
$ git add .
$ git commit -m "sequelize application"
$ git push heroku master
$ heroku open
```
[0]: https://api.heroku.com/signup/devcenter
[1]: https://toolbelt.heroku.com/
[2]: https://devcenter.heroku.com/articles/quickstart
[3]: https://devcenter.heroku.com/articles/heroku-postgresql#establish-primary-db
\ No newline at end of file
# Associations
This section describes the various association types in sequelize. When calling a method such as `User.hasOne(Project)`, we say that the `User` model (the model that the function is being invoked on) is the __source__ and the `Project` model (the model being passed as an argument) is the __target__.
## One-To-One associations
......@@ -285,7 +287,7 @@ User.findAll({
```
## Scopes
This section concerns association scopes. For a definition of association scopes vs. scopes on associated models, see [Scopes](scopes).
This section concerns association scopes. For a definition of association scopes vs. scopes on associated models, see [Scopes](/scopes.html).
Association scopes allow you to place a scope (a set of default attributes for `get` and `create`) on the association. Scopes can be placed both on the associated model (the target of the association), and on the through table for n:m relations.
......
../changelog.md
\ No newline at end of file
@import url(http://fonts.googleapis.com/css?family=Titillium+Web);
table {
width:100%;
}
th:nth-child(1),
td:nth-child(1) {
width: 35%;
word-break: break-all;
}
td:nth-child(2),
td:nth-child(2) {
width: 20%;
word-break: break-word;
}
td,
th {
padding: 6px 13px;
border: 1px solid #ddd;
}
tr:nth-child(2n) {
background-color: #f8f8f8;
}
#teaser-home {
height: 250px;
position: relative;
margin-bottom: 24px;
}
#teaser-home img {
position: absolute;
top: 0;
}
#teaser-home span {
color: #2F406A;
position: absolute;
top: 0;
left: 250px;
font-size: 100px;
display: inline-block;
height: 250px;
line-height: 250px;
font-family: 'Titillium Web', sans-serif;
}
a.toctree-l3 {
margin-left: 0.8em;
}
p > code {
padding: 0;
padding-top: 0.2em;
padding-bottom: 0.2em;
margin: 0;
font-size: 85%;
background-color: rgba(0,0,0,0.04);
border-radius: 3px;
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
}
p > code:before, p > code:after {
letter-spacing: -0.2em;
content: "\00a0";
}
@media screen and (max-width: 768px) {
#teaser-home {
height: auto;
text-align: center;
}
#teaser-home img {
position: relative;
width: 100%;
max-width: 250px;
content:url(/images/logo.png);
}
#teaser-home span {
display: none;
}
}
'use strict';
var dox = require('dox')
, program = require('commander')
, fs = require('fs')
, path = require('path')
, git = require('git')
, _ = require('lodash');
program
.version('0.0.2')
.option('-f, --file [file]', 'Process a single file', '')
.option('-a, --all', 'Process all files, generate index etc. (default if no options are specified')
.option('-o --out [dir]', '', path.dirname(__filename) + '/api')
.parse(process.argv);
var files;
if (program.file) {
files = [{file: program.file, output: 'tmp'}];
} else {
files = [
{file:'lib/errors.js', output: 'errors'},
{file:'lib/sequelize.js', output: 'sequelize'},
{file:'lib/instance.js', output: 'instance'},
{file:'lib/model.js', output: 'model'},
{file:'lib/hooks.js', output: 'hooks'},
{file:'lib/associations/mixin.js', output: 'associations/index'},
{file:'lib/transaction.js', output: 'transaction'},
{file:'lib/data-types.js', output: 'datatypes'},
{file:'lib/deferrable.js', output: 'deferrable'},
{file:'lib/associations/belongs-to-many.js', output: 'associations/belongs-to-many'},
{file:'lib/associations/has-many.js', output: 'associations/has-many'},
{file:'lib/associations/has-one.js', output: 'associations/has-one'},
{file:'lib/associations/belongs-to.js', output: 'associations/belongs-to'}
];
}
var Comment = function(data, file) {
this.data = data;
this.file = file;
this.string = '';
};
Comment.prototype.getTag = function(tagName) {
return _.find(this.data.tags, function (tag) {
return tag.type === tagName;
});
};
Comment.prototype.getTags = function(tagName) {
return _.filter(this.data.tags, { type: tagName });
};
Comment.prototype.hasTag = function(tagName) {
return this.getTag(tagName) !== undefined;
};
Comment.prototype.getName = function () {
var tag = (['name', 'class', 'property', 'method']).reduce(function (tag, tagName) {
return tag || this.getTag(tagName);
}.bind(this), null);
if (tag) {
return tag.string;
}
return this.data.ctx.name;
};
Comment.prototype.getParams = function () {
if (this.isProperty()) {
return '';
}
// Only show params without a dot in them (dots means attributes of object, so no need to clutter the signature too much)
var params = [] ;
this.getTags('param').forEach(function (paramTag) {
if (paramTag.name.indexOf('.') === -1) {
params.push(paramTag.name);
}
});
return '(' + params.join(', ') + ')';
};
Comment.prototype.isProperty = function () {
return !this.hasTag('method') && this.data.ctx && this.data.ctx.type === 'property';
};
Comment.prototype.putString = function(str) {
this.string += str;
};
Comment.prototype.putLine = function(str) {
str = str || '';
this.putString(str + '\n');
};
Comment.prototype.putLines = function(lines) {
lines.forEach(function (line) {
this.putLine(line);
}, this);
};
Comment.prototype.toString = function () {
return this.string + '\n';
};
['class', 'mixin', 'constructor'].forEach(function (prop) {
Comment.prototype['is' + prop.charAt(0).toUpperCase() + prop.slice(1)] = function () {
return this.hasTag(prop);
};
});
Comment.prototype.githubLink = function() {
return 'https://github.com/sequelize/sequelize/blob/' + Comment.commit + '/' + this.file + '#L' + this.data.codeStart;
};
Comment.concatTypes = function (types, convertEntities) {
if (convertEntities === undefined) {
convertEntities = true;
}
var type = types.join('|');
if (type.indexOf('<') !== -1 && type.indexOf('>') === -1) {
// If the string is Array<something|somethingelse> the closing > disappears...
type += '>';
}
if (convertEntities) {
type = Comment.escapeForTable(type);
}
return type;
};
Comment.escapeForTable = function (text) {
// Convert a couple of things to their HTML-entities
// The spacing around | is intentional, in order to introduce some linebreaks in the params table
return text.replace(/\|/g, ' &#124; ')
.replace(/>/g, '&gt;')
.replace(/</g, '&lt;');
};
var parseComments = function (comments, file) {
var output = ''
, comment
, name
, returns
, mixes
, deprecated
, see
, params
, extend
, aliases;
comments.forEach(function (data) {
if (data.tags.length) {
comment = new Comment(data, file);
name = comment.getName();
comment.putLine('<a name="' + name.toLowerCase() + '"></a>');
if (comment.isClass()) {
comment.putLine('# Class ' + name);
} else if (comment.isMixin()) {
comment.putLine('# Mixin ' + name);
} else if (comment.isConstructor()) {
comment.putLine('## `new ' + name + comment.getParams() + '`');
} else {
comment.putString('## `' + name + comment.getParams() + '`');
if (comment.hasTag('return')) {
returns = comment.getTag('return');
var returnType = Comment.concatTypes(returns.types, false); // We don't convert HTML entities since tihs is displayed in a literal block
comment.putString(' -> `' + returnType + '`');
}
comment.putLine();
}
comment.putLine('[View code](' + comment.githubLink() + ')');
comment.putLine();
comment.putLine(comment.data.description.full);
if ((mixes = comment.getTags('mixes')).length) {
comment.putLine('### Mixes:');
mixes.forEach(function (mixin) {
comment.putLine('* ' + mixin.string);
});
}
if (deprecated = comment.getTag('deprecated')) {
comment.putLine('**Deprecated** ' + deprecated.string);
}
if ((see = comment.getTags('see')).length) {
comment.putLine();
comment.putLine('**See:**');
comment.putLine();
var link;
see.forEach(function (see) {
if (see.local) {
link = see.local.match(/{(.*?(?:|#.*?))}/)[1];
comment.putLine('* [' + link + '](' + link.toLowerCase() + ')');
} else {
comment.putLine('* [' + see.title | see.url + '](' + see.url + ')');
}
});
comment.putLine();
}
if (comment.hasTag('param')) {
params = comment.getTags('param');
comment.putLines([
'',
'**Params:**',
'',
'| Name | Type | Description |',
'| ---- | ---- | ----------- |'
]);
var type;
params.forEach(function (param) {
type = Comment.concatTypes(param.types);
comment.putLine('| ' + Comment.escapeForTable(param.name) + ' | ' + type + ' | ' + Comment.escapeForTable(param.description) + ' |');
});
comment.putLine();
}
if (returns && returns.description) {
comment.putLine('__Returns:__ ' + returns.description);
}
if ((aliases = comment.getTags('alias')).length) {
comment.putLine('__Aliases:__ ' + aliases.map(function (a) {
return a.string;
}).join(', '));
}
if (extend = comment.getTag('extends')) {
comment.putLine();
comment.putLine('__Extends:__ ' + extend.otherClass);
}
comment.putLine();
comment.putLine('***');
output += comment.toString();
}
});
output += '_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)_';
return output;
};
var obj, path;
new git.Repo(path.dirname(__filename) + '/..', function (err, repo) {
repo.head(function (err, status) {
Comment.commit = status.commit;
files.forEach(function (file) {
fs.readFile(file.file, function (err, code) {
obj = dox.parseComments(code.toString(), { raw: true});
path = program.out + '/' + file.output + '.md';
console.log(path);
var output = parseComments(obj, file.file);
fs.writeFile(path, output);
});
});
});
});
## Syncing
`sequelize.sync()` will, based on your model definitions, create any missing tables.
If `force: true` it will first drop tables before recreating them.
## Migrations / Manual schema changes
Sequelize has a [sister library](https://github.com/sequelize/umzug) for handling execution and logging of migration tasks.
Sequelize provides a list of ways to programmatically create or change a table schema.
To read more about below functions go to [Migrations section of docs.](migrations)
### createTable
### addColumn
### changeColumn
### removeColumn
### addIndex
### removeIndex
### addConstraint
### removeConstraint
const cheerio = require('cheerio');
const esdocConfig = require('../.esdoc.json');
exports.onHandleHTML = function(ev) {
const $ = cheerio.load(ev.data.html);
const $title = $('head title');
if ($title.text().indexOf(esdocConfig.title) === -1) {
$title.text($title.text() + ' | ' + esdocConfig.title);
}
const $header = $('header');
$header.prepend('<a href="/"><img src="manual/asset/logo-small.png" class="header-logo" /></a>');
$header.append('<div class="search-container"><div class="gcse-search"></div></div>');
$('head').append('<script type="text/javascript" async=true src="https://cse.google.com/cse.js?cx=015434599481993553871:zku_jjbxubw" />');
$('.repo-url-github').after('<a href="http://sequelize-slack.herokuapp.com/" class="slack-link"><img class="slack-logo" src="manual/asset/slack.svg"/>Join us on Slack</a>');
// remove unnecessary scripts
const scripts = ['script/search_index.js', 'script/search.js', 'script/inherited-summary.js', 'script/test-summary.js', 'script/inner-link.js'];
for (const script of scripts) {
$(`script[src="${script}"]`).remove();
}
ev.data.html = $.html();
};
# Getting started
## Installation
Sequelize is available via NPM.
......@@ -35,7 +37,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
var sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
```
The Sequelize constructor takes a whole slew of options that are available via the [API reference](http://sequelize.readthedocs.org/en/latest/api/sequelize/).
The Sequelize constructor takes a whole slew of options that are available via the [API reference](/class/lib/sequelize.js~Sequelize.html).
## Test the connection
......@@ -76,7 +78,7 @@ User.sync({force: true}).then(function () {
});
```
You can read more about creating models at [Model API reference](http://sequelize.readthedocs.org/en/latest/api/model/)
You can read more about creating models at [Model API reference](/class/lib/model.js~Model.html)
## Your first query
......@@ -86,7 +88,7 @@ User.findAll().then(function(users) {
})
```
You can read more about finder functions on models like `.findAll()` at [Data retrieval](http://docs.sequelizejs.com/en/latest/docs/models-usage/) or how to do specific queries like `WHERE` and `JSONB` at [Querying](http://docs.sequelizejs.com/en/latest/docs/querying/).
You can read more about finder functions on models like `.findAll()` at [Data retrieval](/manual/tutorial/models-usage.html#data-retrieval-finders) or how to do specific queries like `WHERE` and `JSONB` at [Querying](/manual/tutorial/querying.html).
### Application wide model options
......
# Hooks
Hooks (also known as callbacks or lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a `beforeUpdate` hook.
For a full list of hooks, see [Hooks API](/api/hooks).
......
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="118px" height="118px" viewBox="0 0 118 118" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
<!-- Generator: Sketch 3.1.1 (8761) - http://www.bohemiancoding.com/sketch -->
<title>Group</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
<g id="Artboard-1" sketch:type="MSArtboardGroup" transform="translate(-42.000000, -47.000000)">
<g id="Group" sketch:type="MSLayerGroup" transform="translate(42.000000, 48.000000)">
<path d="M10.258,61.859 C5.863,61.892 2.14,59.273 0.768,55.186 C0.715,55.027 0.669,54.872 0.625,54.72 C-0.871,49.484 2.03,44.008 7.23,42.255 L90.613,14.32 C91.627,14.029 92.648,13.881 93.659,13.874 C98.17,13.838 101.996,16.515 103.403,20.69 L103.527,21.093 C105.086,26.545 101.211,31.413 96.568,32.973 C96.564,32.975 95.721,33.262 13.646,61.282 C12.535,61.658 11.396,61.849 10.258,61.859" id="Fill-9" fill="#70CADB" sketch:type="MSShapeGroup"></path>
<path d="M24.157,102.867 C19.729,102.899 15.992,100.317 14.636,96.289 C14.586,96.134 14.537,95.979 14.494,95.825 C12.977,90.527 15.874,84.994 21.09,83.237 L104.478,55.045 C105.554,54.686 106.667,54.5 107.785,54.491 C112.227,54.457 116.129,57.17 117.506,61.245 L117.634,61.67 C118.438,64.484 117.963,67.651 116.363,70.148 C115.168,72.007 111.404,73.642 111.404,73.642 L27.698,102.261 C26.533,102.651 25.343,102.856 24.157,102.867" id="Fill-16" fill="#E01765" sketch:type="MSShapeGroup"></path>
<path d="M93.572,103.043 C89.125,103.079 85.186,100.272 83.77,96.067 L55.94,13.402 L55.801,12.937 C54.294,7.667 57.192,2.168 62.391,0.415 C63.43,0.065 64.506,-0.118 65.588,-0.127 C67.196,-0.139 68.752,0.223 70.217,0.947 C72.667,2.167 74.5,4.267 75.375,6.86 L103.203,89.518 L103.284,89.783 C104.846,95.256 101.953,100.759 96.756,102.509 C95.725,102.854 94.653,103.035 93.572,103.043" id="Fill-17" fill="#E8A723" sketch:type="MSShapeGroup"></path>
<path d="M52.205,116.969 C47.758,117.003 43.816,114.197 42.398,109.986 L14.575,27.323 C14.527,27.17 14.48,27.02 14.435,26.863 C12.931,21.593 15.821,16.093 21.018,14.34 C22.053,13.995 23.124,13.814 24.205,13.805 C28.652,13.771 32.592,16.577 34.01,20.784 L61.834,103.449 C61.886,103.595 61.933,103.753 61.975,103.906 C63.482,109.179 60.59,114.682 55.386,116.435 C54.353,116.78 53.284,116.96 52.205,116.969" id="Fill-18" fill="#3EB890" sketch:type="MSShapeGroup"></path>
<path d="M79.852,84.429 L99.257,77.794 L92.914,58.955 L73.486,65.522 L79.852,84.429" id="Fill-19" fill="#CC1F27" sketch:type="MSShapeGroup"></path>
<path d="M38.549,98.551 L57.952,91.917 L51.562,72.935 L32.138,79.502 L38.549,98.551" id="Fill-20" fill="#361238" sketch:type="MSShapeGroup"></path>
<path d="M66.037,43.396 C74.762,40.418 80.994,38.29 85.444,36.771 L79.176,18.151 L59.732,24.665 L66.037,43.396" id="Fill-21" fill="#65863A" sketch:type="MSShapeGroup"></path>
<path d="M24.73,57.498 C31.891,55.054 38.334,52.854 44.137,50.873 L37.791,32.017 L18.348,38.53 L24.73,57.498" id="Fill-22" fill="#1A937D" sketch:type="MSShapeGroup"></path>
</g>
</g>
</g>
</svg>
\ No newline at end of file
# Imprint - Boring legal stuff for the rest of us.
# Imprint
- Boring legal stuff for the rest of us.
As there are people who are suing for fun and glory, you can find the respective information about the author of the page right here. Have fun reading ...
## AUTHOR(S)
......
<div id="teaser-home">
<image src="images/logo-small.png" alt="Sequelize | The Node.js ORM">
<span>Sequelize</span>
</div>
![logo](manual/asset/logo-small.png)
<span class="sequelize">Sequelize</span>
Sequelize is a promise-based ORM for Node.js. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and
[![Travis build](https://img.shields.io/travis/sequelize/sequelize/master.svg?style=flat-square)](https://travis-ci.org/sequelize/sequelize)
[![npm](https://img.shields.io/npm/dm/sequelize.svg?style=flat-square)](https://npmjs.org/package/sequelize)
[![npm](https://img.shields.io/npm/v/sequelize.svg?style=flat-square)](https://github.com/sequelize/sequelize/releases)
Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and
more.
[Installation](docs/getting-started/)
[Installation](manual/installation/getting-started)
## Example usage
......
# Instances
## Building a non-persistent instance
In order to create instances of defined classes just do as follows&period; You might recognize the syntax if you coded Ruby in the past&period; Using the `build`-method will return an unsaved object&comma; which you explicitly have to save&period;
......@@ -288,7 +290,7 @@ Person.findOne({ where: { name: 'john' } }).then(function(person) {
})
```
## Incrementing certain values of an instance
## Incrementing
In order to increment values of an instance without running into concurrency issues&comma; you may use `increment`&period;
......@@ -319,7 +321,7 @@ User.findById(1).then(function(user) {
}).then(/* ... */)
```
## Decrementing certain values of an instance
## Decrementing
In order to decrement values of an instance without running into concurrency issues&comma; you may use `decrement`&period;
......
# Working with legacy tables
While out of the box Sequelize will seem a bit opinionated it's trivial to both legacy and forward proof your application by defining (otherwise generated) table and field names.
## Tables
......
# Migrations
Sequelize `2.0.0` introduces a new CLI which is based on [gulp][0] and combines [sequelize-cli][1] and [gulp-sequelize][2]. The CLI ships support for migrations and project bootstrapping. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe the way how to get to the new state and how to revert the changes in order to get back to the old state.
## The CLI
......
## Definition
# Model definition
To define mappings between a model and a table, use the `define` method. Sequelize will then automatically add the attributes `createdAt` and `updatedAt` to it. So you will be able to know when the database entry went into the db and when it was updated the last time. If you do not want timestamps on your models, only want some timestamps, or you are working with an existing database where the columns are named something else, jump straight on to [configuration ][0]to see how to do that.
......@@ -77,7 +77,7 @@ The comment option can also be used on a table, see [model configuration][0]
## Data types
Below are some of the datatypes supported by sequelize. For a full and updated list, see [DataTypes](../api/datatypes).
Below are some of the datatypes supported by sequelize. For a full and updated list, see [DataTypes](/variable/index.html#static-variable-DataTypes).
```js
Sequelize.STRING // VARCHAR(255)
......@@ -252,7 +252,7 @@ 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](transactions/#options) for further information.
the rule in a transaction. See [the transaction section](/manual/tutorial/transactions.html#options) for further information.
## Getters & setters
......@@ -297,7 +297,7 @@ Employee
### Defining as part of the model options
Below is an example of defining the getters and setters in the model options. The `fullName` getter, is an example of how you can define pseudo properties on your models - attributes which are not actually part of your database schema. In fact, pseudo properties can be defined in two ways: using model getters, or by using a column with the [`VIRTUAL` datatype](../api/datatypes#virtual). Virtual datatypes can have validations, while getters for virtual attributes cannot.
Below is an example of defining the getters and setters in the model options. The `fullName` getter, is an example of how you can define pseudo properties on your models - attributes which are not actually part of your database schema. In fact, pseudo properties can be defined in two ways: using model getters, or by using a column with the [`VIRTUAL` datatype](/variable/index.html#static-variable-DataTypes). Virtual datatypes can have validations, while getters for virtual attributes cannot.
Note that the `this.firstname` and `this.lastname` references in the `fullName` getter function will trigger a call to the respective getter functions. If you do not want that then use the `getDataValue()` method to access the raw value (see below).
......
# Model usage
## Data retrieval / Finders
Finder methods are intended to query data from the database. They do *not* return plain objects but instead return model instances. Because finder methods return model instances you can call any model instance member on the result as described in the documentation for [*instances*](http://docs.sequelizejs.com/en/latest/docs/instances/).
Finder methods are intended to query data from the database. They do *not* return plain objects but instead return model instances. Because finder methods return model instances you can call any model instance member on the result as described in the documentation for [*instances*](/manual/tutorial/instances.html).
In this document we'll explore what finder methods can do:
......
# Querying
## Attributes
To select only some attributes, you can use the `attributes` option. Most often, you pass an array:
......@@ -148,7 +150,7 @@ $col: 'user.organization_id' // = "user"."organization_id", with dialect specifi
Range types can be queried with all supported operators.
Keep in mind, the provided range value can
[define the bound inclusion/exclusion](models-definition/#range-types)
[define the bound inclusion/exclusion](/manual/tutorial/models-definition.html#range-types)
as well.
```js
......
# Raw queries
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function `sequelize.query`.
By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
......@@ -28,7 +30,7 @@ sequelize.query('SELECT * FROM projects', { model: Projects }).then(function(pro
})
```
# Replacements
## Replacements
Replacements in a query can be done in two different ways, either using named parameters (starting with `:`), or unnamed, represented by a `?`. Replacements are passed in the options object.
* If an array is passed, `?` will be replaced in the order that they appear in the array
......@@ -68,8 +70,7 @@ sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',
})
```
# Bind Parameter
## Bind Parameter
Bind parameters are like replacements. Except replacements are escaped and inserted into the query by sequelize before the query is sent to the database, while bind parameters are sent to the database outside the SQL query text. A query can have either bind parameters or replacements.
Only SQLite and PostgreSQL support bind parameters. Other dialects will insert them into the SQL query in the same way it is done for replacements. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.
......
git+https://github.com/dart-lang/py-gfm.git
# Definition
# Scopes
Scoping allows you to define commonly used queries that you can easily use later. Scopes can include all the same attributes as regular finders, `where`, `include`, `limit` etc.
## Definition
Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:
```js
......@@ -71,7 +73,7 @@ activeUsers: {
}
```
# Usage
## Usage
Scopes are applied by calling `.scope` on the model definition, passing the name of one or more scopes. `.scope` returns a fully functional model instance with all the regular methods: `.findAll`, `.update`, `.count`, `.destroy` etc. You can save this model instance and reuse it later:
```js
......@@ -165,7 +167,7 @@ WHERE deleted = true AND firstName = 'john'
Here the `deleted` scope is merged with the finder. If we were to pass `where: { firstName: 'john', deleted: false }` to the finder, the `deleted` scope would be overwritten.
# Associations
## Associations
Sequelize has two different but related scope concepts in relation to associations. The difference is subtle but important:
* **Association scopes** Allow you to specify default attributes when getting and setting associations - useful when implementing polymorphic associations. This scope is only invoked on the association between the two models, when using the `get`, `set`, `add` and `create` associated model functions
......@@ -184,7 +186,7 @@ this.Post.hasMany(this.Comment, {
});
```
When calling `post.getComments()`, this will automatically add `WHERE commentable = 'post'`. Similarly, when adding new comments to a post, `commentable` will automagically be set to `'post'`. The association scope is meant to live in the background without the programmer having to worry about it - it cannot be disabled. For a more complete polymorphic example, see [Association scopes](associations/#scopes)
When calling `post.getComments()`, this will automatically add `WHERE commentable = 'post'`. Similarly, when adding new comments to a post, `commentable` will automagically be set to `'post'`. The association scope is meant to live in the background without the programmer having to worry about it - it cannot be disabled. For a more complete polymorphic example, see [Association scopes](/manual/tutorial/associations.html#scopes)
Consider then, that Post has a default scope which only shows active posts: `where: { active: true }`. This scope lives on the associated model (Post), and not on the association like the `commentable` scope did. Just like the default scope is applied when calling `Post.findAll()`, it is also applied when calling `User.getPosts()` - this will only return the active posts for that user.
......
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-96831523-1', 'auto');
ga('send', 'pageview');
@import url(http://fonts.googleapis.com/css?family=Titillium+Web);
.content span.sequelize {
color: #2F406A;
position: absolute;
top: 30px;
left: 550px;
font-size: 100px;
display: inline-block;
height: 250px;
line-height: 250px;
font-family: 'Titillium Web', sans-serif;
}
.content {
max-width: 1200px;
}
.navigation {
overflow-x: hidden;
}
.manual-root .content img {
box-shadow: none !important;
max-width: 300px;
}
.manual-toc a {
width: 240px;
white-space: pre-wrap;
}
blockquote {
background: #fafafa;
border-left: 10px solid #ddd;
margin: 1.5em 10px;
padding: 0.5em 10px;
}
blockquote p {
margin-bottom: 0;
}
h3#static-variable-DataTypes ~ div[data-ice="properties"] table.params tr td:nth-child(3) {
display: none;
}
h3#static-variable-QueryTypes ~ div[data-ice="properties"] table.params tr td:nth-child(2),
h3#static-variable-QueryTypes ~ div[data-ice="properties"] table.params tr td:nth-child(3),
h3#static-variable-QueryTypes ~ div[data-ice="properties"] table.params tr td:nth-child(4) {
display: none;
}
.manual-badge,
.manual-cards {
display: none !important;
}
a[href="source.html"],
a[href^="file/lib/"] {
display: none;
}
.search-box {
display: none;
}
.search-container {
position: absolute;
width: 500px;
top: 0;
right: 50px;
padding-right: 8px;
padding-bottom: 10px;
line-height: normal;
font-size: 12px;
}
.search-container .gsc-control-cse {
padding: 2px 0 0 0 !important;
}
.manual-color:after {
content: '' !important;
}
.slack-logo {
height: 20px;
position: relative;
top: 3px;
padding: 0 5px;
}
.header-logo {
height: 25px;
position: relative;
top: 6px;
}
# Transactions
Sequelize supports two ways of using transactions:
* One which will automatically commit or rollback the transaction based on the result of a promise chain and, (if enabled) pass the transaction to all calls within the callback
......@@ -5,7 +7,7 @@ Sequelize supports two ways of using transactions:
The key difference is that the managed transaction uses a callback that expects a promise to be returned to it while the unmanaged transaction returns a promise.
# Managed transaction (auto-callback)
## Managed transaction (auto-callback)
Managed transactions handle committing or rolling back the transaction automagically. You start a managed transaction by passing a callback to `sequelize.transaction`.
......@@ -93,7 +95,7 @@ sequelize.transaction(function (t1) {
After you've used `Sequelize.useCLS()` all promises returned from sequelize will be patched to maintain CLS context. CLS is a complicated subject - more details in the docs for [cls-bluebird](https://www.npmjs.com/package/cls-bluebird), the patch used to make bluebird promises work with CLS.
# Concurrent/Partial transactions
## Concurrent/Partial transactions
You can have concurrent transactions within a sequence of queries or have some of them excluded from any transactions. Use the `{transaction: }` option to control which transaction a query belong to:
......@@ -112,7 +114,7 @@ sequelize.transaction(function (t1) {
});
```
# Isolation levels
## Isolation levels
The possible isolations levels to use when starting a transaction:
```js
......@@ -136,7 +138,7 @@ return sequelize.transaction({
Note: The SET ISOLATION LEVEL queries are not logged in case of MSSQL as the specified isolationLevel is passed directly to tedious
# 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. Notice that `commit()` and `rollback()` returns a promise.
```js
......@@ -157,7 +159,7 @@ return sequelize.transaction().then(function (t) {
});
```
# Options
## Options
The `transaction` method can be called with an options object as the first argument, that
allows the configuration of the transaction.
......@@ -207,7 +209,7 @@ sequelize.transaction({
})
```
# Usage with other sequelize methods
## Usage with other sequelize methods
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.
......
# Who's using sequelize?
[![Walmart labs logo](asset/walmart-labs-logo.png)](http://www.walmartlabs.com/)
> ... we are avid users of sequelize (and have been for the past 18 months) (Feb 2017)
[![Snaplytics logo](asset/logo-snaplytics-green.png)](https://snaplytics.io)
> We've been using sequelize since we started in the beginning of 2015. We use it for our graphql servers (in connection with [graphql-sequelize](github.com/mickhansen/graphql-sequelize)), and for all our background workers.
[![Connected Cars logo](asset/connected-cars.png)](https://connectedcars.dk/)
'use strict';
const AssociationError = require('./../errors').AssociationError;
/**
* Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).
*
* * hasOne - adds a foreign key to the target and singular association mixins to the source.
* * belongsTo - add a foreign key and singular association mixins to the source.
* * hasMany - adds a foreign key to target and plural association mixins to the source.
* * belongsToMany - creates an N:M association with a join table and adds plural association mixins to the source. The junction table is created with sourceId and targetId.
*
* Creating an association will add a foreign key constraint to the attributes. All associations use `CASCADE` on update and `SET NULL` on delete, except for n:m, which also uses `CASCADE` on delete.
*
* When creating associations, you can provide an alias, via the `as` option. This is useful if the same model is associated twice, or you want your association to be called something other than the name of the target model.
*
* As an example, consider the case where users have many pictures, one of which is their profile picture. All pictures have a `userId`, but in addition the user model also has a `profilePictureId`, to be able to easily load the user's profile picture.
*
* ```js
* User.hasMany(Picture)
* User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false })
*
* user.getPictures() // gets you all pictures
* user.getProfilePicture() // gets you only the profile picture
*
* User.findAll({
* where: ...,
* include: [
* { model: Picture }, // load all pictures
* { model: Picture, as: 'ProfilePicture' }, // load the profile picture.
* // Notice that the spelling must be the exact same as the one in the association
* ]
* })
* ```
* To get full control over the foreign key column added by sequelize, you can use the `foreignKey` option. It can either be a string, that specifies the name, or and object type definition,
* equivalent to those passed to `sequelize.define`.
*
* ```js
* User.hasMany(Picture, { foreignKey: 'uid' })
* ```
*
* The foreign key column in Picture will now be called `uid` instead of the default `userId`.
*
* ```js
* User.hasMany(Picture, {
* foreignKey: {
* name: 'uid',
* allowNull: false
* }
* })
* ```
*
* This specifies that the `uid` column cannot be null. In most cases this will already be covered by the foreign key constraints, which sequelize creates automatically, but can be useful in case where the foreign keys are disabled, e.g. due to circular references (see `constraints: false` below).
*
* When fetching associated models, you can limit your query to only load some models. These queries are written in the same way as queries to `find`/`findAll`. To only get pictures in JPG, you can do:
*
* ```js
* user.getPictures({
* where: {
* format: 'jpg'
* }
* })
* ```
*
* There are several ways to update and add new associations. Continuing with our example of users and pictures:
* ```js
* user.addPicture(p) // Add a single picture
* user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be deleted
* user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current associations
* ```
*
* You don't have to pass in a complete object to the association functions, if your associated model has a single primary key:
*
* ```js
* user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture
* ```
*
* In the example above we have specified that a user belongs to his profile picture. Conceptually, this might not make sense, but since we want to add the foreign key to the user model this is the way to do it.
*
* Note how we also specified `constraints: false` for profile picture. This is because we add a foreign key from user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys to both, it would create a cyclic dependency, and sequelize would not know which table to create first, since user depends on picture, and picture depends on user. These kinds of problems are detected by sequelize before the models are synced to the database, and you will get an error along the lines of `Error: Cyclic dependency found. 'users' is dependent of itself`. If you encounter this, you should either disable some constraints, or rethink your associations completely.
*/
class Association {
constructor(source, target, options) {
options = options || {};
/**
* @type {Model}
*/
this.source = source;
/**
* @type {Model}
*/
this.target = target;
this.options = options;
this.scope = options.scope;
this.isSelfAssociation = this.source === this.target;
this.as = options.as;
/**
* The type of the association. One of `HasMany`, `BelongsTo`, `HasOne`, `BelongsToMany`
* @type {string}
*/
this.associationType = '';
if (source.hasAlias(options.as)) {
throw new AssociationError(`You have used the alias ${options.as} in two separate associations. ` +
......
......@@ -22,7 +22,7 @@ const AssociationError = require('../errors').AssociationError;
* Project.belongsToMany(User, { through: UserProject });
* // through is required!
*
* user.addProject(project, { through: { role: 'manager', transaction: t }});
* user.addProject(project, { through: { role: 'manager' }});
* ```
*
* All methods allow you to pass either a persisted instance, its primary key, or a mixture:
......@@ -33,10 +33,24 @@ const AssociationError = require('../errors').AssociationError;
* });
* ```
*
* In the API reference below, replace `Assocation(s)` with the actual name of your association, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
* If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
*
* @class BelongsToMany
* @memberof Associations
* ```js
* p1.UserProjects = {
* started: true
* }
* user.setProjects([p1, p2], { through: { started: false }}) // The default value is false, but p1 overrides that.
* ```
*
* Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
* ```js
* user.getProjects().then(function (projects) {
* let p1 = projects[0]
* p1.UserProjects.started // Is this project started yet?
* })
* ```
*
* In the API reference below, add the name of the association to the method, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
*
* @see {@link Model.belongsToMany}
*/
......@@ -196,126 +210,15 @@ class BelongsToMany extends Association {
const singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model#findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
* @method getAssociations
* @memberof Associations.BelongsToMany
* @instance
*/
get: 'get' + plural,
/**
* Set the associated models by passing an array of instances or their primary keys. Everything that it not in the passed array will be un-associated.
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
* @param {Object} [options.validate] Run validation for the join model
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
* @method setAssociations
* @memberof Associations.BelongsToMany
* @instance
*/
set: 'set' + plural,
/**
* Associate several persisted instances with this.
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this.
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
* @method addAssociations
* @memberof Associations.BelongsToMany
* @instance
*/
addMultiple: 'add' + plural,
/**
* Associate a persisted instance with this.
*
* @param {Model|String|Number} [newAssociation] A persisted instance or primary key of instance to associate with this.
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
* @method addAssociation
* @memberof Associations.BelongsToMany
* @instance
*/
add: 'add' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to create and add
* @param {Object} [options.through] Additional attributes for the join table
* @return {Promise}
* @method createAssociation
* @memberof Associations.BelongsToMany
* @instance
*/
create: 'create' + singular,
/**
* Un-associate the instance.
*
* @param {Model|String|Number} [oldAssociated] Can be an Instance or its primary key
* @param {Object} [options] Options passed to `through.destroy`
* @return {Promise}
* @method removeAssociation
* @memberof Associations.BelongsToMany
* @instance
*/
remove: 'remove' + singular,
/**
* Un-associate several instances.
*
* @param {Array<Model|String|Number>} [oldAssociated] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to `through.destroy`
* @return {Promise}
* @method removeAssociations
* @memberof Associations.BelongsToMany
* @instance
*/
removeMultiple: 'remove' + plural,
/**
* Check if an instance is associated with this.
*
* @param {Model|String|Number} [instance] Can be an Instance or its primary key
* @param {Object} [options] Options passed to getAssociations
* @return {Promise}
* @method hasAssociation
* @memberof Associations.BelongsToMany
* @instance
*/
hasSingle: 'has' + singular,
/**
* Check if all instances are associated with this.
*
* @param {Array<Model|String|Number>} [instances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations
* @return {Promise}
* @method hasAssociations
* @memberof Associations.BelongsToMany
* @instance
*/
hasAll: 'has' + plural,
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>}
* @method countAssociations
* @memberof Associations.BelongsToMany
* @instance
*/
count: 'count' + plural
};
}
......@@ -457,6 +360,16 @@ class BelongsToMany extends Association {
Helpers.mixinMethods(this, obj, methods, aliases);
}
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
*/
get(instance, options) {
options = Utils.cloneDeep(options) || {};
......@@ -516,6 +429,14 @@ class BelongsToMany extends Association {
return model.findAll(options);
}
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>}
*/
count(instance, options) {
const association = this;
const model = association.target;
......@@ -532,6 +453,13 @@ class BelongsToMany extends Association {
return association.get(instance, options).then(result => parseInt(result.count, 10));
}
/**
* Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated
*
* @param {Model[]|Model|string[]|String|number[]|Number} [instance(s)] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations
* @return {Promise<boolean>}
*/
has(sourceInstance, instances, options) {
const association = this;
const where = {};
......@@ -566,6 +494,15 @@ class BelongsToMany extends Association {
return association.get(sourceInstance, options).then(associatedObjects => associatedObjects.length === instances.length);
}
/**
* Set the associated models by passing an array of instances or their primary keys. Everything that it not in the passed array will be un-associated.
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
* @param {Object} [options.validate] Run validation for the join model
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
*/
set(sourceInstance, newAssociatedObjects, options) {
options = options || {};
......@@ -650,6 +587,15 @@ class BelongsToMany extends Association {
});
}
/**
* Associate one ore several rows with `this`.
*
* @param {Model[]|Model|string[]|string|number[]|Number} [newAssociation(s)] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
*/
add(sourceInstance, newInstances, options) {
// If newInstances is null or undefined, no-op
if (!newInstances) return Utils.Promise.resolve();
......@@ -725,6 +671,13 @@ class BelongsToMany extends Association {
});
}
/**
* Un-associate one or more instance(s).
*
* @param {Model|String|Number} [oldAssociated] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `through.destroy`
* @return {Promise}
*/
remove(sourceInstance, oldAssociatedObjects, options) {
const association = this;
......@@ -739,6 +692,14 @@ class BelongsToMany extends Association {
return association.through.model.destroy(_.defaults({where}, options));
}
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to create and add
* @param {Object} [options.through] Additional attributes for the join table
* @return {Promise}
*/
create(sourceInstance, values, options) {
const association = this;
......
......@@ -9,10 +9,7 @@ const Association = require('./base');
/**
* One-to-one association
*
* In the API reference below, replace `Assocation` with the actual name of your association, e.g. for `User.belongsTo(Project)` the getter will be `user.getProject()`.
*
* @class BelongsTo
* @memberof Associations
* In the API reference below, add the name of the association to the method, e.g. for `User.belongsTo(Project)` the getter will be `user.getProject()`.
*
* @see {@link Model.belongsTo}
*/
......@@ -69,39 +66,8 @@ class BelongsTo extends Association {
const singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findOne} for a full explanation of options
* @return {Promise<Model>}
* @method getAssociation
* @memberof Associations.BelongsTo
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @return {Promise}
* @method setAssociation
* @memberof Associations.BelongsTo
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @see {@link Model#create} for a full explanation of options
* @return {Promise}
* @method createAssociation
* @memberof Associations.BelongsTo
*/
create: 'create' + singular
};
}
......@@ -139,6 +105,15 @@ class BelongsTo extends Association {
Helpers.mixinMethods(this, obj, methods);
}
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findOne} for a full explanation of options
* @return {Promise<Model>}
*/
get(instances, options) {
const association = this;
const where = {};
......@@ -199,6 +174,14 @@ class BelongsTo extends Association {
return Target.findOne(options);
}
/**
* Set the associated model.
*
* @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @return {Promise}
*/
set(sourceInstance, associatedInstance, options) {
const association = this;
......@@ -223,6 +206,14 @@ class BelongsTo extends Association {
return sourceInstance.save(options);
}
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @see {@link Model#create} for a full explanation of options
* @return {Promise}
*/
create(sourceInstance, values, fieldsOrOptions) {
const association = this;
......
......@@ -8,10 +8,8 @@ const Association = require('./base');
/**
* One-to-many association
*
* In the API reference below, replace `Association(s)` with the actual name of your association, e.g. for `User.hasMany(Project)` the getter will be `user.getProjects()`.
*
* @class HasMany
* @memberof Associations
* In the API reference below, add the name of the association to the method, e.g. for `User.hasMany(Project)` the getter will be `user.getProjects()`.
* If the association is aliased, use the alias instead, e.g. `User.hasMany(Project, { as: 'jobs' })` will be `user.getJobs()`.
*
* @see {@link Model.hasMany}
*/
......@@ -99,112 +97,15 @@ class HasMany extends Association {
const singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model#findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
* @method getAssociations
* @memberof Associations.HasMany
*/
get: 'get' + plural,
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
* @method setAssociations
* @memberof Associations.HasMany
*/
set: 'set' + plural,
/**
* Associate several persisted instances with this.
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this.
* @param {Object} [options] Options passed to `target.update`.
* @param {Object} [options.validate] Run validation for the join model.
* @return {Promise}
* @method addAssociations
* @memberof Associations.HasMany
*/
addMultiple: 'add' + plural,
/**
* Associate a persisted instance with this.
*
* @param {Model|String|Number} [newAssociation] A persisted instance or primary key of instance to associate with this.
* @param {Object} [options] Options passed to `target.update`.
* @param {Object} [options.validate] Run validation for the join model.
* @return {Promise}
* @method addAssociation
* @memberof Associations.HasMany
*/
add: 'add' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create`.
* @return {Promise}
* @method createAssociation
* @memberof Associations.HasMany
*/
create: 'create' + singular,
/**
* Un-associate the instance.
*
* @param {Model|String|Number} [oldAssociated] Can be an Instance or its primary key
* @param {Object} [options] Options passed to `target.update`
* @return {Promise}
* @method removeAssociation
* @memberof Associations.HasMany
*/
remove: 'remove' + singular,
/**
* Un-associate several instances.
*
* @param {Array<Model|String|Number>} [oldAssociatedArray] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to `through.destroy`
* @return {Promise}
* @method removeAssociations
* @memberof Associations.HasMany
*/
removeMultiple: 'remove' + plural,
/**
* Check if an instance is associated with this.
*
* @param {Model|String|Number} [instance] Can be an Instance or its primary key
* @param {Object} [options] Options passed to getAssociations
* @return {Promise}
* @method hasAssociation
* @memberof Associations.HasMany
*/
hasSingle: 'has' + singular,
/**
* Check if all instances are associated with this.
*
* @param {Array<Model|String|Number>} [instances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations
* @return {Promise}
* @method hasAssociations
* @memberof Associations.HasMany
*/
hasAll: 'has' + plural,
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>}
* @method countAssociations
* @memberof Associations.HasMany
*/
count: 'count' + plural
};
}
......@@ -250,6 +151,16 @@ class HasMany extends Association {
Helpers.mixinMethods(this, obj, methods, aliases);
}
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
*/
get(instances, options) {
const association = this;
const where = {};
......@@ -323,6 +234,14 @@ class HasMany extends Association {
});
}
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>}
*/
count(instance, options) {
const association = this;
const model = association.target;
......@@ -338,6 +257,13 @@ class HasMany extends Association {
return association.get(instance, options).then(result => parseInt(result.count, 10));
}
/**
* Check if one or more rows are associated with `this`.
*
* @param {Model[]|Model|string[]|String|number[]|Number} [instance(s)]
* @param {Object} [options] Options passed to getAssociations
* @return {Promise}
*/
has(sourceInstance, targetInstances, options) {
const association = this;
const where = {};
......@@ -371,6 +297,14 @@ class HasMany extends Association {
return association.get(sourceInstance, options).then(associatedObjects => associatedObjects.length === targetInstances.length);
}
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
*/
set(sourceInstance, targetInstances, options) {
const association = this;
......@@ -436,6 +370,14 @@ class HasMany extends Association {
});
}
/**
* Associate one or more target rows with `this`. This method accepts a Model / string / number to associate a single row,
* or a mixed array of Model / string / numbers to associate multiple rows.
*
* @param {Model[]|Model|string[]|string|number[]|number} [newAssociation(s)]
* @param {Object} [options] Options passed to `target.update`.
* @return {Promise}
*/
add(sourceInstance, targetInstances, options) {
if (!targetInstances) return Utils.Promise.resolve();
......@@ -457,6 +399,13 @@ class HasMany extends Association {
return association.target.unscoped().update(update, _.defaults({where}, options)).return(sourceInstance);
}
/**
* Un-associate one or several target rows.
*
* @param {Model[]|Model|String[]|string|Number[]|number} [oldAssociatedInstance(s)]
* @param {Object} [options] Options passed to `target.update`
* @return {Promise}
*/
remove(sourceInstance, targetInstances, options) {
const association = this;
const update = {};
......@@ -475,6 +424,13 @@ class HasMany extends Association {
return association.target.unscoped().update(update, _.defaults({where}, options)).return(this);
}
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create`.
* @return {Promise}
*/
create(sourceInstance, values, options) {
const association = this;
......
......@@ -8,11 +8,8 @@ const Association = require('./base');
/**
* One-to-one association
*
* In the API reference below, replace `Association` with the actual name of your association, e.g. for `User.hasOne(Project)` the getter will be `user.getProject()`.
* This is almost the same as `belongsTo` with one exception. The foreign key will be defined on the target model.
*
* @class HasOne
* @memberof Associations
* In the API reference below, add the name of the association to the method, e.g. for `User.hasOne(Project)` the getter will be `user.getProject()`.
* This is almost the same as `belongsTo` with one exception - The foreign key will be defined on the target model.
*
* @see {@link Model.hasOne}
*/
......@@ -66,38 +63,8 @@ class HasOne extends Association {
const singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model#findOne} for a full explanation of options
* @return {Promise<Model>}
* @method getAssociation
* @memberof Associations.HasOne
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of a persisted instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
* @return {Promise}
* @method setAssociation
* @memberof Associations.HasOne
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @see {@link Model#create} for a full explanation of options
* @return {Promise}
* @method createAssociation
* @memberof Associations.HasOne
*/
create: 'create' + singular
};
}
......@@ -137,6 +104,15 @@ class HasOne extends Association {
Helpers.mixinMethods(this, obj, methods);
}
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findOne} for a full explanation of options
* @return {Promise<Model>}
*/
get(instances, options) {
const association = this;
const where = {};
......@@ -195,6 +171,13 @@ class HasOne extends Association {
return Target.findOne(options);
}
/**
* Set the associated model.
*
* @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of a persisted instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
* @return {Promise}
*/
set(sourceInstance, associatedInstance, options) {
const association = this;
......@@ -238,6 +221,14 @@ class HasOne extends Association {
});
}
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @see {@link Model#create} for a full explanation of options
* @return {Promise}
*/
create(sourceInstance, values, options) {
const association = this;
......
......@@ -48,6 +48,7 @@ exports.addForeignKeyConstraints = addForeignKeyConstraints;
/**
* Mixin (inject) association methods to model prototype
*
* @private
* @param {Object} Association instance
* @param {Object} Model prototype
* @param {Array} Method names to inject
......
......@@ -7,104 +7,7 @@ const HasMany = require('./has-many');
const BelongsToMany = require('./belongs-to-many');
const BelongsTo = require('./belongs-to');
/**
* Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).
*
* * hasOne - adds a foreign key to the target and singular association mixins to the source.
* * belongsTo - add a foreign key and singular association mixins to the source.
* * hasMany - adds a foreign key to target and plural association mixins to the source.
* * belongsToMany - creates an N:M association with a join table and adds plural association mixins to the source. The junction table is created with sourceId and targetId.
*
* Creating an association will add a foreign key constraint to the attributes. All associations use `CASCADE` on update and `SET NULL` on delete, except for n:m, which also uses `CASCADE` on delete.
*
* When creating associations, you can provide an alias, via the `as` option. This is useful if the same model is associated twice, or you want your association to be called something other than the name of the target model.
*
* As an example, consider the case where users have many pictures, one of which is their profile picture. All pictures have a `userId`, but in addition the user model also has a `profilePictureId`, to be able to easily load the user's profile picture.
*
* ```js
* User.hasMany(Picture)
* User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false })
*
* user.getPictures() // gets you all pictures
* user.getProfilePicture() // gets you only the profile picture
*
* User.findAll({
* where: ...,
* include: [
* { model: Picture }, // load all pictures
* { model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be the exact same as the one in the association
* ]
* })
* ```
* To get full control over the foreign key column added by sequelize, you can use the `foreignKey` option. It can either be a string, that specifies the name, or and object type definition,
* equivalent to those passed to `sequelize.define`.
*
* ```js
* User.hasMany(Picture, { foreignKey: 'uid' })
* ```
*
* The foreign key column in Picture will now be called `uid` instead of the default `userId`.
*
* ```js
* User.hasMany(Picture, {
* foreignKey: {
* name: 'uid',
* allowNull: false
* }
* })
* ```
*
* This specifies that the `uid` column cannot be null. In most cases this will already be covered by the foreign key constraints, which sequelize creates automatically, but can be useful in case where the foreign keys are disabled, e.g. due to circular references (see `constraints: false` below).
*
* When fetching associated models, you can limit your query to only load some models. These queries are written in the same way as queries to `find`/`findAll`. To only get pictures in JPG, you can do:
*
* ```js
* user.getPictures({
* where: {
* format: 'jpg'
* }
* })
* ```
*
* There are several ways to update and add new associations. Continuing with our example of users and pictures:
* ```js
* user.addPicture(p) // Add a single picture
* user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be deleted
* user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current associations
* ```
*
* You don't have to pass in a complete object to the association functions, if your associated model has a single primary key:
*
* ```js
* user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture
* ```
*
* In the example above we have specified that a user belongs to his profile picture. Conceptually, this might not make sense, but since we want to add the foreign key to the user model this is the way to do it.
*
* Note how we also specified `constraints: false` for profile picture. This is because we add a foreign key from user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys to both, it would create a cyclic dependency, and sequelize would not know which table to create first, since user depends on picture, and picture depends on user. These kinds of problems are detected by sequelize before the models are synced to the database, and you will get an error along the lines of `Error: Cyclic dependency found. 'users' is dependent of itself`. If you encounter this, you should either disable some constraints, or rethink your associations completely.
*
* @namespace Associations
* @name Associations
*/
const Mixin = {
/**
* Creates a 1:m association between this (the source) and the provided target. The foreign key is added on the target.
*
* Example: `User.hasMany(Profile)`. This will add userId to the profile table.
*
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {string|object} [options.as] The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
* @param {string} [options.sourceKey] The name of the field to use as the key for the association in the source table. Defaults to the primary key of the source table
* @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @returns {Associations.HasMany}
* @memberof Model
*/
hasMany(target, options) { // testhint options:none
if (!target.prototype || !(target.prototype instanceof this.sequelize.Model)) {
throw new Error(this.name + '.hasMany called with something that\'s not a subclass of Sequelize.Model');
......@@ -129,63 +32,6 @@ const Mixin = {
return association;
},
/**
* Create an N:M association with a join table.
*
* ```js
* User.belongsToMany(Project, { through: 'UserProjects' })
* Project.belongsToMany(User, { through: 'UserProjects' })
* ```
* Defining `through` is required. Sequelize would previously attempt to auto generate names but that would not always lead to the most logical setups.
*
* If you define a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before with a join table that stores whether the project has been started yet:
* ```js
* let UserProjects = sequelize.define('UserProjects', {
* started: Sequelize.BOOLEAN
* })
* User.belongsToMany(Project, { through: UserProjects })
* Project.belongsToMany(User, { through: UserProjects })
* ```
* ```js
* jan.addProject(homework, { started: false }) // The homework project is not started yet
* jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started
* ```
*
* If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
*
* ```js
* p1.UserProjects = {
* started: true
* }
* user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
* ```
*
* Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
* ```js
* user.getProjects().then(function (projects) {
* let p1 = projects[0]
* p1.UserProjects.started // Is this project started yet?
* })
* ```
*
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {Model|string|object} [options.through] The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.
* @param {Model} [options.through.model] The model used to join both sides of the N:M association.
* @param {object} [options.through.scope] A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model)
* @param {boolean} [options.through.unique=true] If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes)
* @param {string|object} [options.as] The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the join table (representing the source model) or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
* @param {string|object} [options.otherKey] The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target
* @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
* @param {boolean} [options.timestamps=sequelize.options.timestamps] Should the join model have timestamps
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @returns {Associations.BelongsToMany}
* @memberof Model
*/
belongsToMany(targetModel, options) { // testhint options:none
if (!targetModel.prototype || !(targetModel.prototype instanceof this.sequelize.Model)) {
throw new Error(this.name + '.belongsToMany called with something that\'s not a subclass of Sequelize.Model');
......@@ -253,43 +99,8 @@ function singleLinked(Type) {
};
}
/**
* 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.
*
* @method hasOne
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @returns {Associations.HasOne}
* @memberof Model
*/
Mixin.hasOne = singleLinked(HasOne);
/**
* 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.
*
* @method belongsTo
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the source table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target
* @param {string} [options.targetKey] The name of the field to use as the key for the association in the target table. Defaults to the primary key of the target table
* @param {string} [options.onDelete='SET&nbsp;NULL|NO&nbsp;ACTION'] SET NULL if foreignKey allows nulls, NO ACTION if otherwise
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @returns {Associations.BelongsTo}
* @memberof Model
*/
Mixin.belongsTo = singleLinked(BelongsTo);
module.exports = Mixin;
......
'use strict';
/*jshint -W110 */
const util = require('util');
const inherits = require('./utils/inherits');
......@@ -12,51 +11,6 @@ const momentTz = require('moment-timezone');
const moment = require('moment');
const Utils = require('./utils');
/**
* A convenience class holding commonly used data types. The datatypes are used when defining a new model using `Sequelize.define`, like this:
* ```js
* sequelize.define('model', {
* column: DataTypes.INTEGER
* })
* ```
* When defining a model you can just as easily pass a string as type, but often using the types defined here is beneficial. For example, using `DataTypes.BLOB`, mean
* that that column will be returned as an instance of `Buffer` when being fetched by sequelize.
*
* Some data types have special properties that can be accessed in order to change the data type.
* For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`.
* The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as well. The available properties are listed under each data type.
*
* To provide a length for the data type, you can invoke it like a function: `INTEGER(2)`
*
* Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not be used to define types. Instead they are used as shorthands for
* defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:
* ```js
* sequelize.define('model', {
* uuid: {
* type: DataTypes.UUID,
* defaultValue: DataTypes.UUIDV1,
* primaryKey: true
* }
* })
* ```
* There may be times when you want to generate your own UUID conforming to some other algorithm. This is accomplised
* using the defaultValue property as well, but instead of specifying one of the supplied UUID types, you return a value
* from a function.
* ```js
* sequelize.define('model', {
* uuid: {
* type: DataTypes.UUID,
* defaultValue: function() {
* return generateMyId()
* },
* primaryKey: true
* }
* })
* ```
*
* @namespace DataTypes
*/
function ABSTRACT() {}
ABSTRACT.prototype.dialectTypes = '';
......@@ -80,12 +34,6 @@ ABSTRACT.prototype.stringify = function stringify(value, options) {
return value;
};
/**
* A variable length string. Default length 255
*
* @property BINARY
* @memberof DataTypes
*/
function STRING(length, binary) {
const options = typeof length === 'object' && length || {length, binary};
......@@ -119,13 +67,6 @@ Object.defineProperty(STRING.prototype, 'BINARY', {
}
});
/**
* A fixed length string. Default length 255
*
* Available properties: `BINARY`
*
* @memberof DataTypes
*/
function CHAR(length, binary) {
const options = typeof length === 'object' && length || {length, binary};
......@@ -139,11 +80,6 @@ CHAR.prototype.toSql = function toSql() {
return 'CHAR(' + this._length + ')' + (this._binary ? ' BINARY' : '');
};
/**
* An (un)limited length text column. Available lengths: `tiny`, `medium`, `long`
*
* @memberof DataTypes
*/
function TEXT(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof TEXT)) return new TEXT(options);
......@@ -226,13 +162,6 @@ Object.defineProperty(NUMBER.prototype, 'ZEROFILL', {
}
});
/**
* A 32 bit integer.
*
* @property UNSIGNED
* @property ZEROFILL
* @memberof DataTypes
*/
function INTEGER(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof INTEGER)) return new INTEGER(options);
......@@ -249,16 +178,6 @@ INTEGER.prototype.validate = function validate(value) {
return true;
};
/**
* A 64 bit integer.
*
* Note: an attribute defined as `BIGINT` will be treated like a `string` due this [feature from node-postgres](https://github.com/brianc/node-postgres/pull/353) to prevent precision loss. To have this attribute as a `number`, this is a possible [workaround](https://github.com/sequelize/sequelize/issues/2383#issuecomment-58006083).
*
* @property UNSIGNED
* @property ZEROFILL
* @memberof DataTypes
*/
function BIGINT(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof BIGINT)) return new BIGINT(options);
......@@ -275,13 +194,6 @@ BIGINT.prototype.validate = function validate(value) {
return true;
};
/**
* Floating point number (4-byte precision). Accepts one or two arguments for precision
*
* @property UNSIGNED
* @property ZEROFILL
* @memberof DataTypes
*/
function FLOAT(length, decimals) {
const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof FLOAT)) return new FLOAT(options);
......@@ -298,13 +210,6 @@ FLOAT.prototype.validate = function validate(value) {
return true;
};
/**
* Floating point number (4-byte precision). Accepts one or two arguments for precision
*
* @property UNSIGNED
* @property ZEROFILL
* @memberof DataTypes
*/
function REAL(length, decimals) {
const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof REAL)) return new REAL(options);
......@@ -314,13 +219,6 @@ inherits(REAL, NUMBER);
REAL.prototype.key = REAL.key = 'REAL';
/**
* Floating point number (8-byte precision). Accepts one or two arguments for precision
*
* @property UNSIGNED
* @property ZEROFILL
* @memberof DataTypes
*/
function DOUBLE(length, decimals) {
const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof DOUBLE)) return new DOUBLE(options);
......@@ -330,13 +228,6 @@ inherits(DOUBLE, NUMBER);
DOUBLE.prototype.key = DOUBLE.key = 'DOUBLE PRECISION';
/**
* Decimal number. Accepts one or two arguments for precision
*
* @property UNSIGNED
* @property ZEROFILL
* @memberof DataTypes
*/
function DECIMAL(precision, scale) {
const options = typeof precision === 'object' && precision || {precision, scale};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
......@@ -375,11 +266,6 @@ for (const floating of [FLOAT, DOUBLE, REAL]) {
};
}
/**
* A boolean / tinyint column, depending on dialect
*
* @memberof DataTypes
*/
function BOOLEAN() {
if (!(this instanceof BOOLEAN)) return new BOOLEAN();
}
......@@ -397,12 +283,6 @@ BOOLEAN.prototype.validate = function validate(value) {
return true;
};
/**
* A time column
*
* @memberof DataTypes
*/
function TIME() {
if (!(this instanceof TIME)) return new TIME();
}
......@@ -413,11 +293,6 @@ TIME.prototype.toSql = function toSql() {
return 'TIME';
};
/**
* A datetime column
*
* @memberof DataTypes
*/
function DATE(length) {
const options = typeof length === 'object' && length || {length};
......@@ -461,12 +336,6 @@ DATE.prototype._stringify = function _stringify(date, options) {
return date.format('YYYY-MM-DD HH:mm:ss.SSS Z');
};
/**
* A date only column
*
* @memberof DataTypes
*/
function DATEONLY() {
if (!(this instanceof DATEONLY)) return new DATEONLY();
}
......@@ -481,12 +350,6 @@ DATEONLY.prototype._stringify = function _stringify(date) {
return moment(date).format('YYYY-MM-DD');
};
/**
* A key / value column. Only available in postgres.
*
* @memberof DataTypes
*/
function HSTORE() {
if (!(this instanceof HSTORE)) return new HSTORE();
}
......@@ -501,12 +364,6 @@ HSTORE.prototype.validate = function validate(value) {
return true;
};
/**
* A JSON string column. Only available in postgres and sqlite.
*
* @function JSON
* @memberof DataTypes
*/
function JSONTYPE() {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
}
......@@ -521,11 +378,6 @@ JSONTYPE.prototype._stringify = function _stringify(value) {
return JSON.stringify(value);
};
/**
* A pre-processed JSON data column. Only available in postgres.
*
* @memberof DataTypes
*/
function JSONB() {
if (!(this instanceof JSONB)) return new JSONB();
JSONTYPE.call(this);
......@@ -534,11 +386,6 @@ inherits(JSONB, JSONTYPE);
JSONB.prototype.key = JSONB.key = 'JSONB';
/**
* A default value of the current timestamp
*
* @memberof DataTypes
*/
function NOW() {
if (!(this instanceof NOW)) return new NOW();
}
......@@ -546,11 +393,6 @@ inherits(NOW, ABSTRACT);
NOW.prototype.key = NOW.key = 'NOW';
/**
* Binary storage. Available lengths: `tiny`, `medium`, `long`
*
* @memberof DataTypes
*/
function BLOB(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof BLOB)) return new BLOB(options);
......@@ -598,14 +440,6 @@ BLOB.prototype._hexify = function _hexify(hex) {
return "X'" + hex + "'";
};
/**
* Range types are data types representing a range of values of some element type (called the range's subtype).
* Only available in postgres.
* See {@link http://www.postgresql.org/docs/9.4/static/rangetypes.html|Postgres documentation} for more details
*
* @memberof DataTypes
*/
function RANGE(subtype) {
const options = _.isPlainObject(subtype) ? subtype : {subtype};
......@@ -663,12 +497,6 @@ RANGE.prototype.validate = function validate(value) {
return true;
};
/**
* A column storing a unique universal identifier. Use with `UUIDV1` or `UUIDV4` for default values.
*
* @memberof DataTypes
*/
function UUID() {
if (!(this instanceof UUID)) return new UUID();
}
......@@ -683,12 +511,6 @@ UUID.prototype.validate = function validate(value, options) {
return true;
};
/**
* A default unique universal identifier generated following the UUID v1 standard
*
* @memberof DataTypes
*/
function UUIDV1() {
if (!(this instanceof UUIDV1)) return new UUIDV1();
}
......@@ -703,12 +525,6 @@ UUIDV1.prototype.validate = function validate(value, options) {
return true;
};
/**
* A default unique universal identifier generated following the UUID v4 standard
*
* @memberof DataTypes
*/
function UUIDV4() {
if (!(this instanceof UUIDV4)) return new UUIDV4();
}
......@@ -723,47 +539,6 @@ UUIDV4.prototype.validate = function validate(value, options) {
return true;
};
/**
* 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:
* ```js
* sequelize.define('user', {
* password_hash: DataTypes.STRING,
* password: {
* type: DataTypes.VIRTUAL,
* set: function (val) {
* this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
* this.setDataValue('password_hash', this.salt + val);
* },
* validate: {
* isLongEnough: function (val) {
* if (val.length < 7) {
* throw new Error("Please choose a longer password")
* }
* }
* }
* }
* })
* ```
* In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
*
* VIRTUAL also takes a return type and dependency fields as arguments
* If a virtual attribute is present in `attributes` it will automatically pull in the extra fields as well.
* Return type is mostly useful for setups that rely on types like GraphQL.
* ```js
* {
* active: {
* type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
* get: function() {
* return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
* }
* }
* }
* ```
*
* @memberof DataTypes
*/
function VIRTUAL(ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
......@@ -775,11 +550,6 @@ inherits(VIRTUAL, ABSTRACT);
VIRTUAL.prototype.key = VIRTUAL.key = 'VIRTUAL';
/**
* An enumeration. `DataTypes.ENUM('value', 'another value')`.
*
* @memberof DataTypes
*/
function ENUM(value) {
const options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce((result, element) => {
......@@ -801,11 +571,6 @@ ENUM.prototype.validate = function validate(value) {
return true;
};
/**
* An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in postgres.
*
* @memberof DataTypes
*/
function ARRAY(type) {
const options = _.isPlainObject(type) ? type : {type};
if (!(this instanceof ARRAY)) return new ARRAY(options);
......@@ -836,57 +601,6 @@ const helpers = {
SCALE: [DECIMAL]
};
/**
* A column storing Geometry information.
*
* Only available in PostgreSQL (with PostGIS) or MySQL.
* In MySQL, allowable Geometry types are 'POINT', 'LINESTRING', 'POLYGON'.
*
* When using, GeoJSON is accepted as input and returned as output.
* In PostGIS, the GeoJSON is parsed using the PostGIS function `ST_GeomFromGeoJSON`.
* In MySQL it is parsed using the function `GeomFromText`.
* Therefore, one can just follow the [GeoJSON spec](http://geojson.org/geojson-spec.html) for handling geometry objects. See the following examples:
*
* ```js
* // Create a new point:
* const point = { type: 'Point', coordinates: [39.807222,-76.984722]};
*
* User.create({username: 'username', geometry: point }).then(newUser => {
* ...
* });
*
* // Create a new linestring:
* const line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] };
*
* User.create({username: 'username', geometry: line }).then(newUser => {
* ...
* });
*
* // Create a new polygon:
* const polygon = { type: 'Polygon', coordinates: [
* [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
* [100.0, 1.0], [100.0, 0.0] ]
* ]};
*
* User.create({username: 'username', geometry: polygon }).then(newUser => {
* ...
* });
* // Create a new point with a custom SRID:
* const point = {
* type: 'Point',
* coordinates: [39.807222,-76.984722],
* crs: { type: 'name', properties: { name: 'EPSG:4326'} }
* };
*
* User.create({username: 'username', geometry: point }).then(newUser => {
* ...
* });
* ```
*
* @memberof DataTypes
*/
function GEOMETRY(type, srid) {
const options = _.isPlainObject(type) ? type : {type, srid};
......@@ -905,12 +619,6 @@ GEOMETRY.prototype._stringify = function _stringify(value, options) {
return 'GeomFromText(' + options.escape(Wkt.convert(value)) + ')';
};
/**
* A geography datatype represents two dimensional spacial objects in an elliptic coord system.
*
* @memberof DataTypes
*/
function GEOGRAPHY(type, srid) {
const options = _.isPlainObject(type) ? type : {type, srid};
......@@ -945,7 +653,154 @@ for (const helper of Object.keys(helpers)) {
}
}
const dataTypes = {
/**
* A convenience class holding commonly used data types. The datatypes are used when defining a new model using `Sequelize.define`, like this:
* ```js
* sequelize.define('model', {
* column: DataTypes.INTEGER
* })
* ```
* When defining a model you can just as easily pass a string as type, but often using the types defined here is beneficial. For example, using `DataTypes.BLOB`, mean
* that that column will be returned as an instance of `Buffer` when being fetched by sequelize.
*
* To provide a length for the data type, you can invoke it like a function: `INTEGER(2)`
*
* Some data types have special properties that can be accessed in order to change the data type.
* For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`.
* The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as well.
*
* * All number types (`INTEGER`, `BIGINT`, `FLOAT`, `DOUBLE`, `REAL`, `DECIMAL`) expose the properties `UNSIGNED` and `ZEROFILL`
* * The `CHAR` and `STRING` types expose the `BINARY` property
*
*
* Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not be used to define types. Instead they are used as shorthands for
* defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:
* ```js`
* sequelize.define('model',` {
* uuid: {
* type: DataTypes.UUID,
* defaultValue: DataTypes.UUIDV1,
* primaryKey: true
* }
* })
* ```
* There may be times when you want to generate your own UUID conforming to some other algorithm. This is accomplished
* using the defaultValue property as well, but instead of specifying one of the supplied UUID types, you return a value
* from a function.
* ```js
* sequelize.define('model', {
* uuid: {
* type: DataTypes.UUID,
* defaultValue: function() {
* return generateMyId()
* },
* primaryKey: true
* }
* })
* ```
*
* @property {function(length=255: integer)} STRING A variable length string
* @property {function(length=255: integer)} CHAR A fixed length string.
* @property {function([length]: string)} TEXT An unlimited length text column. Available lengths: `tiny`, `medium`, `long`
* @property {function(length=255: integer)} INTEGER A 32 bit integer.
* @property {function(length: integer)} BIGINT A 64 bit integer. Note: an attribute defined as `BIGINT` will be treated like a `string` due this [feature from node-postgres](https://github.com/brianc/node-postgres/pull/353) to prevent precision loss. To have this attribute as a `number`, this is a possible [workaround](https://github.com/sequelize/sequelize/issues/2383#issuecomment-58006083).
* @property {function(length: integer, decimals: integer)} FLOAT Floating point number (4-byte precision).
* @property {function(length: integer, decimals: integer)} DOUBLE Floating point number (8-byte precision).
* @property {function(precision: integer, scale: integer)} DECIMAL Decimal number.
* @property {function(length: integer, decimals: integer)} REAL Floating point number (4-byte precision).
* @property {function} BOOLEAN A boolean / tinyint column, depending on dialect
* @property {function(length: string)} BLOB Binary storage. Available lengths: `tiny`, `medium`, `long`
* @property {function(values: string[])} ENUM An enumeration. `DataTypes.ENUM('value', 'another value')`.
* @property {function(length: integer)} DATE A datetime column
* @property {function} DATEONLY A date only column (no timestamp)
* @property {function} TIME A time column
* @property {function} NOW A default value of the current timestamp
* @property {function} UUID A column storing a unique universal identifier. Use with `UUIDV1` or `UUIDV4` for default values.
* @property {function} UUIDV1 A default unique universal identifier generated following the UUID v1 standard
* @property {function} UUIDV4 A default unique universal identifier generated following the UUID v4 standard
* @property {function} HSTORE A key / value store column. Only available in postgres.
* @property {function} JSON A JSON string column. Only available in postgres and sqlite.
* @property {function} JSONB A binary storage JSON column. Only available in postgres.
* @property {function(type: DataTypes)} ARRAY An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in postgres.
* @property {function(type: DataTypes)} RANGE Range types are data types representing a range of values of some element type (called the range's subtype).
* Only available in postgres. See [the Postgres documentation](http://www.postgresql.org/docs/9.4/static/rangetypes.html) for more details
* @property {function(type: string, srid: string)} GEOMETRY A column storing Geometry information. It is only available in PostgreSQL (with PostGIS) or MySQL.
* In MySQL, allowable Geometry types are `POINT`, `LINESTRING`, `POLYGON`.
*
* GeoJSON is accepted as input and returned as output.
* In PostGIS, the GeoJSON is parsed using the PostGIS function `ST_GeomFromGeoJSON`.
* In MySQL it is parsed using the function `GeomFromText`.
* Therefore, one can just follow the [GeoJSON spec](http://geojson.org/geojson-spec.html) for handling geometry objects. See the following examples:
*
* ```js
* // Create a new point:
* const point = { type: 'Point', coordinates: [39.807222,-76.984722]};
*
* User.create({username: 'username', geometry: point });
*
* // Create a new linestring:
* const line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] };
*
* User.create({username: 'username', geometry: line });
*
* // Create a new polygon:
* const polygon = { type: 'Polygon', coordinates: [
* [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
* [100.0, 1.0], [100.0, 0.0] ]
* ]};
*
* User.create({username: 'username', geometry: polygon });
* // Create a new point with a custom SRID:
* const point = {
* type: 'Point',
* coordinates: [39.807222,-76.984722],
* crs: { type: 'name', properties: { name: 'EPSG:4326'} }
* };
*
* User.create({username: 'username', geometry: point })
* ```
* @property {function(type: string, srid: string)} GEOGRAPHY A geography datatype represents two dimensional spacial objects in an elliptic coord system.
* @property {function(returnType: DataTypes, fields: string[])} VIRTUAL 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:
* ```js
* sequelize.define('user', {
* password_hash: DataTypes.STRING,
* password: {
* type: DataTypes.VIRTUAL,
* set: function (val) {
* // Remember to set the data value, otherwise it won't be validated
* this.setDataValue('password', val);
* this.setDataValue('password_hash', this.salt + val);
* },
* validate: {
* isLongEnough: function (val) {
* if (val.length < 7) {
* throw new Error("Please choose a longer password")
* }
* }
* }
* }
* })
* ```
* In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
*
* VIRTUAL also takes a return type and dependency fields as arguments
* If a virtual attribute is present in `attributes` it will automatically pull in the extra fields as well.
* Return type is mostly useful for setups that rely on types like GraphQL.
* ```js
* {
* active: {
* type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
* get: function() {
* return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
* }
* }
* }
* ```
*/
const DataTypes = module.exports = {
ABSTRACT,
STRING,
CHAR,
......@@ -980,13 +835,13 @@ const dataTypes = {
GEOGRAPHY
};
_.each(dataTypes, dataType => {
_.each(DataTypes, dataType => {
dataType.types = {};
});
dataTypes.postgres = require('./dialects/postgres/data-types')(dataTypes);
dataTypes.mysql = require('./dialects/mysql/data-types')(dataTypes);
dataTypes.sqlite = require('./dialects/sqlite/data-types')(dataTypes);
dataTypes.mssql = require('./dialects/mssql/data-types')(dataTypes);
DataTypes.postgres = require('./dialects/postgres/data-types')(DataTypes);
DataTypes.mysql = require('./dialects/mysql/data-types')(DataTypes);
DataTypes.sqlite = require('./dialects/sqlite/data-types')(DataTypes);
DataTypes.mssql = require('./dialects/mssql/data-types')(DataTypes);
module.exports = dataTypes;
module.exports = DataTypes;
......@@ -34,9 +34,6 @@ const util = require('util');
* });
* ```
*
* @namespace Deferrable
* @memberof Sequelize
*
* @property INITIALLY_DEFERRED Defer constraints checks to the end of transactions.
* @property INITIALLY_IMMEDIATE Trigger the constraint checks immediately
* @property NOT 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.
......
......@@ -12,7 +12,6 @@ const throwMethodUndefined = function(methodName) {
};
const QueryGenerator = {
/* jshint proto:true */
__proto__: AbstractQueryGenerator,
options: {},
dialect: 'mssql',
......
......@@ -161,7 +161,7 @@ class Query extends AbstractQuery {
result = {};
for (const _result of data) {
if (_result.Default) {
_result.Default = _result.Default.replace("('", '').replace("')", '').replace(/'/g, ''); /* jshint ignore: line */
_result.Default = _result.Default.replace("('", '').replace("')", '').replace(/'/g, '');
}
result[_result.Name] = {
......@@ -281,7 +281,7 @@ class Query extends AbstractQuery {
isShowOrDescribeQuery() {
let result = false;
result = result || this.sql.toLowerCase().indexOf("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'") === 0; /* jshint ignore: line */
result = result || this.sql.toLowerCase().indexOf("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'") === 0;
result = result || this.sql.toLowerCase().indexOf('select tablename = t.name, name = ind.name,') === 0;
result = result || this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0;
......
......@@ -91,7 +91,6 @@ class ConnectionManager extends AbstractConnectionManager {
return new Utils.Promise((resolve, reject) => {
const connection = this.lib.createConnection(connectionConfig);
/*jshint latedef:false*/
const errorHandler = (e) => {
// clean up connect event if there is error
connection.removeListener('connect', connectHandler);
......@@ -103,7 +102,6 @@ class ConnectionManager extends AbstractConnectionManager {
connection.removeListener('error', errorHandler);
resolve(connection);
};
/*jshint latedef:true*/
connection.once('error', errorHandler);
connection.once('connect', connectHandler);
......
......@@ -4,7 +4,6 @@ const Utils = require('../../utils');
const AbstractQueryGenerator = require('../abstract/query-generator');
const QueryGenerator = {
/* jshint proto:true */
__proto__: AbstractQueryGenerator,
dialect: 'mysql',
......
......@@ -25,7 +25,6 @@ const UnknownConstraintError = require('../../errors').UnknownConstraintError;
function removeColumn(tableName, columnName, options) {
options = options || {};
/* jshint validthis:true */
return this.sequelize.query(
this.QueryGenerator.getForeignKeyQuery(tableName, columnName),
_.assign({ raw: true }, options)
......@@ -49,7 +48,6 @@ function removeColumn(tableName, columnName, options) {
function removeConstraint(tableName, constraintName, options) {
/* jshint validthis:true */
const sql = this.QueryGenerator.showConstraintsQuery(tableName, constraintName);
return this.sequelize.query(sql, Object.assign({}, options, { type: this.sequelize.QueryTypes.SHOWCONSTRAINTS }))
......
'use strict';
/*jshint -W110 */
const _ = require('lodash');
const wkx = require('wkx');
const inherits = require('../../utils/inherits');
......
'use strict';
/* jshint -W110 */
const Utils = require('../../utils');
const util = require('util');
const DataTypes = require('../../data-types');
......@@ -9,7 +8,6 @@ const semver = require('semver');
const _ = require('lodash');
const QueryGenerator = {
/* jshint proto:true */
__proto__: AbstractQueryGenerator,
options: {},
dialect: 'postgres',
......
'use strict';
/* jshint -W110 */
const Utils = require('../../utils');
const util = require('util');
const Transaction = require('../../transaction');
......@@ -9,7 +8,6 @@ const MySqlQueryGenerator = require('../mysql/query-generator');
const AbstractQueryGenerator = require('../abstract/query-generator');
const QueryGenerator = {
/* jshint proto:true */
__proto__: MySqlQueryGenerator,
options: {},
dialect: 'sqlite',
......
......@@ -31,7 +31,6 @@ const UnknownConstraintError = require('../../errors').UnknownConstraintError;
function removeColumn(tableName, attributeName, options) {
options = options || {};
/* jshint validthis:true */
return this.describeTable(tableName, options).then(fields => {
delete fields[attributeName];
......@@ -63,7 +62,6 @@ function changeColumn(tableName, attributes, options) {
const attributeName = Object.keys(attributes)[0];
options = options || {};
/* jshint validthis:true */
return this.describeTable(tableName, options).then(fields => {
fields[attributeName] = attributes[attributeName];
......@@ -95,7 +93,6 @@ exports.changeColumn = changeColumn;
function renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
/* jshint validthis:true */
return this.describeTable(tableName, options).then(fields => {
fields[attrNameAfter] = Utils._.clone(fields[attrNameBefore]);
delete fields[attrNameBefore];
......@@ -110,7 +107,7 @@ exports.renameColumn = renameColumn;
function removeConstraint(tableName, constraintName, options) {
let createTableSql;
/* jshint validthis:true */
return this.showConstraint(tableName, constraintName)
.then(constraints => {
const constraint = constraints[0];
......@@ -147,7 +144,6 @@ function removeConstraint(tableName, constraintName, options) {
exports.removeConstraint = removeConstraint;
function addConstraint(tableName, options) {
/* jshint validthis:true */
const constraintSnippet = this.QueryGenerator.getConstraintSnippet(tableName, options);
const describeCreateTableSql = this.QueryGenerator.describeCreateTableQuery(tableName);
let createTableSql;
......
......@@ -108,8 +108,6 @@ class Query extends AbstractQuery {
const query = this;
// cannot use arrow function here because the function is bound to the statement
function afterExecute(err, results) {
/* jshint validthis:true */
debug(`executed(${query.database.uuid || 'default'}) : ${query.sql}`);
if (benchmark) {
......
'use strict';
/**
* 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.
*
* This means that errors can be accessed using `Sequelize.ValidationError` or `sequelize.ValidationError
*
* @namespace Errors
*/
/**
* The Base Error all Sequelize Errors inherit from.
*
* @alias Error
* @memberof Errors
*/
class BaseError extends Error {
constructor(message) {
super(message);
this.name = 'SequelizeBaseError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
}
}
exports.BaseError = BaseError;
/**
* Scope Error. Thrown when the sequelize cannot query the specified scope.
*
* @param {string} message Error message
*
* @extends BaseError
* @memberof Errors
*/
class SequelizeScopeError extends BaseError {
constructor(parent) {
super(parent);
this.name = 'SequelizeScopeError';
}
}
exports.SequelizeScopeError = SequelizeScopeError;
/**
* 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.
*
* @param {string} message Error message
* @param {Array} [errors] Array of ValidationErrorItem objects describing the validation errors
*
* @extends BaseError
* @memberof Errors
*
* @property errors An array of ValidationErrorItems
*/
class ValidationError extends BaseError {
constructor(message, errors) {
super(message);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(err => err.type + ': ' + err.message).join(',\n');
}
}
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
get(path) {
return this.errors.reduce((reduced, error) => {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
}
}
exports.ValidationError = ValidationError;
/**
* Thrown when attempting to update a stale model instance
* @extends BaseError
* @constructor
*/
class OptimisticLockError extends BaseError {
constructor(options) {
options = options || {};
options.message = options.message || 'Attempting to update a stale model instance: ' + options.modelName;
super(options);
this.name = 'SequelizeOptimisticLockError';
this.message = options.message;
this.modelName = options.modelName;
this.values = options.values;
this.where = options.where;
}
}
exports.OptimisticLockError = OptimisticLockError;
/**
* A base class for all database related errors.
* @extends BaseError
* @class DatabaseError
* @memberof Errors
*
* @property parent The database specific error which triggered this one
* @property sql The SQL that triggered the error
* @property message The message from the DB.
* @property fields The fields of the unique constraint
* @property value The value(s) which triggered the error
* @property index The name of the index that triggered the error
*/
class DatabaseError extends BaseError {
constructor(parent) {
super(parent.message);
this.name = 'SequelizeDatabaseError';
this.parent = parent;
this.original = parent;
this.sql = parent.sql;
}
}
exports.DatabaseError = DatabaseError;
/**
* Thrown when a database query times out because of a deadlock
* @extends DatabaseError
* @memberof Errors
*/
class TimeoutError extends DatabaseError {
constructor(parent) {
super(parent);
this.name = 'SequelizeTimeoutError';
}
}
exports.TimeoutError = TimeoutError;
/**
* Thrown when a unique constraint is violated in the database
* @extends DatabaseError
* @memberof Errors
*
* @property
* @property sql
*/
class UniqueConstraintError extends ValidationError {
constructor(options) {
options = options || {};
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
super(options.message, options.errors);
this.name = 'SequelizeUniqueConstraintError';
this.message = options.message;
this.errors = options.errors;
this.fields = options.fields;
this.parent = options.parent;
this.original = options.parent;
this.sql = options.parent.sql;
}
}
exports.UniqueConstraintError = UniqueConstraintError;
/**
* Thrown when a foreign key constraint is violated in the database
* @extends DatabaseError
* @memberof Errors
*/
class ForeignKeyConstraintError extends DatabaseError {
constructor(options) {
options = options || {};
options.parent = options.parent || { sql: '' };
super(options.parent);
this.name = 'SequelizeForeignKeyConstraintError';
this.message = options.message || options.parent.message || 'Database Error';
this.fields = options.fields;
this.table = options.table;
this.value = options.value;
this.index = options.index;
}
}
exports.ForeignKeyConstraintError = ForeignKeyConstraintError;
/**
* Thrown when an exclusion constraint is violated in the database
* @extends DatabaseError
* @memberof Errors
*/
class ExclusionConstraintError extends DatabaseError {
constructor(options) {
options = options || {};
options.parent = options.parent || { sql: '' };
super(options.parent);
this.name = 'SequelizeExclusionConstraintError';
this.message = options.message || options.parent.message;
this.constraint = options.constraint;
this.fields = options.fields;
this.table = options.table;
}
}
exports.ExclusionConstraintError = ExclusionConstraintError;
/**
* Thrown when constraint name is not found in the database
*/
class UnknownConstraintError extends DatabaseError {
constructor(message) {
const parent = { message };
super(parent);
this.name = 'SequelizeUnknownConstraintError';
this.message = message || 'The specified constraint does not exist';
}
}
exports.UnknownConstraintError = UnknownConstraintError;
/**
* Validation Error Item
* Instances of this class are included in the `ValidationError.errors` property.
*
* @param {string} message An error message
* @param {string} type The type of the validation error
* @param {string} path The field that triggered the validation error
* @param {string} value The value that generated the error
* @memberof Errors
*/
class ValidationErrorItem {
constructor(message, type, path, value) {
this.message = message || '';
this.type = type || null;
this.path = path || null;
this.value = value !== undefined ? value : null;
}
}
exports.ValidationErrorItem = ValidationErrorItem;
/**
* A base class for all connection related errors.
* @extends BaseError
* @memberof Errors
*
* @property parent The connection specific error which triggered this one
*/
class ConnectionError extends BaseError {
constructor(parent) {
super(parent ? parent.message : '');
this.name = 'SequelizeConnectionError';
this.parent = parent;
this.original = parent;
}
}
exports.ConnectionError = ConnectionError;
/**
* Thrown when a connection to a database is refused
* @extends ConnectionError
* @memberof Errors
*/
class ConnectionRefusedError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeConnectionRefusedError';
}
}
exports.ConnectionRefusedError = ConnectionRefusedError;
/**
* Thrown when a connection to a database is refused due to insufficient privileges
* @extends ConnectionError
* @memberof Errors
*/
class AccessDeniedError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeAccessDeniedError';
}
}
exports.AccessDeniedError = AccessDeniedError;
/**
* Thrown when a connection to a database has a hostname that was not found
* @extends ConnectionError
* @memberof Errors
*/
class HostNotFoundError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeHostNotFoundError';
}
}
exports.HostNotFoundError = HostNotFoundError;
/**
* Thrown when a connection to a database has a hostname that was not reachable
* @extends ConnectionError
* @memberof Errors
*/
class HostNotReachableError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeHostNotReachableError';
}
}
exports.HostNotReachableError = HostNotReachableError;
/**
* Thrown when a connection to a database has invalid values for any of the connection parameters
* @extends ConnectionError
* @memberof Errors
*/
class InvalidConnectionError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeInvalidConnectionError';
}
}
exports.InvalidConnectionError = InvalidConnectionError;
/**
* Thrown when a connection to a database times out
* @extends ConnectionError
* @memberof Errors
*/
class ConnectionTimedOutError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeConnectionTimedOutError';
}
}
exports.ConnectionTimedOutError = ConnectionTimedOutError;
/**
* Thrown when a some problem occurred with Instance methods (see message for details)
* @extends BaseError
* @memberof Errors
*/
class InstanceError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeInstanceError';
this.message = message;
}
}
exports.InstanceError = InstanceError;
/**
* Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
* @extends BaseError
* @memberof Errors
*/
class EmptyResultError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeEmptyResultError';
this.message = message;
}
}
exports.EmptyResultError = EmptyResultError;
/**
* Thrown when an include statement is improperly constructed (see message for details)
* @extends BaseError
* @memberof Errors
*/
class EagerLoadingError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeEagerLoadingError';
this.message = message;
}
}
exports.EagerLoadingError = EagerLoadingError;
/**
* Thrown when an association is improperly constructed (see message for details)
* @extends BaseError
* @memberof Errors
*/
class AssociationError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeAssociationError';
this.message = message;
}
}
exports.AssociationError = AssociationError;
/**
* Thrown when a query is passed invalid options (see message for details)
* @extends BaseError
* @memberof Errors
*/
class QueryError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeQueryError';
this.message = message;
}
}
exports.QueryError = QueryError;
module.exports = require('./errors/index.js');
'use strict';
/**
* 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.
*
* This means that errors can be accessed using `Sequelize.ValidationError` or `sequelize.ValidationError`
* The Base Error all Sequelize Errors inherit from.
*/
class BaseError extends Error {
constructor(message) {
super(message);
this.name = 'SequelizeBaseError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
}
}
exports.BaseError = BaseError;
/**
* Scope Error. Thrown when the sequelize cannot query the specified scope.
*/
class SequelizeScopeError extends BaseError {
constructor(parent) {
super(parent);
this.name = 'SequelizeScopeError';
}
}
exports.SequelizeScopeError = SequelizeScopeError;
/**
* 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.
*
* @param {string} message Error message
* @param {Array} [errors] Array of ValidationErrorItem objects describing the validation errors
*
* @property errors An array of ValidationErrorItems
*/
class ValidationError extends BaseError {
constructor(message, errors) {
super(message);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
*
* @type {ValidationErrorItem[]}
*/
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(err => err.type + ': ' + err.message).join(',\n');
}
}
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {ValidationErrorItem[]} Validation error items for the specified path
*/
get(path) {
return this.errors.reduce((reduced, error) => {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
}
}
exports.ValidationError = ValidationError;
/**
* Thrown when attempting to update a stale model instance
*/
class OptimisticLockError extends BaseError {
constructor(options) {
options = options || {};
options.message = options.message || 'Attempting to update a stale model instance: ' + options.modelName;
super(options);
this.name = 'SequelizeOptimisticLockError';
this.message = options.message;
/**
* The name of the model on which the update was attempted
* @type {string}
*/
this.modelName = options.modelName;
/**
* The values of the attempted update
* @type {object}
*/
this.values = options.values;
/**
*
* @type {object}
*/
this.where = options.where;
}
}
exports.OptimisticLockError = OptimisticLockError;
/**
* A base class for all database related errors.
*/
class DatabaseError extends BaseError {
constructor(parent) {
super(parent.message);
this.name = 'SequelizeDatabaseError';
/**
* @type {Error}
*/
this.parent = parent;
/**
* @type {Error}
*/
this.original = parent;
/**
* The SQL that triggered the error
* @type {string}
*/
this.sql = parent.sql;
}
}
exports.DatabaseError = DatabaseError;
/**
* Thrown when a database query times out because of a deadlock
*/
class TimeoutError extends DatabaseError {
constructor(parent) {
super(parent);
this.name = 'SequelizeTimeoutError';
}
}
exports.TimeoutError = TimeoutError;
/**
* Thrown when a unique constraint is violated in the database
*/
class UniqueConstraintError extends ValidationError {
constructor(options) {
options = options || {};
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
super(options.message, options.errors);
this.name = 'SequelizeUniqueConstraintError';
this.message = options.message;
this.errors = options.errors;
this.fields = options.fields;
this.parent = options.parent;
this.original = options.parent;
this.sql = options.parent.sql;
}
}
exports.UniqueConstraintError = UniqueConstraintError;
/**
* Thrown when a foreign key constraint is violated in the database
*/
class ForeignKeyConstraintError extends DatabaseError {
constructor(options) {
options = options || {};
options.parent = options.parent || { sql: '' };
super(options.parent);
this.name = 'SequelizeForeignKeyConstraintError';
this.message = options.message || options.parent.message || 'Database Error';
this.fields = options.fields;
this.table = options.table;
this.value = options.value;
this.index = options.index;
}
}
exports.ForeignKeyConstraintError = ForeignKeyConstraintError;
/**
* Thrown when an exclusion constraint is violated in the database
*/
class ExclusionConstraintError extends DatabaseError {
constructor(options) {
options = options || {};
options.parent = options.parent || { sql: '' };
super(options.parent);
this.name = 'SequelizeExclusionConstraintError';
this.message = options.message || options.parent.message;
this.constraint = options.constraint;
this.fields = options.fields;
this.table = options.table;
}
}
exports.ExclusionConstraintError = ExclusionConstraintError;
/**
* Thrown when constraint name is not found in the database
*/
class UnknownConstraintError extends DatabaseError {
constructor(message) {
const parent = { message };
super(parent);
this.name = 'SequelizeUnknownConstraintError';
this.message = message || 'The specified constraint does not exist';
}
}
exports.UnknownConstraintError = UnknownConstraintError;
/**
* Validation Error Item
* Instances of this class are included in the `ValidationError.errors` property.
*
* @param {string} message An error message
* @param {string} type The type of the validation error
* @param {string} path The field that triggered the validation error
* @param {string} value The value that generated the error
*/
class ValidationErrorItem {
constructor(message, type, path, value) {
this.message = message || '';
this.type = type || null;
this.path = path || null;
this.value = value !== undefined ? value : null;
}
}
exports.ValidationErrorItem = ValidationErrorItem;
/**
* A base class for all connection related errors.
*/
class ConnectionError extends BaseError {
constructor(parent) {
super(parent ? parent.message : '');
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @type {Error}
*/
this.parent = parent;
this.original = parent;
}
}
exports.ConnectionError = ConnectionError;
/**
* Thrown when a connection to a database is refused
*/
class ConnectionRefusedError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeConnectionRefusedError';
}
}
exports.ConnectionRefusedError = ConnectionRefusedError;
/**
* Thrown when a connection to a database is refused due to insufficient privileges
*/
class AccessDeniedError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeAccessDeniedError';
}
}
exports.AccessDeniedError = AccessDeniedError;
/**
* Thrown when a connection to a database has a hostname that was not found
*/
class HostNotFoundError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeHostNotFoundError';
}
}
exports.HostNotFoundError = HostNotFoundError;
/**
* Thrown when a connection to a database has a hostname that was not reachable
*/
class HostNotReachableError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeHostNotReachableError';
}
}
exports.HostNotReachableError = HostNotReachableError;
/**
* Thrown when a connection to a database has invalid values for any of the connection parameters
*/
class InvalidConnectionError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeInvalidConnectionError';
}
}
exports.InvalidConnectionError = InvalidConnectionError;
/**
* Thrown when a connection to a database times out
*/
class ConnectionTimedOutError extends ConnectionError {
constructor(parent) {
super(parent);
this.name = 'SequelizeConnectionTimedOutError';
}
}
exports.ConnectionTimedOutError = ConnectionTimedOutError;
/**
* Thrown when a some problem occurred with Instance methods (see message for details)
*/
class InstanceError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeInstanceError';
this.message = message;
}
}
exports.InstanceError = InstanceError;
/**
* Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
*/
class EmptyResultError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeEmptyResultError';
this.message = message;
}
}
exports.EmptyResultError = EmptyResultError;
/**
* Thrown when an include statement is improperly constructed (see message for details)
*/
class EagerLoadingError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeEagerLoadingError';
this.message = message;
}
}
exports.EagerLoadingError = EagerLoadingError;
/**
* Thrown when an association is improperly constructed (see message for details)
*/
class AssociationError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeAssociationError';
this.message = message;
}
}
exports.AssociationError = AssociationError;
/**
* Thrown when a query is passed invalid options (see message for details)
*/
class QueryError extends BaseError {
constructor(message) {
super(message);
this.name = 'SequelizeQueryError';
this.message = message;
}
}
exports.QueryError = QueryError;
......@@ -641,7 +641,7 @@ class Model {
*
* For a list of possible data types, see {@link DataTypes}
*
* For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations
* For more about validation, see http://docs.sequelizejs.com/manual/tutorial/models-definition.html#validations
*
* @see {@link DataTypes}
* @see {@link Hooks}
......@@ -1309,7 +1309,7 @@ class Model {
* // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
* ```
*
* @param {...Array|Object|String|null} options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
* @param {Array|Object|String|null} options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
* @return {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
*/
static scope(option) {
......@@ -1477,7 +1477,7 @@ class Model {
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {Boolean|Error} [options.rejectOnEmpty=false] Throws an error when no records found
*
* @see {@link Sequelize#query}
* @link {@link Sequelize.query}
* @return {Promise<Array<Model>>}
*/
static findAll(options) {
......@@ -1650,7 +1650,7 @@ class Model {
* @param {Transaction} [options.transaction] Transaction to run query under
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @see {@link Model#findAll} for a full explanation of options
* @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Model>}
*/
static findById(param, options) {
......@@ -1681,7 +1681,7 @@ class Model {
* @param {Transaction} [options.transaction] Transaction to run query under
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @see {@link Model#findAll} for an explanation of options
* @see {@link Model.findAll} for an explanation of options
* @return {Promise<Model>}
*/
static findOne(options) {
......@@ -1715,12 +1715,12 @@ class Model {
* @param {Object} [options.where] A hash of search attributes.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
* @param {DataType|String} [options.dataType] 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.
* @param {DataTypes|String} [options.dataType] 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.
* @param {boolean} [options.distinct] Applies DISTINCT to the field being aggregated over
* @param {Transaction} [options.transaction] Transaction to run query under
* @param {Boolean} [options.plain] When `true`, the first returned value of `aggregateFunction` is cast to `dataType` and returned. If additional attributes are specified, along with `group` clauses, set `plain` to `false` to return all values of all returned rows. Defaults to `true`
*
* @return {Promise<options.dataType|object>} Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in which case the complete data result is returned.
* @return {Promise<DataTypes|object>} Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in which case the complete data result is returned.
*/
static aggregate(attribute, aggregateFunction, options) {
options = Utils.cloneDeep(options);
......@@ -1838,7 +1838,7 @@ class Model {
*
* @param {Object} [findOptions] See findAll
*
* @see {@link Model#findAll} for a specification of find and query options
* @see {@link Model.findAll} for a specification of find and query options
* @return {Promise<{count: Integer, rows: Model[]}>}
*/
static findAndCount(options) {
......@@ -2036,7 +2036,7 @@ class Model {
* @param {Object} options.where where A hash of search attributes.
* @param {Object} [options.defaults] Default values to use if creating a new instance
* @param {Transaction} [options.transaction] Transaction to run query under
* @see {@link Model#findAll} for a full specification of find and options
* @see {@link Model.findAll} for a full specification of find and options
* @return {Promise<Model,created>}
*/
static findOrCreate(options) {
......@@ -2129,7 +2129,7 @@ class Model {
* @param {Object} options
* @param {Object} options.where where A hash of search attributes.
* @param {Object} [options.defaults] Default values to use if creating a new instance
* @see {@link Model#findAll} for a full specification of find and options
* @see {@link Model.findAll} for a full specification of find and options
* @return {Promise<Model,created>}
*/
static findCreateFind(options) {
......@@ -2252,7 +2252,7 @@ class Model {
* @param {Boolean} [options.returning=false] Append RETURNING * to get back auto generated values (Postgres only)
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise<Array<Instance>>}
* @return {Promise<Array<Model>>}
*/
static bulkCreate(records, options) {
if (!records.length) {
......@@ -2317,7 +2317,6 @@ class Model {
});
}
}).then(() => {
/* jshint -W030 */
for (const instance of instances) {
const values = instance.dataValues;
......@@ -3092,7 +3091,7 @@ class Model {
*
* If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
*
* @see {@link Model#findAll} for more information about includes
* @see {@link Model.findAll} for more information about includes
* @param {String|Object} key
* @param {any} value
* @param {Object} [options]
......@@ -3605,7 +3604,7 @@ class Model {
* 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.
*
* @see {@link Model#findAll}
* @see {@link Model.findAll}
* @param {Object} [options] Options that are passed on to `Model.find`
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
*
......@@ -3934,6 +3933,95 @@ class Model {
plain: true
});
}
/**
* Creates a 1:m association between this (the source) and the provided target. The foreign key is added on the target.
*
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {string|object} [options.as] The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
* @param {string} [options.sourceKey] The name of the field to use as the key for the association in the source table. Defaults to the primary key of the source table
* @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @returns {HasMany}
* @example
* User.hasMany(Profile) // This will add userId to the profile table
*/
static hasMany(target, options) {} // eslint-disable-line
/**
* Create an N:M association with a join table. Defining `through` is required.
*
* @param {Model} target
* @param {object} options
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {Model|string|object} options.through The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.
* @param {Model} [options.through.model] The model used to join both sides of the N:M association.
* @param {object} [options.through.scope] A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model)
* @param {boolean} [options.through.unique=true] If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes)
* @param {string|object} [options.as] The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the join table (representing the source model) or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
* @param {string|object} [options.otherKey] The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target
* @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
* @param {boolean} [options.timestamps=sequelize.options.timestamps] Should the join model have timestamps
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @return {BelongsToMany}
* @example
* // Automagically generated join model
* User.belongsToMany(Project, { through: 'UserProjects' })
* Project.belongsToMany(User, { through: 'UserProjects' })
*
* // Join model with additional attributes
* const UserProjects = sequelize.define('UserProjects', {
* started: Sequelize.BOOLEAN
* })
* User.belongsToMany(Project, { through: UserProjects })
* Project.belongsToMany(User, { through: UserProjects })
*/
static belongsToMany(target, options) {} // eslint-disable-line
/**
* Creates an association between this (the source) and the provided target. The foreign key is added on the target.
*
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @returns {HasOne}
* @example
* User.hasOne(Profile) // This will add userId to the profile table
*/
static hasOne(target, options) {} // eslint-disable-line
/**
* Creates an association between this (the source) and the provided target. The foreign key is added on the source.
*
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the source table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target
* @param {string} [options.targetKey] The name of the field to use as the key for the association in the target table. Defaults to the primary key of the target table
* @param {string} [options.onDelete='SET&nbsp;NULL|NO&nbsp;ACTION'] SET NULL if foreignKey allows nulls, NO ACTION if otherwise
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @returns {BelongsTo}
* @example
* Profile.belongsTo(User) // This will add userId to the profile table
*/
static belongsTo(target, options) {} // eslint-disable-line
}
// Aliases
......
'use strict';
/**
* @namespace QueryTypes
* @memberof Sequelize
* An enum of query types used by `sequelize.query`
*
* @see {@link Sequelize#query}
*
* @property SELECT
* @property INSERT
......@@ -20,7 +20,7 @@
* @property FOREIGNKEYS
* @property SHOWCONSTRAINTS
*/
module.exports = {
const QueryTypes = module.exports = { // eslint-disable-line
SELECT: 'SELECT',
INSERT: 'INSERT',
UPDATE: 'UPDATE',
......
......@@ -27,9 +27,8 @@ const _ = require('lodash');
* ```
*
* In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
*
* @class Sequelize
*/
class Sequelize {
/**
* Instantiate sequelize with name of database, username and password
......@@ -49,14 +48,14 @@ const _ = require('lodash');
* // with password and options
* const sequelize = new Sequelize('my_database', 'john', 'doe', {})
*
* // with uri (see below)
* // with database, username, and password in the options object
* const sequelize = new Sequelize({ database, username, password });
*
* // with uri
* const sequelize = new Sequelize('mysql://localhost:3306/database', {})
* ```
*
* @name Sequelize
* @constructor
*
* @param {String} database The name of the database
* @param {String} [database] The name of the database
* @param {String} [username=null] The username which is used to authenticate against the database.
* @param {String} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.
* @param {Object} [options={}] An object with options.
......@@ -94,25 +93,6 @@ const _ = require('lodash');
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
* @param {Boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
*/
/**
* Instantiate sequelize with an URI
* @name Sequelize
* @constructor
*
* @param {String} uri A full database URI
* @param {object} [options={}] See above for possible options
*/
/**
* Instantiate sequelize with an options object
* @name Sequelize
* @constructor
*
* @param {object} [options={}] See above for possible options
*/
class Sequelize {
constructor(database, username, password, options) {
let config;
......@@ -294,9 +274,19 @@ class Sequelize {
/**
* 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 defined by the object that is given as the second argument. Each key of the object represents a column
*
* ```js
* @param {String} modelName The name of the model. The model will be stored in `sequelize.models` under this name
* @param {Object} attributes An object, where each attribute is a column of the table. See {@link Model.init}
* @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init()
*
* @see {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects.
* @see <a href="../manual/tutorial/models-definition.html">The manual section about defining models</a>
* @see {@link DataTypes} For a list of possible data types
*
* @return {Model}
*
* @example
* sequelize.define('modelName', {
* columnA: {
* type: Sequelize.BOOLEAN,
......@@ -316,26 +306,6 @@ class Sequelize {
* })
*
* sequelize.models.modelName // The model will now be available in models under the name given to define
* ```
*
*
* As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
*
* For a list of possible data types, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types
*
* For more about getters and setters, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters
*
* For more about instance and class methods, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models
*
* For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations
*
* @see {@link DataTypes}
* @param {String} modelName The name of the model. The model will be stored in `sequelize.models` under this name
* @param {String} modelName The name of the model. The model will be stored in `sequelize.models` under this name
* @param {Object} attributes An object, where each attribute is a column of the table. See Model.init()
* @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init()
*
* @return {Model}
*/
define(modelName, attributes, options) { // testhint options:none
options = options || {};
......@@ -430,14 +400,14 @@ class Sequelize {
* @param {Object} [options={}] Query options.
* @param {Boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
* @param {String} [options.type='RAW'] The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
* @param {QueryTypes} [options.type='RAW'] The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
* @param {Boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
* @param {Boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
* @param {Object|Array} [options.replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
* @param {Object|Array} [options.bind] Either an object of named bind parameter in the format `_param` or an array of unnamed bind parameter to replace `$1, $2, ...` in your SQL.
* @param {Boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Instance} [options.instance] A sequelize instance used to build the return instance
* @param {new Model()} [options.instance] A sequelize instance used to build the return instance
* @param {Model} [options.model] A sequelize model used to build the returned model instances (used to be called callee)
* @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
* @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
......@@ -448,9 +418,8 @@ class Sequelize {
* @param {Object} [options.fieldMap] Map returned fields to arbitrary names for `SELECT` query type.
*
* @return {Promise}
* @memberof Sequelize
*
* @see {@link Model#build} for more information about instance option.
* @see {@link Model.build} for more information about instance option.
*/
query(sql, options) {
......@@ -618,7 +587,7 @@ class Sequelize {
* Note, that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this command will do nothing.
*
* @see {@link Model#schema}
* @see {@link Model.schema}
* @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
......@@ -731,7 +700,7 @@ class Sequelize {
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @see {@link Model#truncate} for more information
* @see {@link Model.truncate} for more information
*/
truncate(options) {
const models = [];
......@@ -753,7 +722,7 @@ class Sequelize {
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
* @see {@link Model#drop} for options
* @see {@link Model.drop} for options
*
* @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
......@@ -796,9 +765,9 @@ class Sequelize {
* })
* ```
*
* @see {@link Model#findAll}
* @see {@link Model#define}
* @see {@link Sequelize#col}
* @see {@link Model.findAll}
* @see {@link Sequelize.define}
* @see {@link Sequelize.col}
* @method fn
*
* @param {String} fn The function you want to call
......@@ -807,6 +776,10 @@ class Sequelize {
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.fn}
* @example <caption>Convert a user's username to upper case</caption>
* instance.updateAttributes({
* username: self.sequelize.fn('upper', self.sequelize.col('username'))
* })
*/
static fn(fn) {
return new Utils.Fn(fn, Utils.sliceArgs(arguments, 1));
......@@ -856,7 +829,7 @@ class Sequelize {
/**
* An AND query
* @see {@link Model#findAll}
* @see {@link Model.findAll}
*
* @method and
* @param {String|Object} args Each argument will be joined by AND
......@@ -870,7 +843,7 @@ class Sequelize {
/**
* An OR query
* @see {@link Model#findAll}
* @see {@link Model.findAll}
*
* @method or
* @param {String|Object} args Each argument will be joined by OR
......@@ -884,7 +857,7 @@ class Sequelize {
/**
* Creates an object representing nested where conditions for postgres's json data-type.
* @see {@link Model#findAll}
* @see {@link Model.findAll}
*
* @method json
* @param {String|Object} conditions A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.
......@@ -904,16 +877,13 @@ class Sequelize {
*
* For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your string to be escaped, use `sequelize.literal`.
*
* @see {@link Model#findAll}
* @see {@link Model.findAll}
*
* @param {Object} attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax
* @param {string} [comparator='=']
* @param {String|Object} logic The condition. Can be both a simply type, or a further condition (`$or`, `$and`, `.literal` etc.)
* @method where
* @alias condition
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.where}
*/
static where(attr, comparator, logic) {
return new Utils.Where(attr, comparator, logic);
......@@ -1169,7 +1139,7 @@ Sequelize.prototype.Promise = Sequelize.Promise = Promise;
/**
* Available query types for use with `sequelize.query`
* @see {@link Sequelize.QueryTypes}
* @see {@link QueryTypes}
*/
Sequelize.prototype.QueryTypes = Sequelize.QueryTypes = QueryTypes;
......
'use strict';
/* jshint -W110 */
const dataTypes = require('./data-types');
const _ = require('lodash');
......
......@@ -6,21 +6,18 @@ const Utils = require('./utils');
* 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.
* @class Transaction
* @constructor
*
* @see {@link Sequelize.transaction}
*/
class Transaction {
/**
* @param {Sequelize} sequelize A configured sequelize Instance
* @param {Object} options An object with options
* @param {Boolean} options.autocommit Sets the autocommit property of the transaction.
* @param {String} options.type=true Sets the type 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.
* @param {String} options.readOnly=false Sets the read-only property of the transaction. Such transactions
* will use read replicas when available
*
* @see {@link Sequelize.transaction}
*/
class Transaction {
constructor(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
......@@ -179,9 +176,8 @@ class Transaction {
}
}
}
}
/**
/**
* Types can be set per-transaction by passing `options.type` to `sequelize.transaction`.
* Default to `DEFERRED` but you can override the default type by passing `options.transactionType` in `new Sequelize`.
* Sqlite only.
......@@ -203,13 +199,15 @@ class Transaction {
* @property IMMEDIATE
* @property EXCLUSIVE
*/
Transaction.TYPES = {
static get TYPES() {
return {
DEFERRED: 'DEFERRED',
IMMEDIATE: 'IMMEDIATE',
EXCLUSIVE: 'EXCLUSIVE'
};
};
}
/**
/**
* Isolations levels 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`.
*
......@@ -231,14 +229,17 @@ Transaction.TYPES = {
* @property REPEATABLE_READ
* @property SERIALIZABLE
*/
Transaction.ISOLATION_LEVELS = {
static get ISOLATION_LEVELS () {
return {
READ_UNCOMMITTED: 'READ UNCOMMITTED',
READ_COMMITTED: 'READ COMMITTED',
REPEATABLE_READ: 'REPEATABLE READ',
SERIALIZABLE: 'SERIALIZABLE'
};
};
}
/**
/**
* Possible options for row locking. Used in conjunction with `find` calls:
*
* ```js
......@@ -264,17 +265,28 @@ Transaction.ISOLATION_LEVELS = {
* ```
* UserModel will be locked but TaskModel won't!
*
* @return {Object}
* @property UPDATE
* @property SHARE
* @property KEY_SHARE Postgres 9.3+ only
* @property NO_KEY_UPDATE Postgres 9.3+ only
*/
Transaction.LOCK = Transaction.prototype.LOCK = {
static get LOCK() {
return {
UPDATE: 'UPDATE',
SHARE: 'SHARE',
KEY_SHARE: 'KEY SHARE',
NO_KEY_UPDATE: 'NO KEY UPDATE'
};
};
}
/**
* @see {@link Transaction.LOCK}
*/
get LOCK() {
return Transaction.LOCK;
}
}
module.exports = Transaction;
module.exports.Transaction = Transaction;
......
......@@ -8,7 +8,6 @@
* @private
*/
/* jshint -W030 */
const depd = require('depd'),
debug = require('debug'),
_ = require('lodash');
......
site_name: Sequelize | The Node.js ORM for PostgreSQL, MySQL, SQLite and MSSQL
site_description: Sequelize is an ORM for Node.js. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL.
repo_url: https://github.com/sequelize/sequelize
site_favicon: favicon.ico
site_url: http://docs.sequelizejs.com
theme: readthedocs
extra_css:
- css/custom.css
extra_javascript:
- //cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js
pages:
- Home: 'index.md'
- Documentation:
- 'Getting Started': 'docs/getting-started.md'
- 'Working with table schemas': 'docs/schema.md'
- Models:
- 'Definition': 'docs/models-definition.md'
- 'Usage': 'docs/models-usage.md'
- 'Querying': 'docs/querying.md'
- 'Scopes': 'docs/scopes.md'
- 'Instances': 'docs/instances.md'
- 'Relations / Associations': 'docs/associations.md'
- 'Hooks': 'docs/hooks.md'
- 'Transactions': 'docs/transactions.md'
- 'Working with legacy tables': 'docs/legacy.md'
- 'Raw queries': 'docs/raw-queries.md'
- 'Migrations': 'docs/migrations.md'
- API:
- 'Sequelize': 'api/sequelize.md'
- 'Model': 'api/model.md'
- 'Instance': 'api/instance.md'
- Associations:
- Overview: 'api/associations/index.md'
- 'BelongsTo (1:1)': 'api/associations/belongs-to.md'
- 'HasOne (1:1)': 'api/associations/has-one.md'
- 'HasMany (1:m)': 'api/associations/has-many.md'
- 'BelongsToMany (n:m)': 'api/associations/belongs-to-many.md'
- 'Hooks': 'api/hooks.md'
- 'Transaction': 'api/transaction.md'
- 'Datatypes': 'api/datatypes.md'
- 'Deferrable': 'api/deferrable.md'
- 'Errors': 'api/errors.md'
- Misc:
- 'Changelog': 'changelog.md'
- 'Imprint': 'imprint.md'
......@@ -60,12 +60,11 @@
"chai-as-promised": "^5.3.0",
"chai-datetime": "^1.4.1",
"chai-spies": "^0.7.1",
"commander": "^2.9.0",
"cheerio": "^0.22.0",
"continuation-local-storage": "^3.2.0",
"cross-env": "^3.0.0",
"dox": "^0.9.0",
"esdoc": "^0.5.2",
"eslint": "^3.6.0",
"git": "^0.1.5",
"hints": "^1.1.0",
"istanbul": "^0.4.5",
"lcov-result-merger": "^1.2.0",
......@@ -99,7 +98,7 @@
"test-docker": "npm run test-docker-unit && npm run test-docker-integration",
"test-docker-unit": "env-cmd ./test/config/.docker.env npm run test-unit",
"test-docker-integration": "env-cmd ./test/config/.docker.env npm run test-integration",
"docs": "node docs/docs-generator.js",
"docs": "esdoc && cp docs/ROUTER esdoc/ROUTER",
"teaser": "node -e \"console.log('#'.repeat(process.env.DIALECT.length + 22) + '\\n# Running tests for ' + process.env.DIALECT + ' #\\n' + '#'.repeat(process.env.DIALECT.length + 22))\"",
"test-unit": "mocha --globals setImmediate,clearImmediate --ui tdd --check-leaks --colors -t 30000 --reporter spec \"test/unit/**/*.js\"",
"test-unit-mysql": "cross-env DIALECT=mysql npm run test-unit",
......
......@@ -169,7 +169,7 @@ describe(Support.getTestDialectTeaser('Utils'), () => {
describe('expectation', () => {
it('uses the instanceof method if the expectation is a class', () => {
expect(Utils.validateParameter(new Number(1), Number)).to.be.true; // jshint ignore:line
expect(Utils.validateParameter(new Number(1), Number)).to.be.true;
});
});
......
......@@ -339,7 +339,7 @@ function getArgumentsConformFn(method, args, hints, tree) {
body = getFunctionCode(method).slice(start, hints.end.start);
// create function that conforms arguments
return new Function(args, body + ';return [' + args + '];'); // jshint ignore:line
return new Function(args, body + ';return [' + args + '];');
}
/**
......
......@@ -55,9 +55,7 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
const type = DataTypes.STRING();
expect(type.validate('foobar')).to.equal(true);
/*jshint -W053 */
expect(type.validate(new String('foobar'))).to.equal(true);
/*jshint +W053 */
expect(type.validate(12)).to.equal(true);
});
});
......
'use strict';
/* jshint -W110 */
const Support = require(__dirname + '/../support'),
DataTypes = require(__dirname + '/../../../lib/data-types'),
expectsql = Support.expectsql,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!