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

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 643 additions and 2192 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"
]
}
}
......@@ -15,4 +15,5 @@ docs/api/tmp.md
ssce.js
coverage
.vscode/
*.sublime*
\ No newline at end of file
*.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="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="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 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. ` +
......@@ -38,4 +127,4 @@ class Association {
}
}
module.exports = Association;
\ No newline at end of file
module.exports = Association;
......@@ -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;
......@@ -241,4 +232,4 @@ class BelongsTo extends Association {
module.exports = BelongsTo;
module.exports.BelongsTo = BelongsTo;
module.exports.default = BelongsTo;
\ No newline at end of file
module.exports.default = BelongsTo;
......@@ -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
......
......@@ -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',
......@@ -204,7 +203,7 @@ const QueryGenerator = {
'from INFORMATION_SCHEMA.TABLE_CONSTRAINTS',
`WHERE table_name='${tableName}'`
].join(' ');
if (constraintName) {
sql += ` AND constraint_name = '${constraintName}'`;
}
......
......@@ -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,13 +48,12 @@ 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 }))
.then(constraints => {
const constraint = constraints[0];
let query;
let query;
if (constraint && constraint.constraintType) {
if (constraint.constraintType === 'FOREIGN KEY') {
query = this.QueryGenerator.dropForeignKeyQuery(tableName, constraintName);
......@@ -65,7 +63,7 @@ function removeConstraint(tableName, constraintName, options) {
} else {
throw new UnknownConstraintError(`Constraint ${constraintName} on table ${tableName} does not exist`);
}
return this.sequelize.query(query, options);
});
}
......
'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];
......@@ -119,7 +116,7 @@ function removeConstraint(tableName, constraintName, options) {
createTableSql = constraint.sql;
constraint.constraintName = this.QueryGenerator.quoteIdentifier(constraint.constraintName);
let constraintSnippet = `, CONSTRAINT ${constraint.constraintName} ${constraint.constraintType} ${constraint.constraintCondition}`;
if (constraint.constraintType === 'FOREIGN KEY') {
const referenceTableName = this.QueryGenerator.quoteTable(constraint.referenceTableName);
constraint.referenceTableKeys = constraint.referenceTableKeys.map(columnName => this.QueryGenerator.quoteIdentifier(columnName));
......@@ -129,7 +126,7 @@ function removeConstraint(tableName, constraintName, options) {
constraintSnippet += ` ON DELETE ${constraint.deleteAction}`;
}
createTableSql = createTableSql.replace(constraintSnippet, '');
createTableSql = createTableSql.replace(constraintSnippet, '');
createTableSql += ';';
return this.describeTable(tableName, options);
......@@ -147,11 +144,10 @@ 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;
return this.sequelize.query(describeCreateTableSql, options)
.then(constraints => {
const sql = constraints[0].sql;
......@@ -169,4 +165,4 @@ function addConstraint(tableName, options) {
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
});
}
exports.addConstraint = addConstraint;
\ No newline at end of file
exports.addConstraint = addConstraint;
......@@ -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) {
......@@ -332,7 +330,7 @@ class Query extends AbstractQuery {
const constraintCondition = constraintSql.match(/\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)/)[0];
constraintSql = constraintSql.replace(/\(.+\)/, '');
const constraint = constraintSql.split(' ');
if (constraint[1] === 'PRIMARY' || constraint[1] === 'FOREIGN') {
constraint[1]+= ' KEY';
}
......
'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',
......
'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
*
* @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 {
/**
* @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.
*/
constructor(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
......@@ -179,44 +176,45 @@ 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.
*
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
*
* // your transactions
*
* }).then(result => {
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* // do something with the err.
* });
* ```
* @property DEFERRED
* @property IMMEDIATE
* @property EXCLUSIVE
*/
Transaction.TYPES = {
DEFERRED: 'DEFERRED',
IMMEDIATE: 'IMMEDIATE',
EXCLUSIVE: 'EXCLUSIVE'
};
/**
* 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.
*
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
*
* // your transactions
*
* }).then(result => {
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* // do something with the err.
* });
* ```
* @property DEFERRED
* @property IMMEDIATE
* @property EXCLUSIVE
*/
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`.
*
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
/**
* 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`.
*
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
*
* // your transactions
*
......@@ -225,56 +223,70 @@ Transaction.TYPES = {
* }).catch(err => {
* // do something with the err.
* });
* ```
* @property READ_UNCOMMITTED
* @property READ_COMMITTED
* @property REPEATABLE_READ
* @property SERIALIZABLE
*/
Transaction.ISOLATION_LEVELS = {
READ_UNCOMMITTED: 'READ UNCOMMITTED',
READ_COMMITTED: 'READ COMMITTED',
REPEATABLE_READ: 'REPEATABLE READ',
SERIALIZABLE: 'SERIALIZABLE'
};
* ```
* @property READ_UNCOMMITTED
* @property READ_COMMITTED
* @property REPEATABLE_READ
* @property SERIALIZABLE
*/
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
* 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!
*
* @property UPDATE
* @property SHARE
* @property KEY_SHARE Postgres 9.3+ only
* @property NO_KEY_UPDATE Postgres 9.3+ only
*/
Transaction.LOCK = Transaction.prototype.LOCK = {
UPDATE: 'UPDATE',
SHARE: 'SHARE',
KEY_SHARE: 'KEY SHARE',
NO_KEY_UPDATE: 'NO KEY UPDATE'
};
/**
* Possible options for row locking. Used in conjunction with `find` calls:
*
* ```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!
*
* @return {Object}
* @property UPDATE
* @property SHARE
* @property KEY_SHARE Postgres 9.3+ only
* @property NO_KEY_UPDATE Postgres 9.3+ only
*/
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!