diff --git a/.eslintrc.json b/.eslintrc.json
index 38d78cf4ea61..8cd7cbdb3a18 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -1,12 +1,18 @@
{
- "extends": "eslint:recommended",
+ "parser": "@typescript-eslint/parser",
+ "extends": [
+ "eslint:recommended",
+ "plugin:@typescript-eslint/eslint-recommended",
+ "plugin:@typescript-eslint/recommended"
+ ],
"rules": {
+ "@typescript-eslint/no-loss-of-precision": "off",
"mocha/no-exclusive-tests": "error",
"mocha/no-skipped-tests": "warn",
"jsdoc/check-param-names": "error",
"jsdoc/check-tag-names": "error",
- "jsdoc/check-types": "error",
+ "jsdoc/check-types": "off",
"jsdoc/newline-after-description": "error",
"jsdoc/no-undefined-types": "off",
"jsdoc/require-description-complete-sentence": "off",
@@ -15,9 +21,9 @@
"jsdoc/require-param": "error",
"jsdoc/require-param-description": "off",
"jsdoc/require-param-name": "error",
- "jsdoc/require-param-type": "error",
+ "jsdoc/require-param-type": "off",
"jsdoc/require-returns-description": "off",
- "jsdoc/require-returns-type": "error",
+ "jsdoc/require-returns-type": "off",
"jsdoc/valid-types": "error",
// style
@@ -34,11 +40,14 @@
}
],
"semi": ["error", "always"],
- "space-before-function-paren": ["error", {
- "named": "never",
- "anonymous": "never",
- "asyncArrow": "always"
- }],
+ "space-before-function-paren": [
+ "error",
+ {
+ "named": "never",
+ "anonymous": "never",
+ "asyncArrow": "always"
+ }
+ ],
"space-before-blocks": "error",
"space-infix-ops": "error",
"no-multi-spaces": "error",
@@ -66,7 +75,6 @@
// functional
"valid-jsdoc": "off",
- "strict": ["error", "global"],
"no-var": "error",
"prefer-const": "error",
"prefer-arrow-callback": "error",
@@ -97,6 +105,19 @@
"no-case-declarations": "off",
"prefer-object-spread": "error"
},
+ "overrides": [
+ {
+ "files": ["**/*.js"],
+ "rules": {
+ "@typescript-eslint/no-var-requires": "off",
+ "@typescript-eslint/no-empty-function": "off",
+ "@typescript-eslint/no-this-alias": "off",
+ "jsdoc/require-param-type": "error",
+ "jsdoc/check-types": "error",
+ "jsdoc/require-returns-type": "error"
+ }
+ }
+ ],
"settings": {
"jsdoc": {
"tagNamePreference": {
@@ -108,7 +129,8 @@
"ecmaVersion": 2020,
"sourceType": "script"
},
- "plugins": ["mocha", "jsdoc"],
+ "ignorePatterns": ["lib/**/*", "types/**/*", "test/types/**/*", "src/**/*.d.ts"],
+ "plugins": ["mocha", "jsdoc", "@typescript-eslint"],
"env": {
"node": true,
"mocha": true,
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000000..ce2684934d6f
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+* -lf
\ No newline at end of file
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 000000000000..1bad4b3d7eda
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,12 @@
+# These are supported funding model platforms
+
+github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
+patreon: # Replace with a single Patreon username
+open_collective: sequelize
+ko_fi: # Replace with a single Ko-fi username
+tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
+community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
+liberapay: # Replace with a single Liberapay username
+issuehunt: # Replace with a single IssueHunt username
+otechie: # Replace with a single Otechie username
+custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 9be60467005d..3f5e52402f12 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -1,10 +1,9 @@
---
name: Bug report
about: Create a bug report to help us improve
-title: ''
-labels: ''
-assignees: ''
-
+title: ""
+labels: ""
+assignees: ""
---
-### Pull Request check-list
+### Pull Request Checklist
_Please make sure to review and check all of these items:_
-- [ ] Does `npm run test` or `npm run test-DIALECT` pass with this change (including linting)?
-- [ ] Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
- [ ] Have you added new tests to prevent regressions?
+- [ ] Does `npm run test` or `npm run test-DIALECT` pass with this change (including linting)?
- [ ] Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?
- [ ] Did you update the typescript typings accordingly (if applicable)?
+- [ ] Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
- [ ] Did you follow the commit message conventions explained in [CONTRIBUTING.md](https://github.com/sequelize/sequelize/blob/main/CONTRIBUTING.md)?
-### Description of change
+### Description Of Change
+
+### Todos
+
+- [ ]
+- [ ]
+- [ ]
diff --git a/.github/stale.yml b/.github/stale.yml
deleted file mode 100644
index dca733fa73dd..000000000000
--- a/.github/stale.yml
+++ /dev/null
@@ -1,40 +0,0 @@
-
-# Configuration for probot-stale - https://github.com/probot/stale
-
-# Number of days of inactivity before an issue becomes stale
-# daysUntilStale: 90
-daysUntilStale: 900000 # Temporarily disable
-
-# Number of days of inactivity before a stale issue is closed
-# daysUntilClose: 7
-daysUntilClose: 70000 # Temporarily disable
-
-# Issues with these labels will never be considered stale
-exemptLabels:
- - pinned
- - type: feature
- - type: docs
- - type: bug
- - discussion
- - type: performance
- - breaking change
- - good first issue
- - suggestion
-
-# Set to true to ignore issues in a milestone (defaults to false)
-exemptMilestones: true
-
-# Label to use when marking an issue as stale
-staleLabel: stale
-
-# Limit to only `issues` or `pulls`
-only: issues
-
-# Comment to post when marking an issue as stale. Set to `false` to disable
-markComment: >
- This issue has been automatically marked as stale because it has not had
- recent activity. It will be closed if no further activity occurs.
- If this is still an issue, just leave a comment 🙂
-
-# Comment to post when closing a stale issue. Set to `false` to disable
-closeComment: false
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 941c0ed80a0e..9a1d127fd6eb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,5 +1,9 @@
name: CI
-on: [push, pull_request]
+on:
+ push:
+ branches:
+ - v6
+ pull_request:
env:
SEQ_DB: sequelize_test
@@ -11,57 +15,134 @@ jobs:
name: Lint code and docs
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
- - uses: actions/setup-node@v1
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
+ with:
+ node-version: 18.x
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
+ - run: yarn lint
+ - run: yarn lint-docs
+ docs:
+ name: Generate docs
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
with:
- node-version: 12.x
- - run: npm install
- - run: npm run lint
- - run: npm run lint-docs
+ node-version: 18.x
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
+ - run: yarn docs
test-typings:
strategy:
fail-fast: false
matrix:
- ts-version: ['3.9', '4.0', '4.1']
+ ts-version: ["4.1", "4.2", "4.3", "4.4", "4.5", "4.6", "4.7", "4.8", "4.9", "5.0", "5.1", "5.2"]
name: TS Typings (${{ matrix.ts-version }})
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
- - uses: actions/setup-node@v1
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
+ with:
+ node-version: 18.x
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
+ - run: yarn add --dev typescript@~${{ matrix.ts-version }} --ignore-engines
+ - run: yarn test-typings
+ test-oracle:
+ strategy:
+ fail-fast: false
+ matrix:
+ oracle-version: [18, 23]
+ node-version: [10, 18]
+ name: Oracle DB ${{ matrix.oracle-version }} (Node ${{ matrix.node-version }})
+ runs-on: ubuntu-22.04
+ env:
+ DIALECT: oracle
+ SEQ_ORACLE_USER: sequelizetest
+ SEQ_ORACLE_PW: sequelizepassword
+ SEQ_ORACLE_DB: XEPDB1
+ SEQ_ORACLE_HOST: localhost
+ SEQ_ORACLE_PORT: 1521
+ LD_LIBRARY_PATH: ${{ github.workspace }}/.oracle/instantclient
+ UV_THREADPOOL_SIZE: 128
+ steps:
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
with:
- node-version: 12.x
- - run: npm install
- - run: npm install --save-dev typescript@~${{ matrix.ts-version }}
- - run: npm run test-typings
+ node-version: ${{ matrix.node-version }}
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
+ - if: matrix.oracle-version == '18'
+ name: Install Local Oracle DB 18
+ run: yarn start-oracle-oldest
+ - if: matrix.oracle-version == '23'
+ name: Install Local Oracle DB 23
+ run: yarn start-oracle-latest
+ - name: Unit Tests
+ run: yarn test-unit
+ - name: Integration Tests
+ run: yarn test-integration
+ test-db2:
+ strategy:
+ fail-fast: false
+ matrix:
+ node-version: [10, 18]
+ name: DB2 (Node ${{ matrix.node-version }})
+ runs-on: ubuntu-22.04
+ env:
+ DIALECT: db2
+ SEQ_DB: testdb
+ SEQ_USER: db2inst1
+ SEQ_PW: password
+ SEQ_TEST_CLEANUP_TIMEOUT: 1200000
+ SEQ_PORT: 50000
+ steps:
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ matrix.node-version }}
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
+ - name: Install Local DB2 Copy
+ run: yarn start-db2
+ - name: Unit Tests
+ run: yarn test-unit
+ continue-on-error: true
+ - name: Integration Tests
+ run: yarn test-integration
+ continue-on-error: true
test-sqlite:
strategy:
fail-fast: false
matrix:
- node-version: [10, 12]
+ node-version: [10, 18]
name: SQLite (Node ${{ matrix.node-version }})
- runs-on: ubuntu-latest
+ runs-on: ubuntu-22.04
env:
DIALECT: sqlite
steps:
- - uses: actions/checkout@v2
- - uses: actions/setup-node@v1
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- - run: npm install
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
- name: Unit Tests
- run: npm run test-unit
+ run: yarn test-unit
- name: Integration Tests
- run: npm run test-integration
+ run: yarn test-integration
test-postgres:
strategy:
fail-fast: false
matrix:
- node-version: [10, 12]
+ node-version: [10, 18]
postgres-version: [9.5, 10] # Does not work with 12
minify-aliases: [true, false]
native: [true, false]
name: Postgres ${{ matrix.postgres-version }}${{ matrix.native && ' (native)' || '' }} (Node ${{ matrix.node-version }})${{ matrix.minify-aliases && ' (minified aliases)' || '' }}
- runs-on: ubuntu-latest
+ runs-on: ubuntu-22.04
services:
postgres:
image: sushantdhiman/postgres:${{ matrix.postgres-version }}
@@ -78,18 +159,19 @@ jobs:
SEQ_PG_MINIFY_ALIASES: ${{ matrix.minify-aliases && '1' || '' }}
steps:
- run: PGPASSWORD=sequelize_test psql -h localhost -p 5432 -U sequelize_test sequelize_test -c '\l'
- - uses: actions/checkout@v2
- - uses: actions/setup-node@v1
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- - run: npm install
- - run: npm install pg-native
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
+ - run: yarn add pg-native --ignore-engines
if: matrix.native
- name: Unit Tests
- run: npm run test-unit
+ run: yarn test-unit
if: ${{ !matrix.minify-aliases }}
- name: Integration Tests
- run: npm run test-integration
+ run: yarn test-integration
test-mysql-mariadb:
strategy:
fail-fast: false
@@ -102,7 +184,15 @@ jobs:
- name: MySQL 5.7
image: mysql:5.7
dialect: mysql
- node-version: 12
+ node-version: 18
+ - name: MySQL 8.0
+ image: mysql:8.0
+ dialect: mysql
+ node-version: 10
+ - name: MySQL 8.0
+ image: mysql:8.0
+ dialect: mysql
+ node-version: 18
- name: MariaDB 10.3
image: mariadb:10.3
dialect: mariadb
@@ -110,9 +200,17 @@ jobs:
- name: MariaDB 10.3
image: mariadb:10.3
dialect: mariadb
- node-version: 12
+ node-version: 18
+ - name: MariaDB 10.5
+ image: mariadb:10.5
+ dialect: mariadb
+ node-version: 10
+ - name: MariaDB 10.5
+ image: mariadb:10.5
+ dialect: mariadb
+ node-version: 18
name: ${{ matrix.name }} (Node ${{ matrix.node-version }})
- runs-on: ubuntu-latest
+ runs-on: ubuntu-22.04
services:
mysql:
image: ${{ matrix.image }}
@@ -129,33 +227,35 @@ jobs:
DIALECT: ${{ matrix.dialect }}
steps:
- run: mysql --host 127.0.0.1 --port 3306 -uroot -psequelize_test -e "GRANT ALL ON *.* TO 'sequelize_test'@'%' with grant option; FLUSH PRIVILEGES;"
- - uses: actions/checkout@v2
- - uses: actions/setup-node@v1
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- - run: npm install
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
- name: Unit Tests
- run: npm run test-unit
+ run: yarn test-unit
- name: Integration Tests
- run: npm run test-integration
+ run: yarn test-integration
test-mssql:
strategy:
fail-fast: false
matrix:
- node-version: [10, 12]
+ node-version: [10, 18]
mssql-version: [2017, 2019]
name: MSSQL ${{ matrix.mssql-version }} (Node ${{ matrix.node-version }})
- runs-on: ubuntu-latest
+ runs-on: ubuntu-22.04
services:
mssql:
image: mcr.microsoft.com/mssql/server:${{ matrix.mssql-version }}-latest
env:
ACCEPT_EULA: Y
SA_PASSWORD: Password12!
+ MSSQL_SA_PASSWORD: Password12!
ports:
- 1433:1433
options: >-
- --health-cmd="/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P \"Password12!\" -l 30 -Q \"SELECT 1\""
+ --health-cmd="/opt/mssql-tools${{ matrix.mssql-version == '2019' && '18' || '' }}/bin/sqlcmd -S localhost -U SA -P \"Password12!\" -C -l 30 -Q \"SELECT 1\""
--health-start-period 10s
--health-interval 10s
--health-timeout 5s
@@ -166,28 +266,68 @@ jobs:
SEQ_PW: Password12!
SEQ_PORT: 1433
steps:
- - run: /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Password12!" -Q "CREATE DATABASE sequelize_test; ALTER DATABASE sequelize_test SET READ_COMMITTED_SNAPSHOT ON;"
- - uses: actions/checkout@v2
- - uses: actions/setup-node@v1
+ - run: /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Password12!" -C -Q "CREATE DATABASE sequelize_test; ALTER DATABASE sequelize_test SET READ_COMMITTED_SNAPSHOT ON;"
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- - run: npm install
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
- name: Unit Tests
- run: npm run test-unit
+ run: yarn test-unit
- name: Integration Tests
- run: npm run test-integration
+ run: yarn test-integration
+ test-snowflake:
+ strategy:
+ fail-fast: false
+ matrix:
+ node-version: [10, 18]
+ name: SNOWFLAKE (Node ${{ matrix.node-version }})
+ runs-on: ubuntu-22.04
+ env:
+ DIALECT: snowflake
+ steps:
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ matrix.node-version }}
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
+ - name: Unit Tests
+ run: yarn test-unit
+ # - name: Integration Tests
+ # run: yarn test-integration
release:
name: Release
runs-on: ubuntu-latest
- needs: [lint, test-typings, test-sqlite, test-postgres, test-mysql-mariadb, test-mssql]
- if: github.event_name == 'push' && github.ref == 'refs/heads/v6'
+ needs:
+ [
+ lint,
+ docs,
+ test-typings,
+ test-sqlite,
+ test-postgres,
+ test-mysql-mariadb,
+ ]
+ if: github.event_name == 'push' && (github.ref == 'refs/heads/v6' || github.ref == 'refs/heads/v6-beta')
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
steps:
- uses: actions/checkout@v2
- - uses: actions/setup-node@v1
+ - uses: actions/setup-node@v3
with:
- node-version: 12.x
- - run: npm install
+ node-version: 18.x
+ - run: yarn global add node-gyp --ignore-engines
+ - run: yarn install --frozen-lockfile --ignore-engines
- run: npx semantic-release
+ - id: sequelize
+ uses: sdepold/github-action-get-latest-release@master
+ with:
+ repository: sequelize/sequelize
+ - name: Notify channels
+ run: |
+ curl -XPOST -u "sdepold:${{ secrets.GH_TOKEN }}" -H "Accept: application/vnd.github.v3+json" -H "Content-Type: application/json" https://api.github.com/repos/sequelize/sequelize/dispatches --data '{"event_type":"Release notifier","client_payload":{"release-id": ${{ steps.sequelize.outputs.id }}}}'
+ - name: Notify docs repo
+ run: |
+ curl -XPOST -u "sdepold:${{ secrets.GH_TOKEN }}" -H "Accept: application/vnd.github.v3+json" -H "Content-Type: application/json" https://api.github.com/repos/sequelize/website/dispatches --data '{"event_type":"Build website"}'
diff --git a/.github/workflows/notify.yml b/.github/workflows/notify.yml
new file mode 100644
index 000000000000..d884405af71e
--- /dev/null
+++ b/.github/workflows/notify.yml
@@ -0,0 +1,28 @@
+name: Notify release channels
+on:
+ release:
+ types: [published]
+jobs:
+ tweet:
+ name: Tweet release
+ runs-on: ubuntu-latest
+ steps:
+ - uses: ethomson/send-tweet-action@v1
+ with:
+ status: "We have just released ${{ github.event.release.name }} of Sequelize. https://github.com/sequelize/sequelize/releases/tag/${{ github.event.release.name }}"
+ consumer-key: ${{ secrets.TWITTER_CONSUMER_API_KEY }}
+ consumer-secret: ${{ secrets.TWITTER_CONSUMER_API_SECRET }}
+ access-token: ${{ secrets.TWITTER_ACCESS_TOKEN }}
+ access-token-secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}
+ notify-opencollective:
+ name: Notify OpenCollective
+ runs-on: ubuntu-latest
+ steps:
+ - uses: sequelize/proxy-release-to-open-collective@main
+ with:
+ releaseId: ${{ github.event.release.id }}
+ projectSlug: sequelize/sequelize
+ ocSlug: sequelize
+ ocApiKey: ${{ secrets.OPEN_COLLECTIVE_KEY }}
+ githubToken: ${{ secrets.GITHUB_TOKEN }}
+
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
new file mode 100644
index 000000000000..99e744ce18ed
--- /dev/null
+++ b/.github/workflows/stale.yml
@@ -0,0 +1,22 @@
+name: "Stale issue handler"
+on:
+ workflow_dispatch:
+ schedule:
+ - cron: "0 0 * * *"
+
+jobs:
+ stale:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/stale@main
+ id: stale
+ with:
+ stale-issue-label: "stale"
+ stale-issue-message: 'This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂'
+ days-before-stale: 14
+ days-before-close: 14
+ operations-per-run: 1000
+ days-before-pr-close: -1
+ exempt-issue-labels: 'type: bug, type: docs, type: feature, type: other, type: performance, type: refactor, type: typescript' # All 'type: ' labels
+ - name: Print outputs
+ run: echo ${{ join(steps.stale.outputs.*, ',') }}
diff --git a/.gitignore b/.gitignore
index b47ee9c01b3e..54389f25c6e5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,7 +5,6 @@ npm-debug.log*
*~
test.sqlite
*.sublime*
-yarn.lock
.nyc_output
coverage-*
@@ -15,3 +14,6 @@ test/binary/tmp/*
.vscode/
esdoc
node_modules
+/lib
+/types
+.oracle/
diff --git a/.husky/commit-msg b/.husky/commit-msg
new file mode 100755
index 000000000000..d71a03b9f3e0
--- /dev/null
+++ b/.husky/commit-msg
@@ -0,0 +1,4 @@
+#!/bin/sh
+. "$(dirname "$0")/_/husky.sh"
+
+yarn commitlint --edit $1
diff --git a/.husky/pre-commit b/.husky/pre-commit
new file mode 100755
index 000000000000..d2ae35e84b09
--- /dev/null
+++ b/.husky/pre-commit
@@ -0,0 +1,4 @@
+#!/bin/sh
+. "$(dirname "$0")/_/husky.sh"
+
+yarn lint-staged
diff --git a/CONTACT.md b/CONTACT.md
index 0f7c3b636c8d..6c2f782067f1 100644
--- a/CONTACT.md
+++ b/CONTACT.md
@@ -5,6 +5,5 @@ You can use the information below to contact maintainers directly. We will try t
### Via Email
-- **Pedro Augusto de Paula Barbosa** papb1996@gmail.com
-- **Jan Aagaard Meier** janzeh@gmail.com
- **Sascha Depold** sascha@depold.com
+- **Fauzan** fncolon@pm.me
diff --git a/CONTRIBUTING.DOCS.md b/CONTRIBUTING.DOCS.md
index 844993d92094..579b0b8e6d55 100644
--- a/CONTRIBUTING.DOCS.md
+++ b/CONTRIBUTING.DOCS.md
@@ -9,12 +9,4 @@ The whole documentation is rendered using ESDoc and continuously deployed to Git
The tutorials, written in markdown, are located in the `docs` folder. ESDoc is configured to find them in the `"manual"` field of `.esdoc.json`.
-To generate the docs locally, run `npm run docs` and open the generated `esdoc/index.html` in your favorite browser.
-
-## Articles and example based docs
-
-Write markdown, and have fun :)
-
-## API docs
-
-Change the source code documentation comments, using JSDoc syntax, and rerun `npm run docs` to see your changes.
+To generate the documentations locally, run `npm run docs` and open the generated `esdoc/index.html` in your favorite browser.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a454b3b55ce9..479465728745 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,14 +2,14 @@
We are happy to see that you might be interested in contributing to Sequelize! There is no need to ask for permission to contribute. For example, anyone can open issues and propose changes to the source code (via Pull Requests). Here are some ways people can contribute:
-* Opening well-written bug reports (via [New Issue](https://github.com/sequelize/sequelize/issues/new/choose))
-* Opening well-written feature requests (via [New Issue](https://github.com/sequelize/sequelize/issues/new/choose))
-* Proposing improvements to the documentation (via [New Issue](https://github.com/sequelize/sequelize/issues/new/choose))
-* Opening Pull Requests to fix bugs or make other improvements
-* Reviewing (i.e. commenting on) open Pull Requests, to help their creators improve it if needed and allow maintainers to take less time looking into them
-* Helping to clarify issues opened by others, commenting and asking for clarification
-* Answering [questions tagged with `sequelize.js` on StackOverflow](https://stackoverflow.com/questions/tagged/sequelize.js)
-* Helping people in our [public Slack channel](https://sequelize.slack.com/) (note: if you don't have access, get yourself an invite automatically via [this link](http://sequelize-slack.herokuapp.com/))
+- Opening well-written bug reports (via [New Issue](https://github.com/sequelize/sequelize/issues/new/choose))
+- Opening well-written feature requests (via [New Issue](https://github.com/sequelize/sequelize/issues/new/choose))
+- Proposing improvements to the documentation (via [New Issue](https://github.com/sequelize/sequelize/issues/new/choose))
+- Opening Pull Requests to fix bugs or make other improvements
+- Reviewing (i.e. commenting on) open Pull Requests, to help their creators improve it if needed and allow maintainers to take less time looking into them
+- Helping to clarify issues opened by others, commenting and asking for clarification
+- Answering [questions tagged with `sequelize.js` on StackOverflow](https://stackoverflow.com/questions/tagged/sequelize.js)
+- Helping people in our [public Slack channel](https://sequelize.slack.com/) (note: if you don't have access, get yourself an invite automatically via [this link](https://sequelize.org/slack))
Sequelize is strongly moved by contributions from people like you. All maintainers also work on their free time here.
@@ -35,28 +35,27 @@ You can also create and execute your SSCCE locally: see [Section 5](https://gith
We're more than happy to accept feature requests! Before we get into how you can bring these to our attention, let's talk about our process for evaluating feature requests:
-- A feature request can have three states - *approved*, *pending* and *rejected*.
- - *Approved* feature requests are accepted by maintainers as a valuable addition to Sequelize, and are ready to be worked on by anyone.
- - *Rejected* feature requests were considered not applicable to be a part of the Sequelize ORM. This can change, so feel free to comment on a rejected feature request providing a good reasoning and clarification on why it should be reconsidered.
- - *Pending* feature requests are waiting to be looked at by maintainers. They may or may not need clarification. Contributors can still submit pull requests implementing a pending feature request, if they want, at their own risk of having the feature request rejected (and the pull request closed without being merged).
-
+- A feature request can have three states - _approved_, _pending_ and _rejected_.
+ - _Approved_ feature requests are accepted by maintainers as a valuable addition to Sequelize, and are ready to be worked on by anyone.
+ - _Rejected_ feature requests were considered not applicable to be a part of the Sequelize ORM. This can change, so feel free to comment on a rejected feature request providing a good reasoning and clarification on why it should be reconsidered.
+ - _Pending_ feature requests are waiting to be looked at by maintainers. They may or may not need clarification. Contributors can still submit pull requests implementing a pending feature request, if they want, at their own risk of having the feature request rejected (and the pull request closed without being merged).
Please be sure to communicate the following:
- 1. What problem your feature request aims to solve OR what aspect of the Sequelize workflow it aims to improve.
+1. What problem your feature request aims to solve OR what aspect of the Sequelize workflow it aims to improve.
- 2. Under what conditions are you anticipating this feature to be most beneficial?
+2. Under what conditions are you anticipating this feature to be most beneficial?
- 3. Why does it make sense that Sequelize should integrate this feature?
+3. Why does it make sense that Sequelize should integrate this feature?
- 4. See our [Feature Request template](https://github.com/sequelize/sequelize/blob/main/.github/ISSUE_TEMPLATE/feature_request.md) for more details on what to include. Please be sure to follow this template.
+4. See our [Feature Request template](https://github.com/sequelize/sequelize/blob/main/.github/ISSUE_TEMPLATE/feature_request.md) for more details on what to include. Please be sure to follow this template.
- If we don't approve your feature request, we'll provide you with our reasoning before closing it out. Some common reasons for denial may include (but are not limited to):
+If we don't approve your feature request, we'll provide you with our reasoning before closing it out. Some common reasons for denial may include (but are not limited to):
- - Something too similar to already exists within Sequelize
- - This feature seems out of scope of what Sequelize exists to accomplish
+- Something too similar to already exists within Sequelize
+- This feature seems out of scope of what Sequelize exists to accomplish
- We don't want to deny feature requests that could potentially make our users lives easier, so please be sure to clearly communicate your goals within your request!
+We don't want to deny feature requests that could potentially make our users lives easier, so please be sure to clearly communicate your goals within your request!
### Opening an issue to request improvements to the documentation
@@ -70,7 +69,7 @@ Anyone can open a Pull Request, there is no need to ask for permission. Maintain
The target of the Pull Request should be the `main` branch (or in rare cases the `v5` branch, if previously agreed with a maintainer).
-Please check the *allow edits from maintainers* box when opening it. Thank you in advance for any pull requests that you open!
+Please check the _allow edits from maintainers_ box when opening it. Thank you in advance for any pull requests that you open!
If you started to work on something but didn't finish it yet, you can open a draft pull request if you want (by choosing the "draft" option). Maintainers will know that it's not ready to be reviewed yet.
@@ -80,60 +79,66 @@ If your pull request implements a new feature, it's better if the feature was al
Once you open a pull request, our automated checks will run (they take a few minutes). Make sure they are all passing. If they're not, make new commits to your branch fixing that, and the pull request will pick them up automatically and rerun our automated checks.
-Note: if you believe a test failed but is completely unrelated to your changes, it could be a rare situation of a *flaky test* that is not your fault, and if it's indeed the case, and everything else passed, a maintainer will ignore the *flaky test* and merge your pull request, so don't worry.
+Note: if you believe a test failed but is completely unrelated to your changes, it could be a rare situation of a _flaky test_ that is not your fault, and if it's indeed the case, and everything else passed, a maintainer will ignore the _flaky test_ and merge your pull request, so don't worry.
A pull request that fixes a bug or implements a new feature must add at least one automated test that:
- Passes
- Would not pass if executed without your implementation
-
## How to prepare a development environment for Sequelize
### 0. Requirements
Most operating systems provide all the needed tools (including Windows, Linux and MacOS):
-* Mandatory:
+- Mandatory:
- * [Node.js](http://nodejs.org)
- * [Git](https://git-scm.com/)
+ - [Node.js](http://nodejs.org), it is preferred to use the current LTS version of Node
+ - [Git](https://git-scm.com/)
-* Optional (recommended):
+- Optional (recommended):
- * [Docker](https://docs.docker.com/get-docker/)
- * It is not mandatory because you can easily locally run tests against SQLite without it.
- * It is practically mandatory if you want to locally run tests against any other database engine (MySQL, MariaDB, Postgres and MSSQL), unless you happen to have the engine installed and is willing to make some manual configuration.
- * [Visual Studio Code](https://code.visualstudio.com/)
- * [EditorConfig extension](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig)
- * Also run `npm install --global editorconfig` to make sure this extension will work properly
- * [ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
+ - [Docker](https://docs.docker.com/get-docker/)
+ - It is not mandatory because you can easily locally run tests against SQLite without it.
+ - It is practically mandatory if you want to locally run tests against any other database engine (MySQL, MariaDB, Postgres,Db2 and MSSQL), unless you happen to have the engine installed and is willing to make some manual configuration.
+ - [Visual Studio Code](https://code.visualstudio.com/)
+ - [EditorConfig extension](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig)
+ - Also run `npm install --global editorconfig` to make sure this extension will work properly
+ - [ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
### 1. Clone the repository
-Clone the repository (if you haven't already) via `git clone https://github.com/sequelize/sequelize`. If you plan on submitting a pull request, you can create a fork by clicking the *fork* button and clone it instead with `git clone https://github.com/your-github-username/sequelize`, or add your fork as an upstream on the already cloned repo with `git remote add upstream https://github.com/your-github-username/sequelize`.
+Clone the repository (if you haven't already) via `git clone https://github.com/sequelize/sequelize`. If you plan on submitting a pull request, you can create a fork by clicking the _fork_ button and clone it instead with `git clone https://github.com/your-github-username/sequelize`, or add your fork as an upstream on the already cloned repo with `git remote add upstream https://github.com/your-github-username/sequelize`.
### 2. Install the Node.js dependencies
Run `npm install` (or `yarn install`) within the cloned repository folder.
+#### 2.1 Adding and updating dependencies
+
+[Yarn v1](https://classic.yarnpkg.com/en/) is used in the CI/CD pipeline so adding and updating dependencies must be done with Yarn v1. Depending on the Node version used, you might encounter a `Found incompatible module` error. To solve that, you can pass the `--ignore-engines` flag. This is not needed if you use Node `^14.17.0 || >=16.0.0`.
+
### 3. Prepare local databases to run tests
If you're happy to run tests only against an SQLite database, you can skip this section.
-#### 3a. With Docker (recommended)
+#### 3.1. With Docker (recommended)
If you have Docker installed, use any of the following commands to start fresh local databases of the dialect of your choice:
-* `npm run setup-mariadb`
-* `npm run setup-mysql`
-* `npm run setup-postgres`
-* `npm run setup-mssql`
+- `npm run start-mariadb`
+- `npm run start-mysql`
+- `npm run start-postgres`
+- `npm run start-mssql`
+- `npm run start-db2`
-*Note:* if you're using Windows, make sure you run these from Git Bash (or another MinGW environment), since these commands will execute bash scripts. Recall that [it's very easy to include Git Bash as your default integrated terminal on Visual Studio Code](https://code.visualstudio.com/docs/editor/integrated-terminal).
+_Note:_ if you're using Windows, make sure you run these from Git Bash (or another MinGW environment), since these commands will execute bash scripts. Recall that [it's very easy to include Git Bash as your default integrated terminal on Visual Studio Code](https://code.visualstudio.com/docs/editor/integrated-terminal).
Each of these commands will start a Docker container with the corresponding database, ready to run Sequelize tests (or an SSCCE).
+You can run `npm run stop-X` to stop the servers once you're done.
+
##### Hint for Postgres
You can also easily start a local [pgadmin4](https://www.pgadmin.org/docs/pgadmin4/latest/) instance at `localhost:8888` to inspect the contents of the test Postgres database as follows:
@@ -142,13 +147,10 @@ You can also easily start a local [pgadmin4](https://www.pgadmin.org/docs/pgadmi
docker run -d --name pgadmin4 -p 8888:80 -e 'PGADMIN_DEFAULT_EMAIL=test@example.com' -e 'PGADMIN_DEFAULT_PASSWORD=sequelize_test' dpage/pgadmin4
```
-#### 3b. Without Docker
+#### 3.2. Without Docker
You will have to manually install and configure each of database engines you want. Check the `dev/dialect-name` folder within this repository and look carefully at how it is defined via Docker and via the auxiliary bash script, and mimic that exactly (except for the database name, username, password, host and port, that you can customize via the `SEQ_DB`, `SEQ_USER`, `SEQ_PW`, `SEQ_HOST` and `SEQ_PORT` environment variables, respectively).
-
-
-
### 4. Running tests
Before starting any work, try to run the tests locally in order to be sure your setup is fine. Start by running the SQLite tests:
@@ -159,10 +161,11 @@ npm run test-sqlite
Then, if you want to run tests for another dialect, assuming you've set it up as written on section 3, run the corresponding command:
-* `npm run test-mysql`
-* `npm run test-mariadb`
-* `npm run test-postgres`
-* `npm run test-mssql`
+- `npm run test-mysql`
+- `npm run test-mariadb`
+- `npm run test-postgres`
+- `npm run test-mssql`
+- `npm run test-db2`
There are also the `test-unit-*` and `test-integration-*` sets of npm scripts (for example, `test-integration-postgres`).
@@ -173,21 +176,23 @@ While you're developing, you may want to execute only a single test (or a few),
Hint: if you're creating a new test, you can execute only that test locally against all dialects by adapting the `spec` and `grep` options on `.mocharc.jsonc` and running the following from your terminal (assuming you already set up the database instances via the corresponding `npm run setup-*` calls, as explained on [Section 3a](https://github.com/sequelize/sequelize/blob/main/CONTRIBUTING.md#3a-with-docker-recommended)):
```
-DIALECT=mariadb npx mocha && DIALECT=mysql npx mocha && DIALECT=postgres npx mocha && DIALECT=sqlite npx mocha && DIALECT=mssql npx mocha
+DIALECT=mariadb npx mocha && DIALECT=mysql npx mocha && DIALECT=postgres npx mocha && DIALECT=sqlite npx mocha && DIALECT=mssql npx mocha && DIALECT=db2 npx mocha
```
-
### 5. Running an SSCCE
-You can modify the `sscce.js` file (at the root of the repository) to create an [SSCCE](http://www.sscce.org/).
+What is SSCCE? [find out here](http://www.sscce.org/).
+
+You can modify the `sscce.js` file (at the root of the repository) to create an SSCCE.
Run it for the dialect of your choice using one of the following commands:
-* `npm run sscce-mariadb`
-* `npm run sscce-mysql`
-* `npm run sscce-postgres`
-* `npm run sscce-sqlite`
-* `npm run sscce-mssql`
+- `npm run sscce-mariadb`
+- `npm run sscce-mysql`
+- `npm run sscce-postgres`
+- `npm run sscce-sqlite`
+- `npm run sscce-mssql`
+- `npm run sscce-db2`
_Note:_ First, you need to set up (once) the database instance for corresponding dialect, as explained on [Section 3a](https://github.com/sequelize/sequelize/blob/main/CONTRIBUTING.md#3a-with-docker-recommended).
@@ -195,7 +200,6 @@ _Note:_ First, you need to set up (once) the database instance for corresponding
If you open the `package.json` file with Visual Studio Code, you will find a small `debug` button rendered right above the `"scripts": {` line. By clicking it, a popup will appear where you can choose which npm script you want to debug. Select one of the `sscce-*` scripts (listed above) and VSCode will immediately launch your SSCCE in debug mode (meaning that it will stop on any breakpoints that you place within `sscce.js` or any other Sequelize source code).
-
### 6. Commit your modifications
Sequelize follows the [AngularJS Commit Message Conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#heading=h.em2hiij8p46d). The allowed categories are `build`, `ci`, `docs`, `feat`, `fix`, `perf`, `refactor`, `revert`, `style`, `test` and `meta`.
diff --git a/ENGINE.md b/ENGINE.md
index 57f2d36e1066..1bcb2c084c23 100644
--- a/ENGINE.md
+++ b/ENGINE.md
@@ -1,10 +1,12 @@
# Database Engine Support
## v6
-| Engine | Minimum supported version |
-| :------------: | :------------: |
-| PostgreSQL | [9.5](https://www.postgresql.org/docs/9.5/ ) |
-| MySQL | [5.7](https://dev.mysql.com/doc/refman/5.7/en/) |
-| MariaDB | [10.3](https://mariadb.com/kb/en/changes-improvements-in-mariadb-103/) |
-| Microsoft SQL Server | `12.0.2000` |
-| SQLite | [3.0](https://www.sqlite.org/version3.html) |
+
+| Engine | Minimum supported version |
+| :------------------: | :---------------------------------------------------------------------------------------: |
+| PostgreSQL | [9.5.0](https://www.postgresql.org/docs/9.5/index.html) |
+| MySQL | [5.7.0](https://dev.mysql.com/doc/refman/5.7/en/) |
+| MariaDB | [10.1.44](https://mariadb.com/kb/en/changes-improvements-in-mariadb-101/) |
+| Microsoft SQL Server | [SQL Server 2014 Express](https://www.microsoft.com/en-US/download/details.aspx?id=42299) |
+| SQLite | [3.8.0](https://www.sqlite.org/version3.html) |
+| db2 | [11.5](https://www.ibm.com/in-en/products/db2-database) |
diff --git a/README.md b/README.md
index b1ae2d0b4297..3bc983b542ae 100644
--- a/README.md
+++ b/README.md
@@ -1,71 +1,83 @@
-# Sequelize
+
+
[](https://www.npmjs.com/package/sequelize)
[](https://github.com/sequelize/sequelize/actions?query=workflow%3ACI)
-
[](https://www.npmjs.com/package/sequelize)
+[](https://github.com/sequelize/sequelize/graphs/contributors)
+[](https://opencollective.com/sequelize#section-contributors)
+[](https://opencollective.com/sequelize)
[](https://github.com/sequelize/sequelize)
[](https://github.com/semantic-release/semantic-release)
+[](https://opensource.org/licenses/MIT)
-Sequelize is a promise-based [Node.js](https://nodejs.org/en/about/) [ORM tool](https://en.wikipedia.org/wiki/Object-relational_mapping) for [Postgres](https://en.wikipedia.org/wiki/PostgreSQL), [MySQL](https://en.wikipedia.org/wiki/MySQL), [MariaDB](https://en.wikipedia.org/wiki/MariaDB), [SQLite](https://en.wikipedia.org/wiki/SQLite) and [Microsoft SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server). It features solid transaction support, relations, eager and lazy loading, read replication and more.
+Sequelize is an easy-to-use and promise-based [Node.js](https://nodejs.org/en/about/) [ORM tool](https://en.wikipedia.org/wiki/Object-relational_mapping) for [Postgres](https://en.wikipedia.org/wiki/PostgreSQL), [MySQL](https://en.wikipedia.org/wiki/MySQL), [MariaDB](https://en.wikipedia.org/wiki/MariaDB), [SQLite](https://en.wikipedia.org/wiki/SQLite), [DB2](https://en.wikipedia.org/wiki/IBM_Db2_Family), [Microsoft SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server), and [Snowflake](https://www.snowflake.com/). It features solid transaction support, relations, eager and lazy loading, read replication and more.
-Sequelize follows [Semantic Versioning](http://semver.org) and supports Node v10 and above.
+Would you like to contribute? Read [our contribution guidelines](https://github.com/sequelize/sequelize/blob/main/CONTRIBUTING.md) to know more. There are many ways to help! 😃
-New to Sequelize? Take a look at the [Tutorials and Guides](https://sequelize.org/master). You might also be interested in the [API Reference](https://sequelize.org/master/identifiers).
+## 🚀 Seeking New Maintainers for Sequelize! 🚀
-Would you like to contribute? Read [our contribution guidelines](https://github.com/sequelize/sequelize/blob/main/CONTRIBUTING.md) to know more. There are many ways to help.
+We're looking for new maintainers to help finalize and release the next major version of Sequelize! If you're passionate about open-source and database ORMs, we'd love to have you onboard.
-### v6 Release
+### 💰 Funding Available
+We distribute **$2,500 per quarter** among maintainers and have additional funds for full-time contributions.
-You can find the detailed changelog [here](https://github.com/sequelize/sequelize/blob/main/docs/manual/other-topics/upgrade-to-v6.md).
+### 🛠️ What You’ll Work On
+- Finalizing and releasing Sequelize’s next major version
+- Improving TypeScript support and database integrations
+- Fixing critical issues and shaping the ORM’s future
-## Note: Looking for maintainers!
+### 🤝 How to Get Involved
+Interested? Join our Slack and reach out to **@WikiRik** or **@sdepold**:
+➡️ **[sequelize.org/slack](https://sequelize.org/slack)**
-Recently, a bigger part of the former core maintainers (thanks to all your hard work!) have been rather busy. Hence, the available time to look after our beloved ORM has been shrinking and shrinking drastically, generating a great chance for you:
+We’d love to have you on board! 🚀
-We are looking for more core maintainers who are interested in improving/fixing our TypeScript typings, improving the documentation, organizing issues, reviewing PRs, streamlining the overall code base and planning the future roadmap.
+## :computer: Getting Started
-If that sounds interesting to you, please reach out to us on [our Slack channel](https://sequelize.slack.com/) by sending a direct message to *Pedro A P B*. If you don't have access, get yourself an invite automatically via [this link](http://sequelize-slack.herokuapp.com/). We are looking forward to meet you!
+Ready to start using Sequelize? Head to [sequelize.org](https://sequelize.org) to begin!
-## Installation
+- [Our Getting Started guide for Sequelize 6 (stable)](https://sequelize.org/docs/v6/getting-started)
-```sh
-$ npm i sequelize # This will install v6
+## :money_with_wings: Supporting the project
-# And one of the following:
-$ npm i pg pg-hstore # Postgres
-$ npm i mysql2
-$ npm i mariadb
-$ npm i sqlite3
-$ npm i tedious # Microsoft SQL Server
-```
+Do you like Sequelize and would like to give back to the engineering team behind it?
-## Documentation
+We have recently created an [OpenCollective based money pool](https://opencollective.com/sequelize) which is shared amongst all core maintainers based on their contributions. Every support is wholeheartedly welcome. ❤️
-- [v6 Documentation](https://sequelize.org/master)
-- [v5/v4/v3 Documentation](https://sequelize.org)
-- [Contributing](https://github.com/sequelize/sequelize/blob/main/CONTRIBUTING.md)
+## :pencil: Major version changelog
-## Responsible disclosure
+Please find upgrade information to major versions here:
-If you have security issues to report, please refer to our [Responsible Disclosure Policy](https://github.com/sequelize/sequelize/blob/main/SECURITY.md) for more details.
+- [Upgrade from v5 to v6](https://sequelize.org/docs/v6/other-topics/upgrade-to-v6)
-## Resources
+## :book: Resources
+- [Documentation](https://sequelize.org)
+- [Databases Compatibility Table](https://sequelize.org/releases/)
- [Changelog](https://github.com/sequelize/sequelize/releases)
-- [Slack Inviter](http://sequelize-slack.herokuapp.com/)
+- [Discussions](https://github.com/sequelize/sequelize/discussions)
+- [Slack](https://sequelize.org/slack)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/sequelize.js)
-### Tools
+### :wrench: Tools
- [CLI](https://github.com/sequelize/cli)
-- [With TypeScript](https://sequelize.org/master/manual/typescript.html)
+- [With TypeScript](https://sequelize.org/docs/v6/other-topics/typescript)
- [Enhanced TypeScript with decorators](https://github.com/RobinBuschmann/sequelize-typescript)
- [For GraphQL](https://github.com/mickhansen/graphql-sequelize)
- [For CockroachDB](https://github.com/cockroachdb/sequelize-cockroachdb)
-- [Plugins](https://sequelize.org/master/manual/resources.html)
+- [Awesome Sequelize](https://sequelize.org/docs/v6/other-topics/resources/)
+- [For YugabyteDB](https://github.com/yugabyte/sequelize-yugabytedb)
-### Translations
+### :speech_balloon: Translations
-- [English](https://sequelize.org/master) (OFFICIAL)
-- [中文文档](https://github.com/demopark/sequelize-docs-Zh-CN) (UNOFFICIAL)
+- [English](https://sequelize.org) (Official)
+- [中文文档](https://github.com/demopark/sequelize-docs-Zh-CN) (Unofficial)
+
+## :warning: Responsible disclosure
+
+If you have security issues to report, please refer to our
+[Responsible Disclosure Policy](https://github.com/sequelize/sequelize/blob/main/SECURITY.md) for more details.
diff --git a/SECURITY.md b/SECURITY.md
index f204f8e8e29e..5260ac0b1702 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -6,8 +6,8 @@ The following table describes the versions of this project that are currently su
| Version | Supported |
| ------- | ------------------ |
-| 6.x | :heavy_check_mark: |
-| 5.x | :heavy_check_mark: |
+| 6.x | :heavy_check_mark: |
+| 5.x | :heavy_check_mark: |
## Responsible disclosure policy
diff --git a/build.js b/build.js
new file mode 100644
index 000000000000..a8b1f4604749
--- /dev/null
+++ b/build.js
@@ -0,0 +1,110 @@
+'use strict';
+
+const glob = require('fast-glob');
+const { promisify } = require('util');
+const { build } = require('esbuild');
+const fs = require('fs');
+const copyFiles = promisify( require('copyfiles'));
+const path = require('path');
+const exec = promisify(require('child_process').exec);
+
+const stat = promisify(fs.stat);
+const copyFile = promisify(fs.copyFile);
+
+// if this script is moved, this will need to be adjusted
+const rootDir = __dirname;
+const outdir = path.join(rootDir, 'lib');
+const typesDir = path.join(rootDir, 'types');
+
+const nodeMajorVersion = Number(process.version.match(/(?<=^v)\d+/));
+
+async function rmDir(dirName) {
+ try {
+ await stat(dirName);
+ if (nodeMajorVersion >= 14) {
+ const rm = promisify(fs.rm);
+ await rm(dirName, { recursive: true });
+ } else {
+ const rmdir = promisify(fs.rmdir);
+ if (nodeMajorVersion >= 12) {
+ await rmdir(dirName, { recursive: true });
+ } else {
+ await rmdir(dirName);
+ }}
+ } catch {
+ /* no-op */
+ }
+}
+
+async function main() {
+ console.log('Compiling sequelize...');
+ const [sourceFiles] = await Promise.all([
+ // Find all .js and .ts files from /src
+ glob('./src/**/*.{mjs,cjs,js,mts,cts,ts}', { onlyFiles: true, absolute: false }),
+ // Delete /lib for a full rebuild.
+ rmDir(outdir),
+ // Delete /types for a full rebuild.
+ rmDir(typesDir)
+ ]);
+
+ const filesToCompile = [];
+ const filesToCopyToLib = [];
+ const declarationFiles = [];
+
+ for (const file of sourceFiles) {
+ // mjs files cannot be built as they would be compiled to commonjs
+ if (file.endsWith('.mjs')) {
+ filesToCopyToLib.push(file);
+ } else if (file.endsWith('.d.ts')) {
+ declarationFiles.push(file);
+ } else {
+ filesToCompile.push(file);
+ }
+ }
+
+ // copy .d.ts files prior to generating them from the .ts files
+ // so the .ts files in lib/ will take priority..
+ await copyFiles(
+ // The last path in the list is the output directory
+ declarationFiles.concat(typesDir),
+ { up: 1 }
+ );
+
+ if (filesToCopyToLib.length > 0) {
+ await copyFiles(
+ // The last path in the list is the output directory
+ filesToCopyToLib.concat(outdir),
+ { up: 1 }
+ );
+ }
+
+ await Promise.all([
+ build({
+ // Adds source mapping
+ sourcemap: true,
+ // The compiled code should be usable in node v10
+ target: 'node10',
+ // The source code's format is commonjs.
+ format: 'cjs',
+
+ outdir,
+ entryPoints: filesToCompile
+ .map(file => path.resolve(file))
+ }),
+
+ exec('tsc', {
+ env: {
+ // binaries installed from modules have symlinks in
+ // /node_modules/.bin.
+ PATH: `${process.env.PATH || ''}:${path.join(
+ rootDir,
+ 'node_modules/.bin'
+ )}`
+ },
+ cwd: rootDir
+ })
+ ]);
+}
+
+main().catch(console.error).finally(process.exit);
+
diff --git a/dev/db2/11.5/.env_list b/dev/db2/11.5/.env_list
new file mode 100644
index 000000000000..2cf451f91a7e
--- /dev/null
+++ b/dev/db2/11.5/.env_list
@@ -0,0 +1,15 @@
+LICENSE=accept
+DB2INSTANCE=db2inst1
+DB2INST1_PASSWORD=password
+DBNAME=testdb
+BLU=false
+ENABLE_ORACLE_COMPATIBILITY=false
+UPDATEAVAIL=NO
+TO_CREATE_SAMPLEDB=false
+REPODB=false
+IS_OSXFS=false
+PERSISTENT_HOME=false
+HADR_ENABLED=false
+ETCD_ENDPOINT=
+ETCD_USERNAME=
+ETCD_PASSWORD=
\ No newline at end of file
diff --git a/dev/db2/11.5/check.js b/dev/db2/11.5/check.js
new file mode 100644
index 000000000000..c364203fd9eb
--- /dev/null
+++ b/dev/db2/11.5/check.js
@@ -0,0 +1,8 @@
+'use strict';
+
+const sequelize = require('../../../test/support').createSequelizeInstance();
+
+(async () => {
+ await sequelize.authenticate();
+ await sequelize.close();
+})();
diff --git a/dev/db2/11.5/start.sh b/dev/db2/11.5/start.sh
new file mode 100644
index 000000000000..110907b49c7a
--- /dev/null
+++ b/dev/db2/11.5/start.sh
@@ -0,0 +1,29 @@
+cd dev/db2/11.5
+export DIALECT=db2
+
+mkdir -p Docker
+if [ ! "$(sudo docker ps -q -f name=db2server)" ]; then
+ if [ "$(sudo docker ps -aq -f status=exited -f name=db2server)" ];
+ then
+ # cleanup
+ sudo docker rm -f db2server
+ sudo rm -rf /Docker
+ fi
+ sudo docker run -h db2server --name db2server --restart=always --detach --privileged=true -p 50000:50000 --env-file .env_list -v /Docker:/database ibmcom/db2-amd64:11.5.6.0a
+ count=1
+ while true
+ do
+ if (sudo docker logs db2server | grep 'Setup has completed')
+ then
+ sudo docker exec db2server bash -c "su db2inst1 & disown"
+ break
+ fi
+ if ($count -gt 30); then
+ echo "Error: Db2 docker setup has not completed in 10 minutes."
+ break
+ fi
+ sleep 20
+ let "count=count+1"
+ done
+ echo "Local DB2-11.5 instance is ready for Sequelize tests."
+fi
diff --git a/dev/db2/11.5/stop.sh b/dev/db2/11.5/stop.sh
new file mode 100644
index 000000000000..9a9741861310
--- /dev/null
+++ b/dev/db2/11.5/stop.sh
@@ -0,0 +1,3 @@
+sudo docker stop db2server
+
+echo "Local Db2 instance stopped (if it was running)."
diff --git a/dev/mariadb/10.3/start.sh b/dev/mariadb/10.3/start.sh
index 0e80e04f6520..492b19bca12e 100755
--- a/dev/mariadb/10.3/start.sh
+++ b/dev/mariadb/10.3/start.sh
@@ -3,14 +3,14 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-mariadb-103 down --remove-orphans
-docker-compose -p sequelize-mariadb-103 up -d
+docker compose -p sequelize-mariadb-103 down --remove-orphans
+docker compose -p sequelize-mariadb-103 up -d
./../../wait-until-healthy.sh sequelize-mariadb-103
docker exec sequelize-mariadb-103 \
mysql --host 127.0.0.1 --port 3306 -uroot -psequelize_test -e "GRANT ALL ON *.* TO 'sequelize_test'@'%' with grant option; FLUSH PRIVILEGES;"
-node check.js
+DIALECT=mariadb node check.js
echo "Local MariaDB-10.3 instance is ready for Sequelize tests."
diff --git a/dev/mariadb/10.3/stop.sh b/dev/mariadb/10.3/stop.sh
index e2629c115979..bee20b8ff7bd 100755
--- a/dev/mariadb/10.3/stop.sh
+++ b/dev/mariadb/10.3/stop.sh
@@ -3,6 +3,6 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-mariadb-103 down --remove-orphans
+docker compose -p sequelize-mariadb-103 down --remove-orphans
echo "Local MariaDB-10.3 instance stopped (if it was running)."
diff --git a/dev/mssql/2019/start.sh b/dev/mssql/2019/start.sh
index 9fe3c2b48997..61ec91ac623a 100755
--- a/dev/mssql/2019/start.sh
+++ b/dev/mssql/2019/start.sh
@@ -3,14 +3,14 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-mssql-2019 down --remove-orphans
-docker-compose -p sequelize-mssql-2019 up -d
+docker compose -p sequelize-mssql-2019 down --remove-orphans
+docker compose -p sequelize-mssql-2019 up -d
./../../wait-until-healthy.sh sequelize-mssql-2019
docker exec sequelize-mssql-2019 \
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Password12!" -Q "CREATE DATABASE sequelize_test; ALTER DATABASE sequelize_test SET READ_COMMITTED_SNAPSHOT ON;"
-node check.js
+DIALECT=mssql node check.js
echo "Local MSSQL-2019 instance is ready for Sequelize tests."
diff --git a/dev/mssql/2019/stop.sh b/dev/mssql/2019/stop.sh
index 0c8d73b3fee1..10249f0e619d 100755
--- a/dev/mssql/2019/stop.sh
+++ b/dev/mssql/2019/stop.sh
@@ -3,6 +3,6 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-mssql-2019 down --remove-orphans
+docker compose -p sequelize-mssql-2019 down --remove-orphans
echo "Local MSSQL-2019 instance stopped (if it was running)."
diff --git a/dev/mysql/5.7/start.sh b/dev/mysql/5.7/start.sh
index fb8b02a8b43d..8ef78e301c16 100755
--- a/dev/mysql/5.7/start.sh
+++ b/dev/mysql/5.7/start.sh
@@ -3,8 +3,8 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-mysql-57 down --remove-orphans
-docker-compose -p sequelize-mysql-57 up -d
+docker compose -p sequelize-mysql-57 down --remove-orphans
+docker compose -p sequelize-mysql-57 up -d
./../../wait-until-healthy.sh sequelize-mysql-57
diff --git a/dev/mysql/5.7/stop.sh b/dev/mysql/5.7/stop.sh
index 36e3e076065e..60c6a7b3d868 100755
--- a/dev/mysql/5.7/stop.sh
+++ b/dev/mysql/5.7/stop.sh
@@ -3,6 +3,6 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-mysql-57 down --remove-orphans
+docker compose -p sequelize-mysql-57 down --remove-orphans
echo "Local MySQL-5.7 instance stopped (if it was running)."
diff --git a/dev/mysql/8.0/check.js b/dev/mysql/8.0/check.js
new file mode 100644
index 000000000000..c364203fd9eb
--- /dev/null
+++ b/dev/mysql/8.0/check.js
@@ -0,0 +1,8 @@
+'use strict';
+
+const sequelize = require('../../../test/support').createSequelizeInstance();
+
+(async () => {
+ await sequelize.authenticate();
+ await sequelize.close();
+})();
diff --git a/dev/mysql/8.0/docker-compose.yml b/dev/mysql/8.0/docker-compose.yml
new file mode 100644
index 000000000000..fce29b8c9886
--- /dev/null
+++ b/dev/mysql/8.0/docker-compose.yml
@@ -0,0 +1,21 @@
+services:
+ mysql-80:
+ container_name: sequelize-mysql-80
+ image: mysql:8.0
+ environment:
+ MYSQL_DATABASE: sequelize_test
+ MYSQL_USER: sequelize_test
+ MYSQL_PASSWORD: sequelize_test
+ MYSQL_ROOT_PASSWORD: sequelize_test
+ ports:
+ - 20057:3306
+ # tmpfs: /var/lib/mysql:rw
+ healthcheck:
+ test: ["CMD", "mysqladmin", "-usequelize_test", "-psequelize_test", "status"]
+ interval: 3s
+ timeout: 1s
+ retries: 10
+
+networks:
+ default:
+ name: sequelize-mysql-80-network
diff --git a/dev/mysql/8.0/start.sh b/dev/mysql/8.0/start.sh
new file mode 100755
index 000000000000..046ba95d145b
--- /dev/null
+++ b/dev/mysql/8.0/start.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
+cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
+
+
+docker compose -p sequelize-mysql-80 down --remove-orphans
+docker compose -p sequelize-mysql-80 up -d
+
+./../../wait-until-healthy.sh sequelize-mysql-80
+
+docker exec sequelize-mysql-80 \
+ mysql --host 127.0.0.1 --port 3306 -uroot -psequelize_test -e "GRANT ALL ON *.* TO 'sequelize_test'@'%' with grant option; FLUSH PRIVILEGES;"
+
+node check.js
+
+echo "Local MySQL-8.0 instance is ready for Sequelize tests."
diff --git a/dev/mysql/8.0/stop.sh b/dev/mysql/8.0/stop.sh
new file mode 100755
index 000000000000..8bcf3da8323e
--- /dev/null
+++ b/dev/mysql/8.0/stop.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
+cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
+
+
+docker compose -p sequelize-mysql-80 down --remove-orphans
+
+echo "Local MySQL-8.0 instance stopped (if it was running)."
diff --git a/dev/oracle/18-slim/docker-compose.yml b/dev/oracle/18-slim/docker-compose.yml
new file mode 100644
index 000000000000..1ba87e65e686
--- /dev/null
+++ b/dev/oracle/18-slim/docker-compose.yml
@@ -0,0 +1,17 @@
+# Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved
+
+services:
+ oraclexedb:
+ container_name: oraclexedb
+ image: gvenzl/oracle-xe:18-slim
+ environment:
+ ORACLE_PASSWORD: password
+ ports:
+ - 1521:1521
+ healthcheck:
+ test: ["CMD-SHELL", "sqlplus", "system/password@XEPDB1"]
+ retries: 10
+
+networks:
+ default:
+ name: sequelize-oraclexedb-network
diff --git a/dev/oracle/18-slim/start.sh b/dev/oracle/18-slim/start.sh
new file mode 100755
index 000000000000..aa0c719e1797
--- /dev/null
+++ b/dev/oracle/18-slim/start.sh
@@ -0,0 +1,61 @@
+# Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved
+
+#!/usr/bin/env bash
+set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
+cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
+
+# Remove an existing Oracle DB docker image
+docker compose -p oraclexedb down --remove-orphans
+
+# Bring up new Oracle DB docker image
+docker compose -p oraclexedb up -d
+
+# Wait until Oracle DB is set up and docker state is healthy
+./../wait-until-healthy.sh oraclexedb
+
+# Moving privileges.sql to docker container
+docker cp ../privileges.sql oraclexedb:/opt/oracle/.
+
+# Granting all the needed privileges to sequelizetest user
+docker exec -t oraclexedb sqlplus system/password@XEPDB1 @privileges.sql
+
+SEQ_WORKSPACE="$PWD"/../../../
+
+if [[ ! -d "$SEQ_WORKSPACE"/.oracle/ ]]
+then
+ mkdir "$SEQ_WORKSPACE"/.oracle/
+ if [[ $(uname) == 'Linux' ]]
+ then
+ wget https://download.oracle.com/otn_software/linux/instantclient/217000/instantclient-basic-linux.x64-21.7.0.0.0dbru.zip --no-check-certificate &&
+ unzip instantclient-basic-linux.x64-21.7.0.0.0dbru.zip -d "$SEQ_WORKSPACE"/.oracle/ &&
+ rm instantclient-basic-linux.x64-21.7.0.0.0dbru.zip &&
+ mv "$SEQ_WORKSPACE"/.oracle/instantclient_21_7 "$SEQ_WORKSPACE"/.oracle/instantclient
+
+ echo "Local Oracle instant client on Linux has been setup!"
+ elif [[ $(uname) == 'Darwin' ]]
+ then
+ if [[ ! -d ~/Downloads/instantclient_19_8 ]]
+ then
+ curl -O https://download.oracle.com/otn_software/mac/instantclient/198000/instantclient-basic-macos.x64-19.8.0.0.0dbru.dmg &&
+ hdiutil mount instantclient-basic-macos.x64-19.8.0.0.0dbru.dmg &&
+ /Volumes/instantclient-basic-macos.x64-19.8.0.0.0dbru/install_ic.sh &&
+ hdiutil unmount /Volumes/instantclient-basic-macos.x64-19.8.0.0.0dbru &&
+ rm instantclient-basic-macos.x64-19.8.0.0.0dbru.dmg &&
+ mv ~/Downloads/instantclient_19_8/ "$SEQ_WORKSPACE"/.oracle/instantclient
+ else
+ cp -rf ~/Downloads/instantclient_19_8/ "$SEQ_WORKSPACE"/.oracle/instantclient
+ fi
+ ln -s "$SEQ_WORKSPACE"/.oracle/instantclient/libclntsh.dylib "$SEQ_WORKSPACE"/node_modules/oracledb/build/Release/
+
+ echo "Local Oracle instant client on macOS has been setup!"
+ else
+ # Windows
+ curl -O https://download.oracle.com/otn_software/nt/instantclient/216000/instantclient-basic-windows.x64-21.6.0.0.0dbru.zip &&
+ unzip instantclient-basic-windows.x64-21.6.0.0.0dbru.zip -d "$SEQ_WORKSPACE"/.oracle/ &&
+ rm instantclient-basic-windows.x64-21.6.0.0.0dbru.zip &&
+ mv "$SEQ_WORKSPACE"/.oracle/instantclient_21_6/* "$SEQ_WORKSPACE"/node_modules/oracledb/build/Release
+
+ echo "Local Oracle instant client on $(uname) has been setup!"
+ fi
+fi
+echo "Local Oracle DB is ready for use!"
diff --git a/dev/oracle/18-slim/stop.sh b/dev/oracle/18-slim/stop.sh
new file mode 100755
index 000000000000..d3ac45b9a0c4
--- /dev/null
+++ b/dev/oracle/18-slim/stop.sh
@@ -0,0 +1,10 @@
+# Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved
+
+#!/usr/bin/env bash
+set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
+cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
+
+
+docker compose -p oraclexedb down --remove-orphans
+
+echo "Local Oracle DB instance stopped (if it was running)."
diff --git a/dev/oracle/23-slim/docker-compose.yml b/dev/oracle/23-slim/docker-compose.yml
new file mode 100644
index 000000000000..95d8c749ed2e
--- /dev/null
+++ b/dev/oracle/23-slim/docker-compose.yml
@@ -0,0 +1,19 @@
+# Copyright (c) 2022, 2024 Oracle and/or its affiliates. All rights reserved
+
+services:
+ oraclexedb:
+ container_name: oraclexedb
+ image: gvenzl/oracle-free:23.4-slim
+ environment:
+ ORACLE_PASSWORD: password
+ ORACLE_DATABASE: XEPDB1
+
+ ports:
+ - 1521:1521
+ healthcheck:
+ test: ["CMD-SHELL", "sqlplus", "system/password@localhost:1521/XEPDB1"]
+ retries: 10
+
+networks:
+ default:
+ name: sequelize-oraclexedb-network
diff --git a/dev/oracle/23-slim/start.sh b/dev/oracle/23-slim/start.sh
new file mode 100755
index 000000000000..dd14eb1d476b
--- /dev/null
+++ b/dev/oracle/23-slim/start.sh
@@ -0,0 +1,61 @@
+# Copyright (c) 2022, 2024 Oracle and/or its affiliates. All rights reserved
+
+#!/usr/bin/env bash
+set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
+cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
+
+# Remove an existing Oracle DB docker image
+docker compose -p oraclexedb down --remove-orphans
+
+# Bring up new Oracle DB docker image
+docker compose -p oraclexedb up -d
+
+# Wait until Oracle DB is set up and docker state is healthy
+./../wait-until-healthy.sh oraclexedb
+
+# Moving privileges.sql to docker container
+docker cp ../privileges.sql oraclexedb:/opt/oracle/.
+
+# Granting all the needed privileges to sequelizetest user
+docker exec -t oraclexedb sqlplus system/password@localhost:1521/XEPDB1 @privileges.sql
+
+SEQ_WORKSPACE="$PWD"/../../../
+
+if [[ ! -d "$SEQ_WORKSPACE"/.oracle/ ]]
+then
+ mkdir "$SEQ_WORKSPACE"/.oracle/
+ if [[ $(uname) == 'Linux' ]]
+ then
+ wget https://download.oracle.com/otn_software/linux/instantclient/217000/instantclient-basic-linux.x64-21.7.0.0.0dbru.zip --no-check-certificate &&
+ unzip instantclient-basic-linux.x64-21.7.0.0.0dbru.zip -d "$SEQ_WORKSPACE"/.oracle/ &&
+ rm instantclient-basic-linux.x64-21.7.0.0.0dbru.zip &&
+ mv "$SEQ_WORKSPACE"/.oracle/instantclient_21_7 "$SEQ_WORKSPACE"/.oracle/instantclient
+
+ echo "Local Oracle instant client on Linux has been setup!"
+ elif [[ $(uname) == 'Darwin' ]]
+ then
+ if [[ ! -d ~/Downloads/instantclient_19_8 ]]
+ then
+ curl -O https://download.oracle.com/otn_software/mac/instantclient/198000/instantclient-basic-macos.x64-19.8.0.0.0dbru.dmg &&
+ hdiutil mount instantclient-basic-macos.x64-19.8.0.0.0dbru.dmg &&
+ /Volumes/instantclient-basic-macos.x64-19.8.0.0.0dbru/install_ic.sh &&
+ hdiutil unmount /Volumes/instantclient-basic-macos.x64-19.8.0.0.0dbru &&
+ rm instantclient-basic-macos.x64-19.8.0.0.0dbru.dmg &&
+ mv ~/Downloads/instantclient_19_8/ "$SEQ_WORKSPACE"/.oracle/instantclient
+ else
+ cp -rf ~/Downloads/instantclient_19_8/ "$SEQ_WORKSPACE"/.oracle/instantclient
+ fi
+ ln -s "$SEQ_WORKSPACE"/.oracle/instantclient/libclntsh.dylib "$SEQ_WORKSPACE"/node_modules/oracledb/build/Release/
+
+ echo "Local Oracle instant client on macOS has been setup!"
+ else
+ # Windows
+ curl -O https://download.oracle.com/otn_software/nt/instantclient/216000/instantclient-basic-windows.x64-21.6.0.0.0dbru.zip &&
+ unzip instantclient-basic-windows.x64-21.6.0.0.0dbru.zip -d "$SEQ_WORKSPACE"/.oracle/ &&
+ rm instantclient-basic-windows.x64-21.6.0.0.0dbru.zip &&
+ mv "$SEQ_WORKSPACE"/.oracle/instantclient_21_6/* "$SEQ_WORKSPACE"/node_modules/oracledb/build/Release
+
+ echo "Local Oracle instant client on $(uname) has been setup!"
+ fi
+fi
+echo "Local Oracle DB is ready for use!"
diff --git a/dev/oracle/23-slim/stop.sh b/dev/oracle/23-slim/stop.sh
new file mode 100755
index 000000000000..d3ac45b9a0c4
--- /dev/null
+++ b/dev/oracle/23-slim/stop.sh
@@ -0,0 +1,10 @@
+# Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved
+
+#!/usr/bin/env bash
+set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
+cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
+
+
+docker compose -p oraclexedb down --remove-orphans
+
+echo "Local Oracle DB instance stopped (if it was running)."
diff --git a/dev/oracle/privileges.sql b/dev/oracle/privileges.sql
new file mode 100644
index 000000000000..afea910fdc49
--- /dev/null
+++ b/dev/oracle/privileges.sql
@@ -0,0 +1,27 @@
+-- Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved
+
+create user sequelizetest identified by sequelizepassword;
+grant connect to sequelizetest with admin option;
+grant create session to sequelizetest with admin option;
+grant grant any privilege to sequelizetest with admin option;
+grant grant any role to sequelizetest with admin option;
+grant create any table to sequelizetest with admin option;
+grant insert any table to sequelizetest with admin option;
+grant select any table to sequelizetest with admin option;
+grant update any table to sequelizetest with admin option;
+grant delete any table to sequelizetest with admin option;
+grant drop any table to sequelizetest with admin option;
+grant create view to sequelizetest with admin option;
+grant create user to sequelizetest with admin option;
+grant drop user to sequelizetest with admin option;
+grant create any trigger to sequelizetest with admin option;
+grant create any procedure to sequelizetest with admin option;
+grant create any sequence to sequelizetest with admin option;
+grant select any sequence to sequelizetest with admin option;
+grant drop any sequence to sequelizetest with admin option;
+grant create any synonym to sequelizetest with admin option;
+grant create any index to sequelizetest with admin option;
+grant alter user to sequelizetest with admin option;
+grant alter any table to sequelizetest with admin option;
+alter user sequelizetest quota unlimited on users;
+exit;
diff --git a/dev/oracle/wait-until-healthy.sh b/dev/oracle/wait-until-healthy.sh
new file mode 100755
index 000000000000..096242f82a05
--- /dev/null
+++ b/dev/oracle/wait-until-healthy.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+
+if [ "$#" -ne 1 ]; then
+ >&2 echo "Please provide the container name or hash"
+ exit 1
+fi
+
+for _ in {1..50}
+do
+ state=$(docker inspect -f '{{ .State.Health.Status }}' $1 2>&1)
+ return_code=$?
+ if [ ${return_code} -eq 0 ] && [ "$state" == "healthy" ]; then
+ echo "$1 is healthy!"
+ sleep 60
+ exit 0
+ fi
+ sleep 6
+done
+
+>&2 echo "Timeout of 5m exceeded when waiting for container to be healthy: $1"
+exit 1
diff --git a/dev/postgres/10/start.sh b/dev/postgres/10/start.sh
index 6a2ea51738e9..fe0dc41117f1 100755
--- a/dev/postgres/10/start.sh
+++ b/dev/postgres/10/start.sh
@@ -3,8 +3,8 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-postgres-10 down --remove-orphans
-docker-compose -p sequelize-postgres-10 up -d
+docker compose -p sequelize-postgres-10 down --remove-orphans
+docker compose -p sequelize-postgres-10 up -d
./../../wait-until-healthy.sh sequelize-postgres-10
diff --git a/dev/postgres/10/stop.sh b/dev/postgres/10/stop.sh
index 907d2074513b..53dd5c47fbf7 100755
--- a/dev/postgres/10/stop.sh
+++ b/dev/postgres/10/stop.sh
@@ -3,6 +3,6 @@ set -Eeuxo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" # https://stackoverflow.com/a/17744637
-docker-compose -p sequelize-postgres-10 down --remove-orphans
+docker compose -p sequelize-postgres-10 down --remove-orphans
echo "Local Postgres-10 instance stopped (if it was running)."
diff --git a/dev/release-v6.ts b/dev/release-v6.ts
new file mode 100755
index 000000000000..dda5fd792e7b
--- /dev/null
+++ b/dev/release-v6.ts
@@ -0,0 +1,143 @@
+/* eslint-disable camelcase */
+/**
+ * Merges all the to be released commits into the v6 branch and pushes it to the remote.
+ * The push will then trigger the release process via the GitHub Action workflow.
+ *
+ * Main branch must be up-to-date. To be executed on the target branch.
+ *
+ * Usage:
+ * DRY_RUN= GITHUB_TOKEN= node_modules/.bin/ts-node dev/release-v6.ts
+ */
+
+import { Octokit } from '@octokit/rest';
+import { Endpoints } from '@octokit/types';
+import { execSync } from 'child_process';
+
+type Card =
+ Endpoints['GET /projects/columns/cards/{card_id}']['response']['data'];
+type PullRequest =
+ Endpoints['GET /repos/{owner}/{repo}/pulls/{pull_number}']['response']['data'];
+type CardCommit = {
+ card: Card;
+ commit: PullRequest;
+};
+
+const OWNER = 'sequelize';
+const REPO = 'sequelize';
+const TO_BE_RELEASED_COLUMN_ID = 17352881;
+const RELEASING_COLUMN_ID = 17444349;
+
+(async () => {
+ const token = process.env.GITHUB_TOKEN;
+
+ if (!token) {
+ console.error('GITHUB_TOKEN variable is not set');
+ process.exit(1);
+ }
+
+ const github = new Octokit({ auth: token });
+ const commits = await getCommitsFromProject(github);
+
+ await processCommitsInSeries(github, commits);
+})();
+
+// Helpers
+
+async function processCommitsInSeries(github: Octokit, commits: CardCommit[]) {
+ let commit: CardCommit | undefined = commits.shift();
+
+ while (commit) {
+ await mergeCommit(github, commit);
+ commit = commits.shift();
+ }
+}
+
+async function getCommitsFromProject(github: Octokit): Promise {
+ const cards = await github.rest.projects.listCards({
+ column_id: TO_BE_RELEASED_COLUMN_ID
+ });
+
+ const commits = await Promise.all(
+ cards.data.filter(isIssueCard).map(async (card: Card) => ({
+ card,
+ commit: await cardToMergedCommit(github, card)
+ }))
+ );
+
+ const filtered = commits.filter(({ commit }) =>
+ Boolean(commit)
+ ) as CardCommit[];
+
+ return filtered.sort(sortCommits);
+}
+
+function isIssueCard(card: Card) {
+ return card.content_url?.includes('/issues/');
+}
+
+async function cardToMergedCommit(
+ github: Octokit,
+ card: Card
+): Promise {
+ const issueNumber = card.content_url?.split('/').pop();
+ const { data: pullRequest } = await github.pulls.get({
+ owner: OWNER,
+ repo: REPO,
+ pull_number: Number(issueNumber)
+ });
+
+ if (!pullRequest?.merged) {
+ return;
+ }
+
+ return pullRequest;
+}
+
+function sortCommits(a: CardCommit, b: CardCommit) {
+ const aDate = new Date(a.commit.merged_at || '');
+ const bDate = new Date(b.commit.merged_at || '');
+
+ return aDate.getTime() - bDate.getTime();
+}
+
+async function mergeCommit(github: Octokit, { card, commit }: CardCommit) {
+ mergeCommitTeaser(commit);
+
+ if (commit.merge_commit_sha) {
+ await gitMerge(commit.merge_commit_sha);
+ await moveCard(github, card, RELEASING_COLUMN_ID);
+ }
+}
+
+function mergeCommitTeaser(commit: PullRequest) {
+ console.info();
+ console.info('Merging commit:', commit.title);
+ console.info('- Commit SHA:', commit.merge_commit_sha);
+ console.info('- Commit URL:', commit.html_url);
+}
+
+async function moveCard(github: Octokit, card: Card, to: number) {
+ let result = 'skipped';
+
+ if (process.env.DRY_RUN === 'false') {
+ const response = await github.rest.projects.moveCard({
+ card_id: card.id,
+ position: 'bottom',
+ column_id: to
+ });
+
+ result = response.status === 201 ? 'success' : 'error';
+ }
+
+ console.info('- Card moved to column:', result);
+}
+
+async function gitMerge(sha: string) {
+ const gitCommand = `git cherry-pick ${sha}`;
+
+ console.info('- Git command:', gitCommand);
+
+ if (process.env.DRY_RUN === 'false') {
+ execSync(gitCommand, { stdio: 'inherit' });
+ }
+}
diff --git a/docs.sh b/docs.sh
new file mode 100644
index 000000000000..d34b3dc61a7f
--- /dev/null
+++ b/docs.sh
@@ -0,0 +1,23 @@
+set -e
+
+rimraf esdoc
+
+exec 5>&1
+OUT=$(esdoc -c docs/esdoc-config.js|tee /dev/fd/5)
+
+cp docs/favicon.ico esdoc/favicon.ico
+cp docs/ROUTER.txt esdoc/ROUTER
+
+node docs/run-docs-transforms.js
+node docs/redirects/create-redirects.js
+
+rimraf esdoc/file esdoc/source.html
+
+set +e
+GREP_RESULT=$(echo "$OUT" | grep -c 'could not parse the following code\|SyntaxError')
+set -e
+
+if [ "$GREP_RESULT" -ge 1 ]; then
+ echo "esdoc generation encountered an error. See above logging for details."
+ exit 1
+fi
diff --git a/docs/ROUTER.txt b/docs/ROUTER.txt
index da1d58631241..b68706f2111e 100644
--- a/docs/ROUTER.txt
+++ b/docs/ROUTER.txt
@@ -10,18 +10,18 @@
301 /en/latest/docs/getting-started/ https://sequelize.org/master/manual/getting-started.html
301 /en/latest/docs/:section/ https://sequelize.org/master/manual/:section.html
-301 /en/latest/api/sequelize/ https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html
-301 /en/latest/api/model/ https://sequelize.org/master/class/lib/model.js~Model.html
-301 /en/latest/api/instance/ https://sequelize.org/master/class/lib/model.js~Model.html
-301 /en/latest/api/associations/ https://sequelize.org/master/class/lib/associations/base.js~Association.html
-301 /en/latest/api/associations/belongs-to/ https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html
-301 /en/latest/api/associations/belongs-to-many/ https://sequelize.org/master/class/lib/associations/belongs-to-.many.js~BelongsToMany.html
-301 /en/latest/api/associations/has-one/ https://sequelize.org/master/class/lib/associations/has-one.js~HasOne.html
-301 /en/latest/api/associations/has-many/ https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
-301 /en/latest/api/transaction/ https://sequelize.org/master/class/lib/transaction.js~Transaction.html
+301 /en/latest/api/sequelize/ https://sequelize.org/master/class/src/sequelize.js~Sequelize.html
+301 /en/latest/api/model/ https://sequelize.org/master/class/src/model.js~Model.html
+301 /en/latest/api/instance/ https://sequelize.org/master/class/src/model.js~Model.html
+301 /en/latest/api/associations/ https://sequelize.org/master/class/src/associations/base.js~Association.html
+301 /en/latest/api/associations/belongs-to/ https://sequelize.org/master/class/src/associations/belongs-to.js~BelongsTo.html
+301 /en/latest/api/associations/belongs-to-many/ https://sequelize.org/master/class/src/associations/belongs-to-.many.js~BelongsToMany.html
+301 /en/latest/api/associations/has-one/ https://sequelize.org/master/class/src/associations/has-one.js~HasOne.html
+301 /en/latest/api/associations/has-many/ https://sequelize.org/master/class/src/associations/has-many.js~HasMany.html
+301 /en/latest/api/transaction/ https://sequelize.org/master/class/src/transaction.js~Transaction.html
301 /en/latest/api/datatypes/ https://sequelize.org/master/variable/index.html#static-variable-DataTypes
301 /en/latest/api/deferrable/ https://sequelize.org/master/variable/index.html#static-variable-Deferrable
-301 /en/latest/api/errors/ https://sequelize.org/master/class/lib/errors/base-error.js~BaseError.html
+301 /en/latest/api/errors/ https://sequelize.org/master/class/src/errors/base-error.js~BaseError.html
301 /manual/tutorial/:section.html https://sequelize.org/master/manual/:section.html
301 /manual/installation/:section.html https://sequelize.org/master/manual/:section.html
@@ -33,4 +33,4 @@
301 /:foo/:bar/:baz https://sequelize.org/master/:foo/:bar/:baz
301 /:foo/:bar/:baz/:quz https://sequelize.org/master/:foo/:bar/:baz/:quz
-301 / https://sequelize.org/
\ No newline at end of file
+301 / https://sequelize.org/
diff --git a/docs/css/style.css b/docs/css/style.css
index c99916d7bb00..4c931cc131f2 100644
--- a/docs/css/style.css
+++ b/docs/css/style.css
@@ -1,15 +1,23 @@
@import url(https://fonts.googleapis.com/css?family=Titillium+Web);
+div.logo {
+ display: flex;
+ align-content: center;
+}
+
div.logo img {
- width: 200px;
- height: 200px;
+ width: 100px;
+ height: 100px;
box-shadow: none !important;
+ margin-right: 16px;
}
+div.logo h1,
div.sequelize {
color: #399af3;
font-size: 60px;
- font-family: 'Titillium Web', sans-serif;
+ font-family: "Titillium Web", sans-serif;
+ border-width: 0;
}
.center {
@@ -55,8 +63,8 @@ div.sequelize {
padding-bottom: 0;
}
-.search-box>span {
- display:block;
+.search-box > span {
+ display: block;
width: 100%;
}
@@ -129,11 +137,11 @@ code {
display: inline-block;
}
- .layout-container .navigation>div {
+ .layout-container .navigation > div {
display: none;
}
- .layout-container .navigation.open>div {
+ .layout-container .navigation.open > div {
display: block;
}
@@ -173,6 +181,6 @@ header a {
}
a[href="source.html"],
-a[href^="file/lib/"] {
+a[href^="file/src/"] {
display: none;
-}
\ No newline at end of file
+}
diff --git a/docs/esdoc-config.js b/docs/esdoc-config.js
index 3e2f3436a948..e43d76c09eab 100644
--- a/docs/esdoc-config.js
+++ b/docs/esdoc-config.js
@@ -1,13 +1,11 @@
'use strict';
-const { getDeclaredManuals, checkManuals } = require('./manual-utils');
-
-checkManuals();
-
module.exports = {
- source: './lib',
+ index: `${__dirname}/index.md`,
+ source: './src',
destination: './esdoc',
- includes: ['\\.js$'],
+ includes: ['\\.[tj]s$'],
+ excludes: ['\\.d.ts$'],
plugins: [
{
name: 'esdoc-ecmascript-proposal-plugin',
@@ -45,12 +43,13 @@ module.exports = {
site: 'https://sequelize.org/master/'
},
manual: {
- index: './docs/index.md',
- globalIndex: true,
asset: './docs/images',
- files: getDeclaredManuals()
+ files: []
}
}
+ },
+ {
+ name: './esdoc-ts'
}
]
};
diff --git a/docs/images/bitovi-logo.png b/docs/images/bitovi-logo.png
deleted file mode 100644
index a0bfca78f930..000000000000
Binary files a/docs/images/bitovi-logo.png and /dev/null differ
diff --git a/docs/images/clevertech.png b/docs/images/clevertech.png
deleted file mode 100644
index 70bb50fc6ca2..000000000000
Binary files a/docs/images/clevertech.png and /dev/null differ
diff --git a/docs/images/connected-cars.png b/docs/images/connected-cars.png
deleted file mode 100644
index 807e7fa91b3d..000000000000
Binary files a/docs/images/connected-cars.png and /dev/null differ
diff --git a/docs/images/ermeshotels-logo.png b/docs/images/ermeshotels-logo.png
deleted file mode 100644
index a1153b476d93..000000000000
Binary files a/docs/images/ermeshotels-logo.png and /dev/null differ
diff --git a/docs/images/filsh.png b/docs/images/filsh.png
deleted file mode 100644
index 9fa27f81a9a9..000000000000
Binary files a/docs/images/filsh.png and /dev/null differ
diff --git a/docs/images/logo-simple.svg b/docs/images/logo-simple.svg
new file mode 100644
index 000000000000..f8599b6c50f0
--- /dev/null
+++ b/docs/images/logo-simple.svg
@@ -0,0 +1 @@
+
diff --git a/docs/images/logo-snaplytics-green.png b/docs/images/logo-snaplytics-green.png
deleted file mode 100644
index c87113dc4887..000000000000
Binary files a/docs/images/logo-snaplytics-green.png and /dev/null differ
diff --git a/docs/images/logo.png b/docs/images/logo.png
deleted file mode 100644
index 3317765b1a4f..000000000000
Binary files a/docs/images/logo.png and /dev/null differ
diff --git a/docs/images/logo.svg b/docs/images/logo.svg
new file mode 100644
index 000000000000..0ee676a33cc8
--- /dev/null
+++ b/docs/images/logo.svg
@@ -0,0 +1,41 @@
+
+
diff --git a/docs/images/metamarkets.png b/docs/images/metamarkets.png
deleted file mode 100644
index 62180838027a..000000000000
Binary files a/docs/images/metamarkets.png and /dev/null differ
diff --git a/docs/images/shutterstock.png b/docs/images/shutterstock.png
deleted file mode 100644
index a89b014f2c8e..000000000000
Binary files a/docs/images/shutterstock.png and /dev/null differ
diff --git a/docs/images/slack.svg b/docs/images/slack.svg
deleted file mode 100644
index c37dc5eb49e3..000000000000
--- a/docs/images/slack.svg
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
diff --git a/docs/images/walmart-labs-logo.png b/docs/images/walmart-labs-logo.png
deleted file mode 100644
index f463966c4efa..000000000000
Binary files a/docs/images/walmart-labs-logo.png and /dev/null differ
diff --git a/docs/index.md b/docs/index.md
index 79bf6dc78615..1ff71d06b0ae 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,48 +1,3 @@
-
-
- 
-
-
Sequelize
-
+# Sequelize 6 API Reference
-[](https://www.npmjs.com/package/sequelize)
-[](https://github.com/sequelize/sequelize/actions?query=workflow%3ACI)
-[](https://www.npmjs.com/package/sequelize)
-
-[](https://github.com/sequelize/sequelize)
-[](https://github.com/sequelize/sequelize)
-[](https://github.com/sequelize/sequelize)
-[](http://sequelize-slack.herokuapp.com/)
-[](https://www.npmjs.com/package/sequelize)
-[](https://github.com/sequelize/sequelize/blob/main/LICENSE)
-[](https://github.com/semantic-release/semantic-release)
-
-Sequelize is a promise-based [Node.js](https://nodejs.org/en/about/) [ORM tool](https://en.wikipedia.org/wiki/Object-relational_mapping) for [Postgres](https://en.wikipedia.org/wiki/PostgreSQL), [MySQL](https://en.wikipedia.org/wiki/MySQL), [MariaDB](https://en.wikipedia.org/wiki/MariaDB), [SQLite](https://en.wikipedia.org/wiki/SQLite) and [Microsoft SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server). It features solid transaction support, relations, eager and lazy loading, read replication and more.
-
-Sequelize follows [Semantic Versioning](http://semver.org) and supports Node v10 and above.
-
-You are currently looking at the **Tutorials and Guides** for Sequelize. You might also be interested in the [API Reference](identifiers.html).
-
-## Quick example
-
-```js
-const { Sequelize, Model, DataTypes } = require('sequelize');
-const sequelize = new Sequelize('sqlite::memory:');
-
-class User extends Model {}
-User.init({
- username: DataTypes.STRING,
- birthday: DataTypes.DATE
-}, { sequelize, modelName: 'user' });
-
-(async () => {
- await sequelize.sync();
- const jane = await User.create({
- username: 'janedoe',
- birthday: new Date(1980, 6, 20)
- });
- console.log(jane.toJSON());
-})();
-```
-
-To learn more about how to use Sequelize, read the tutorials available in the left menu. Begin with [Getting Started](manual/getting-started.html).
+Click on an entry in the sidebar to open its API Reference.
diff --git a/docs/manual-groups.json b/docs/manual-groups.json
index 91bf48cc2753..a4a0596ec7dd 100644
--- a/docs/manual-groups.json
+++ b/docs/manual-groups.json
@@ -1,51 +1,52 @@
-{
- "Core Concepts": [
- "core-concepts/getting-started.md",
- "core-concepts/model-basics.md",
- "core-concepts/model-instances.md",
- "core-concepts/model-querying-basics.md",
- "core-concepts/model-querying-finders.md",
- "core-concepts/getters-setters-virtuals.md",
- "core-concepts/validations-and-constraints.md",
- "core-concepts/raw-queries.md",
- "core-concepts/assocs.md",
- "core-concepts/paranoid.md"
- ],
- "Advanced Association Concepts": [
- "advanced-association-concepts/eager-loading.md",
- "advanced-association-concepts/creating-with-associations.md",
- "advanced-association-concepts/advanced-many-to-many.md",
- "advanced-association-concepts/association-scopes.md",
- "advanced-association-concepts/polymorphic-associations.md"
- ],
- "Other Topics": [
- "other-topics/dialect-specific-things.md",
- "other-topics/transactions.md",
- "other-topics/hooks.md",
- "other-topics/query-interface.md",
- "other-topics/naming-strategies.md",
- "other-topics/scopes.md",
- "other-topics/sub-queries.md",
- "other-topics/other-data-types.md",
- "other-topics/constraints-and-circularities.md",
- "other-topics/extending-data-types.md",
- "other-topics/indexes.md",
- "other-topics/optimistic-locking.md",
- "other-topics/read-replication.md",
- "other-topics/connection-pool.md",
- "other-topics/legacy.md",
- "other-topics/migrations.md",
- "other-topics/typescript.md",
- "other-topics/resources.md",
- "other-topics/upgrade-to-v6.md",
- "other-topics/whos-using.md",
- "other-topics/legal.md"
- ],
- "__hidden__": [
- "moved/associations.md",
- "moved/data-types.md",
- "moved/models-definition.md",
- "moved/models-usage.md",
- "moved/querying.md"
- ]
-}
+{
+ "Core Concepts": [
+ "core-concepts/getting-started.md",
+ "core-concepts/model-basics.md",
+ "core-concepts/model-instances.md",
+ "core-concepts/model-querying-basics.md",
+ "core-concepts/model-querying-finders.md",
+ "core-concepts/getters-setters-virtuals.md",
+ "core-concepts/validations-and-constraints.md",
+ "core-concepts/raw-queries.md",
+ "core-concepts/assocs.md",
+ "core-concepts/paranoid.md"
+ ],
+ "Advanced Association Concepts": [
+ "advanced-association-concepts/eager-loading.md",
+ "advanced-association-concepts/creating-with-associations.md",
+ "advanced-association-concepts/advanced-many-to-many.md",
+ "advanced-association-concepts/association-scopes.md",
+ "advanced-association-concepts/polymorphic-associations.md"
+ ],
+ "Other Topics": [
+ "other-topics/dialect-specific-things.md",
+ "other-topics/transactions.md",
+ "other-topics/hooks.md",
+ "other-topics/query-interface.md",
+ "other-topics/naming-strategies.md",
+ "other-topics/scopes.md",
+ "other-topics/sub-queries.md",
+ "other-topics/other-data-types.md",
+ "other-topics/constraints-and-circularities.md",
+ "other-topics/extending-data-types.md",
+ "other-topics/indexes.md",
+ "other-topics/optimistic-locking.md",
+ "other-topics/read-replication.md",
+ "other-topics/connection-pool.md",
+ "other-topics/legacy.md",
+ "other-topics/migrations.md",
+ "other-topics/typescript.md",
+ "other-topics/resources.md",
+ "other-topics/upgrade-to-v6.md",
+ "other-topics/whos-using.md",
+ "other-topics/aws-lambda.md",
+ "other-topics/legal.md"
+ ],
+ "__hidden__": [
+ "moved/associations.md",
+ "moved/data-types.md",
+ "moved/models-definition.md",
+ "moved/models-usage.md",
+ "moved/querying.md"
+ ]
+}
diff --git a/docs/manual-utils.js b/docs/manual-utils.js
deleted file mode 100644
index a09ce52d216a..000000000000
--- a/docs/manual-utils.js
+++ /dev/null
@@ -1,37 +0,0 @@
-'use strict';
-
-const _ = require('lodash');
-const jetpack = require('fs-jetpack');
-const { normalize } = require('path');
-const assert = require('assert');
-
-function getDeclaredManuals() {
- const declaredManualGroups = require('./manual-groups.json');
- return _.flatten(Object.values(declaredManualGroups)).map(file => {
- return normalize(`./docs/manual/${file}`);
- });
-}
-
-function getAllManuals() {
- return jetpack.find('./docs/manual/', { matching: '*.md' }).map(m => {
- return normalize(`./${m}`);
- });
-}
-
-function checkManuals() {
- // First we check that declared manuals and all manuals are the same
- const declared = getDeclaredManuals().sort();
- const all = getAllManuals().sort();
- assert.deepStrictEqual(declared, all);
-
- // Then we check that every manual begins with a single `#`. This is
- // important for ESDoc to render the left menu correctly.
- for (const manualRelativePath of all) {
- assert(
- /^#[^#]/.test(jetpack.read(manualRelativePath)),
- `Manual '${manualRelativePath}' must begin with a single '#'`
- );
- }
-}
-
-module.exports = { getDeclaredManuals, getAllManuals, checkManuals };
diff --git a/docs/manual/advanced-association-concepts/advanced-many-to-many.md b/docs/manual/advanced-association-concepts/advanced-many-to-many.md
deleted file mode 100644
index 371f66201f8c..000000000000
--- a/docs/manual/advanced-association-concepts/advanced-many-to-many.md
+++ /dev/null
@@ -1,667 +0,0 @@
-# Advanced M:N Associations
-
-Make sure you have read the [associations guide](assocs.html) before reading this guide.
-
-Let's start with an example of a Many-to-Many relationship between `User` and `Profile`.
-
-```js
-const User = sequelize.define('user', {
- username: DataTypes.STRING,
- points: DataTypes.INTEGER
-}, { timestamps: false });
-const Profile = sequelize.define('profile', {
- name: DataTypes.STRING
-}, { timestamps: false });
-```
-
-The simplest way to define the Many-to-Many relationship is:
-
-```js
-User.belongsToMany(Profile, { through: 'User_Profiles' });
-Profile.belongsToMany(User, { through: 'User_Profiles' });
-```
-
-By passing a string to `through` above, we are asking Sequelize to automatically generate a model named `User_Profiles` as the *through table* (also known as junction table), with only two columns: `userId` and `profileId`. A composite unique key will be established on these two columns.
-
-We can also define ourselves a model to be used as the through table.
-
-```js
-const User_Profile = sequelize.define('User_Profile', {}, { timestamps: false });
-User.belongsToMany(Profile, { through: User_Profile });
-Profile.belongsToMany(User, { through: User_Profile });
-```
-
-The above has the exact same effect. Note that we didn't define any attributes on the `User_Profile` model. The fact that we passed it into a `belongsToMany` call tells sequelize to create the two attributes `userId` and `profileId` automatically, just like other associations also cause Sequelize to automatically add a column to one of the involved models.
-
-However, defining the model by ourselves has several advantages. We can, for example, define more columns on our through table:
-
-```js
-const User_Profile = sequelize.define('User_Profile', {
- selfGranted: DataTypes.BOOLEAN
-}, { timestamps: false });
-User.belongsToMany(Profile, { through: User_Profile });
-Profile.belongsToMany(User, { through: User_Profile });
-```
-
-With this, we can now track an extra information at the through table, namely the `selfGranted` boolean. For example, when calling the `user.addProfile()` we can pass values for the extra columns using the `through` option.
-
-Example:
-
-```js
-const amidala = await User.create({ username: 'p4dm3', points: 1000 });
-const queen = await Profile.create({ name: 'Queen' });
-await amidala.addProfile(queen, { through: { selfGranted: false } });
-const result = await User.findOne({
- where: { username: 'p4dm3' },
- include: Profile
-});
-console.log(result);
-```
-
-Output:
-
-```json
-{
- "id": 4,
- "username": "p4dm3",
- "points": 1000,
- "profiles": [
- {
- "id": 6,
- "name": "queen",
- "User_Profile": {
- "userId": 4,
- "profileId": 6,
- "selfGranted": false
- }
- }
- ]
-}
-```
-
-You can create all relationship in single `create` call too.
-
-Example:
-
-```js
-const amidala = await User.create({
- username: 'p4dm3',
- points: 1000,
- profiles: [{
- name: 'Queen',
- User_Profile: {
- selfGranted: true
- }
- }]
-}, {
- include: Profile
-});
-
-const result = await User.findOne({
- where: { username: 'p4dm3' },
- include: Profile
-});
-
-console.log(result);
-```
-
-Output:
-
-```json
-{
- "id": 1,
- "username": "p4dm3",
- "points": 1000,
- "profiles": [
- {
- "id": 1,
- "name": "Queen",
- "User_Profile": {
- "selfGranted": true,
- "userId": 1,
- "profileId": 1
- }
- }
- ]
-}
-```
-
-You probably noticed that the `User_Profiles` table does not have an `id` field. As mentioned above, it has a composite unique key instead. The name of this composite unique key is chosen automatically by Sequelize but can be customized with the `uniqueKey` option:
-
-```js
-User.belongsToMany(Profile, { through: User_Profiles, uniqueKey: 'my_custom_unique' });
-```
-
-Another possibility, if desired, is to force the through table to have a primary key just like other standard tables. To do this, simply define the primary key in the model:
-
-```js
-const User_Profile = sequelize.define('User_Profile', {
- id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true,
- allowNull: false
- },
- selfGranted: DataTypes.BOOLEAN
-}, { timestamps: false });
-User.belongsToMany(Profile, { through: User_Profile });
-Profile.belongsToMany(User, { through: User_Profile });
-```
-
-The above will still create two columns `userId` and `profileId`, of course, but instead of setting up a composite unique key on them, the model will use its `id` column as primary key. Everything else will still work just fine.
-
-## Through tables versus normal tables and the "Super Many-to-Many association"
-
-Now we will compare the usage of the last Many-to-Many setup shown above with the usual One-to-Many relationships, so that in the end we conclude with the concept of a *"Super Many-to-Many relationship"*.
-
-### Models recap (with minor rename)
-
-To make things easier to follow, let's rename our `User_Profile` model to `grant`. Note that everything works in the same way as before. Our models are:
-
-```js
-const User = sequelize.define('user', {
- username: DataTypes.STRING,
- points: DataTypes.INTEGER
-}, { timestamps: false });
-
-const Profile = sequelize.define('profile', {
- name: DataTypes.STRING
-}, { timestamps: false });
-
-const Grant = sequelize.define('grant', {
- id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true,
- allowNull: false
- },
- selfGranted: DataTypes.BOOLEAN
-}, { timestamps: false });
-```
-
-We established a Many-to-Many relationship between `User` and `Profile` using the `Grant` model as the through table:
-
-```js
-User.belongsToMany(Profile, { through: Grant });
-Profile.belongsToMany(User, { through: Grant });
-```
-
-This automatically added the columns `userId` and `profileId` to the `Grant` model.
-
-**Note:** As shown above, we have chosen to force the `grant` model to have a single primary key (called `id`, as usual). This is necessary for the *Super Many-to-Many relationship* that will be defined soon.
-
-### Using One-to-Many relationships instead
-
-Instead of setting up the Many-to-Many relationship defined above, what if we did the following instead?
-
-```js
-// Setup a One-to-Many relationship between User and Grant
-User.hasMany(Grant);
-Grant.belongsTo(User);
-
-// Also setup a One-to-Many relationship between Profile and Grant
-Profile.hasMany(Grant);
-Grant.belongsTo(Profile);
-```
-
-The result is essentially the same! This is because `User.hasMany(Grant)` and `Profile.hasMany(Grant)` will automatically add the `userId` and `profileId` columns to `Grant`, respectively.
-
-This shows that one Many-to-Many relationship isn't very different from two One-to-Many relationships. The tables in the database look the same.
-
-The only difference is when you try to perform an eager load with Sequelize.
-
-```js
-// With the Many-to-Many approach, you can do:
-User.findAll({ include: Profile });
-Profile.findAll({ include: User });
-// However, you can't do:
-User.findAll({ include: Grant });
-Profile.findAll({ include: Grant });
-Grant.findAll({ include: User });
-Grant.findAll({ include: Profile });
-
-// On the other hand, with the double One-to-Many approach, you can do:
-User.findAll({ include: Grant });
-Profile.findAll({ include: Grant });
-Grant.findAll({ include: User });
-Grant.findAll({ include: Profile });
-// However, you can't do:
-User.findAll({ include: Profile });
-Profile.findAll({ include: User });
-// Although you can emulate those with nested includes, as follows:
-User.findAll({
- include: {
- model: Grant,
- include: Profile
- }
-}); // This emulates the `User.findAll({ include: Profile })`, however
- // the resulting object structure is a bit different. The original
- // structure has the form `user.profiles[].grant`, while the emulated
- // structure has the form `user.grants[].profiles[]`.
-```
-
-### The best of both worlds: the Super Many-to-Many relationship
-
-We can simply combine both approaches shown above!
-
-```js
-// The Super Many-to-Many relationship
-User.belongsToMany(Profile, { through: Grant });
-Profile.belongsToMany(User, { through: Grant });
-User.hasMany(Grant);
-Grant.belongsTo(User);
-Profile.hasMany(Grant);
-Grant.belongsTo(Profile);
-```
-
-This way, we can do all kinds of eager loading:
-
-```js
-// All these work:
-User.findAll({ include: Profile });
-Profile.findAll({ include: User });
-User.findAll({ include: Grant });
-Profile.findAll({ include: Grant });
-Grant.findAll({ include: User });
-Grant.findAll({ include: Profile });
-```
-
-We can even perform all kinds of deeply nested includes:
-
-```js
-User.findAll({
- include: [
- {
- model: Grant,
- include: [User, Profile]
- },
- {
- model: Profile,
- include: {
- model: User,
- include: {
- model: Grant,
- include: [User, Profile]
- }
- }
- }
- ]
-});
-```
-
-## Aliases and custom key names
-
-Similarly to the other relationships, aliases can be defined for Many-to-Many relationships.
-
-Before proceeding, please recall [the aliasing example for `belongsTo`](assocs.html#defining-an-alias) on the [associations guide](assocs.html). Note that, in that case, defining an association impacts both the way includes are done (i.e. passing the association name) and the name Sequelize chooses for the foreign key (in that example, `leaderId` was created on the `Ship` model).
-
-Defining an alias for a `belongsToMany` association also impacts the way includes are performed:
-
-```js
-Product.belongsToMany(Category, { as: 'groups', through: 'product_categories' });
-Category.belongsToMany(Product, { as: 'items', through: 'product_categories' });
-
-// [...]
-
-await Product.findAll({ include: Category }); // This doesn't work
-
-await Product.findAll({ // This works, passing the alias
- include: {
- model: Category,
- as: 'groups'
- }
-});
-
-await Product.findAll({ include: 'groups' }); // This also works
-```
-
-However, defining an alias here has nothing to do with the foreign key names. The names of both foreign keys created in the through table are still constructed by Sequelize based on the name of the models being associated. This can readily be seen by inspecting the generated SQL for the through table in the example above:
-
-```sql
-CREATE TABLE IF NOT EXISTS `product_categories` (
- `createdAt` DATETIME NOT NULL,
- `updatedAt` DATETIME NOT NULL,
- `productId` INTEGER NOT NULL REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- `categoryId` INTEGER NOT NULL REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- PRIMARY KEY (`productId`, `categoryId`)
-);
-```
-
-We can see that the foreign keys are `productId` and `categoryId`. To change these names, Sequelize accepts the options `foreignKey` and `otherKey` respectively (i.e., the `foreignKey` defines the key for the source model in the through relation, and `otherKey` defines it for the target model):
-
-```js
-Product.belongsToMany(Category, {
- through: 'product_categories',
- foreignKey: 'objectId', // replaces `productId`
- otherKey: 'typeId' // replaces `categoryId`
-});
-Category.belongsToMany(Product, {
- through: 'product_categories',
- foreignKey: 'typeId', // replaces `categoryId`
- otherKey: 'objectId' // replaces `productId`
-});
-```
-
-Generated SQL:
-
-```sql
-CREATE TABLE IF NOT EXISTS `product_categories` (
- `createdAt` DATETIME NOT NULL,
- `updatedAt` DATETIME NOT NULL,
- `objectId` INTEGER NOT NULL REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- `typeId` INTEGER NOT NULL REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- PRIMARY KEY (`objectId`, `typeId`)
-);
-```
-
-As shown above, when you define a Many-to-Many relationship with two `belongsToMany` calls (which is the standard way), you should provide the `foreignKey` and `otherKey` options appropriately in both calls. If you pass these options in only one of the calls, the Sequelize behavior will be unreliable.
-
-## Self-references
-
-Sequelize supports self-referential Many-to-Many relationships, intuitively:
-
-```js
-Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
-// This will create the table PersonChildren which stores the ids of the objects.
-```
-
-## Specifying attributes from the through table
-
-By default, when eager loading a many-to-many relationship, Sequelize will return data in the following structure (based on the first example in this guide):
-
-```json
-// User.findOne({ include: Profile })
-{
- "id": 4,
- "username": "p4dm3",
- "points": 1000,
- "profiles": [
- {
- "id": 6,
- "name": "queen",
- "grant": {
- "userId": 4,
- "profileId": 6,
- "selfGranted": false
- }
- }
- ]
-}
-```
-
-Notice that the outer object is an `User`, which has a field called `profiles`, which is a `Profile` array, such that each `Profile` comes with an extra field called `grant` which is a `Grant` instance. This is the default structure created by Sequelize when eager loading from a Many-to-Many relationship.
-
-However, if you want only some of the attributes of the through table, you can provide an array with the attributes you want in the `attributes` option. For example, if you only want the `selfGranted` attribute from the through table:
-
-```js
-User.findOne({
- include: {
- model: Profile,
- through: {
- attributes: ['selfGranted']
- }
- }
-});
-```
-
-Output:
-
-```json
-{
- "id": 4,
- "username": "p4dm3",
- "points": 1000,
- "profiles": [
- {
- "id": 6,
- "name": "queen",
- "grant": {
- "selfGranted": false
- }
- }
- ]
-}
-```
-
-If you don't want the nested `grant` field at all, use `attributes: []`:
-
-```js
-User.findOne({
- include: {
- model: Profile,
- through: {
- attributes: []
- }
- }
-});
-```
-
-Output:
-
-```json
-{
- "id": 4,
- "username": "p4dm3",
- "points": 1000,
- "profiles": [
- {
- "id": 6,
- "name": "queen"
- }
- ]
-}
-```
-
-If you are using mixins (such as `user.getProfiles()`) instead of finder methods (such as `User.findAll()`), you have to use the `joinTableAttributes` option instead:
-
-```js
-someUser.getProfiles({ joinTableAttributes: ['selfGranted'] });
-```
-
-Output:
-
-```json
-[
- {
- "id": 6,
- "name": "queen",
- "grant": {
- "selfGranted": false
- }
- }
-]
-```
-
-## Many-to-many-to-many relationships and beyond
-
-Consider you are trying to model a game championship. There are players and teams. Teams play games. However, players can change teams in the middle of the championship (but not in the middle of a game). So, given one specific game, there are certain teams participating in that game, and each of these teams has a set of players (for that game).
-
-So we start by defining the three relevant models:
-
-```js
-const Player = sequelize.define('Player', { username: DataTypes.STRING });
-const Team = sequelize.define('Team', { name: DataTypes.STRING });
-const Game = sequelize.define('Game', { name: DataTypes.INTEGER });
-```
-
-Now, the question is: how to associate them?
-
-First, we note that:
-
-* One game has many teams associated to it (the ones that are playing that game);
-* One team may have participated in many games.
-
-The above observations show that we need a Many-to-Many relationship between Game and Team. Let's use the Super Many-to-Many relationship as explained earlier in this guide:
-
-```js
-// Super Many-to-Many relationship between Game and Team
-const GameTeam = sequelize.define('GameTeam', {
- id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true,
- allowNull: false
- }
-});
-Team.belongsToMany(Game, { through: GameTeam });
-Game.belongsToMany(Team, { through: GameTeam });
-GameTeam.belongsTo(Game);
-GameTeam.belongsTo(Team);
-Game.hasMany(GameTeam);
-Team.hasMany(GameTeam);
-```
-
-The part about players is trickier. We note that the set of players that form a team depends not only on the team (obviously), but also on which game is being considered. Therefore, we don't want a Many-to-Many relationship between Player and Team. We also don't want a Many-to-Many relationship between Player and Game. Instead of associating a Player to any of those models, what we need is an association between a Player and something like a *"team-game pair constraint"*, since it is the pair (team plus game) that defines which players belong there. So what we are looking for turns out to be precisely the junction model, GameTeam, itself! And, we note that, since a given *game-team pair* specifies many players, and on the other hand that the same player can participate of many *game-team pairs*, we need a Many-to-Many relationship between Player and GameTeam!
-
-To provide the greatest flexibility, let's use the Super Many-to-Many relationship construction here again:
-
-```js
-// Super Many-to-Many relationship between Player and GameTeam
-const PlayerGameTeam = sequelize.define('PlayerGameTeam', {
- id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true,
- allowNull: false
- }
-});
-Player.belongsToMany(GameTeam, { through: PlayerGameTeam });
-GameTeam.belongsToMany(Player, { through: PlayerGameTeam });
-PlayerGameTeam.belongsTo(Player);
-PlayerGameTeam.belongsTo(GameTeam);
-Player.hasMany(PlayerGameTeam);
-GameTeam.hasMany(PlayerGameTeam);
-```
-
-The above associations achieve precisely what we want. Here is a full runnable example of this:
-
-```js
-const { Sequelize, Op, Model, DataTypes } = require('sequelize');
-const sequelize = new Sequelize('sqlite::memory:', {
- define: { timestamps: false } // Just for less clutter in this example
-});
-const Player = sequelize.define('Player', { username: DataTypes.STRING });
-const Team = sequelize.define('Team', { name: DataTypes.STRING });
-const Game = sequelize.define('Game', { name: DataTypes.INTEGER });
-
-// We apply a Super Many-to-Many relationship between Game and Team
-const GameTeam = sequelize.define('GameTeam', {
- id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true,
- allowNull: false
- }
-});
-Team.belongsToMany(Game, { through: GameTeam });
-Game.belongsToMany(Team, { through: GameTeam });
-GameTeam.belongsTo(Game);
-GameTeam.belongsTo(Team);
-Game.hasMany(GameTeam);
-Team.hasMany(GameTeam);
-
-// We apply a Super Many-to-Many relationship between Player and GameTeam
-const PlayerGameTeam = sequelize.define('PlayerGameTeam', {
- id: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true,
- allowNull: false
- }
-});
-Player.belongsToMany(GameTeam, { through: PlayerGameTeam });
-GameTeam.belongsToMany(Player, { through: PlayerGameTeam });
-PlayerGameTeam.belongsTo(Player);
-PlayerGameTeam.belongsTo(GameTeam);
-Player.hasMany(PlayerGameTeam);
-GameTeam.hasMany(PlayerGameTeam);
-
-(async () => {
-
- await sequelize.sync();
- await Player.bulkCreate([
- { username: 's0me0ne' },
- { username: 'empty' },
- { username: 'greenhead' },
- { username: 'not_spock' },
- { username: 'bowl_of_petunias' }
- ]);
- await Game.bulkCreate([
- { name: 'The Big Clash' },
- { name: 'Winter Showdown' },
- { name: 'Summer Beatdown' }
- ]);
- await Team.bulkCreate([
- { name: 'The Martians' },
- { name: 'The Earthlings' },
- { name: 'The Plutonians' }
- ]);
-
- // Let's start defining which teams were in which games. This can be done
- // in several ways, such as calling `.setTeams` on each game. However, for
- // brevity, we will use direct `create` calls instead, referring directly
- // to the IDs we want. We know that IDs are given in order starting from 1.
- await GameTeam.bulkCreate([
- { GameId: 1, TeamId: 1 }, // this GameTeam will get id 1
- { GameId: 1, TeamId: 2 }, // this GameTeam will get id 2
- { GameId: 2, TeamId: 1 }, // this GameTeam will get id 3
- { GameId: 2, TeamId: 3 }, // this GameTeam will get id 4
- { GameId: 3, TeamId: 2 }, // this GameTeam will get id 5
- { GameId: 3, TeamId: 3 } // this GameTeam will get id 6
- ]);
-
- // Now let's specify players.
- // For brevity, let's do it only for the second game (Winter Showdown).
- // Let's say that that s0me0ne and greenhead played for The Martians, while
- // not_spock and bowl_of_petunias played for The Plutonians:
- await PlayerGameTeam.bulkCreate([
- // In 'Winter Showdown' (i.e. GameTeamIds 3 and 4):
- { PlayerId: 1, GameTeamId: 3 }, // s0me0ne played for The Martians
- { PlayerId: 3, GameTeamId: 3 }, // greenhead played for The Martians
- { PlayerId: 4, GameTeamId: 4 }, // not_spock played for The Plutonians
- { PlayerId: 5, GameTeamId: 4 } // bowl_of_petunias played for The Plutonians
- ]);
-
- // Now we can make queries!
- const game = await Game.findOne({
- where: {
- name: "Winter Showdown"
- },
- include: {
- model: GameTeam,
- include: [
- {
- model: Player,
- through: { attributes: [] } // Hide unwanted `PlayerGameTeam` nested object from results
- },
- Team
- ]
- }
- });
-
- console.log(`Found game: "${game.name}"`);
- for (let i = 0; i < game.GameTeams.length; i++) {
- const team = game.GameTeams[i].Team;
- const players = game.GameTeams[i].Players;
- console.log(`- Team "${team.name}" played game "${game.name}" with the following players:`);
- console.log(players.map(p => `--- ${p.username}`).join('\n'));
- }
-
-})();
-```
-
-Output:
-
-```text
-Found game: "Winter Showdown"
-- Team "The Martians" played game "Winter Showdown" with the following players:
---- s0me0ne
---- greenhead
-- Team "The Plutonians" played game "Winter Showdown" with the following players:
---- not_spock
---- bowl_of_petunias
-```
-
-So this is how we can achieve a *many-to-many-to-many* relationship between three models in Sequelize, by taking advantage of the Super Many-to-Many relationship technique!
-
-This idea can be applied recursively for even more complex, *many-to-many-to-...-to-many* relationships (although at some point queries might become slow).
diff --git a/docs/manual/advanced-association-concepts/association-scopes.md b/docs/manual/advanced-association-concepts/association-scopes.md
deleted file mode 100644
index 42224f5e0cf6..000000000000
--- a/docs/manual/advanced-association-concepts/association-scopes.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Association Scopes
-
-This section concerns association scopes, which are similar but not the same as [model scopes](scopes.html).
-
-Association scopes can be placed both on the associated model (the target of the association) and on the through table for Many-to-Many relationships.
-
-## Concept
-
-Similarly to how a [model scope](scopes.html) is automatically applied on the model static calls, such as `Model.scope('foo').findAll()`, an association scope is a rule (more precisely, a set of default attributes and options) that is automatically applied on instance calls from the model. Here, *instance calls* mean method calls that are called from an instance (rather than from the Model itself). Mixins are the main example of instance methods (`instance.getSomething`, `instance.setSomething`, `instance.addSomething` and `instance.createSomething`).
-
-Association scopes behave just like model scopes, in the sense that both cause an automatic application of things like `where` clauses to finder calls; the difference being that instead of applying to static finder calls (which is the case for model scopes), the association scopes automatically apply to instance finder calls (such as mixins).
-
-## Example
-
-A basic example of an association scope for the One-to-Many association between models `Foo` and `Bar` is shown below.
-
-* Setup:
-
- ```js
- const Foo = sequelize.define('foo', { name: DataTypes.STRING });
- const Bar = sequelize.define('bar', { status: DataTypes.STRING });
- Foo.hasMany(Bar, {
- scope: {
- status: 'open'
- },
- as: 'openBars'
- });
- await sequelize.sync();
- const myFoo = await Foo.create({ name: "My Foo" });
- ```
-
-* After this setup, calling `myFoo.getOpenBars()` generates the following SQL:
-
- ```sql
- SELECT
- `id`, `status`, `createdAt`, `updatedAt`, `fooId`
- FROM `bars` AS `bar`
- WHERE `bar`.`status` = 'open' AND `bar`.`fooId` = 1;
- ```
-
-With this we can see that upon calling the `.getOpenBars()` mixin, the association scope `{ status: 'open' }` was automatically applied into the `WHERE` clause of the generated SQL.
-
-## Achieving the same behavior with standard scopes
-
-We could have achieved the same behavior with standard scopes:
-
-```js
-// Foo.hasMany(Bar, {
-// scope: {
-// status: 'open'
-// },
-// as: 'openBars'
-// });
-
-Bar.addScope('open', {
- where: {
- status: 'open'
- }
-});
-Foo.hasMany(Bar);
-Foo.hasMany(Bar.scope('open'), { as: 'openBars' });
-```
-
-With the above code, `myFoo.getOpenBars()` yields the same SQL shown above.
\ No newline at end of file
diff --git a/docs/manual/advanced-association-concepts/creating-with-associations.md b/docs/manual/advanced-association-concepts/creating-with-associations.md
deleted file mode 100644
index 60f5e80ea71d..000000000000
--- a/docs/manual/advanced-association-concepts/creating-with-associations.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Creating with Associations
-
-An instance can be created with nested association in one step, provided all elements are new.
-
-In contrast, performing updates and deletions involving nested objects is currently not possible. For that, you will have to perform each separate action explicitly.
-
-## BelongsTo / HasMany / HasOne association
-
-Consider the following models:
-
-```js
-class Product extends Model {}
-Product.init({
- title: Sequelize.STRING
-}, { sequelize, modelName: 'product' });
-class User extends Model {}
-User.init({
- firstName: Sequelize.STRING,
- lastName: Sequelize.STRING
-}, { sequelize, modelName: 'user' });
-class Address extends Model {}
-Address.init({
- type: DataTypes.STRING,
- line1: Sequelize.STRING,
- line2: Sequelize.STRING,
- city: Sequelize.STRING,
- state: Sequelize.STRING,
- zip: Sequelize.STRING,
-}, { sequelize, modelName: 'address' });
-
-// We save the return values of the association setup calls to use them later
-Product.User = Product.belongsTo(User);
-User.Addresses = User.hasMany(Address);
-// Also works for `hasOne`
-```
-
-A new `Product`, `User`, and one or more `Address` can be created in one step in the following way:
-
-```js
-return Product.create({
- title: 'Chair',
- user: {
- firstName: 'Mick',
- lastName: 'Broadstone',
- addresses: [{
- type: 'home',
- line1: '100 Main St.',
- city: 'Austin',
- state: 'TX',
- zip: '78704'
- }]
- }
-}, {
- include: [{
- association: Product.User,
- include: [ User.Addresses ]
- }]
-});
-```
-
-Observe the usage of the `include` option in the `Product.create` call. That is necessary for Sequelize to understand what you are trying to create along with the association.
-
-Note: here, our user model is called `user`, with a lowercase `u` - This means that the property in the object should also be `user`. If the name given to `sequelize.define` was `User`, the key in the object should also be `User`. Likewise for `addresses`, except it's pluralized being a `hasMany` association.
-
-## BelongsTo association with an alias
-
-The previous example can be extended to support an association alias.
-
-```js
-const Creator = Product.belongsTo(User, { as: 'creator' });
-
-return Product.create({
- title: 'Chair',
- creator: {
- firstName: 'Matt',
- lastName: 'Hansen'
- }
-}, {
- include: [ Creator ]
-});
-```
-
-## HasMany / BelongsToMany association
-
-Let's introduce the ability to associate a product with many tags. Setting up the models could look like:
-
-```js
-class Tag extends Model {}
-Tag.init({
- name: Sequelize.STRING
-}, { sequelize, modelName: 'tag' });
-
-Product.hasMany(Tag);
-// Also works for `belongsToMany`.
-```
-
-Now we can create a product with multiple tags in the following way:
-
-```js
-Product.create({
- id: 1,
- title: 'Chair',
- tags: [
- { name: 'Alpha'},
- { name: 'Beta'}
- ]
-}, {
- include: [ Tag ]
-})
-```
-
-And, we can modify this example to support an alias as well:
-
-```js
-const Categories = Product.hasMany(Tag, { as: 'categories' });
-
-Product.create({
- id: 1,
- title: 'Chair',
- categories: [
- { id: 1, name: 'Alpha' },
- { id: 2, name: 'Beta' }
- ]
-}, {
- include: [{
- association: Categories,
- as: 'categories'
- }]
-})
-```
\ No newline at end of file
diff --git a/docs/manual/advanced-association-concepts/eager-loading.md b/docs/manual/advanced-association-concepts/eager-loading.md
deleted file mode 100644
index 9dd787c6727e..000000000000
--- a/docs/manual/advanced-association-concepts/eager-loading.md
+++ /dev/null
@@ -1,664 +0,0 @@
-# Eager Loading
-
-As briefly mentioned in [the associations guide](assocs.html), eager Loading is the act of querying data of several models at once (one 'main' model and one or more associated models). At the SQL level, this is a query with one or more [joins](https://en.wikipedia.org/wiki/Join_\(SQL\)).
-
-When this is done, the associated models will be added by Sequelize in appropriately named, automatically created field(s) in the returned objects.
-
-In Sequelize, eager loading is mainly done by using the `include` option on a model finder query (such as `findOne`, `findAll`, etc).
-
-## Basic example
-
-Let's assume the following setup:
-
-```js
-const User = sequelize.define('user', { name: DataTypes.STRING }, { timestamps: false });
-const Task = sequelize.define('task', { name: DataTypes.STRING }, { timestamps: false });
-const Tool = sequelize.define('tool', {
- name: DataTypes.STRING,
- size: DataTypes.STRING
-}, { timestamps: false });
-User.hasMany(Task);
-Task.belongsTo(User);
-User.hasMany(Tool, { as: 'Instruments' });
-```
-
-### Fetching a single associated element
-
-OK. So, first of all, let's load all tasks with their associated user:
-
-```js
-const tasks = await Task.findAll({ include: User });
-console.log(JSON.stringify(tasks, null, 2));
-```
-
-Output:
-
-```json
-[{
- "name": "A Task",
- "id": 1,
- "userId": 1,
- "user": {
- "name": "John Doe",
- "id": 1
- }
-}]
-```
-
-Here, `tasks[0].user instanceof User` is `true`. This shows that when Sequelize fetches associated models, they are added to the output object as model instances.
-
-Above, the associated model was added to a new field called `user` in the fetched task. The name of this field was automatically chosen by Sequelize based on the name of the associated model, where its pluralized form is used when applicable (i.e., when the association is `hasMany` or `belongsToMany`). In other words, since `Task.belongsTo(User)`, a task is associated to one user, therefore the logical choice is the singular form (which Sequelize follows automatically).
-
-### Fetching all associated elements
-
-Now, instead of loading the user that is associated to a given task, we will do the opposite - we will find all tasks associated to a given user.
-
-The method call is essentially the same. The only difference is that now the extra field created in the query result uses the pluralized form (`tasks` in this case), and its value is an array of task instances (instead of a single instance, as above).
-
-```js
-const users = await User.findAll({ include: Task });
-console.log(JSON.stringify(users, null, 2));
-```
-
-Output:
-
-```json
-[{
- "name": "John Doe",
- "id": 1,
- "tasks": [{
- "name": "A Task",
- "id": 1,
- "userId": 1
- }]
-}]
-```
-
-Notice that the accessor (the `tasks` property in the resulting instance) is pluralized since the association is one-to-many.
-
-### Fetching an Aliased association
-
-If an association is aliased (using the `as` option), you must specify this alias when including the model. Instead of passing the model directly to the `include` option, you should instead provide an object with two options: `model` and `as`.
-
-Notice how the user's `Tool`s are aliased as `Instruments` above. In order to get that right you have to specify the model you want to load, as well as the alias:
-
-```js
-const users = await User.findAll({
- include: { model: Tool, as: 'Instruments' }
-});
-console.log(JSON.stringify(users, null, 2));
-```
-
-Output:
-
-```json
-[{
- "name": "John Doe",
- "id": 1,
- "Instruments": [{
- "name": "Scissor",
- "id": 1,
- "userId": 1
- }]
-}]
-```
-
-You can also include by alias name by specifying a string that matches the association alias:
-
-```js
-User.findAll({ include: 'Instruments' }); // Also works
-User.findAll({ include: { association: 'Instruments' } }); // Also works
-```
-
-### Required eager loading
-
-When eager loading, we can force the query to return only records which have an associated model, effectively converting the query from the default `OUTER JOIN` to an `INNER JOIN`. This is done with the `required: true` option, as follows:
-
-```js
-User.findAll({
- include: {
- model: Task,
- required: true
- }
-});
-```
-
-This option also works on nested includes.
-
-### Eager loading filtered at the associated model level
-
-When eager loading, we can also filter the associated model using the `where` option, as in the following example:
-
-```js
-User.findAll({
- include: {
- model: Tool,
- as: 'Instruments'
- where: {
- size: {
- [Op.ne]: 'small'
- }
- }
- }
-});
-```
-
-Generated SQL:
-
-```sql
-SELECT
- `user`.`id`,
- `user`.`name`,
- `Instruments`.`id` AS `Instruments.id`,
- `Instruments`.`name` AS `Instruments.name`,
- `Instruments`.`size` AS `Instruments.size`,
- `Instruments`.`userId` AS `Instruments.userId`
-FROM `users` AS `user`
-INNER JOIN `tools` AS `Instruments` ON
- `user`.`id` = `Instruments`.`userId` AND
- `Instruments`.`size` != 'small';
-```
-
-Note that the SQL query generated above will only fetch users that have at least one tool that matches the condition (of not being `small`, in this case). This is the case because, when the `where` option is used inside an `include`, Sequelize automatically sets the `required` option to `true`. This means that, instead of an `OUTER JOIN`, an `INNER JOIN` is done, returning only the parent models with at least one matching children.
-
-Note also that the `where` option used was converted into a condition for the `ON` clause of the `INNER JOIN`. In order to obtain a *top-level* `WHERE` clause, instead of an `ON` clause, something different must be done. This will be shown next.
-
-#### Referring to other columns
-
-If you want to apply a `WHERE` clause in an included model referring to a value from an associated model, you can simply use the `Sequelize.col` function, as show in the example below:
-
-```js
-// Find all projects with a least one task where task.state === project.state
-Project.findAll({
- include: {
- model: Task,
- where: {
- state: Sequelize.col('project.state')
- }
- }
-})
-```
-
-### Complex where clauses at the top-level
-
-To obtain top-level `WHERE` clauses that involve nested columns, Sequelize provides a way to reference nested columns: the `'$nested.column$'` syntax.
-
-It can be used, for example, to move the where conditions from an included model from the `ON` condition to a top-level `WHERE` clause.
-
-```js
-User.findAll({
- where: {
- '$Instruments.size$': { [Op.ne]: 'small' }
- },
- include: [{
- model: Tool,
- as: 'Instruments'
- }]
-});
-```
-
-Generated SQL:
-
-```sql
-SELECT
- `user`.`id`,
- `user`.`name`,
- `Instruments`.`id` AS `Instruments.id`,
- `Instruments`.`name` AS `Instruments.name`,
- `Instruments`.`size` AS `Instruments.size`,
- `Instruments`.`userId` AS `Instruments.userId`
-FROM `users` AS `user`
-LEFT OUTER JOIN `tools` AS `Instruments` ON
- `user`.`id` = `Instruments`.`userId`
-WHERE `Instruments`.`size` != 'small';
-```
-
-The `$nested.column$` syntax also works for columns that are nested several levels deep, such as `$some.super.deeply.nested.column$`. Therefore, you can use this to make complex filters on deeply nested columns.
-
-For a better understanding of all differences between the inner `where` option (used inside an `include`), with and without the `required` option, and a top-level `where` using the `$nested.column$` syntax, below we have four examples for you:
-
-```js
-// Inner where, with default `required: true`
-await User.findAll({
- include: {
- model: Tool,
- as: 'Instruments',
- where: {
- size: { [Op.ne]: 'small' }
- }
- }
-});
-
-// Inner where, `required: false`
-await User.findAll({
- include: {
- model: Tool,
- as: 'Instruments',
- where: {
- size: { [Op.ne]: 'small' }
- },
- required: false
- }
-});
-
-// Top-level where, with default `required: false`
-await User.findAll({
- where: {
- '$Instruments.size$': { [Op.ne]: 'small' }
- },
- include: {
- model: Tool,
- as: 'Instruments'
- }
-});
-
-// Top-level where, `required: true`
-await User.findAll({
- where: {
- '$Instruments.size$': { [Op.ne]: 'small' }
- },
- include: {
- model: Tool,
- as: 'Instruments',
- required: true
- }
-});
-```
-
-Generated SQLs, in order:
-
-```sql
--- Inner where, with default `required: true`
-SELECT [...] FROM `users` AS `user`
-INNER JOIN `tools` AS `Instruments` ON
- `user`.`id` = `Instruments`.`userId`
- AND `Instruments`.`size` != 'small';
-
--- Inner where, `required: false`
-SELECT [...] FROM `users` AS `user`
-LEFT OUTER JOIN `tools` AS `Instruments` ON
- `user`.`id` = `Instruments`.`userId`
- AND `Instruments`.`size` != 'small';
-
--- Top-level where, with default `required: false`
-SELECT [...] FROM `users` AS `user`
-LEFT OUTER JOIN `tools` AS `Instruments` ON
- `user`.`id` = `Instruments`.`userId`
-WHERE `Instruments`.`size` != 'small';
-
--- Top-level where, `required: true`
-SELECT [...] FROM `users` AS `user`
-INNER JOIN `tools` AS `Instruments` ON
- `user`.`id` = `Instruments`.`userId`
-WHERE `Instruments`.`size` != 'small';
-```
-
-### Fetching with `RIGHT OUTER JOIN` (MySQL, MariaDB, PostgreSQL and MSSQL only)
-
-By default, associations are loaded using a `LEFT OUTER JOIN` - that is to say it only includes records from the parent table. You can change this behavior to a `RIGHT OUTER JOIN` by passing the `right` option, if the dialect you are using supports it.
-
-Currenly, SQLite does not support [right joins](https://www.sqlite.org/omitted.html).
-
-*Note:* `right` is only respected if `required` is false.
-
-```js
-User.findAll({
- include: [{
- model: Task // will create a left join
- }]
-});
-User.findAll({
- include: [{
- model: Task,
- right: true // will create a right join
- }]
-});
-User.findAll({
- include: [{
- model: Task,
- required: true,
- right: true // has no effect, will create an inner join
- }]
-});
-User.findAll({
- include: [{
- model: Task,
- where: { name: { [Op.ne]: 'empty trash' } },
- right: true // has no effect, will create an inner join
- }]
-});
-User.findAll({
- include: [{
- model: Tool,
- where: { name: { [Op.ne]: 'empty trash' } },
- required: false // will create a left join
- }]
-});
-User.findAll({
- include: [{
- model: Tool,
- where: { name: { [Op.ne]: 'empty trash' } },
- required: false
- right: true // will create a right join
- }]
-});
-```
-
-## Multiple eager loading
-
-The `include` option can receive an array in order to fetch multiple associated models at once:
-
-```js
-Foo.findAll({
- include: [
- {
- model: Bar,
- required: true
- },
- {
- model: Baz,
- where: /* ... */
- },
- Qux // Shorthand syntax for { model: Qux } also works here
- ]
-})
-```
-
-## Eager loading with Many-to-Many relationships
-
-When you perform eager loading on a model with a Belongs-to-Many relationship, Sequelize will fetch the junction table data as well, by default. For example:
-
-```js
-const Foo = sequelize.define('Foo', { name: DataTypes.TEXT });
-const Bar = sequelize.define('Bar', { name: DataTypes.TEXT });
-Foo.belongsToMany(Bar, { through: 'Foo_Bar' });
-Bar.belongsToMany(Foo, { through: 'Foo_Bar' });
-
-await sequelize.sync();
-const foo = await Foo.create({ name: 'foo' });
-const bar = await Bar.create({ name: 'bar' });
-await foo.addBar(bar);
-const fetchedFoo = Foo.findOne({ include: Bar });
-console.log(JSON.stringify(fetchedFoo, null, 2));
-```
-
-Output:
-
-```json
-{
- "id": 1,
- "name": "foo",
- "Bars": [
- {
- "id": 1,
- "name": "bar",
- "Foo_Bar": {
- "FooId": 1,
- "BarId": 1
- }
- }
- ]
-}
-```
-
-Note that every bar instance eager loaded into the `"Bars"` property has an extra property called `Foo_Bar` which is the relevant Sequelize instance of the junction model. By default, Sequelize fetches all attributes from the junction table in order to build this extra property.
-
-However, you can specify which attributes you want fetched. This is done with the `attributes` option applied inside the `through` option of the include. For example:
-
-```js
-Foo.findAll({
- include: [{
- model: Bar,
- through: {
- attributes: [/* list the wanted attributes here */]
- }
- }]
-});
-```
-
-If you don't want anything from the junction table, you can explicitly provide an empty array to the `attributes` option, and in this case nothing will be fetched and the extra property will not even be created:
-
-```js
-Foo.findOne({
- include: {
- model: Bar,
- attributes: []
- }
-});
-```
-
-Output:
-
-```json
-{
- "id": 1,
- "name": "foo",
- "Bars": [
- {
- "id": 1,
- "name": "bar"
- }
- ]
-}
-```
-
-Whenever including a model from a Many-to-Many relationship, you can also apply a filter on the junction table. This is done with the `where` option applied inside the `through` option of the include. For example:
-
-```js
-User.findAll({
- include: [{
- model: Project,
- through: {
- where: {
- // Here, `completed` is a column present at the junction table
- completed: true
- }
- }
- }]
-});
-```
-
-Generated SQL (using SQLite):
-
-```sql
-SELECT
- `User`.`id`,
- `User`.`name`,
- `Projects`.`id` AS `Projects.id`,
- `Projects`.`name` AS `Projects.name`,
- `Projects->User_Project`.`completed` AS `Projects.User_Project.completed`,
- `Projects->User_Project`.`UserId` AS `Projects.User_Project.UserId`,
- `Projects->User_Project`.`ProjectId` AS `Projects.User_Project.ProjectId`
-FROM `Users` AS `User`
-LEFT OUTER JOIN `User_Projects` AS `Projects->User_Project` ON
- `User`.`id` = `Projects->User_Project`.`UserId`
-LEFT OUTER JOIN `Projects` AS `Projects` ON
- `Projects`.`id` = `Projects->User_Project`.`ProjectId` AND
- `Projects->User_Project`.`completed` = 1;
-```
-
-## Including everything
-
-To include all associated models, you can use the `all` and `nested` options:
-
-```js
-// Fetch all models associated with User
-User.findAll({ include: { all: true }});
-
-// Fetch all models associated with User and their nested associations (recursively)
-User.findAll({ include: { all: true, nested: true }});
-```
-
-## Including soft deleted records
-
-In case you want to eager load soft deleted records you can do that by setting `include.paranoid` to `false`:
-
-```js
-User.findAll({
- include: [{
- model: Tool,
- as: 'Instruments',
- where: { size: { [Op.ne]: 'small' } },
- paranoid: false
- }]
-});
-```
-
-## Ordering eager loaded associations
-
-When you want to apply `ORDER` clauses to eager loaded models, you must use the top-level `order` option with augmented arrays, starting with the specification of the nested model you want to sort.
-
-This is better understood with examples.
-
-```js
-Company.findAll({
- include: Division,
- order: [
- // We start the order array with the model we want to sort
- [Division, 'name', 'ASC']
- ]
-});
-Company.findAll({
- include: Division,
- order: [
- [Division, 'name', 'DESC']
- ]
-});
-Company.findAll({
- // If the include uses an alias...
- include: { model: Division, as: 'Div' },
- order: [
- // ...we use the same syntax from the include
- // in the beginning of the order array
- [{ model: Division, as: 'Div' }, 'name', 'DESC']
- ]
-});
-
-Company.findAll({
- // If we have includes nested in several levels...
- include: {
- model: Division,
- include: Department
- },
- order: [
- // ... we replicate the include chain of interest
- // at the beginning of the order array
- [Division, Department, 'name', 'DESC']
- ]
-});
-```
-
-In the case of many-to-many relationships, you are also able to sort by attributes in the through table. For example, assuming we have a Many-to-Many relationship between `Division` and `Department` whose junction model is `DepartmentDivision`, you can do:
-
-```js
-Company.findAll({
- include: {
- model: Division,
- include: Department
- },
- order: [
- [Division, DepartmentDivision, 'name', 'ASC']
- ]
-});
-```
-
-In all the above examples, you have noticed that the `order` option is used at the top-level. The only situation in which `order` also works inside the include option is when `separate: true` is used. In that case, the usage is as follows:
-
-```js
-// This only works for `separate: true` (which in turn
-// only works for has-many relationships).
-User.findAll({
- include: {
- model: Post,
- separate: true,
- order: [
- ['createdAt', 'DESC']
- ]
- }
-});
-```
-
-### Complex ordering involving sub-queries
-
-Take a look at the [guide on sub-queries](sub-queries.html) for an example of how to use a sub-query to assist a more complex ordering.
-
-## Nested eager loading
-
-You can use nested eager loading to load all related models of a related model:
-
-```js
-const users = await User.findAll({
- include: {
- model: Tool,
- as: 'Instruments',
- include: {
- model: Teacher,
- include: [ /* etc */ ]
- }
- }
-});
-console.log(JSON.stringify(users, null, 2));
-```
-
-Output:
-
-```json
-[{
- "name": "John Doe",
- "id": 1,
- "Instruments": [{ // 1:M and N:M association
- "name": "Scissor",
- "id": 1,
- "userId": 1,
- "Teacher": { // 1:1 association
- "name": "Jimi Hendrix"
- }
- }]
-}]
-```
-
-This will produce an outer join. However, a `where` clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add `required: false`.
-
-```js
-User.findAll({
- include: [{
- model: Tool,
- as: 'Instruments',
- include: [{
- model: Teacher,
- where: {
- school: "Woodstock Music School"
- },
- required: false
- }]
- }]
-});
-```
-
-The query above will return all users, and all their instruments, but only those teachers associated with `Woodstock Music School`.
-
-## Using `findAndCountAll` with includes
-
-The `findAndCountAll` utility function supports includes. Only the includes that are marked as `required` will be considered in `count`. For example, if you want to find and count all users who have a profile:
-
-```js
-User.findAndCountAll({
- include: [
- { model: Profile, required: true }
- ],
- limit: 3
-});
-```
-
-Because the include for `Profile` has `required` set it will result in an inner join, and only the users who have a profile will be counted. If we remove `required` from the include, both users with and without profiles will be counted. Adding a `where` clause to the include automatically makes it required:
-
-```js
-User.findAndCountAll({
- include: [
- { model: Profile, where: { active: true } }
- ],
- limit: 3
-});
-```
-
-The query above will only count users who have an active profile, because `required` is implicitly set to true when you add a where clause to the include.
\ No newline at end of file
diff --git a/docs/manual/advanced-association-concepts/polymorphic-associations.md b/docs/manual/advanced-association-concepts/polymorphic-associations.md
deleted file mode 100644
index 39ee46372626..000000000000
--- a/docs/manual/advanced-association-concepts/polymorphic-associations.md
+++ /dev/null
@@ -1,427 +0,0 @@
-# Polymorphic Associations
-
-_**Note:** the usage of polymorphic associations in Sequelize, as outlined in this guide, should be done with caution. Don't just copy-paste code from here, otherwise you might easily make mistakes and introduce bugs in your code. Make sure you understand what is going on._
-
-## Concept
-
-A **polymorphic association** consists on two (or more) associations happening with the same foreign key.
-
-For example, consider the models `Image`, `Video` and `Comment`. The first two represent something that a user might post. We want to allow comments to be placed in both of them. This way, we immediately think of establishing the following associations:
-
-* A One-to-Many association between `Image` and `Comment`:
-
- ```js
- Image.hasMany(Comment);
- Comment.belongsTo(Image);
- ```
-
-* A One-to-Many association between `Video` and `Comment`:
-
- ```js
- Video.hasMany(Comment);
- Comment.belongsTo(Video);
- ```
-
-However, the above would cause Sequelize to create two foreign keys on the `Comment` table: `ImageId` and `VideoId`. This is not ideal because this structure makes it look like a comment can be attached at the same time to one image and one video, which isn't true. Instead, what we really want here is precisely a polymorphic association, in which a `Comment` points to a single **Commentable**, an abstract polymorphic entity that represents one of `Image` or `Video`.
-
-Before proceeding to how to configure such an association, let's see how using it looks like:
-
-```js
-const image = await Image.create({ url: "https://placekitten.com/408/287" });
-const comment = await image.createComment({ content: "Awesome!" });
-
-console.log(comment.commentableId === image.id); // true
-
-// We can also retrieve which type of commentable a comment is associated to.
-// The following prints the model name of the associated commentable instance.
-console.log(comment.commentableType); // "Image"
-
-// We can use a polymorphic method to retrieve the associated commentable, without
-// having to worry whether it's an Image or a Video.
-const associatedCommentable = await comment.getCommentable();
-
-// In this example, `associatedCommentable` is the same thing as `image`:
-const isDeepEqual = require('deep-equal');
-console.log(isDeepEqual(image, commentable)); // true
-```
-
-## Configuring a One-to-Many polymorphic association
-
-To setup the polymorphic association for the example above (which is an example of One-to-Many polymorphic association), we have the following steps:
-
-* Define a string field called `commentableType` in the `Comment` model;
-* Define the `hasMany` and `belongsTo` association between `Image`/`Video` and `Comment`:
- * Disabling constraints (i.e. using `{ constraints: false }`), since the same foreign key is referencing multiple tables;
- * Specifying the appropriate [association scopes](association-scopes.html);
-* To properly support lazy loading, define a new instance method on the `Comment` model called `getCommentable` which calls, under the hood, the correct mixin to fetch the appropriate commentable;
-* To properly support eager loading, define an `afterFind` hook on the `Comment` model that automatically populates the `commentable` field in every instance;
-* To prevent bugs/mistakes in eager loading, you can also delete the concrete fields `image` and `video` from Comment instances in the same `afterFind` hook, leaving only the abstract `commentable` field available.
-
-Here is an example:
-
-```js
-// Helper function
-const uppercaseFirst = str => `${str[0].toUpperCase()}${str.substr(1)}`;
-
-class Image extends Model {}
-Image.init({
- title: DataTypes.STRING,
- url: DataTypes.STRING
-}, { sequelize, modelName: 'image' });
-
-class Video extends Model {}
-Video.init({
- title: DataTypes.STRING,
- text: DataTypes.STRING
-}, { sequelize, modelName: 'video' });
-
-class Comment extends Model {
- getCommentable(options) {
- if (!this.commentableType) return Promise.resolve(null);
- const mixinMethodName = `get${uppercaseFirst(this.commentableType)}`;
- return this[mixinMethodName](options);
- }
-}
-Comment.init({
- title: DataTypes.STRING,
- commentableId: DataTypes.INTEGER,
- commentableType: DataTypes.STRING
-}, { sequelize, modelName: 'comment' });
-
-Image.hasMany(Comment, {
- foreignKey: 'commentableId',
- constraints: false,
- scope: {
- commentableType: 'image'
- }
-});
-Comment.belongsTo(Image, { foreignKey: 'commentableId', constraints: false });
-
-Video.hasMany(Comment, {
- foreignKey: 'commentableId',
- constraints: false,
- scope: {
- commentableType: 'video'
- }
-});
-Comment.belongsTo(Video, { foreignKey: 'commentableId', constraints: false });
-
-Comment.addHook("afterFind", findResult => {
- if (!Array.isArray(findResult)) findResult = [findResult];
- for (const instance of findResult) {
- if (instance.commentableType === "image" && instance.image !== undefined) {
- instance.commentable = instance.image;
- } else if (instance.commentableType === "video" && instance.video !== undefined) {
- instance.commentable = instance.video;
- }
- // To prevent mistakes:
- delete instance.image;
- delete instance.dataValues.image;
- delete instance.video;
- delete instance.dataValues.video;
- }
-});
-```
-
-Since the `commentableId` column references several tables (two in this case), we cannot add a `REFERENCES` constraint to it. This is why the `constraints: false` option was used.
-
-Note that, in the code above:
-
-* The *Image -> Comment* association defined an association scope: `{ commentableType: 'image' }`
-* The *Video -> Comment* association defined an association scope: `{ commentableType: 'video' }`
-
-These scopes are automatically applied when using the association functions (as explained in the [Association Scopes](association-scopes.html) guide). Some examples are below, with their generated SQL statements:
-
-* `image.getComments()`:
-
- ```sql
- SELECT "id", "title", "commentableType", "commentableId", "createdAt", "updatedAt"
- FROM "comments" AS "comment"
- WHERE "comment"."commentableType" = 'image' AND "comment"."commentableId" = 1;
- ```
-
- Here we can see that `` `comment`.`commentableType` = 'image'`` was automatically added to the `WHERE` clause of the generated SQL. This is exactly the behavior we want.
-
-* `image.createComment({ title: 'Awesome!' })`:
-
- ```sql
- INSERT INTO "comments" (
- "id", "title", "commentableType", "commentableId", "createdAt", "updatedAt"
- ) VALUES (
- DEFAULT, 'Awesome!', 'image', 1,
- '2018-04-17 05:36:40.454 +00:00', '2018-04-17 05:36:40.454 +00:00'
- ) RETURNING *;
- ```
-
-* `image.addComment(comment)`:
-
- ```sql
- UPDATE "comments"
- SET "commentableId"=1, "commentableType"='image', "updatedAt"='2018-04-17 05:38:43.948 +00:00'
- WHERE "id" IN (1)
- ```
-
-### Polymorphic lazy loading
-
-The `getCommentable` instance method on `Comment` provides an abstraction for lazy loading the associated commentable - working whether the comment belongs to an Image or a Video.
-
-It works by simply converting the `commentableType` string into a call to the correct mixin (either `getImage` or `getVideo`).
-
-Note that the `getCommentable` implementation above:
-
-* Returns `null` when no association is present (which is good);
-* Allows you to pass an options object to `getCommentable(options)`, just like any other standard Sequelize method. This is useful to specify where-conditions or includes, for example.
-
-### Polymorphic eager loading
-
-Now, we want to perform a polymorphic eager loading of the associated commentables for one (or more) comments. We want to achieve something similar to the following idea:
-
-```js
-const comment = await Comment.findOne({
- include: [ /* What to put here? */ ]
-});
-console.log(comment.commentable); // This is our goal
-```
-
-The solution is to tell Sequelize to include both Images and Videos, so that our `afterFind` hook defined above will do the work, automatically adding the `commentable` field to the instance object, providing the abstraction we want.
-
-For example:
-
-```js
-const comments = await Comment.findAll({
- include: [Image, Video]
-});
-for (const comment of comments) {
- const message = `Found comment #${comment.id} with ${comment.commentableType} commentable:`;
- console.log(message, comment.commentable.toJSON());
-}
-```
-
-Output example:
-
-```text
-Found comment #1 with image commentable: { id: 1,
- title: 'Meow',
- url: 'https://placekitten.com/408/287',
- createdAt: 2019-12-26T15:04:53.047Z,
- updatedAt: 2019-12-26T15:04:53.047Z }
-```
-
-### Caution - possibly invalid eager/lazy loading!
-
-Consider a comment `Foo` whose `commentableId` is 2 and `commentableType` is `image`. Consider also that `Image A` and `Video X` both happen to have an id equal to 2. Conceptually, it is clear that `Video X` is not associated to `Foo`, because even though its id is 2, the `commentableType` of `Foo` is `image`, not `video`. However, this distinction is made by Sequelize only at the level of the abstractions performed by `getCommentable` and the hook we created above.
-
-This means that if you call `Comment.findAll({ include: Video })` in the situation above, `Video X` will be eager loaded into `Foo`. Thankfully, our `afterFind` hook will delete it automatically, to help prevent bugs, but regardless it is important that you understand what is going on.
-
-The best way to prevent this kind of mistake is to **avoid using the concrete accessors and mixins directly at all costs** (such as `.image`, `.getVideo()`, `.setImage()`, etc), always preferring the abstractions we created, such as `.getCommentable()` and `.commentable`. If you really need to access eager-loaded `.image` and `.video` for some reason, make sure you wrap that in a type check such as `comment.commentableType === 'image'`.
-
-## Configuring a Many-to-Many polymorphic association
-
-In the above example, we had the models `Image` and `Video` being abstractly called *commentables*, with one *commentable* having many comments. However, one given comment would belong to a single *commentable* - this is why the whole situation is a One-to-Many polymorphic association.
-
-Now, to consider a Many-to-Many polymorphic association, instead of considering comments, we will consider tags. For convenience, instead of calling Image and Video as *commentables*, we will now call them *taggables*. One *taggable* may have several tags, and at the same time one tag can be placed in several *taggables*.
-
-The setup for this goes as follows:
-
-* Define the juncion model explicitly, specifying the two foreign keys as `tagId` and `taggableId` (this way it is a junction model for a Many-to-Many relationship between `Tag` and the abstract concept of *taggable*);
-* Define a string field called `taggableType` in the junction model;
-* Define the `belongsToMany` associations between the two models and `Tag`:
- * Disabling constraints (i.e. using `{ constraints: false }`), since the same foreign key is referencing multiple tables;
- * Specifying the appropriate [association scopes](association-scopes.html);
-* Define a new instance method on the `Tag` model called `getTaggables` which calls, under the hood, the correct mixin to fetch the appropriate taggables.
-
-Implementation:
-
-```js
-class Tag extends Model {
- getTaggables(options) {
- const images = await this.getImages(options);
- const videos = await this.getVideos(options);
- // Concat images and videos in a single array of taggables
- return images.concat(videos);
- }
-}
-Tag.init({
- name: DataTypes.STRING
-}, { sequelize, modelName: 'tag' });
-
-// Here we define the junction model explicitly
-class Tag_Taggable extends Model {}
-Tag_Taggable.init({
- tagId: {
- type: DataTypes.INTEGER,
- unique: 'tt_unique_constraint'
- },
- taggableId: {
- type: DataTypes.INTEGER,
- unique: 'tt_unique_constraint',
- references: null
- },
- taggableType: {
- type: DataTypes.STRING,
- unique: 'tt_unique_constraint'
- }
-}, { sequelize, modelName: 'tag_taggable' });
-
-Image.belongsToMany(Tag, {
- through: {
- model: Tag_Taggable,
- unique: false,
- scope: {
- taggableType: 'image'
- }
- },
- foreignKey: 'taggableId',
- constraints: false
-});
-Tag.belongsToMany(Image, {
- through: {
- model: Tag_Taggable,
- unique: false
- },
- foreignKey: 'tagId',
- constraints: false
-});
-
-Video.belongsToMany(Tag, {
- through: {
- model: Tag_Taggable,
- unique: false,
- scope: {
- taggableType: 'video'
- }
- },
- foreignKey: 'taggableId',
- constraints: false
-});
-Tag.belongsToMany(Video, {
- through: {
- model: Tag_Taggable,
- unique: false
- },
- foreignKey: 'tagId',
- constraints: false
-});
-```
-
-The `constraints: false` option disables references constraints, as the `taggableId` column references several tables, we cannot add a `REFERENCES` constraint to it.
-
-Note that:
-
-* The *Image -> Tag* association defined an association scope: `{ taggableType: 'image' }`
-* The *Video -> Tag* association defined an association scope: `{ taggableType: 'video' }`
-
-These scopes are automatically applied when using the association functions. Some examples are below, with their generated SQL statements:
-
-* `image.getTags()`:
-
- ```sql
- SELECT
- `tag`.`id`,
- `tag`.`name`,
- `tag`.`createdAt`,
- `tag`.`updatedAt`,
- `tag_taggable`.`tagId` AS `tag_taggable.tagId`,
- `tag_taggable`.`taggableId` AS `tag_taggable.taggableId`,
- `tag_taggable`.`taggableType` AS `tag_taggable.taggableType`,
- `tag_taggable`.`createdAt` AS `tag_taggable.createdAt`,
- `tag_taggable`.`updatedAt` AS `tag_taggable.updatedAt`
- FROM `tags` AS `tag`
- INNER JOIN `tag_taggables` AS `tag_taggable` ON
- `tag`.`id` = `tag_taggable`.`tagId` AND
- `tag_taggable`.`taggableId` = 1 AND
- `tag_taggable`.`taggableType` = 'image';
- ```
-
- Here we can see that `` `tag_taggable`.`taggableType` = 'image'`` was automatically added to the `WHERE` clause of the generated SQL. This is exactly the behavior we want.
-
-* `tag.getTaggables()`:
-
- ```sql
- SELECT
- `image`.`id`,
- `image`.`url`,
- `image`.`createdAt`,
- `image`.`updatedAt`,
- `tag_taggable`.`tagId` AS `tag_taggable.tagId`,
- `tag_taggable`.`taggableId` AS `tag_taggable.taggableId`,
- `tag_taggable`.`taggableType` AS `tag_taggable.taggableType`,
- `tag_taggable`.`createdAt` AS `tag_taggable.createdAt`,
- `tag_taggable`.`updatedAt` AS `tag_taggable.updatedAt`
- FROM `images` AS `image`
- INNER JOIN `tag_taggables` AS `tag_taggable` ON
- `image`.`id` = `tag_taggable`.`taggableId` AND
- `tag_taggable`.`tagId` = 1;
-
- SELECT
- `video`.`id`,
- `video`.`url`,
- `video`.`createdAt`,
- `video`.`updatedAt`,
- `tag_taggable`.`tagId` AS `tag_taggable.tagId`,
- `tag_taggable`.`taggableId` AS `tag_taggable.taggableId`,
- `tag_taggable`.`taggableType` AS `tag_taggable.taggableType`,
- `tag_taggable`.`createdAt` AS `tag_taggable.createdAt`,
- `tag_taggable`.`updatedAt` AS `tag_taggable.updatedAt`
- FROM `videos` AS `video`
- INNER JOIN `tag_taggables` AS `tag_taggable` ON
- `video`.`id` = `tag_taggable`.`taggableId` AND
- `tag_taggable`.`tagId` = 1;
- ```
-
-Note that the above implementation of `getTaggables()` allows you to pass an options object to `getCommentable(options)`, just like any other standard Sequelize method. This is useful to specify where-conditions or includes, for example.
-
-### Applying scopes on the target model
-
-In the example above, the `scope` options (such as `scope: { taggableType: 'image' }`) were applied to the *through* model, not the *target* model, since it was used under the `through` option.
-
-We can also apply an association scope on the target model. We can even do both at the same time.
-
-To illustrate this, consider an extension of the above example between tags and taggables, where each tag has a status. This way, to get all pending tags of an image, we could establish another `belognsToMany` relationship between `Image` and `Tag`, this time applying a scope on the through model and another scope on the target model:
-
-```js
-Image.belongsToMany(Tag, {
- through: {
- model: Tag_Taggable,
- unique: false,
- scope: {
- taggableType: 'image'
- }
- },
- scope: {
- status: 'pending'
- },
- as: 'pendingTags',
- foreignKey: 'taggableId',
- constraints: false
-});
-```
-
-This way, when calling `image.getPendingTags()`, the following SQL query will be generated:
-
-```sql
-SELECT
- `tag`.`id`,
- `tag`.`name`,
- `tag`.`status`,
- `tag`.`createdAt`,
- `tag`.`updatedAt`,
- `tag_taggable`.`tagId` AS `tag_taggable.tagId`,
- `tag_taggable`.`taggableId` AS `tag_taggable.taggableId`,
- `tag_taggable`.`taggableType` AS `tag_taggable.taggableType`,
- `tag_taggable`.`createdAt` AS `tag_taggable.createdAt`,
- `tag_taggable`.`updatedAt` AS `tag_taggable.updatedAt`
-FROM `tags` AS `tag`
-INNER JOIN `tag_taggables` AS `tag_taggable` ON
- `tag`.`id` = `tag_taggable`.`tagId` AND
- `tag_taggable`.`taggableId` = 1 AND
- `tag_taggable`.`taggableType` = 'image'
-WHERE (
- `tag`.`status` = 'pending'
-);
-```
-
-We can see that both scopes were applied automatically:
-
-* `` `tag_taggable`.`taggableType` = 'image'`` was added automatically to the `INNER JOIN`;
-* `` `tag`.`status` = 'pending'`` was added automatically to an outer where clause.
\ No newline at end of file
diff --git a/docs/manual/core-concepts/assocs.md b/docs/manual/core-concepts/assocs.md
deleted file mode 100644
index b511d7c62f80..000000000000
--- a/docs/manual/core-concepts/assocs.md
+++ /dev/null
@@ -1,784 +0,0 @@
-# Associations
-
-Sequelize supports the standard associations: [One-To-One](https://en.wikipedia.org/wiki/One-to-one_%28data_model%29), [One-To-Many](https://en.wikipedia.org/wiki/One-to-many_%28data_model%29) and [Many-To-Many](https://en.wikipedia.org/wiki/Many-to-many_%28data_model%29).
-
-To do this, Sequelize provides **four** types of associations that should be combined to create them:
-
-* The `HasOne` association
-* The `BelongsTo` association
-* The `HasMany` association
-* The `BelongsToMany` association
-
-The guide will start explaining how to define these four types of associations, and then will follow up to explain how to combine those to define the three standard association types ([One-To-One](https://en.wikipedia.org/wiki/One-to-one_%28data_model%29), [One-To-Many](https://en.wikipedia.org/wiki/One-to-many_%28data_model%29) and [Many-To-Many](https://en.wikipedia.org/wiki/Many-to-many_%28data_model%29)).
-
-## Defining the Sequelize associations
-
-The four association types are defined in a very similar way. Let's say we have two models, `A` and `B`. Telling Sequelize that you want an association between the two needs just a function call:
-
-```js
-const A = sequelize.define('A', /* ... */);
-const B = sequelize.define('B', /* ... */);
-
-A.hasOne(B); // A HasOne B
-A.belongsTo(B); // A BelongsTo B
-A.hasMany(B); // A HasMany B
-A.belongsToMany(B, { through: 'C' }); // A BelongsToMany B through the junction table C
-```
-
-They all accept an options object as a second parameter (optional for the first three, mandatory for `belongsToMany` containing at least the `through` property):
-
-```js
-A.hasOne(B, { /* options */ });
-A.belongsTo(B, { /* options */ });
-A.hasMany(B, { /* options */ });
-A.belongsToMany(B, { through: 'C', /* options */ });
-```
-
-The order in which the association is defined is relevant. In other words, the order matters, for the four cases. In all examples above, `A` is called the **source** model and `B` is called the **target** model. This terminology is important.
-
-The `A.hasOne(B)` association means that a One-To-One relationship exists between `A` and `B`, with the foreign key being defined in the target model (`B`).
-
-The `A.belongsTo(B)` association means that a One-To-One relationship exists between `A` and `B`, with the foreign key being defined in the source model (`A`).
-
-The `A.hasMany(B)` association means that a One-To-Many relationship exists between `A` and `B`, with the foreign key being defined in the target model (`B`).
-
-These three calls will cause Sequelize to automatically add foreign keys to the appropriate models (unless they are already present).
-
-The `A.belongsToMany(B, { through: 'C' })` association means that a Many-To-Many relationship exists between `A` and `B`, using table `C` as [junction table](https://en.wikipedia.org/wiki/Associative_entity), which will have the foreign keys (`aId` and `bId`, for example). Sequelize will automatically create this model `C` (unless it already exists) and define the appropriate foreign keys on it.
-
-*Note: In the examples above for `belongsToMany`, a string (`'C'`) was passed to the through option. In this case, Sequelize automatically generates a model with this name. However, you can also pass a model directly, if you have already defined it.*
-
-These are the main ideas involved in each type of association. However, these relationships are often used in pairs, in order to enable better usage with Sequelize. This will be seen later on.
-
-## Creating the standard relationships
-
-As mentioned, usually the Sequelize associations are defined in pairs. In summary:
-
-* To create a **One-To-One** relationship, the `hasOne` and `belongsTo` associations are used together;
-* To create a **One-To-Many** relationship, the `hasMany` and `belongsTo` associations are used together;
-* To create a **Many-To-Many** relationship, two `belongsToMany` calls are used together.
- * Note: there is also a *Super Many-To-Many* relationship, which uses six associations at once, and will be discussed in the [Advanced Many-to-Many relationships guide](advanced-many-to-many.html).
-
-This will all be seen in detail next. The advantages of using these pairs instead of one single association will be discussed in the end of this chapter.
-
-## One-To-One relationships
-
-### Philosophy
-
-Before digging into the aspects of using Sequelize, it is useful to take a step back to consider what happens with a One-To-One relationship.
-
-Let's say we have two models, `Foo` and `Bar`. We want to establish a One-To-One relationship between Foo and Bar. We know that in a relational database, this will be done by establishing a foreign key in one of the tables. So in this case, a very relevant question is: in which table do we want this foreign key to be? In other words, do we want `Foo` to have a `barId` column, or should `Bar` have a `fooId` column instead?
-
-In principle, both options are a valid way to establish a One-To-One relationship between Foo and Bar. However, when we say something like *"there is a One-To-One relationship between Foo and Bar"*, it is unclear whether or not the relationship is *mandatory* or optional. In other words, can a Foo exist without a Bar? Can a Bar exist without a Foo? The answers to these questions helps figuring out where we want the foreign key column to be.
-
-### Goal
-
-For the rest of this example, let's assume that we have two models, `Foo` and `Bar`. We want to setup a One-To-One relationship between them such that `Bar` gets a `fooId` column.
-
-### Implementation
-
-The main setup to achieve the goal is as follows:
-
-```js
-Foo.hasOne(Bar);
-Bar.belongsTo(Foo);
-```
-
-Since no option was passed, Sequelize will infer what to do from the names of the models. In this case, Sequelize knows that a `fooId` column must be added to `Bar`.
-
-This way, calling `Bar.sync()` after the above will yield the following SQL (on PostgreSQL, for example):
-
-```sql
-CREATE TABLE IF NOT EXISTS "foos" (
- /* ... */
-);
-CREATE TABLE IF NOT EXISTS "bars" (
- /* ... */
- "fooId" INTEGER REFERENCES "foos" ("id") ON DELETE SET NULL ON UPDATE CASCADE
- /* ... */
-);
-```
-
-### Options
-
-Various options can be passed as a second parameter of the association call.
-
-#### `onDelete` and `onUpdate`
-
-For example, to configure the `ON DELETE` and `ON UPDATE` behaviors, you can do:
-
-```js
-Foo.hasOne(Bar, {
- onDelete: 'RESTRICT',
- onUpdate: 'RESTRICT'
-});
-Bar.belongsTo(Foo);
-```
-
-The possible choices are `RESTRICT`, `CASCADE`, `NO ACTION`, `SET DEFAULT` and `SET NULL`.
-
-The defaults for the One-To-One associations is `SET NULL` for `ON DELETE` and `CASCADE` for `ON UPDATE`.
-
-#### Customizing the foreign key
-
-Both the `hasOne` and `belongsTo` calls shown above will infer that the foreign key to be created should be called `fooId`. To use a different name, such as `myFooId`:
-
-```js
-// Option 1
-Foo.hasOne(Bar, {
- foreignKey: 'myFooId'
-});
-Bar.belongsTo(Foo);
-
-// Option 2
-Foo.hasOne(Bar, {
- foreignKey: {
- name: 'myFooId'
- }
-});
-Bar.belongsTo(Foo);
-
-// Option 3
-Foo.hasOne(Bar);
-Bar.belongsTo(Foo, {
- foreignKey: 'myFooId'
-});
-
-// Option 4
-Foo.hasOne(Bar);
-Bar.belongsTo(Foo, {
- foreignKey: {
- name: 'myFooId'
- }
-});
-```
-
-As shown above, the `foreignKey` option accepts a string or an object. When receiving an object, this object will be used as the definition for the column just like it would do in a standard `sequelize.define` call. Therefore, specifying options such as `type`, `allowNull`, `defaultValue`, etc, just work.
-
-For example, to use `UUID` as the foreign key data type instead of the default (`INTEGER`), you can simply do:
-
-```js
-const { DataTypes } = require("Sequelize");
-
-Foo.hasOne(Bar, {
- foreignKey: {
- // name: 'myFooId'
- type: DataTypes.UUID
- }
-});
-Bar.belongsTo(Foo);
-```
-
-#### Mandatory versus optional associations
-
-By default, the association is considered optional. In other words, in our example, the `fooId` is allowed to be null, meaning that one Bar can exist without a Foo. Changing this is just a matter of specifying `allowNull: false` in the foreign key options:
-
-```js
-Foo.hasOne(Bar, {
- foreignKey: {
- allowNull: false
- }
-});
-// "fooId" INTEGER NOT NULL REFERENCES "foos" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT
-```
-
-## One-To-Many relationships
-
-### Philosophy
-
-One-To-Many associations are connecting one source with multiple targets, while all these targets are connected only with this single source.
-
-This means that, unlike the One-To-One association, in which we had to choose where the foreign key would be placed, there is only one option in One-To-Many associations. For example, if one Foo has many Bars (and this way each Bar belongs to one Foo), then the only sensible implementation is to have a `fooId` column in the `Bar` table. The opposite is impossible, since one Foo has many Bars.
-
-### Goal
-
-In this example, we have the models `Team` and `Player`. We want to tell Sequelize that there is a One-To-Many relationship between them, meaning that one Team has many Players, while each Player belongs to a single Team.
-
-### Implementation
-
-The main way to do this is as follows:
-
-```js
-Team.hasMany(Player);
-Player.belongsTo(Team);
-```
-
-Again, as mentioned, the main way to do it used a pair of Sequelize associations (`hasMany` and `belongsTo`).
-
-For example, in PostgreSQL, the above setup will yield the following SQL upon `sync()`:
-
-```sql
-CREATE TABLE IF NOT EXISTS "Teams" (
- /* ... */
-);
-CREATE TABLE IF NOT EXISTS "Players" (
- /* ... */
- "TeamId" INTEGER REFERENCES "Teams" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
- /* ... */
-);
-```
-
-### Options
-
-The options to be applied in this case are the same from the One-To-One case. For example, to change the name of the foreign key and make sure that the relationship is mandatory, we can do:
-
-```js
-Team.hasMany(Player, {
- foreignKey: 'clubId'
-});
-Player.belongsTo(Team);
-```
-
-Like One-To-One relationships, `ON DELETE` defaults to `SET NULL` and `ON UPDATE` defaults to `CASCADE`.
-
-## Many-To-Many relationships
-
-### Philosophy
-
-Many-To-Many associations connect one source with multiple targets, while all these targets can in turn be connected to other sources beyond the first.
-
-This cannot be represented by adding one foreign key to one of the tables, like the other relationships did. Instead, the concept of a [Junction Model](https://en.wikipedia.org/wiki/Associative_entity) is used. This will be an extra model (and extra table in the database) which will have two foreign key columns and will keep track of the associations. The junction table is also sometimes called *join table* or *through table*.
-
-### Goal
-
-For this example, we will consider the models `Movie` and `Actor`. One actor may have participated in many movies, and one movie had many actors involved with its production. The junction table that will keep track of the associations will be called `ActorMovies`, which will contain the foreign keys `movieId` and `actorId`.
-
-### Implementation
-
-The main way to do this in Sequelize is as follows:
-
-```js
-const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
-const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
-Movie.belongsToMany(Actor, { through: 'ActorMovies' });
-Actor.belongsToMany(Movie, { through: 'ActorMovies' });
-```
-
-Since a string was given in the `through` option of the `belongsToMany` call, Sequelize will automatically create the `ActorMovies` model which will act as the junction model. For example, in PostgreSQL:
-
-```sql
-CREATE TABLE IF NOT EXISTS "ActorMovies" (
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- "MovieId" INTEGER REFERENCES "Movies" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
- "ActorId" INTEGER REFERENCES "Actors" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
- PRIMARY KEY ("MovieId","ActorId")
-);
-```
-
-Instead of a string, passing a model directly is also supported, and in that case the given model will be used as the junction model (and no model will be created automatically). For example:
-
-```js
-const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
-const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
-const ActorMovies = sequelize.define('ActorMovies', {
- MovieId: {
- type: DataTypes.INTEGER,
- references: {
- model: Movie, // 'Movies' would also work
- key: 'id'
- }
- },
- ActorId: {
- type: DataTypes.INTEGER,
- references: {
- model: Actor, // 'Actors' would also work
- key: 'id'
- }
- }
-});
-Movie.belongsToMany(Actor, { through: ActorMovies });
-Actor.belongsToMany(Movie, { through: ActorMovies });
-```
-
-The above yields the following SQL in PostgreSQL, which is equivalent to the one shown above:
-
-```sql
-CREATE TABLE IF NOT EXISTS "ActorMovies" (
- "MovieId" INTEGER NOT NULL REFERENCES "Movies" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- "ActorId" INTEGER NOT NULL REFERENCES "Actors" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- UNIQUE ("MovieId", "ActorId"), -- Note: Sequelize generated this UNIQUE constraint but
- PRIMARY KEY ("MovieId","ActorId") -- it is irrelevant since it's also a PRIMARY KEY
-);
-```
-
-### Options
-
-Unlike One-To-One and One-To-Many relationships, the defaults for both `ON UPDATE` and `ON DELETE` are `CASCADE` for Many-To-Many relationships.
-
-Belongs-To-Many creates a unique key on through model. This unique key name can be overridden using **uniqueKey** option. To prevent creating this unique key, use the ***unique: false*** option.
-
-```js
-Project.belongsToMany(User, { through: UserProjects, uniqueKey: 'my_custom_unique' })
-```
-
-## Basics of queries involving associations
-
-With the basics of defining associations covered, we can look at queries involving associations. The most common queries on this matter are the *read* queries (i.e. SELECTs). Later on, other types of queries will be shown.
-
-In order to study this, we will consider an example in which we have Ships and Captains, and a one-to-one relationship between them. We will allow null on foreign keys (the default), meaning that a Ship can exist without a Captain and vice-versa.
-
-```js
-// This is the setup of our models for the examples below
-const Ship = sequelize.define('ship', {
- name: DataTypes.TEXT,
- crewCapacity: DataTypes.INTEGER,
- amountOfSails: DataTypes.INTEGER
-}, { timestamps: false });
-const Captain = sequelize.define('captain', {
- name: DataTypes.TEXT,
- skillLevel: {
- type: DataTypes.INTEGER,
- validate: { min: 1, max: 10 }
- }
-}, { timestamps: false });
-Captain.hasOne(Ship);
-Ship.belongsTo(Captain);
-```
-
-### Fetching associations - Eager Loading vs Lazy Loading
-
-The concepts of Eager Loading and Lazy Loading are fundamental to understand how fetching associations work in Sequelize. Lazy Loading refers to the technique of fetching the associated data only when you really want it; Eager Loading, on the other hand, refers to the technique of fetching everything at once, since the beginning, with a larger query.
-
-#### Lazy Loading example
-
-```js
-const awesomeCaptain = await Captain.findOne({
- where: {
- name: "Jack Sparrow"
- }
-});
-// Do stuff with the fetched captain
-console.log('Name:', awesomeCaptain.name);
-console.log('Skill Level:', awesomeCaptain.skillLevel);
-// Now we want information about his ship!
-const hisShip = await awesomeCaptain.getShip();
-// Do stuff with the ship
-console.log('Ship Name:', hisShip.name);
-console.log('Amount of Sails:', hisShip.amountOfSails);
-```
-
-Observe that in the example above, we made two queries, only fetching the associated ship when we wanted to use it. This can be especially useful if we may or may not need the ship, perhaps we want to fetch it conditionally, only in a few cases; this way we can save time and memory by only fetching it when necessary.
-
-Note: the `getShip()` instance method used above is one of the methods Sequelize automatically adds to `Captain` instances. There are others. You will learn more about them later in this guide.
-
-#### Eager Loading Example
-
-```js
-const awesomeCaptain = await Captain.findOne({
- where: {
- name: "Jack Sparrow"
- },
- include: Ship
-});
-// Now the ship comes with it
-console.log('Name:', awesomeCaptain.name);
-console.log('Skill Level:', awesomeCaptain.skillLevel);
-console.log('Ship Name:', awesomeCaptain.ship.name);
-console.log('Amount of Sails:', awesomeCaptain.ship.amountOfSails);
-```
-
-As shown above, Eager Loading is performed in Sequelize by using the `include` option. Observe that here only one query was performed to the database (which brings the associated data along with the instance).
-
-This was just a quick introduction to Eager Loading in Sequelize. There is a lot more to it, which you can learn at [the dedicated guide on Eager Loading](eager-loading.html).
-
-### Creating, updating and deleting
-
-The above showed the basics on queries for fetching data involving associations. For creating, updating and deleting, you can either:
-
-* Use the standard model queries directly:
-
- ```js
- // Example: creating an associated model using the standard methods
- Bar.create({
- name: 'My Bar',
- fooId: 5
- });
- // This creates a Bar belonging to the Foo of ID 5 (since fooId is
- // a regular column, after all). Nothing very clever going on here.
- ```
-
-* Or use the *[special methods/mixins](#special-methods-mixins-added-to-instances)* available for associated models, which are explained later on this page.
-
-**Note:** The [`save()` instance method](../class/lib/model.js~Model.html#instance-method-save) is not aware of associations. In other words, if you change a value from a *child* object that was eager loaded along a *parent* object, calling `save()` on the parent will completely ignore the change that happened on the child.
-
-## Association Aliases & Custom Foreign Keys
-
-In all the above examples, Sequelize automatically defined the foreign key names. For example, in the Ship and Captain example, Sequelize automatically defined a `captainId` field on the Ship model. However, it is easy to specify a custom foreign key.
-
-Let's consider the models Ship and Captain in a simplified form, just to focus on the current topic, as shown below (less fields):
-
-```js
-const Ship = sequelize.define('ship', { name: DataTypes.TEXT }, { timestamps: false });
-const Captain = sequelize.define('captain', { name: DataTypes.TEXT }, { timestamps: false });
-```
-
-There are three ways to specify a different name for the foreign key:
-
-* By providing the foreign key name directly
-* By defining an Alias
-* By doing both things
-
-### Recap: the default setup
-
-By using simply `Ship.belongsTo(Captain)`, sequelize will generate the foreign key name automatically:
-
-```js
-Ship.belongsTo(Captain); // This creates the `captainId` foreign key in Ship.
-
-// Eager Loading is done by passing the model to `include`:
-console.log((await Ship.findAll({ include: Captain })).toJSON());
-// Or by providing the associated model name:
-console.log((await Ship.findAll({ include: 'captain' })).toJSON());
-
-// Also, instances obtain a `getCaptain()` method for Lazy Loading:
-const ship = Ship.findOne();
-console.log((await ship.getCaptain()).toJSON());
-```
-
-### Providing the foreign key name directly
-
-The foreign key name can be provided directly with an option in the association definition, as follows:
-
-```js
-Ship.belongsTo(Captain, { foreignKey: 'bossId' }); // This creates the `bossId` foreign key in Ship.
-
-// Eager Loading is done by passing the model to `include`:
-console.log((await Ship.findAll({ include: Captain })).toJSON());
-// Or by providing the associated model name:
-console.log((await Ship.findAll({ include: 'Captain' })).toJSON());
-
-// Also, instances obtain a `getCaptain()` method for Lazy Loading:
-const ship = Ship.findOne();
-console.log((await ship.getCaptain()).toJSON());
-```
-
-### Defining an Alias
-
-Defining an Alias is more powerful than simply specifying a custom name for the foreign key. This is better understood with an example:
-
-
-
-```js
-Ship.belongsTo(Captain, { as: 'leader' }); // This creates the `leaderId` foreign key in Ship.
-
-// Eager Loading no longer works by passing the model to `include`:
-console.log((await Ship.findAll({ include: Captain })).toJSON()); // Throws an error
-// Instead, you have to pass the alias:
-console.log((await Ship.findAll({ include: 'leader' })).toJSON());
-// Or you can pass an object specifying the model and alias:
-console.log((await Ship.findAll({
- include: {
- model: Captain,
- as: 'leader'
- }
-})).toJSON());
-
-// Also, instances obtain a `getLeader()` method for Lazy Loading:
-const ship = Ship.findOne();
-console.log((await ship.getLeader()).toJSON());
-```
-
-Aliases are especially useful when you need to define two different associations between the same models. For example, if we have the models `Mail` and `Person`, we may want to associate them twice, to represent the `sender` and `receiver` of the Mail. In this case we must use an alias for each association, since otherwise a call like `mail.getPerson()` would be ambiguous. With the `sender` and `receiver` aliases, we would have the two methods available and working: `mail.getSender()` and `mail.getReceiver()`, both of them returning a `Promise`.
-
-When defining an alias for a `hasOne` or `belongsTo` association, you should use the singular form of a word (such as `leader`, in the example above). On the other hand, when defining an alias for `hasMany` and `belongsToMany`, you should use the plural form. Defining aliases for Many-to-Many relationships (with `belongsToMany`) is covered in the [Advanced Many-to-Many Associations guide](advanced-many-to-many.html).
-
-### Doing both things
-
-We can define and alias and also directly define the foreign key:
-
-```js
-Ship.belongsTo(Captain, { as: 'leader', foreignKey: 'bossId' }); // This creates the `bossId` foreign key in Ship.
-
-// Since an alias was defined, eager Loading doesn't work by simply passing the model to `include`:
-console.log((await Ship.findAll({ include: Captain })).toJSON()); // Throws an error
-// Instead, you have to pass the alias:
-console.log((await Ship.findAll({ include: 'leader' })).toJSON());
-// Or you can pass an object specifying the model and alias:
-console.log((await Ship.findAll({
- include: {
- model: Captain,
- as: 'leader'
- }
-})).toJSON());
-
-// Also, instances obtain a `getLeader()` method for Lazy Loading:
-const ship = Ship.findOne();
-console.log((await ship.getLeader()).toJSON());
-```
-
-## Special methods/mixins added to instances
-
-When an association is defined between two models, the instances of those models gain special methods to interact with their associated counterparts.
-
-For example, if we have two models, `Foo` and `Bar`, and they are associated, their instances will have the following methods/mixins available, depending on the association type:
-
-### `Foo.hasOne(Bar)`
-
-* `fooInstance.getBar()`
-* `fooInstance.setBar()`
-* `fooInstance.createBar()`
-
-Example:
-
-```js
-const foo = await Foo.create({ name: 'the-foo' });
-const bar1 = await Bar.create({ name: 'some-bar' });
-const bar2 = await Bar.create({ name: 'another-bar' });
-console.log(await foo.getBar()); // null
-await foo.setBar(bar1);
-console.log((await foo.getBar()).name); // 'some-bar'
-await foo.createBar({ name: 'yet-another-bar' });
-const newlyAssociatedBar = await foo.getBar();
-console.log(newlyAssociatedBar.name); // 'yet-another-bar'
-await foo.setBar(null); // Un-associate
-console.log(await foo.getBar()); // null
-```
-
-### `Foo.belongsTo(Bar)`
-
-The same ones from `Foo.hasOne(Bar)`:
-
-* `fooInstance.getBar()`
-* `fooInstance.setBar()`
-* `fooInstance.createBar()`
-
-### `Foo.hasMany(Bar)`
-
-* `fooInstance.getBars()`
-* `fooInstance.countBars()`
-* `fooInstance.hasBar()`
-* `fooInstance.hasBars()`
-* `fooInstance.setBars()`
-* `fooInstance.addBar()`
-* `fooInstance.addBars()`
-* `fooInstance.removeBar()`
-* `fooInstance.removeBars()`
-* `fooInstance.createBar()`
-
-Example:
-
-```js
-const foo = await Foo.create({ name: 'the-foo' });
-const bar1 = await Bar.create({ name: 'some-bar' });
-const bar2 = await Bar.create({ name: 'another-bar' });
-console.log(await foo.getBars()); // []
-console.log(await foo.countBars()); // 0
-console.log(await foo.hasBar(bar1)); // false
-await foo.addBars([bar1, bar2]);
-console.log(await foo.countBars()); // 2
-await foo.addBar(bar1);
-console.log(await foo.countBars()); // 2
-console.log(await foo.hasBar(bar1)); // true
-await foo.removeBar(bar2);
-console.log(await foo.countBars()); // 1
-await foo.createBar({ name: 'yet-another-bar' });
-console.log(await foo.countBars()); // 2
-await foo.setBars([]); // Un-associate all previously associated bars
-console.log(await foo.countBars()); // 0
-```
-
-The getter method accepts options just like the usual finder methods (such as `findAll`):
-
-```js
-const easyTasks = await project.getTasks({
- where: {
- difficulty: {
- [Op.lte]: 5
- }
- }
-});
-const taskTitles = (await project.getTasks({
- attributes: ['title'],
- raw: true
-})).map(task => task.title);
-```
-
-### `Foo.belongsToMany(Bar, { through: Baz })`
-
-The same ones from `Foo.hasMany(Bar)`:
-
-* `fooInstance.getBars()`
-* `fooInstance.countBars()`
-* `fooInstance.hasBar()`
-* `fooInstance.hasBars()`
-* `fooInstance.setBars()`
-* `fooInstance.addBar()`
-* `fooInstance.addBars()`
-* `fooInstance.removeBar()`
-* `fooInstance.removeBars()`
-* `fooInstance.createBar()`
-
-### Note: Method names
-
-As shown in the examples above, the names Sequelize gives to these special methods are formed by a prefix (e.g. `get`, `add`, `set`) concatenated with the model name (with the first letter in uppercase). When necessary, the plural is used, such as in `fooInstance.setBars()`. Again, irregular plurals are also handled automatically by Sequelize. For example, `Person` becomes `People` and `Hypothesis` becomes `Hypotheses`.
-
-If an alias was defined, it will be used instead of the model name to form the method names. For example:
-
-```js
-Task.hasOne(User, { as: 'Author' });
-```
-
-* `taskInstance.getAuthor()`
-* `taskInstance.setAuthor()`
-* `taskInstance.createAuthor()`
-
-## Why associations are defined in pairs?
-
-As mentioned earlier and shown in most examples above, usually associations in Sequelize are defined in pairs:
-
-* To create a **One-To-One** relationship, the `hasOne` and `belongsTo` associations are used together;
-* To create a **One-To-Many** relationship, the `hasMany` and `belongsTo` associations are used together;
-* To create a **Many-To-Many** relationship, two `belongsToMany` calls are used together.
-
-When a Sequelize association is defined between two models, only the *source* model *knows about it*. So, for example, when using `Foo.hasOne(Bar)` (so `Foo` is the source model and `Bar` is the target model), only `Foo` knows about the existence of this association. This is why in this case, as shown above, `Foo` instances gain the methods `getBar()`, `setBar()` and `createBar()`, while on the other hand `Bar` instances get nothing.
-
-Similarly, for `Foo.hasOne(Bar)`, since `Foo` knows about the relationship, we can perform eager loading as in `Foo.findOne({ include: Bar })`, but we can't do `Bar.findOne({ include: Foo })`.
-
-Therefore, to bring full power to Sequelize usage, we usually setup the relationship in pairs, so that both models get to *know about it*.
-
-Practical demonstration:
-
-* If we do not define the pair of associations, calling for example just `Foo.hasOne(Bar)`:
-
- ```js
- // This works...
- await Foo.findOne({ include: Bar });
-
- // But this throws an error:
- await Bar.findOne({ include: Foo });
- // SequelizeEagerLoadingError: foo is not associated to bar!
- ```
-
-* If we define the pair as recommended, i.e., both `Foo.hasOne(Bar)` and `Bar.belongsTo(Foo)`:
-
- ```js
- // This works!
- await Foo.findOne({ include: Bar });
-
- // This also works!
- await Bar.findOne({ include: Foo });
- ```
-
-## Multiple associations involving the same models
-
-In Sequelize, it is possible to define multiple associations between the same models. You just have to define different aliases for them:
-
-```js
-Team.hasOne(Game, { as: 'HomeTeam', foreignKey: 'homeTeamId' });
-Team.hasOne(Game, { as: 'AwayTeam', foreignKey: 'awayTeamId' });
-Game.belongsTo(Team);
-```
-
-## Creating associations referencing a field which is not the primary key
-
-In all the examples above, the associations were defined by referencing the primary keys of the involved models (in our case, their IDs). However, Sequelize allows you to define an association that uses another field, instead of the primary key field, to establish the association.
-
-This other field must have a unique constraint on it (otherwise, it wouldn't make sense).
-
-### For `belongsTo` relationships
-
-First, recall that the `A.belongsTo(B)` association places the foreign key in the *source model* (i.e., in `A`).
-
-Let's again use the example of Ships and Captains. Additionally, we will assume that Captain names are unique:
-
-```js
-const Ship = sequelize.define('ship', { name: DataTypes.TEXT }, { timestamps: false });
-const Captain = sequelize.define('captain', {
- name: { type: DataTypes.TEXT, unique: true }
-}, { timestamps: false });
-```
-
-This way, instead of keeping the `captainId` on our Ships, we could keep a `captainName` instead and use it as our association tracker. In other words, instead of referencing the `id` from the target model (Captain), our relationship will reference another column on the target model: the `name` column. To specify this, we have to define a *target key*. We will also have to specify a name for the foreign key itself:
-
-```js
-Ship.belongsTo(Captain, { targetKey: 'name', foreignKey: 'captainName' });
-// This creates a foreign key called `captainName` in the source model (Ship)
-// which references the `name` field from the target model (Captain).
-```
-
-Now we can do things like:
-
-```js
-await Captain.create({ name: "Jack Sparrow" });
-const ship = await Ship.create({ name: "Black Pearl", captainName: "Jack Sparrow" });
-console.log((await ship.getCaptain()).name); // "Jack Sparrow"
-```
-
-### For `hasOne` and `hasMany` relationships
-
-The exact same idea can be applied to the `hasOne` and `hasMany` associations, but instead of providing a `targetKey`, we provide a `sourceKey` when defining the association. This is because unlike `belongsTo`, the `hasOne` and `hasMany` associations keep the foreign key on the target model:
-
-```js
-const Foo = sequelize.define('foo', {
- name: { type: DataTypes.TEXT, unique: true }
-}, { timestamps: false });
-const Bar = sequelize.define('bar', {
- title: { type: DataTypes.TEXT, unique: true }
-}, { timestamps: false });
-const Baz = sequelize.define('baz', { summary: DataTypes.TEXT }, { timestamps: false });
-Foo.hasOne(Bar, { sourceKey: 'name', foreignKey: 'fooName' });
-Bar.hasMany(Baz, { sourceKey: 'title', foreignKey: 'barTitle' });
-// [...]
-await Bar.setFoo("Foo's Name Here");
-await Baz.addBar("Bar's Title Here");
-```
-
-### For `belongsToMany` relationships
-
-The same idea can also be applied to `belongsToMany` relationships. However, unlike the other situations, in which we have only one foreign key involved, the `belongsToMany` relationship involves two foreign keys which are kept on an extra table (the junction table).
-
-Consider the following setup:
-
-```js
-const Foo = sequelize.define('foo', {
- name: { type: DataTypes.TEXT, unique: true }
-}, { timestamps: false });
-const Bar = sequelize.define('bar', {
- title: { type: DataTypes.TEXT, unique: true }
-}, { timestamps: false });
-```
-
-There are four cases to consider:
-
-* We might want a many-to-many relationship using the default primary keys for both `Foo` and `Bar`:
-
-```js
-Foo.belongsToMany(Bar, { through: 'foo_bar' });
-// This creates a junction table `foo_bar` with fields `fooId` and `barId`
-```
-
-* We might want a many-to-many relationship using the default primary key for `Foo` but a different field for `Bar`:
-
-```js
-Foo.belongsToMany(Bar, { through: 'foo_bar', targetKey: 'title' });
-// This creates a junction table `foo_bar` with fields `fooId` and `barTitle`
-```
-
-* We might want a many-to-many relationship using the a different field for `Foo` and the default primary key for `Bar`:
-
-```js
-Foo.belongsToMany(Bar, { through: 'foo_bar', sourceKey: 'name' });
-// This creates a junction table `foo_bar` with fields `fooName` and `barId`
-```
-
-* We might want a many-to-many relationship using different fields for both `Foo` and `Bar`:
-
-```js
-Foo.belongsToMany(Bar, { through: 'foo_bar', sourceKey: 'name', targetKey: 'title' });
-// This creates a junction table `foo_bar` with fields `fooName` and `barTitle`
-```
-
-### Notes
-
-Don't forget that the field referenced in the association must have a unique constraint placed on it. Otherwise, an error will be thrown (and sometimes with a mysterious error message - such as `SequelizeDatabaseError: SQLITE_ERROR: foreign key mismatch - "ships" referencing "captains"` for SQLite).
-
-The trick to deciding between `sourceKey` and `targetKey` is just to remember where each relationship places its foreign key. As mentioned in the beginning of this guide:
-
-* `A.belongsTo(B)` keeps the foreign key in the source model (`A`), therefore the referenced key is in the target model, hence the usage of `targetKey`.
-
-* `A.hasOne(B)` and `A.hasMany(B)` keep the foreign key in the target model (`B`), therefore the referenced key is in the source model, hence the usage of `sourceKey`.
-
-* `A.belongsToMany(B)` involves an extra table (the junction table), therefore both `sourceKey` and `targetKey` are usable, with `sourceKey` corresponding to some field in `A` (the source) and `targetKey` corresponding to some field in `B` (the target).
diff --git a/docs/manual/core-concepts/getters-setters-virtuals.md b/docs/manual/core-concepts/getters-setters-virtuals.md
deleted file mode 100644
index c280dc3ae344..000000000000
--- a/docs/manual/core-concepts/getters-setters-virtuals.md
+++ /dev/null
@@ -1,201 +0,0 @@
-# Getters, Setters & Virtuals
-
-Sequelize allows you to define custom getters and setters for the attributes of your models.
-
-Sequelize also allows you to specify the so-called *virtual attributes*, which are attributes on the Sequelize Model that doesn't really exist in the underlying SQL table, but instead are populated automatically by Sequelize. They are very useful for simplifying code, for example.
-
-## Getters
-
-A getter is a `get()` function defined for one column in the model definition:
-
-```js
-const User = sequelize.define('user', {
- // Let's say we wanted to see every username in uppercase, even
- // though they are not necessarily uppercase in the database itself
- username: {
- type: DataTypes.STRING,
- get() {
- const rawValue = this.getDataValue('username');
- return rawValue ? rawValue.toUpperCase() : null;
- }
- }
-});
-```
-
-This getter, just like a standard JavaScript getter, is called automatically when the field value is read:
-
-```js
-const user = User.build({ username: 'SuperUser123' });
-console.log(user.username); // 'SUPERUSER123'
-console.log(user.getDataValue('username')); // 'SuperUser123'
-```
-
-Note that, although `SUPERUSER123` was logged above, the value truly stored in the database is still `SuperUser123`. We used `this.getDataValue('username')` to obtain this value, and converted it to uppercase.
-
-Had we tried to use `this.username` in the getter instead, we would have gotten an infinite loop! This is why Sequelize provides the `getDataValue` method.
-
-## Setters
-
-A setter is a `set()` function defined for one column in the model definition. It receives the value being set:
-
-```js
-const User = sequelize.define('user', {
- username: DataTypes.STRING,
- password: {
- type: DataTypes.STRING,
- set(value) {
- // Storing passwords in plaintext in the database is terrible.
- // Hashing the value with an appropriate cryptographic hash function is better.
- this.setDataValue('password', hash(value));
- }
- }
-});
-```
-
-```js
-const user = User.build({ username: 'someone', password: 'NotSo§tr0ngP4$SW0RD!' });
-console.log(user.password); // '7cfc84b8ea898bb72462e78b4643cfccd77e9f05678ec2ce78754147ba947acc'
-console.log(user.getDataValue('password')); // '7cfc84b8ea898bb72462e78b4643cfccd77e9f05678ec2ce78754147ba947acc'
-```
-
-Observe that Sequelize called the setter automatically, before even sending data to the database. The only data the database ever saw was the already hashed value.
-
-If we wanted to involve another field from our model instance in the computation, that is possible and very easy!
-
-```js
-const User = sequelize.define('user', {
- username: DataTypes.STRING,
- password: {
- type: DataTypes.STRING,
- set(value) {
- // Storing passwords in plaintext in the database is terrible.
- // Hashing the value with an appropriate cryptographic hash function is better.
- // Using the username as a salt is better.
- this.setDataValue('password', hash(this.username + value));
- }
- }
-});
-```
-
-**Note:** The above examples involving password handling, although much better than simply storing the password in plaintext, are far from perfect security. Handling passwords properly is hard, everything here is just for the sake of an example to show Sequelize functionality. We suggest involving a cybersecurity expert and/or reading [OWASP](https://www.owasp.org/) documents and/or visiting the [InfoSec StackExchange](https://security.stackexchange.com/).
-
-## Combining getters and setters
-
-Getters and setters can be both defined in the same field.
-
-For the sake of an example, let's say we are modeling a `Post`, whose `content` is a text of unlimited length. To improve memory usage, let's say we want to store a gzipped version of the content.
-
-*Note: modern databases should do some compression automatically in these cases. Please note that this is just for the sake of an example.*
-
-```js
-const { gzipSync, gunzipSync } = require('zlib');
-
-const Post = sequelize.define('post', {
- content: {
- type: DataTypes.TEXT,
- get() {
- const storedValue = this.getDataValue('content');
- const gzippedBuffer = Buffer.from(storedValue, 'base64');
- const unzippedBuffer = gunzipSync(gzippedBuffer);
- return unzippedBuffer.toString();
- },
- set(value) {
- const gzippedBuffer = gzipSync(value);
- this.setDataValue('content', gzippedBuffer.toString('base64'));
- }
- }
-});
-```
-
-With the above setup, whenever we try to interact with the `content` field of our `Post` model, Sequelize will automatically handle the custom getter and setter. For example:
-
-```js
-const post = await Post.create({ content: 'Hello everyone!' });
-
-console.log(post.content); // 'Hello everyone!'
-// Everything is happening under the hood, so we can even forget that the
-// content is actually being stored as a gzipped base64 string!
-
-// However, if we are really curious, we can get the 'raw' data...
-console.log(post.getDataValue('content'));
-// Output: 'H4sIAAAAAAAACvNIzcnJV0gtSy2qzM9LVQQAUuk9jQ8AAAA='
-```
-
-## Virtual fields
-
-Virtual fields are fields that Sequelize populates under the hood, but in reality they don't even exist in the database.
-
-For example, let's say we have the `firstName` and `lastName` attributes for a User.
-
-*Again, this is [only for the sake of an example](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/).*
-
-It would be nice to have a simple way to obtain the *full name* directly! We can combine the idea of `getters` with the special data type Sequelize provides for this kind of situation: `DataTypes.VIRTUAL`:
-
-```js
-const { DataTypes } = require("sequelize");
-
-const User = sequelize.define('user', {
- firstName: DataTypes.TEXT,
- lastName: DataTypes.TEXT,
- fullName: {
- type: DataTypes.VIRTUAL,
- get() {
- return `${this.firstName} ${this.lastName}`;
- },
- set(value) {
- throw new Error('Do not try to set the `fullName` value!');
- }
- }
-});
-```
-
-The `VIRTUAL` field does not cause a column in the table to exist. In other words, the model above will not have a `fullName` column. However, it will appear to have it!
-
-```js
-const user = await User.create({ firstName: 'John', lastName: 'Doe' });
-console.log(user.fullName); // 'John Doe'
-```
-
-## `getterMethods` and `setterMethods`
-
-Sequelize also provides the `getterMethods` and `setterMethods` options in the model definition to specify things that look like, but aren't exactly the same as, virtual attributes. This usage is discouraged and likely to be deprecated in the future (in favor of using virtual attributes directly).
-
-Example:
-
-```js
-const { Sequelize, DataTypes } = require('sequelize');
-const sequelize = new Sequelize('sqlite::memory:');
-
-const User = sequelize.define('user', {
- firstName: DataTypes.STRING,
- lastName: DataTypes.STRING
-}, {
- getterMethods: {
- fullName() {
- return this.firstName + ' ' + this.lastName;
- }
- },
- setterMethods: {
- fullName(value) {
- // Note: this is just for demonstration.
- // See: https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/
- const names = value.split(' ');
- const firstName = names[0];
- const lastName = names.slice(1).join(' ');
- this.setDataValue('firstName', firstName);
- this.setDataValue('lastName', lastName);
- }
- }
-});
-
-(async () => {
- await sequelize.sync();
- let user = await User.create({ firstName: 'John', lastName: 'Doe' });
- console.log(user.fullName); // 'John Doe'
- user.fullName = 'Someone Else';
- await user.save();
- user = await User.findOne();
- console.log(user.firstName); // 'Someone'
- console.log(user.lastName); // 'Else'
-})();
-```
\ No newline at end of file
diff --git a/docs/manual/core-concepts/getting-started.md b/docs/manual/core-concepts/getting-started.md
deleted file mode 100644
index 46a9760255d3..000000000000
--- a/docs/manual/core-concepts/getting-started.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# Getting Started
-
-In this tutorial you will learn to make a simple setup of Sequelize.
-
-## Installing
-
-Sequelize is available via [npm](https://www.npmjs.com/package/sequelize) (or [yarn](https://yarnpkg.com/package/sequelize)).
-
-```sh
-npm install --save sequelize
-```
-
-You'll also have to manually install the driver for your database of choice:
-
-```sh
-# One of the following:
-$ npm install --save pg pg-hstore # Postgres
-$ npm install --save mysql2
-$ npm install --save mariadb
-$ npm install --save sqlite3
-$ npm install --save tedious # Microsoft SQL Server
-```
-
-## Connecting to a database
-
-To connect to the database, you must create a Sequelize instance. This can be done by either passing the connection parameters separately to the Sequelize constructor or by passing a single connection URI:
-
-```js
-const { Sequelize } = require('sequelize');
-
-// Option 1: Passing a connection URI
-const sequelize = new Sequelize('sqlite::memory:') // Example for sqlite
-const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Example for postgres
-
-// Option 2: Passing parameters separately (sqlite)
-const sequelize = new Sequelize({
- dialect: 'sqlite',
- storage: 'path/to/database.sqlite'
-});
-
-// Option 2: Passing parameters separately (other dialects)
-const sequelize = new Sequelize('database', 'username', 'password', {
- host: 'localhost',
- dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
-});
-```
-
-The Sequelize constructor accepts a lot of options. They are documented in the [API Reference](../class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor).
-
-### Testing the connection
-
-You can use the `.authenticate()` function to test if the connection is OK:
-
-```js
-try {
- await sequelize.authenticate();
- console.log('Connection has been established successfully.');
-} catch (error) {
- console.error('Unable to connect to the database:', error);
-}
-```
-
-### Closing the connection
-
-Sequelize will keep the connection open by default, and use the same connection for all queries. If you need to close the connection, call `sequelize.close()` (which is asynchronous and returns a Promise).
-
-## Terminology convention
-
-Observe that, in the examples above, `Sequelize` refers to the library itself while `sequelize` refers to an instance of Sequelize, which represents a connection to one database. This is the recommended convention and it will be followed throughout the documentation.
-
-## Tip for reading the docs
-
-You are encouraged to run code examples locally while reading the Sequelize docs. This will help you learn faster. The easiest way to do this is using the SQLite dialect:
-
-```js
-const { Sequelize, Op, Model, DataTypes } = require("sequelize");
-const sequelize = new Sequelize("sqlite::memory:");
-
-// Code here! It works!
-```
-
-To experiment with the other dialects, which are harder to setup locally, you can use the [Sequelize SSCCE](https://github.com/papb/sequelize-sscce) GitHub repository, which allows you to run code on all supported dialects directly from GitHub, for free, without any setup!
-
-## New databases versus existing databases
-
-If you are starting a project from scratch, and your database does not exist yet, Sequelize can be used since the beginning in order to automate the creation of every table in your database.
-
-Also, if you want to use Sequelize to connect to a database that is already filled with tables and data, that works as well! Sequelize has got you covered in both cases.
-
-## Logging
-
-By default, Sequelize will log to console every SQL query it performs. The `options.logging` option can be used to customize this behavior, by defining the function that gets executed every time Sequelize would log something. The default value is `console.log` and when using that only the first log parameter of log function call is displayed. For example, for query logging the first parameter is the raw query and the second (hidden by default) is the Sequelize object.
-
-Common useful values for `options.logging`:
-
-```js
-const sequelize = new Sequelize('sqlite::memory:', {
- // Choose one of the logging options
- logging: console.log, // Default, displays the first parameter of the log function call
- logging: (...msg) => console.log(msg), // Displays all log function call parameters
- logging: false, // Disables logging
- logging: msg => logger.debug(msg), // Use custom logger (e.g. Winston or Bunyan), displays the first parameter
- logging: logger.debug.bind(logger) // Alternative way to use custom logger, displays all messages
-});
-```
-
-## Promises and async/await
-
-Most of the methods provided by Sequelize are asynchronous and therefore return Promises. They are all [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) , so you can use the Promise API (for example, using `then`, `catch`, `finally`) out of the box.
-
-Of course, using `async` and `await` works normally as well.
diff --git a/docs/manual/core-concepts/model-basics.md b/docs/manual/core-concepts/model-basics.md
deleted file mode 100644
index db4075280dec..000000000000
--- a/docs/manual/core-concepts/model-basics.md
+++ /dev/null
@@ -1,437 +0,0 @@
-# Model Basics
-
-In this tutorial you will learn what models are in Sequelize and how to use them.
-
-## Concept
-
-Models are the essence of Sequelize. A model is an abstraction that represents a table in your database. In Sequelize, it is a class that extends [Model](../class/lib/model.js~Model.html).
-
-The model tells Sequelize several things about the entity it represents, such as the name of the table in the database and which columns it has (and their data types).
-
-A model in Sequelize has a name. This name does not have to be the same name of the table it represents in the database. Usually, models have singular names (such as `User`) while tables have pluralized names (such as `Users`), although this is fully configurable.
-
-## Model Definition
-
-Models can be defined in two equivalent ways in Sequelize:
-
-* Calling [`sequelize.define(modelName, attributes, options)`](../class/lib/sequelize.js~Sequelize.html#instance-method-define)
-* Extending [Model](../class/lib/model.js~Model.html) and calling [`init(attributes, options)`](../class/lib/model.js~Model.html#static-method-init)
-
-After a model is defined, it is available within `sequelize.models` by its model name.
-
-To learn with an example, we will consider that we want to create a model to represent users, which have a `firstName` and a `lastName`. We want our model to be called `User`, and the table it represents is called `Users` in the database.
-
-Both ways to define this model are shown below. After being defined, we can access our model with `sequelize.models.User`.
-
-### Using [`sequelize.define`](../class/lib/sequelize.js~Sequelize.html#instance-method-define):
-
-```js
-const { Sequelize, DataTypes } = require('sequelize');
-const sequelize = new Sequelize('sqlite::memory:');
-
-const User = sequelize.define('User', {
- // Model attributes are defined here
- firstName: {
- type: DataTypes.STRING,
- allowNull: false
- },
- lastName: {
- type: DataTypes.STRING
- // allowNull defaults to true
- }
-}, {
- // Other model options go here
-});
-
-// `sequelize.define` also returns the model
-console.log(User === sequelize.models.User); // true
-```
-
-### Extending [Model](../class/lib/model.js~Model.html)
-
-```js
-const { Sequelize, DataTypes, Model } = require('sequelize');
-const sequelize = new Sequelize('sqlite::memory');
-
-class User extends Model {}
-
-User.init({
- // Model attributes are defined here
- firstName: {
- type: DataTypes.STRING,
- allowNull: false
- },
- lastName: {
- type: DataTypes.STRING
- // allowNull defaults to true
- }
-}, {
- // Other model options go here
- sequelize, // We need to pass the connection instance
- modelName: 'User' // We need to choose the model name
-});
-
-// the defined model is the class itself
-console.log(User === sequelize.models.User); // true
-```
-
-Internally, `sequelize.define` calls `Model.init`, so both approaches are essentially equivalent.
-
-## Table name inference
-
-Observe that, in both methods above, the table name (`Users`) was never explicitly defined. However, the model name was given (`User`).
-
-By default, when the table name is not given, Sequelize automatically pluralizes the model name and uses that as the table name. This pluralization is done under the hood by a library called [inflection](https://www.npmjs.com/package/inflection), so that irregular plurals (such as `person -> people`) are computed correctly.
-
-Of course, this behavior is easily configurable.
-
-### Enforcing the table name to be equal to the model name
-
-You can stop the auto-pluralization performed by Sequelize using the `freezeTableName: true` option. This way, Sequelize will infer the table name to be equal to the model name, without any modifications:
-
-```js
-sequelize.define('User', {
- // ... (attributes)
-}, {
- freezeTableName: true
-});
-```
-
-The example above will create a model named `User` pointing to a table also named `User`.
-
-This behavior can also be defined globally for the sequelize instance, when it is created:
-
-```js
-const sequelize = new Sequelize('sqlite::memory:', {
- define: {
- freezeTableName: true
- }
-});
-```
-
-This way, all tables will use the same name as the model name.
-
-### Providing the table name directly
-
-You can simply tell Sequelize the name of the table directly as well:
-
-```js
-sequelize.define('User', {
- // ... (attributes)
-}, {
- tableName: 'Employees'
-});
-```
-
-## Model synchronization
-
-When you define a model, you're telling Sequelize a few things about its table in the database. However, what if the table actually doesn't even exist in the database? What if it exists, but it has different columns, less columns, or any other difference?
-
-This is where model synchronization comes in. A model can be synchronized with the database by calling [`model.sync(options)`](https://sequelize.org/master/class/lib/model.js~Model.html#static-method-sync), an asynchronous function (that returns a Promise). With this call, Sequelize will automatically perform an SQL query to the database. Note that this changes only the table in the database, not the model in the JavaScript side.
-
-* `User.sync()` - This creates the table if it doesn't exist (and does nothing if it already exists)
-* `User.sync({ force: true })` - This creates the table, dropping it first if it already existed
-* `User.sync({ alter: true })` - This checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model.
-
-Example:
-
-```js
-await User.sync({ force: true });
-console.log("The table for the User model was just (re)created!");
-```
-
-### Synchronizing all models at once
-
-You can use [`sequelize.sync()`](../class/lib/sequelize.js~Sequelize.html#instance-method-sync) to automatically synchronize all models. Example:
-
-```js
-await sequelize.sync({ force: true });
-console.log("All models were synchronized successfully.");
-```
-
-### Dropping tables
-
-To drop the table related to a model:
-
-```js
-await User.drop();
-console.log("User table dropped!");
-```
-
-To drop all tables:
-
-```js
-await sequelize.drop();
-console.log("All tables dropped!");
-```
-
-### Database safety check
-
-As shown above, the `sync` and `drop` operations are destructive. Sequelize accepts a `match` option as an additional safety check, which receives a RegExp:
-
-```js
-// This will run .sync() only if database name ends with '_test'
-sequelize.sync({ force: true, match: /_test$/ });
-```
-
-### Synchronization in production
-
-As shown above, `sync({ force: true })` and `sync({ alter: true })` can be destructive operations. Therefore, they are not recommended for production-level software. Instead, synchronization should be done with the advanced concept of [Migrations](migrations.html), with the help of the [Sequelize CLI](https://github.com/sequelize/cli).
-
-## Timestamps
-
-By default, Sequelize automatically adds the fields `createdAt` and `updatedAt` to every model, using the data type `DataTypes.DATE`. Those fields are automatically managed as well - whenever you use Sequelize to create or update something, those fields will be set correctly. The `createdAt` field will contain the timestamp representing the moment of creation, and the `updatedAt` will contain the timestamp of the latest update.
-
-**Note:** This is done in the Sequelize level (i.e. not done with *SQL triggers*). This means that direct SQL queries (for example queries performed without Sequelize by any other means) will not cause these fields to be updated automatically.
-
-This behavior can be disabled for a model with the `timestamps: false` option:
-
-```js
-sequelize.define('User', {
- // ... (attributes)
-}, {
- timestamps: false
-});
-```
-
-It is also possible to enable only one of `createdAt`/`updatedAt`, and to provide a custom name for these columns:
-
-```js
-class Foo extends Model {}
-Foo.init({ /* attributes */ }, {
- sequelize,
-
- // don't forget to enable timestamps!
- timestamps: true,
-
- // I don't want createdAt
- createdAt: false,
-
- // I want updatedAt to actually be called updateTimestamp
- updatedAt: 'updateTimestamp'
-});
-```
-
-## Column declaration shorthand syntax
-
-If the only thing being specified about a column is its data type, the syntax can be shortened:
-
-```js
-// This:
-sequelize.define('User', {
- name: {
- type: DataTypes.STRING
- }
-});
-
-// Can be simplified to:
-sequelize.define('User', { name: DataTypes.STRING });
-```
-
-## Default Values
-
-By default, Sequelize assumes that the default value of a column is `NULL`. This behavior can be changed by passing a specific `defaultValue` to the column definition:
-
-```js
-sequelize.define('User', {
- name: {
- type: DataTypes.STRING,
- defaultValue: "John Doe"
- }
-});
-```
-
-Some special values, such as `Sequelize.NOW`, are also accepted:
-
-```js
-sequelize.define('Foo', {
- bar: {
- type: DataTypes.DATETIME,
- defaultValue: Sequelize.NOW
- // This way, the current date/time will be used to populate this column (at the moment of insertion)
- }
-});
-```
-
-## Data Types
-
-Every column you define in your model must have a data type. Sequelize provides [a lot of built-in data types](https://github.com/sequelize/sequelize/blob/main/lib/data-types.js). To access a built-in data type, you must import `DataTypes`:
-
-```js
-const { DataTypes } = require("sequelize"); // Import the built-in data types
-```
-
-### Strings
-
-```js
-DataTypes.STRING // VARCHAR(255)
-DataTypes.STRING(1234) // VARCHAR(1234)
-DataTypes.STRING.BINARY // VARCHAR BINARY
-DataTypes.TEXT // TEXT
-DataTypes.TEXT('tiny') // TINYTEXT
-DataTypes.CITEXT // CITEXT PostgreSQL and SQLite only.
-DataTypes.TSVECTOR // TSVECTOR PostgreSQL only.
-```
-
-### Boolean
-
-```js
-DataTypes.BOOLEAN // TINYINT(1)
-```
-
-### Numbers
-
-```js
-DataTypes.INTEGER // INTEGER
-DataTypes.BIGINT // BIGINT
-DataTypes.BIGINT(11) // BIGINT(11)
-
-DataTypes.FLOAT // FLOAT
-DataTypes.FLOAT(11) // FLOAT(11)
-DataTypes.FLOAT(11, 10) // FLOAT(11,10)
-
-DataTypes.REAL // REAL PostgreSQL only.
-DataTypes.REAL(11) // REAL(11) PostgreSQL only.
-DataTypes.REAL(11, 12) // REAL(11,12) PostgreSQL only.
-
-DataTypes.DOUBLE // DOUBLE
-DataTypes.DOUBLE(11) // DOUBLE(11)
-DataTypes.DOUBLE(11, 10) // DOUBLE(11,10)
-
-DataTypes.DECIMAL // DECIMAL
-DataTypes.DECIMAL(10, 2) // DECIMAL(10,2)
-```
-
-#### Unsigned & Zerofill integers - MySQL/MariaDB only
-
-In MySQL and MariaDB, the data types `INTEGER`, `BIGINT`, `FLOAT` and `DOUBLE` can be set as unsigned or zerofill (or both), as follows:
-
-```js
-DataTypes.INTEGER.UNSIGNED
-DataTypes.INTEGER.ZEROFILL
-DataTypes.INTEGER.UNSIGNED.ZEROFILL
-// You can also specify the size i.e. INTEGER(10) instead of simply INTEGER
-// Same for BIGINT, FLOAT and DOUBLE
-```
-
-### Dates
-
-```js
-DataTypes.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres
-DataTypes.DATE(6) // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision
-DataTypes.DATEONLY // DATE without time
-```
-
-### UUIDs
-
-For UUIDs, use `DataTypes.UUID`. It becomes the `UUID` data type for PostgreSQL and SQLite, and `CHAR(36)` for MySQL. Sequelize can generate UUIDs automatically for these fields, simply use `Sequelize.UUIDV1` or `Sequelize.UUIDV4` as the default value:
-
-```js
-{
- type: DataTypes.UUID,
- defaultValue: Sequelize.UUIDV4 // Or Sequelize.UUIDV1
-}
-```
-
-### Others
-
-There are other data types, covered in a [separate guide](other-data-types.html).
-
-## Column Options
-
-When defining a column, apart from specifying the `type` of the column, and the `allowNull` and `defaultValue` options mentioned above, there are a lot more options that can be used. Some examples are below.
-
-```js
-const { Model, DataTypes, Deferrable } = require("sequelize");
-
-class Foo extends Model {}
-Foo.init({
- // instantiating will automatically set the flag to true if not set
- flag: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
-
- // default values for dates => current time
- myDate: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
-
- // setting allowNull to false will add NOT NULL to the column, which means an error will be
- // thrown from the DB when the query is executed if the column is null. If you want to check that a value
- // is not null before querying the DB, look at the validations section below.
- title: { type: DataTypes.STRING, allowNull: false },
-
- // Creating two objects with the same value will throw an error. The unique property can be either a
- // boolean, or a string. If you provide the same string for multiple columns, they will form a
- // composite unique key.
- uniqueOne: { type: DataTypes.STRING, unique: 'compositeIndex' },
- uniqueTwo: { type: DataTypes.INTEGER, unique: 'compositeIndex' },
-
- // The unique property is simply a shorthand to create a unique constraint.
- someUnique: { type: DataTypes.STRING, unique: true },
-
- // Go on reading for further information about primary keys
- identifier: { type: DataTypes.STRING, primaryKey: true },
-
- // autoIncrement can be used to create auto_incrementing integer columns
- incrementMe: { type: DataTypes.INTEGER, autoIncrement: true },
-
- // You can specify a custom column name via the 'field' attribute:
- fieldWithUnderscores: { type: DataTypes.STRING, field: 'field_with_underscores' },
-
- // It is possible to create foreign keys:
- bar_id: {
- type: DataTypes.INTEGER,
-
- references: {
- // This is a reference to another model
- model: Bar,
-
- // This is the column name of the referenced model
- key: 'id',
-
- // With PostgreSQL, it is optionally possible to declare when to check the foreign key constraint, passing the Deferrable type.
- deferrable: Deferrable.INITIALLY_IMMEDIATE
- // Options:
- // - `Deferrable.INITIALLY_IMMEDIATE` - Immediately check the foreign key constraints
- // - `Deferrable.INITIALLY_DEFERRED` - Defer all foreign key constraint check to the end of a transaction
- // - `Deferrable.NOT` - Don't defer the checks at all (default) - This won't allow you to dynamically change the rule in a transaction
- }
- },
-
- // Comments can only be added to columns in MySQL, MariaDB, PostgreSQL and MSSQL
- commentMe: {
- type: DataTypes.INTEGER,
- comment: 'This is a column name that has a comment'
- }
-}, {
- sequelize,
- modelName: 'foo',
-
- // Using `unique: true` in an attribute above is exactly the same as creating the index in the model's options:
- indexes: [{ unique: true, fields: ['someUnique'] }]
-});
-```
-
-## Taking advantage of Models being classes
-
-The Sequelize models are [ES6 classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). You can very easily add custom instance or class level methods.
-
-```js
-class User extends Model {
- static classLevelMethod() {
- return 'foo';
- }
- instanceLevelMethod() {
- return 'bar';
- }
- getFullname() {
- return [this.firstname, this.lastname].join(' ');
- }
-}
-User.init({
- firstname: Sequelize.TEXT,
- lastname: Sequelize.TEXT
-}, { sequelize });
-
-console.log(User.classLevelMethod()); // 'foo'
-const user = User.build({ firstname: 'Jane', lastname: 'Doe' });
-console.log(user.instanceLevelMethod()); // 'bar'
-console.log(user.getFullname()); // 'Jane Doe'
-```
diff --git a/docs/manual/core-concepts/model-instances.md b/docs/manual/core-concepts/model-instances.md
deleted file mode 100644
index 27699dc2412c..000000000000
--- a/docs/manual/core-concepts/model-instances.md
+++ /dev/null
@@ -1,172 +0,0 @@
-# Model Instances
-
-As you already know, a model is an [ES6 class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). An instance of the class represents one object from that model (which maps to one row of the table in the database). This way, model instances are [DAOs](https://en.wikipedia.org/wiki/Data_access_object).
-
-For this guide, the following setup will be assumed:
-
-```js
-const { Sequelize, Model, DataTypes } = require("sequelize");
-const sequelize = new Sequelize("sqlite::memory:");
-
-const User = sequelize.define("user", {
- name: DataTypes.TEXT,
- favoriteColor: {
- type: DataTypes.TEXT,
- defaultValue: 'green'
- },
- age: DataTypes.INTEGER,
- cash: DataTypes.INTEGER
-});
-
-(async () => {
- await sequelize.sync({ force: true });
- // Code here
-})();
-```
-
-## Creating an instance
-
-Although a model is a class, you should not create instances by using the `new` operator directly. Instead, the [`build`](../class/lib/model.js~Model.html#static-method-build) method should be used:
-
-```js
-const jane = User.build({ name: "Jane" });
-console.log(jane instanceof User); // true
-console.log(jane.name); // "Jane"
-```
-
-However, the code above does not communicate with the database at all (note that it is not even asynchronous)! This is because the [`build`](../class/lib/model.js~Model.html#static-method-build) method only creates an object that *represents* data that *can* be mapped to a database. In order to really save (i.e. persist) this instance in the database, the [`save`](../class/lib/model.js~Model.html#instance-method-save) method should be used:
-
-```js
-await jane.save();
-console.log('Jane was saved to the database!');
-```
-
-Note, from the usage of `await` in the snippet above, that `save` is an asynchronous method. In fact, almost every Sequelize method is asynchronous; `build` is one of the very few exceptions.
-
-### A very useful shortcut: the `create` method
-
-Sequelize provides the [`create`](../class/lib/model.js~Model.html#static-method-create) method, which combines the `build` and `save` methods shown above into a single method:
-
-```js
-const jane = await User.create({ name: "Jane" });
-// Jane exists in the database now!
-console.log(jane instanceof User); // true
-console.log(jane.name); // "Jane"
-```
-
-## Note: logging instances
-
-Trying to log a model instance directly to `console.log` will produce a lot of clutter, since Sequelize instances have a lot of things attached to them. Instead, you can use the `.toJSON()` method (which, by the way, automatically guarantees the instances to be `JSON.stringify`-ed well).
-
-```js
-const jane = await User.create({ name: "Jane" });
-// console.log(jane); // Don't do this
-console.log(jane.toJSON()); // This is good!
-console.log(JSON.stringify(jane, null, 4)); // This is also good!
-```
-
-## Default values
-
-Built instances will automatically get default values:
-
-```js
-const jane = User.build({ name: "Jane" });
-console.log(jane.favoriteColor); // "green"
-```
-
-## Updating an instance
-
-If you change the value of some field of an instance, calling `save` again will update it accordingly:
-
-```js
-const jane = await User.create({ name: "Jane" });
-console.log(jane.name); // "Jane"
-jane.name = "Ada";
-// the name is still "Jane" in the database
-await jane.save();
-// Now the name was updated to "Ada" in the database!
-```
-
-## Deleting an instance
-
-You can delete an instance by calling [`destroy`](../class/lib/model.js~Model.html#instance-method-destroy):
-
-```js
-const jane = await User.create({ name: "Jane" });
-console.log(jane.name); // "Jane"
-await jane.destroy();
-// Now this entry was removed from the database
-```
-
-## Reloading an instance
-
-You can reload an instance from the database by calling [`reload`](../class/lib/model.js~Model.html#instance-method-reload):
-
-```js
-const jane = await User.create({ name: "Jane" });
-console.log(jane.name); // "Jane"
-jane.name = "Ada";
-// the name is still "Jane" in the database
-await jane.reload();
-console.log(jane.name); // "Jane"
-```
-
-The reload call generates a `SELECT` query to get the up-to-date data from the database.
-
-## Saving only some fields
-
-It is possible to define which attributes should be saved when calling `save`, by passing an array of column names.
-
-This is useful when you set attributes based on a previously defined object, for example, when you get the values of an object via a form of a web app. Furthermore, this is used internally in the `update` implementation. This is how it looks like:
-
-```js
-const jane = await User.create({ name: "Jane" });
-console.log(jane.name); // "Jane"
-console.log(jane.favoriteColor); // "green"
-jane.name = "Jane II";
-jane.favoriteColor = "blue";
-await jane.save({ fields: ['name'] });
-console.log(jane.name); // "Jane II"
-console.log(jane.favoriteColor); // "blue"
-// The above printed blue because the local object has it set to blue, but
-// in the database it is still "green":
-await jane.reload();
-console.log(jane.name); // "Jane II"
-console.log(jane.favoriteColor); // "green"
-```
-
-## Change-awareness of save
-
-The `save` method is optimized internally to only update fields that really changed. This means that if you don't change anything and call `save`, Sequelize will know that the save is superfluous and do nothing, i.e., no query will be generated (it will still return a Promise, but it will resolve immediately).
-
-Also, if only a few attributes have changed when you call `save`, only those fields will be sent in the `UPDATE` query, to improve performance.
-
-## Incrementing and decrementing integer values
-
-In order to increment/decrement values of an instance without running into concurrency issues, Sequelize provides the [`increment`](../class/lib/model.js~Model.html#instance-method-increment) and [`decrement`](../class/lib/model.js~Model.html#instance-method-decrement) instance methods.
-
-```js
-const jane = await User.create({ name: "Jane", age: 100 });
-const incrementResult = await jane.increment('age', { by: 2 });
-// Note: to increment by 1 you can omit the `by` option and just do `user.increment('age')`
-
-// In PostgreSQL, `incrementResult` will be the updated user, unless the option
-// `{ returning: false }` was set (and then it will be undefined).
-
-// In other dialects, `incrementResult` will be undefined. If you need the updated instance, you will have to call `user.reload()`.
-```
-
-You can also increment multiple fields at once:
-
-```js
-const jane = await User.create({ name: "Jane", age: 100, cash: 5000 });
-await jane.increment({
- 'age': 2,
- 'cash': 100
-});
-
-// If the values are incremented by the same amount, you can use this other syntax as well:
-await jane.increment(['age', 'cash'], { by: 2 });
-```
-
-Decrementing works in the exact same way.
diff --git a/docs/manual/core-concepts/model-querying-basics.md b/docs/manual/core-concepts/model-querying-basics.md
deleted file mode 100644
index cb38b32cd9ae..000000000000
--- a/docs/manual/core-concepts/model-querying-basics.md
+++ /dev/null
@@ -1,701 +0,0 @@
-# Model Querying - Basics
-
-Sequelize provides various methods to assist querying your database for data.
-
-*Important notice: to perform production-ready queries with Sequelize, make sure you have read the [Transactions guide](transactions.html) as well. Transactions are important to ensure data integrity and to provide other benefits.*
-
-This guide will show how to make the standard [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) queries.
-
-## Simple INSERT queries
-
-First, a simple example:
-
-```js
-// Create a new user
-const jane = await User.create({ firstName: "Jane", lastName: "Doe" });
-console.log("Jane's auto-generated ID:", jane.id);
-```
-
-The [`Model.create()`](../class/lib/model.js~Model.html#static-method-create) method is a shorthand for building an unsaved instance with [`Model.build()`](../class/lib/model.js~Model.html#static-method-build) and saving the instance with [`instance.save()`](../class/lib/model.js~Model.html#instance-method-save).
-
-It is also possible to define which attributes can be set in the `create` method. This can be especially useful if you create database entries based on a form which can be filled by a user. Using that would, for example, allow you to restrict the `User` model to set only an username but not an admin flag (i.e., `isAdmin`):
-
-```js
-const user = await User.create({
- username: 'alice123',
- isAdmin: true
-}, { fields: ['username'] });
-// let's assume the default of isAdmin is false
-console.log(user.username); // 'alice123'
-console.log(user.isAdmin); // false
-```
-
-## Simple SELECT queries
-
-You can read the whole table from the database with the [`findAll`](../class/lib/model.js~Model.html#static-method-findAll) method:
-
-```js
-// Find all users
-const users = await User.findAll();
-console.log(users.every(user => user instanceof User)); // true
-console.log("All users:", JSON.stringify(users, null, 2));
-```
-
-```sql
-SELECT * FROM ...
-```
-
-## Specifying attributes for SELECT queries
-
-To select only some attributes, you can use the `attributes` option:
-
-```js
-Model.findAll({
- attributes: ['foo', 'bar']
-});
-```
-
-```sql
-SELECT foo, bar FROM ...
-```
-
-Attributes can be renamed using a nested array:
-
-```js
-Model.findAll({
- attributes: ['foo', ['bar', 'baz'], 'qux']
-});
-```
-
-```sql
-SELECT foo, bar AS baz, qux FROM ...
-```
-
-You can use [`sequelize.fn`](../class/lib/sequelize.js~Sequelize.html#static-method-fn) to do aggregations:
-
-```js
-Model.findAll({
- attributes: [
- 'foo',
- [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats'],
- 'bar'
- ]
-});
-```
-
-```sql
-SELECT foo, COUNT(hats) AS n_hats, bar FROM ...
-```
-
-When using aggregation function, you must give it an alias to be able to access it from the model. In the example above you can get the number of hats with `instance.n_hats`.
-
-Sometimes it may be tiresome to list all the attributes of the model if you only want to add an aggregation:
-
-```js
-// This is a tiresome way of getting the number of hats (along with every column)
-Model.findAll({
- attributes: [
- 'id', 'foo', 'bar', 'baz', 'qux', 'hats', // We had to list all attributes...
- [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats'] // To add the aggregation...
- ]
-});
-
-// This is shorter, and less error prone because it still works if you add / remove attributes from your model later
-Model.findAll({
- attributes: {
- include: [
- [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats']
- ]
- }
-});
-```
-
-```sql
-SELECT id, foo, bar, baz, qux, hats, COUNT(hats) AS n_hats FROM ...
-```
-
-Similarly, it's also possible to remove a selected few attributes:
-
-```js
-Model.findAll({
- attributes: { exclude: ['baz'] }
-});
-```
-
-```sql
--- Assuming all columns are 'id', 'foo', 'bar', 'baz' and 'qux'
-SELECT id, foo, bar, qux FROM ...
-```
-
-## Applying WHERE clauses
-
-The `where` option is used to filter the query. There are lots of operators to use for the `where` clause, available as Symbols from [`Op`](../variable/index.html#static-variable-Op).
-
-### The basics
-
-```js
-Post.findAll({
- where: {
- authorId: 2
- }
-});
-// SELECT * FROM post WHERE authorId = 2
-```
-
-Observe that no operator (from `Op`) was explicitly passed, so Sequelize assumed an equality comparison by default. The above code is equivalent to:
-
-```js
-const { Op } = require("sequelize");
-Post.findAll({
- where: {
- authorId: {
- [Op.eq]: 2
- }
- }
-});
-// SELECT * FROM post WHERE authorId = 2
-```
-
-Multiple checks can be passed:
-
-```js
-Post.findAll({
- where: {
- authorId: 12
- status: 'active'
- }
-});
-// SELECT * FROM post WHERE authorId = 12 AND status = 'active';
-```
-
-Just like Sequelize inferred the `Op.eq` operator in the first example, here Sequelize inferred that the caller wanted an `AND` for the two checks. The code above is equivalent to:
-
-```js
-const { Op } = require("sequelize");
-Post.findAll({
- where: {
- [Op.and]: [
- { authorId: 12 },
- { status: 'active' }
- ]
- }
-});
-// SELECT * FROM post WHERE authorId = 12 AND status = 'active';
-```
-
-An `OR` can be easily performed in a similar way:
-
-```js
-const { Op } = require("sequelize");
-Post.findAll({
- where: {
- [Op.or]: [
- { authorId: 12 },
- { authorId: 13 }
- ]
- }
-});
-// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
-```
-
-Since the above was an `OR` involving the same field, Sequelize allows you to use a slightly different structure which is more readable and generates the same behavior:
-
-```js
-const { Op } = require("sequelize");
-Post.destroy({
- where: {
- authorId: {
- [Op.or]: [12, 13]
- }
- }
-});
-// DELETE FROM post WHERE authorId = 12 OR authorId = 13;
-```
-
-### Operators
-
-Sequelize provides several operators.
-
-```js
-const { Op } = require("sequelize");
-Post.findAll({
- where: {
- [Op.and]: [{ a: 5 }, { b: 6 }], // (a = 5) AND (b = 6)
- [Op.or]: [{ a: 5 }, { b: 6 }], // (a = 5) OR (b = 6)
- someAttribute: {
- // Basics
- [Op.eq]: 3, // = 3
- [Op.ne]: 20, // != 20
- [Op.is]: null, // IS NULL
- [Op.not]: true, // IS NOT TRUE
- [Op.or]: [5, 6], // (someAttribute = 5) OR (someAttribute = 6)
-
- // Using dialect specific column identifiers (PG in the following example):
- [Op.col]: 'user.organization_id', // = "user"."organization_id"
-
- // Number comparisons
- [Op.gt]: 6, // > 6
- [Op.gte]: 6, // >= 6
- [Op.lt]: 10, // < 10
- [Op.lte]: 10, // <= 10
- [Op.between]: [6, 10], // BETWEEN 6 AND 10
- [Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
-
- // Other operators
-
- [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1)
-
- [Op.in]: [1, 2], // IN [1, 2]
- [Op.notIn]: [1, 2], // NOT IN [1, 2]
-
- [Op.like]: '%hat', // LIKE '%hat'
- [Op.notLike]: '%hat', // NOT LIKE '%hat'
- [Op.startsWith]: 'hat', // LIKE 'hat%'
- [Op.endsWith]: 'hat', // LIKE '%hat'
- [Op.substring]: 'hat', // LIKE '%hat%'
- [Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only)
- [Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only)
- [Op.regexp]: '^[h|a|t]', // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
- [Op.notRegexp]: '^[h|a|t]', // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
- [Op.iRegexp]: '^[h|a|t]', // ~* '^[h|a|t]' (PG only)
- [Op.notIRegexp]: '^[h|a|t]', // !~* '^[h|a|t]' (PG only)
-
- [Op.any]: [2, 3], // ANY ARRAY[2, 3]::INTEGER (PG only)
- [Op.match]: Sequelize.fn('to_tsquery', 'fat & rat') // match text search for strings 'fat' and 'rat' (PG only)
-
- // In Postgres, Op.like/Op.iLike/Op.notLike can be combined to Op.any:
- [Op.like]: { [Op.any]: ['cat', 'hat'] } // LIKE ANY ARRAY['cat', 'hat']
-
- // There are more postgres-only range operators, see below
- }
- }
-});
-```
-
-#### Shorthand syntax for `Op.in`
-
-Passing an array directly to the `where` option will implicitly use the `IN` operator:
-
-```js
-Post.findAll({
- where: {
- id: [1,2,3] // Same as using `id: { [Op.in]: [1,2,3] }`
- }
-});
-// SELECT ... FROM "posts" AS "post" WHERE "post"."id" IN (1, 2, 3);
-```
-
-### Logical combinations with operators
-
-The operators `Op.and`, `Op.or` and `Op.not` can be used to create arbitrarily complex nested logical comparisons.
-
-#### Examples with `Op.and` and `Op.or`
-
-```js
-const { Op } = require("sequelize");
-
-Foo.findAll({
- where: {
- rank: {
- [Op.or]: {
- [Op.lt]: 1000,
- [Op.eq]: null
- }
- },
- // rank < 1000 OR rank IS NULL
-
- {
- createdAt: {
- [Op.lt]: new Date(),
- [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
- }
- },
- // createdAt < [timestamp] AND createdAt > [timestamp]
-
- {
- [Op.or]: [
- {
- title: {
- [Op.like]: 'Boat%'
- }
- },
- {
- description: {
- [Op.like]: '%boat%'
- }
- }
- ]
- }
- // title LIKE 'Boat%' OR description LIKE '%boat%'
- }
-});
-```
-
-#### Examples with `Op.not`
-
-```js
-Project.findAll({
- where: {
- name: 'Some Project',
- [Op.not]: [
- { id: [1,2,3] },
- {
- description: {
- [Op.like]: 'Hello%'
- }
- }
- ]
- }
-});
-```
-
-The above will generate:
-
-```sql
-SELECT *
-FROM `Projects`
-WHERE (
- `Projects`.`name` = 'Some Project'
- AND NOT (
- `Projects`.`id` IN (1,2,3)
- AND
- `Projects`.`description` LIKE 'Hello%'
- )
-)
-```
-
-### Advanced queries with functions (not just columns)
-
-What if you wanted to obtain something like `WHERE char_length("content") = 7`?
-
-```js
-Post.findAll({
- where: sequelize.where(sequelize.fn('char_length', sequelize.col('content')), 7)
-});
-// SELECT ... FROM "posts" AS "post" WHERE char_length("content") = 7
-```
-
-Note the usage of the [`sequelize.fn`](../class/lib/sequelize.js~Sequelize.html#static-method-fn) and [`sequelize.col`](../class/lib/sequelize.js~Sequelize.html#static-method-col) methods, which should be used to specify an SQL function call and a table column, respectively. These methods should be used instead of passing a plain string (such as `char_length(content)`) because Sequelize needs to treat this situation differently (for example, using other symbol escaping approaches).
-
-What if you need something even more complex?
-
-```js
-Post.findAll({
- where: {
- [Op.or]: [
- sequelize.where(sequelize.fn('char_length', sequelize.col('content')), 7),
- {
- content: {
- [Op.like]: 'Hello%'
- }
- },
- {
- [Op.and]: [
- { status: 'draft' },
- sequelize.where(sequelize.fn('char_length', sequelize.col('content')), {
- [Op.gt]: 10
- })
- ]
- }
- ]
- }
-});
-```
-
-The above generates the following SQL:
-
-```sql
-SELECT
- ...
-FROM "posts" AS "post"
-WHERE (
- char_length("content") = 7
- OR
- "post"."content" LIKE 'Hello%'
- OR (
- "post"."status" = 'draft'
- AND
- char_length("content") > 10
- )
-)
-```
-
-### Postgres-only Range Operators
-
-Range types can be queried with all supported operators.
-
-Keep in mind, the provided range value can [define the bound inclusion/exclusion](data-types.html#range-types) as well.
-
-```js
-[Op.contains]: 2, // @> '2'::integer (PG range contains element operator)
-[Op.contains]: [1, 2], // @> [1, 2) (PG range contains range operator)
-[Op.contained]: [1, 2], // <@ [1, 2) (PG range is contained by operator)
-[Op.overlap]: [1, 2], // && [1, 2) (PG range overlap (have points in common) operator)
-[Op.adjacent]: [1, 2], // -|- [1, 2) (PG range is adjacent to operator)
-[Op.strictLeft]: [1, 2], // << [1, 2) (PG range strictly left of operator)
-[Op.strictRight]: [1, 2], // >> [1, 2) (PG range strictly right of operator)
-[Op.noExtendRight]: [1, 2], // &< [1, 2) (PG range does not extend to the right of operator)
-[Op.noExtendLeft]: [1, 2], // &> [1, 2) (PG range does not extend to the left of operator)
-```
-
-### Deprecated: Operator Aliases
-
-In Sequelize v4, it was possible to specify strings to refer to operators, instead of using Symbols. This is now deprecated and heavily discouraged, and will probably be removed in the next major version. If you really need it, you can pass the `operatorAliases` option in the Sequelize constructor.
-
-For example:
-
-```js
-const { Sequelize, Op } = require("sequelize");
-const sequelize = new Sequelize('sqlite::memory:', {
- operatorsAliases: {
- $gt: Op.gt
- }
-});
-
-// Now we can use `$gt` instead of `[Op.gt]` in where clauses:
-Foo.findAll({
- where: {
- $gt: 6 // Works like using [Op.gt]
- }
-});
-```
-
-## Simple UPDATE queries
-
-Update queries also accept the `where` option, just like the read queries shown above.
-
-```js
-// Change everyone without a last name to "Doe"
-await User.update({ lastName: "Doe" }, {
- where: {
- lastName: null
- }
-});
-```
-
-## Simple DELETE queries
-
-Delete queries also accept the `where` option, just like the read queries shown above.
-
-```js
-// Delete everyone named "Jane"
-await User.destroy({
- where: {
- firstName: "Jane"
- }
-});
-```
-
-To destroy everything the `TRUNCATE` SQL can be used:
-
-```js
-// Truncate the table
-await User.destroy({
- truncate: true
-});
-```
-
-## Creating in bulk
-
-Sequelize provides the `Model.bulkCreate` method to allow creating multiple records at once, with only one query.
-
-The usage of `Model.bulkCreate` is very similar to `Model.create`, by receiving an array of objects instead of a single object.
-
-```js
-const captains = await Captain.bulkCreate([
- { name: 'Jack Sparrow' },
- { name: 'Davy Jones' }
-]);
-console.log(captains.length); // 2
-console.log(captains[0] instanceof Captain); // true
-console.log(captains[0].name); // 'Jack Sparrow'
-console.log(captains[0].id); // 1 // (or another auto-generated value)
-```
-
-However, by default, `bulkCreate` does not run validations on each object that is going to be created (which `create` does). To make `bulkCreate` run these validations as well, you must pass the `validate: true` option. This will decrease performance. Usage example:
-
-```js
-const Foo = sequelize.define('foo', {
- bar: {
- type: DataTypes.TEXT,
- validate: {
- len: [4, 6]
- }
- }
-});
-
-// This will not throw an error, both instances will be created
-await Foo.bulkCreate([
- { name: 'abc123' },
- { name: 'name too long' }
-]);
-
-// This will throw an error, nothing will be created
-await Foo.bulkCreate([
- { name: 'abc123' },
- { name: 'name too long' }
-], { validate: true });
-```
-
-If you are accepting values directly from the user, it might be beneficial to limit the columns that you want to actually insert. To support this, `bulkCreate()` accepts a `fields` option, an array defining which fields must be considered (the rest will be ignored).
-
-```js
-await User.bulkCreate([
- { username: 'foo' },
- { username: 'bar', admin: true }
-], { fields: ['username'] });
-// Neither foo nor bar are admins.
-```
-
-## Ordering and Grouping
-
-Sequelize provides the `order` and `group` options to work with `ORDER BY` and `GROUP BY`.
-
-### Ordering
-
-The `order` option takes an array of items to order the query by or a sequelize method. These *items* are themselves arrays in the form `[column, direction]`. The column will be escaped correctly and the direction will be checked in a whitelist of valid directions (such as `ASC`, `DESC`, `NULLS FIRST`, etc).
-
-```js
-Subtask.findAll({
- order: [
- // Will escape title and validate DESC against a list of valid direction parameters
- ['title', 'DESC'],
-
- // Will order by max(age)
- sequelize.fn('max', sequelize.col('age')),
-
- // Will order by max(age) DESC
- [sequelize.fn('max', sequelize.col('age')), 'DESC'],
-
- // Will order by otherfunction(`col1`, 12, 'lalala') DESC
- [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
-
- // Will order an associated model's createdAt using the model name as the association's name.
- [Task, 'createdAt', 'DESC'],
-
- // Will order through an associated model's createdAt using the model names as the associations' names.
- [Task, Project, 'createdAt', 'DESC'],
-
- // Will order by an associated model's createdAt using the name of the association.
- ['Task', 'createdAt', 'DESC'],
-
- // Will order by a nested associated model's createdAt using the names of the associations.
- ['Task', 'Project', 'createdAt', 'DESC'],
-
- // Will order by an associated model's createdAt using an association object. (preferred method)
- [Subtask.associations.Task, 'createdAt', 'DESC'],
-
- // Will order by a nested associated model's createdAt using association objects. (preferred method)
- [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],
-
- // Will order by an associated model's createdAt using a simple association object.
- [{model: Task, as: 'Task'}, 'createdAt', 'DESC'],
-
- // Will order by a nested associated model's createdAt simple association objects.
- [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
- ],
-
- // Will order by max age descending
- order: sequelize.literal('max(age) DESC'),
-
- // Will order by max age ascending assuming ascending is the default order when direction is omitted
- order: sequelize.fn('max', sequelize.col('age')),
-
- // Will order by age ascending assuming ascending is the default order when direction is omitted
- order: sequelize.col('age'),
-
- // Will order randomly based on the dialect (instead of fn('RAND') or fn('RANDOM'))
- order: sequelize.random()
-});
-
-Foo.findOne({
- order: [
- // will return `name`
- ['name'],
- // will return `username` DESC
- ['username', 'DESC'],
- // will return max(`age`)
- sequelize.fn('max', sequelize.col('age')),
- // will return max(`age`) DESC
- [sequelize.fn('max', sequelize.col('age')), 'DESC'],
- // will return otherfunction(`col1`, 12, 'lalala') DESC
- [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
- // will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite!
- [sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC']
- ]
-});
-```
-
-To recap, the elements of the order array can be the following:
-
-* A string (which will be automatically quoted)
-* An array, whose first element will be quoted, second will be appended verbatim
-* An object with a `raw` field:
- * The content of `raw` will be added verbatim without quoting
- * Everything else is ignored, and if raw is not set, the query will fail
-* A call to `Sequelize.fn` (which will generate a function call in SQL)
-* A call to `Sequelize.col` (which will quoute the column name)
-
-### Grouping
-
-The syntax for grouping and ordering are equal, except that grouping does not accept a direction as last argument of the array (there is no `ASC`, `DESC`, `NULLS FIRST`, etc).
-
-You can also pass a string directly to `group`, which will be included directly (verbatim) into the generated SQL. Use with caution and don't use with user generated content.
-
-```js
-Project.findAll({ group: 'name' });
-// yields 'GROUP BY name'
-```
-
-## Limits and Pagination
-
-The `limit` and `offset` options allow you to work with limiting / pagination:
-
-```js
-// Fetch 10 instances/rows
-Project.findAll({ limit: 10 });
-
-// Skip 8 instances/rows
-Project.findAll({ offset: 8 });
-
-// Skip 5 instances and fetch the 5 after that
-Project.findAll({ offset: 5, limit: 5 });
-```
-
-Usually these are used alongside the `order` option.
-
-## Utility methods
-
-Sequelize also provides a few utility methods.
-
-### `count`
-
-The `count` method simply counts the occurrences of elements in the database.
-
-```js
-console.log(`There are ${await Project.count()} projects`);
-
-const amount = await Project.count({
- where: {
- id: {
- [Op.gt]: 25
- }
- }
-});
-console.log(`There are ${amount} projects with an id greater than 25`);
-```
-
-### `max`, `min` and `sum`
-
-Sequelize also provides the `max`, `min` and `sum` convenience methods.
-
-Let's assume we have three users, whose ages are 10, 5, and 40.
-
-```js
-await User.max('age'); // 40
-await User.max('age', { where: { age: { [Op.lt]: 20 } } }); // 10
-await User.min('age'); // 5
-await User.min('age', { where: { age: { [Op.gt]: 5 } } }); // 10
-await User.sum('age'); // 55
-await User.sum('age', { where: { age: { [Op.gt]: 5 } } }); // 50
-```
diff --git a/docs/manual/core-concepts/model-querying-finders.md b/docs/manual/core-concepts/model-querying-finders.md
deleted file mode 100644
index c5644a9dca57..000000000000
--- a/docs/manual/core-concepts/model-querying-finders.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# Model Querying - Finders
-
-Finder methods are the ones that generate `SELECT` queries.
-
-By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects. In a few cases, when there are too many results, this wrapping can be inefficient. To disable this wrapping and receive a plain response instead, pass `{ raw: true }` as an option to the finder method.
-
-## `findAll`
-
-The `findAll` method is already known from the previous tutorial. It generates a standard `SELECT` query which will retrieve all entries from the table (unless restricted by something like a `where` clause, for example).
-
-## `findByPk`
-
-The `findByPk` method obtains only a single entry from the table, using the provided primary key.
-
-```js
-const project = await Project.findByPk(123);
-if (project === null) {
- console.log('Not found!');
-} else {
- console.log(project instanceof Project); // true
- // Its primary key is 123
-}
-```
-
-## `findOne`
-
-The `findOne` method obtains the first entry it finds (that fulfills the optional query options, if provided).
-
-```js
-const project = await Project.findOne({ where: { title: 'My Title' } });
-if (project === null) {
- console.log('Not found!');
-} else {
- console.log(project instanceof Project); // true
- console.log(project.title); // 'My Title'
-}
-```
-
-## `findOrCreate`
-
-The method `findOrCreate` will create an entry in the table unless it can find one fulfilling the query options. In both cases, it will return an instance (either the found instance or the created instance) and a boolean indicating whether that instance was created or already existed.
-
-The `where` option is considered for finding the entry, and the `defaults` option is used to define what must be created in case nothing was found. If the `defaults` do not contain values for every column, Sequelize will take the values given to `where` (if present).
-
-Let's assume we have an empty database with a `User` model which has a `username` and a `job`.
-
-```js
-const [user, created] = await User.findOrCreate({
- where: { username: 'sdepold' },
- defaults: {
- job: 'Technical Lead JavaScript'
- }
-});
-console.log(user.username); // 'sdepold'
-console.log(user.job); // This may or may not be 'Technical Lead JavaScript'
-console.log(created); // The boolean indicating whether this instance was just created
-if (created) {
- console.log(user.job); // This will certainly be 'Technical Lead JavaScript'
-}
-```
-
-## `findAndCountAll`
-
-The `findAndCountAll` method is a convenience method that combines `findAll` and `count`. This is useful when dealing with queries related to pagination where you want to retrieve data with a `limit` and `offset` but also need to know the total number of records that match the query.
-
-The `findAndCountAll` method returns an object with two properties:
-
-* `count` - an integer - the total number records matching the query
-* `rows` - an array of objects - the obtained records
-
-```js
-const { count, rows } = await Project.findAndCountAll({
- where: {
- title: {
- [Op.like]: 'foo%'
- }
- },
- offset: 10,
- limit: 2
-});
-console.log(count);
-console.log(rows);
-```
\ No newline at end of file
diff --git a/docs/manual/core-concepts/paranoid.md b/docs/manual/core-concepts/paranoid.md
deleted file mode 100644
index dd580d0578a9..000000000000
--- a/docs/manual/core-concepts/paranoid.md
+++ /dev/null
@@ -1,105 +0,0 @@
-# Paranoid
-
-Sequelize supports the concept of *paranoid* tables. A *paranoid* table is one that, when told to delete a record, it will not truly delete it. Instead, a special column called `deletedAt` will have its value set to the timestamp of that deletion request.
-
-This means that paranoid tables perform a *soft-deletion* of records, instead of a *hard-deletion*.
-
-## Defining a model as paranoid
-
-To make a model paranoid, you must pass the `paranoid: true` option to the model definition. Paranoid requires timestamps to work (i.e. it won't work if you also pass `timestamps: false`).
-
-You can also change the default column name (which is `deletedAt`) to something else.
-
-```js
-class Post extends Model {}
-Post.init({ /* attributes here */ }, {
- sequelize,
- paranoid: true,
-
- // If you want to give a custom name to the deletedAt column
- deletedAt: 'destroyTime'
-});
-```
-
-## Deleting
-
-When you call the `destroy` method, a soft-deletion will happen:
-
-```js
-await Post.destroy({
- where: {
- id: 1
- }
-});
-// UPDATE "posts" SET "deletedAt"=[timestamp] WHERE "deletedAt" IS NULL AND "id" = 1
-```
-
-If you really want a hard-deletion and your model is paranoid, you can force it using the `force: true` option:
-
-```js
-await Post.destroy({
- where: {
- id: 1
- },
- force: true
-});
-// DELETE FROM "posts" WHERE "id" = 1
-```
-
-The above examples used the static `destroy` method as an example (`Post.destroy`), but everything works in the same way with the instance method:
-
-```js
-const post = await Post.create({ title: 'test' });
-console.log(post instanceof Post); // true
-await post.destroy(); // Would just set the `deletedAt` flag
-await post.destroy({ force: true }); // Would really delete the record
-```
-
-## Restoring
-
-To restore soft-deleted records, you can use the `restore` method, which comes both in the static version as well as in the instance version:
-
-```js
-// Example showing the instance `restore` method
-// We create a post, soft-delete it and then restore it back
-const post = await Post.create({ title: 'test' });
-console.log(post instanceof Post); // true
-await post.destroy();
-console.log('soft-deleted!');
-await post.restore();
-console.log('restored!');
-
-// Example showing the static `restore` method.
-// Restoring every soft-deleted post with more than 100 likes
-await Post.restore({
- where: {
- likes: {
- [Op.gt]: 100
- }
- }
-});
-```
-
-## Behavior with other queries
-
-Every query performed by Sequelize will automatically ignore soft-deleted records (except raw queries, of course).
-
-This means that, for example, the `findAll` method will not see the soft-deleted records, fetching only the ones that were not deleted.
-
-Even if you simply call `findByPk` providing the primary key of a soft-deleted record, the result will be `null` as if that record didn't exist.
-
-If you really want to let the query see the soft-deleted records, you can pass the `paranoid: false` option to the query method. For example:
-
-```js
-await Post.findByPk(123); // This will return `null` if the record of id 123 is soft-deleted
-await Post.findByPk(123, { paranoid: false }); // This will retrieve the record
-
-await Post.findAll({
- where: { foo: 'bar' }
-}); // This will not retrieve soft-deleted records
-
-await Post.findAll({
- where: { foo: 'bar' },
- paranoid: false
-}); // This will also retrieve soft-deleted records
-```
\ No newline at end of file
diff --git a/docs/manual/core-concepts/raw-queries.md b/docs/manual/core-concepts/raw-queries.md
deleted file mode 100644
index ff18dffcf8d6..000000000000
--- a/docs/manual/core-concepts/raw-queries.md
+++ /dev/null
@@ -1,186 +0,0 @@
-# Raw Queries
-
-As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the [`sequelize.query`](../class/lib/sequelize.js~Sequelize.html#instance-method-query) method.
-
-By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc). Note that since this is a raw query, the metadata are 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.
-
-```js
-const [results, metadata] = await sequelize.query("UPDATE users SET y = 42 WHERE x = 12");
-// Results will be an empty array and metadata will contain the number of affected rows.
-```
-
-In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:
-
-```js
-const { QueryTypes } = require('sequelize');
-const users = await sequelize.query("SELECT * FROM `users`", { type: QueryTypes.SELECT });
-// We didn't need to destructure the result here - the results were returned directly
-```
-
-Several other query types are available. [Peek into the source for details](https://github.com/sequelize/sequelize/blob/main/src/query-types.ts).
-
-A second option is the model. If you pass a model the returned data will be instances of that model.
-
-```js
-// Callee is the model definition. This allows you to easily map a query to a predefined model
-const projects = await sequelize.query('SELECT * FROM projects', {
- model: Projects,
- mapToModel: true // pass true here if you have any mapped fields
-});
-// Each element of `projects` is now an instance of Project
-```
-
-See more options in the [query API reference](../class/lib/sequelize.js~Sequelize.html#instance-method-query). Some examples:
-
-```js
-const { QueryTypes } = require('sequelize');
-await sequelize.query('SELECT 1', {
- // A function (or false) for logging your queries
- // Will get called for every SQL query that gets sent
- // to the server.
- logging: console.log,
-
- // If plain is true, then sequelize will only return the first
- // record of the result set. In case of false it will return all records.
- plain: false,
-
- // Set this to true if you don't have a model definition for your query.
- raw: false,
-
- // The type of query you are executing. The query type affects how results are formatted before they are passed back.
- type: QueryTypes.SELECT
-});
-
-// Note the second argument being null!
-// Even if we declared a callee here, the raw: true would
-// supersede and return a raw object.
-console.log(await sequelize.query('SELECT * FROM projects', { raw: true }));
-```
-
-## "Dotted" attributes and the `nest` option
-
-If an attribute name of the table contains dots, the resulting objects can become nested objects by setting the `nest: true` option. This is achieved with [dottie.js](https://github.com/mickhansen/dottie.js/) under the hood. See below:
-
-* Without `nest: true`:
-
- ```js
- const { QueryTypes } = require('sequelize');
- const records = await sequelize.query('select 1 as `foo.bar.baz`', {
- type: QueryTypes.SELECT
- });
- console.log(JSON.stringify(records[0], null, 2));
- ```
-
- ```json
- {
- "foo.bar.baz": 1
- }
- ```
-
-* With `nest: true`:
-
- ```js
- const { QueryTypes } = require('sequelize');
- const records = await sequelize.query('select 1 as `foo.bar.baz`', {
- nest: true,
- type: QueryTypes.SELECT
- });
- console.log(JSON.stringify(records[0], null, 2));
- ```
-
- ```json
- {
- "foo": {
- "bar": {
- "baz": 1
- }
- }
- }
- ```
-
-## 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
-* If an object is passed, `:key` will be replaced with the keys from that object. If the object contains keys not found in the query or vice versa, an exception will be thrown.
-
-```js
-const { QueryTypes } = require('sequelize');
-
-await sequelize.query(
- 'SELECT * FROM projects WHERE status = ?',
- {
- replacements: ['active'],
- type: QueryTypes.SELECT
- }
-);
-
-await sequelize.query(
- 'SELECT * FROM projects WHERE status = :status',
- {
- replacements: { status: 'active' },
- type: QueryTypes.SELECT
- }
-);
-```
-
-Array replacements will automatically be handled, the following query searches for projects where the status matches an array of values.
-
-```js
-const { QueryTypes } = require('sequelize');
-
-await sequelize.query(
- 'SELECT * FROM projects WHERE status IN(:status)',
- {
- replacements: { status: ['active', 'inactive'] },
- type: QueryTypes.SELECT
- }
-);
-```
-
-To use the wildcard operator `%`, append it to your replacement. The following query matches users with names that start with 'ben'.
-
-```js
-const { QueryTypes } = require('sequelize');
-
-await sequelize.query(
- 'SELECT * FROM users WHERE name LIKE :search_name',
- {
- replacements: { search_name: 'ben%' },
- type: QueryTypes.SELECT
- }
-);
-```
-
-## 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. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.
-
-* If an array is passed, `$1` is bound to the 1st element in the array (`bind[0]`)
-* If an object is passed, `$key` is bound to `object['key']`. Each key must begin with a non-numeric char. `$1` is not a valid key, even if `object['1']` exists.
-* In either case `$$` can be used to escape a literal `$` sign.
-
-The array or object must contain all bound values or Sequelize will throw an exception. This applies even to cases in which the database may ignore the bound parameter.
-
-The database may add further restrictions to this. Bind parameters cannot be SQL keywords, nor table or column names. They are also ignored in quoted text or data. In PostgreSQL it may also be needed to typecast them, if the type cannot be inferred from the context `$1::varchar`.
-
-```js
-const { QueryTypes } = require('sequelize');
-
-await sequelize.query(
- 'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1',
- {
- bind: ['active'],
- type: QueryTypes.SELECT
- }
-);
-
-await sequelize.query(
- 'SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status',
- {
- bind: { status: 'active' },
- type: QueryTypes.SELECT
- }
-);
-```
diff --git a/docs/manual/core-concepts/validations-and-constraints.md b/docs/manual/core-concepts/validations-and-constraints.md
deleted file mode 100644
index cdc4139c9640..000000000000
--- a/docs/manual/core-concepts/validations-and-constraints.md
+++ /dev/null
@@ -1,270 +0,0 @@
-# Validations & Constraints
-
-In this tutorial you will learn how to setup validations and constraints for your models in Sequelize.
-
-For this tutorial, the following setup will be assumed:
-
-```js
-const { Sequelize, Op, Model, DataTypes } = require("sequelize");
-const sequelize = new Sequelize("sqlite::memory:");
-
-const User = sequelize.define("user", {
- username: {
- type: DataTypes.TEXT,
- allowNull: false,
- unique: true
- },
- hashedPassword: {
- type: DataTypes.STRING(64),
- is: /^[0-9a-f]{64}$/i
- }
-});
-
-(async () => {
- await sequelize.sync({ force: true });
- // Code here
-})();
-```
-
-## Difference between Validations and Constraints
-
-Validations are checks performed in the Sequelize level, in pure JavaScript. They can be arbitrarily complex if you provide a custom validator function, or can be one of the built-in validators offered by Sequelize. If a validation fails, no SQL query will be sent to the database at all.
-
-On the other hand, constraints are rules defined at SQL level. The most basic example of constraint is an Unique Constraint. If a constraint check fails, an error will be thrown by the database and Sequelize will forward this error to JavaScript (in this example, throwing a `SequelizeUniqueConstraintError`). Note that in this case, the SQL query was performed, unlike the case for validations.
-
-## Unique Constraint
-
-Our code example above defines a unique constraint on the `username` field:
-
-```js
-/* ... */ {
- username: {
- type: DataTypes.TEXT,
- allowNull: false,
- unique: true
- },
-} /* ... */
-```
-
-When this model is synchronized (by calling `sequelize.sync` for example), the `username` field will be created in the table as `` `name` TEXT UNIQUE``, and an attempt to insert an username that already exists there will throw a `SequelizeUniqueConstraintError`.
-
-## Allowing/disallowing null values
-
-By default, `null` is an allowed value for every column of a model. This can be disabled setting the `allowNull: false` option for a column, as it was done in the `username` field from our code example:
-
-```js
-/* ... */ {
- username: {
- type: DataTypes.TEXT,
- allowNull: false,
- unique: true
- },
-} /* ... */
-```
-
-Without `allowNull: false`, the call `User.create({})` would work.
-
-### Note about `allowNull` implementation
-
-The `allowNull` check is the only check in Sequelize that is a mix of a *validation* and a *constraint* in the senses described at the beginning of this tutorial. This is because:
-
-* If an attempt is made to set `null` to a field that does not allow null, a `ValidationError` will be thrown *without any SQL query being performed*.
-* In addition, after `sequelize.sync`, the column that has `allowNull: false` will be defined with a `NOT NULL` SQL constraint. This way, direct SQL queries that attempt to set the value to `null` will also fail.
-
-## Validators
-
-Model validators allow you to specify format/content/inheritance validations for each attribute of the model. Validations are automatically run on `create`, `update` and `save`. You can also call `validate()` to manually validate an instance.
-
-### Per-attribute validations
-
-You can define your custom validators or use several built-in validators, implemented by [validator.js (10.11.0)](https://github.com/chriso/validator.js), as shown below.
-
-```js
-sequelize.define('foo', {
- bar: {
- type: DataTypes.STRING,
- validate: {
- is: /^[a-z]+$/i, // matches this RegExp
- is: ["^[a-z]+$",'i'], // same as above, but constructing the RegExp from a string
- not: /^[a-z]+$/i, // does not match this RegExp
- not: ["^[a-z]+$",'i'], // same as above, but constructing the RegExp from a string
- isEmail: true, // checks for email format (foo@bar.com)
- isUrl: true, // checks for url format (http://foo.com)
- isIP: true, // checks for IPv4 (129.89.23.1) or IPv6 format
- isIPv4: true, // checks for IPv4 (129.89.23.1)
- isIPv6: true, // checks for IPv6 format
- isAlpha: true, // will only allow letters
- isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail
- isNumeric: true, // will only allow numbers
- isInt: true, // checks for valid integers
- isFloat: true, // checks for valid floating point numbers
- isDecimal: true, // checks for any numbers
- isLowercase: true, // checks for lowercase
- isUppercase: true, // checks for uppercase
- notNull: true, // won't allow null
- isNull: true, // only allows null
- notEmpty: true, // don't allow empty strings
- equals: 'specific value', // only allow a specific value
- contains: 'foo', // force specific substrings
- notIn: [['foo', 'bar']], // check the value is not one of these
- isIn: [['foo', 'bar']], // check the value is one of these
- notContains: 'bar', // don't allow specific substrings
- len: [2,10], // only allow values with length between 2 and 10
- isUUID: 4, // only allow uuids
- isDate: true, // only allow date strings
- isAfter: "2011-11-05", // only allow date strings after a specific date
- isBefore: "2011-11-05", // only allow date strings before a specific date
- max: 23, // only allow values <= 23
- min: 23, // only allow values >= 23
- isCreditCard: true, // check for valid credit card numbers
-
- // Examples of custom validators:
- isEven(value) {
- if (parseInt(value) % 2 !== 0) {
- throw new Error('Only even values are allowed!');
- }
- }
- isGreaterThanOtherField(value) {
- if (parseInt(value) <= parseInt(this.otherField)) {
- throw new Error('Bar must be greater than otherField.');
- }
- }
- }
- }
-});
-```
-
-Note that where multiple arguments need to be passed to the built-in validation functions, the arguments to be passed must be in an array. But if a single array argument is to be passed, for instance an array of acceptable strings for `isIn`, this will be interpreted as multiple string arguments instead of one array argument. To work around this pass a single-length array of arguments, such as `[['foo', 'bar']]` as shown above.
-
-To use a custom error message instead of that provided by [validator.js](https://github.com/chriso/validator.js), use an object instead of the plain value or array of arguments, for example a validator which needs no argument can be given a custom message with
-
-```js
-isInt: {
- msg: "Must be an integer number of pennies"
-}
-```
-
-or if arguments need to also be passed add an `args` property:
-
-```js
-isIn: {
- args: [['en', 'zh']],
- msg: "Must be English or Chinese"
-}
-```
-
-When using custom validator functions the error message will be whatever message the thrown `Error` object holds.
-
-See [the validator.js project](https://github.com/chriso/validator.js) for more details on the built in validation methods.
-
-**Hint:** You can also define a custom function for the logging part. Just pass a function. The first parameter will be the string that is logged.
-
-### `allowNull` interaction with other validators
-
-If a particular field of a model is set to not allow null (with `allowNull: false`) and that value has been set to `null`, all validators will be skipped and a `ValidationError` will be thrown.
-
-On the other hand, if it is set to allow null (with `allowNull: true`) and that value has been set to `null`, only the built-in validators will be skipped, while the custom validators will still run.
-
-This means you can, for instance, have a string field which validates its length to be between 5 and 10 characters, but which also allows `null` (since the length validator will be skipped automatically when the value is `null`):
-
-```js
-class User extends Model {}
-User.init({
- username: {
- type: DataTypes.STRING,
- allowNull: true,
- validate: {
- len: [5, 10]
- }
- }
-}, { sequelize });
-```
-
-You also can conditionally allow `null` values, with a custom validator, since it won't be skipped:
-
-```js
-class User extends Model {}
-User.init({
- age: Sequelize.INTEGER,
- name: {
- type: DataTypes.STRING,
- allowNull: true,
- validate: {
- customValidator(value) {
- if (value === null && this.age !== 10) {
- throw new Error("name can't be null unless age is 10");
- }
- })
- }
- }
-}, { sequelize });
-```
-
-You can customize `allowNull` error message by setting the `notNull` validator:
-
-```js
-class User extends Model {}
-User.init({
- name: {
- type: DataTypes.STRING,
- allowNull: false,
- validate: {
- notNull: {
- msg: 'Please enter your name'
- }
- }
- }
-}, { sequelize });
-```
-
-### Model-wide validations
-
-Validations can also be defined to check the model after the field-specific validators. Using this you could, for example, ensure either neither of `latitude` and `longitude` are set or both, and fail if one but not the other is set.
-
-Model validator methods are called with the model object's context and are deemed to fail if they throw an error, otherwise pass. This is just the same as with custom field-specific validators.
-
-Any error messages collected are put in the validation result object alongside the field validation errors, with keys named after the failed validation method's key in the `validate` option object. Even though there can only be one error message for each model validation method at any one time, it is presented as a single string error in an array, to maximize consistency with the field errors.
-
-An example:
-
-```js
-class Place extends Model {}
-Place.init({
- name: Sequelize.STRING,
- address: Sequelize.STRING,
- latitude: {
- type: DataTypes.INTEGER,
- validate: {
- min: -90,
- max: 90
- }
- },
- longitude: {
- type: DataTypes.INTEGER,
- validate: {
- min: -180,
- max: 180
- }
- },
-}, {
- sequelize,
- validate: {
- bothCoordsOrNone() {
- if ((this.latitude === null) !== (this.longitude === null)) {
- throw new Error('Either both latitude and longitude, or neither!');
- }
- }
- }
-})
-```
-
-In this simple case an object fails validation if either latitude or longitude is given, but not both. If we try to build one with an out-of-range latitude and no longitude, `somePlace.validate()` might return:
-
-```js
-{
- 'latitude': ['Invalid number: latitude'],
- 'bothCoordsOrNone': ['Either both latitude and longitude, or neither!']
-}
-```
-
-Such validation could have also been done with a custom validator defined on a single attribute (such as the `latitude` attribute, by checking `(value === null) !== (this.longitude === null)`), but the model-wide validation approach is cleaner.
diff --git a/docs/manual/moved/associations.md b/docs/manual/moved/associations.md
deleted file mode 100644
index cf001aac731f..000000000000
--- a/docs/manual/moved/associations.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# \[MOVED\] Associations
-
-The contents of this page were moved to other specialized guides.
-
-If you're here, you might be looking for these topics:
-
-* **Core Concepts**
- * [Associations](assocs.html)
-* **Advanced Association Concepts**
- * [Eager Loading](eager-loading.html)
- * [Creating with Associations](creating-with-associations.html)
- * [Advanced M:N Associations](advanced-many-to-many.html)
- * [Polymorphism & Scopes](polymorphism-and-scopes.html)
-* **Other Topics**
- * [Naming Strategies](naming-strategies.html)
- * [Constraints & Circularities](constraints-and-circularities.html)
\ No newline at end of file
diff --git a/docs/manual/moved/data-types.md b/docs/manual/moved/data-types.md
deleted file mode 100644
index 4ba48b9798d9..000000000000
--- a/docs/manual/moved/data-types.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# \[MOVED\] Data Types
-
-The contents of this page were moved to other specialized guides.
-
-If you're here, you might be looking for these topics:
-
-* **Core Concepts**
- * [Model Basics: Data Types](model-basics.html#data-types)
-* **Other Topics**
- * [Other Data Types](other-data-types.html)
- * [Extending Data Types](extending-data-types.html)
- * [Dialect-Specific Things](dialect-specific-things.html)
\ No newline at end of file
diff --git a/docs/manual/moved/models-definition.md b/docs/manual/moved/models-definition.md
deleted file mode 100644
index 177e8a28dcc1..000000000000
--- a/docs/manual/moved/models-definition.md
+++ /dev/null
@@ -1,55 +0,0 @@
-# \[MOVED\] Models Definition
-
-The contents of this page were moved to [Model Basics](model-basics.html).
-
-The only exception is the guide on `sequelize.import`, which is deprecated and was removed from the docs. However, if you really need it, it was kept here.
-
-----
-
-## Deprecated: `sequelize.import`
-
-> _**Note:** You should not use `sequelize.import`. Please just use `require` instead._
->
-> _This documentation has been kept just in case you really need to maintain old code that uses it._
-
-You can store your model definitions in a single file using the `sequelize.import` method. The returned object is exactly the same as defined in the imported file's function. The import is cached, just like `require`, so you won't run into trouble if importing a file more than once.
-
-```js
-// in your server file - e.g. app.js
-const Project = sequelize.import(__dirname + "/path/to/models/project");
-
-// The model definition is done in /path/to/models/project.js
-module.exports = (sequelize, DataTypes) => {
- return sequelize.define('project', {
- name: DataTypes.STRING,
- description: DataTypes.TEXT
- });
-};
-```
-
-The `import` method can also accept a callback as an argument.
-
-```js
-sequelize.import('project', (sequelize, DataTypes) => {
- return sequelize.define('project', {
- name: DataTypes.STRING,
- description: DataTypes.TEXT
- });
-});
-```
-
-This extra capability is useful when, for example, `Error: Cannot find module` is thrown even though `/path/to/models/project` seems to be correct. Some frameworks, such as Meteor, overload `require`, and might raise an error such as:
-
-```text
-Error: Cannot find module '/home/you/meteorApp/.meteor/local/build/programs/server/app/path/to/models/project.js'
-```
-
-This can be worked around by passing in Meteor's version of `require`:
-
-```js
-// If this fails...
-const AuthorModel = db.import('./path/to/models/project');
-
-// Try this instead!
-const AuthorModel = db.import('project', require('./path/to/models/project'));
-```
\ No newline at end of file
diff --git a/docs/manual/moved/models-usage.md b/docs/manual/moved/models-usage.md
deleted file mode 100644
index 020eeacab726..000000000000
--- a/docs/manual/moved/models-usage.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# \[MOVED\] Models Usage
-
-The contents of this page were moved to other specialized guides.
-
-If you're here, you might be looking for these topics:
-
-* **Core Concepts**
- * [Model Querying - Basics](model-querying-basics.html)
- * [Model Querying - Finders](model-querying-finders.html)
- * [Raw Queries](raw-queries.html)
-* **Advanced Association Concepts**
- * [Eager Loading](eager-loading.html)
\ No newline at end of file
diff --git a/docs/manual/moved/querying.md b/docs/manual/moved/querying.md
deleted file mode 100644
index 94b8d8ae9c99..000000000000
--- a/docs/manual/moved/querying.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# \[MOVED\] Querying
-
-The contents of this page were moved to other specialized guides.
-
-If you're here, you might be looking for these topics:
-
-* **Core Concepts**
- * [Model Querying - Basics](model-querying-basics.html)
- * [Model Querying - Finders](model-querying-finders.html)
- * [Raw Queries](raw-queries.html)
- * [Associations](assocs.html)
-* **Other Topics**
- * [Dialect-Specific Things](dialect-specific-things.html)
\ No newline at end of file
diff --git a/docs/manual/other-topics/connection-pool.md b/docs/manual/other-topics/connection-pool.md
deleted file mode 100644
index d8501ef5ef3c..000000000000
--- a/docs/manual/other-topics/connection-pool.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# Connection Pool
-
-If you're connecting to the database from a single process, you should create only one Sequelize instance. Sequelize will set up a connection pool on initialization. This connection pool can be configured through the constructor's `options` parameter (using `options.pool`), as is shown in the following example:
-
-```js
-const sequelize = new Sequelize(/* ... */, {
- // ...
- pool: {
- max: 5,
- min: 0,
- acquire: 30000,
- idle: 10000
- }
-});
-```
-
-Learn more in the [API Reference for the Sequelize constructor](../class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor). If you're connecting to the database from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of such that the total maximum size is respected. For example, if you want a max connection pool size of 90 and you have three processes, the Sequelize instance of each process should have a max connection pool size of 30.
diff --git a/docs/manual/other-topics/constraints-and-circularities.md b/docs/manual/other-topics/constraints-and-circularities.md
deleted file mode 100644
index c48708a0168f..000000000000
--- a/docs/manual/other-topics/constraints-and-circularities.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Constraints & Circularities
-
-Adding constraints between tables means that tables must be created in the database in a certain order, when using `sequelize.sync`. If `Task` has a reference to `User`, the `User` table must be created before the `Task` table can be created. This can sometimes lead to circular references, where Sequelize cannot find an order in which to sync. Imagine a scenario of documents and versions. A document can have multiple versions, and for convenience, a document has a reference to its current version.
-
-```js
-const { Sequelize, Model, DataTypes } = require("sequelize");
-
-class Document extends Model {}
-Document.init({
- author: DataTypes.STRING
-}, { sequelize, modelName: 'document' });
-
-class Version extends Model {}
-Version.init({
- timestamp: DataTypes.DATE
-}, { sequelize, modelName: 'version' });
-
-Document.hasMany(Version); // This adds documentId attribute to version
-Document.belongsTo(Version, {
- as: 'Current',
- foreignKey: 'currentVersionId'
-}); // This adds currentVersionId attribute to document
-```
-
-However, unfortunately the code above will result in the following error:
-
-```text
-Cyclic dependency found. documents is dependent of itself. Dependency chain: documents -> versions => documents
-```
-
-In order to alleviate that, we can pass `constraints: false` to one of the associations:
-
-```js
-Document.hasMany(Version);
-Document.belongsTo(Version, {
- as: 'Current',
- foreignKey: 'currentVersionId',
- constraints: false
-});
-```
-
-Which will allow us to sync the tables correctly:
-
-```sql
-CREATE TABLE IF NOT EXISTS "documents" (
- "id" SERIAL,
- "author" VARCHAR(255),
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- "currentVersionId" INTEGER,
- PRIMARY KEY ("id")
-);
-
-CREATE TABLE IF NOT EXISTS "versions" (
- "id" SERIAL,
- "timestamp" TIMESTAMP WITH TIME ZONE,
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
- "documentId" INTEGER REFERENCES "documents" ("id") ON DELETE
- SET
- NULL ON UPDATE CASCADE,
- PRIMARY KEY ("id")
-);
-```
-
-## Enforcing a foreign key reference without constraints
-
-Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.
-
-```js
-class Trainer extends Model {}
-Trainer.init({
- firstName: Sequelize.STRING,
- lastName: Sequelize.STRING
-}, { sequelize, modelName: 'trainer' });
-
-// Series will have a trainerId = Trainer.id foreign reference key
-// after we call Trainer.hasMany(series)
-class Series extends Model {}
-Series.init({
- title: Sequelize.STRING,
- subTitle: Sequelize.STRING,
- description: Sequelize.TEXT,
- // Set FK relationship (hasMany) with `Trainer`
- trainerId: {
- type: DataTypes.INTEGER,
- references: {
- model: Trainer,
- key: 'id'
- }
- }
-}, { sequelize, modelName: 'series' });
-
-// Video will have seriesId = Series.id foreign reference key
-// after we call Series.hasOne(Video)
-class Video extends Model {}
-Video.init({
- title: Sequelize.STRING,
- sequence: Sequelize.INTEGER,
- description: Sequelize.TEXT,
- // set relationship (hasOne) with `Series`
- seriesId: {
- type: DataTypes.INTEGER,
- references: {
- model: Series, // Can be both a string representing the table name or a Sequelize model
- key: 'id'
- }
- }
-}, { sequelize, modelName: 'video' });
-
-Series.hasOne(Video);
-Trainer.hasMany(Series);
-```
\ No newline at end of file
diff --git a/docs/manual/other-topics/dialect-specific-things.md b/docs/manual/other-topics/dialect-specific-things.md
deleted file mode 100644
index d7c5e9427609..000000000000
--- a/docs/manual/other-topics/dialect-specific-things.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# Dialect-Specific Things
-
-## Underlying Connector Libraries
-
-### MySQL
-
-The underlying connector library used by Sequelize for MySQL is the [mysql2](https://www.npmjs.com/package/mysql2) npm package (version 1.5.2 or higher).
-
-You can provide custom options to it using the `dialectOptions` in the Sequelize constructor:
-
-```js
-const sequelize = new Sequelize('database', 'username', 'password', {
- dialect: 'mysql',
- dialectOptions: {
- // Your mysql2 options here
- }
-})
-```
-
-### MariaDB
-
-The underlying connector library used by Sequelize for MariaDB is the [mariadb](https://www.npmjs.com/package/mariadb) npm package.
-
-You can provide custom options to it using the `dialectOptions` in the Sequelize constructor:
-
-```js
-const sequelize = new Sequelize('database', 'username', 'password', {
- dialect: 'mariadb',
- dialectOptions: {
- // Your mariadb options here
- // connectTimeout: 1000
- }
-});
-```
-
-### SQLite
-
-The underlying connector library used by Sequelize for SQLite is the [sqlite3](https://www.npmjs.com/package/sqlite3) npm package (version 4.0.0 or above).
-
-You specify the storage file in the Sequelize constructor with the `storage` option (use `:memory:` for an in-memory SQLite instance).
-
-You can provide custom options to it using the `dialectOptions` in the Sequelize constructor:
-
-```js
-const sequelize = new Sequelize('database', 'username', 'password', {
- dialect: 'sqlite',
- storage: 'path/to/database.sqlite' // or ':memory:'
- dialectOptions: {
- // Your sqlite3 options here
- }
-});
-```
-
-### PostgreSQL
-
-The underlying connector library used by Sequelize for PostgreSQL is the [pg](https://www.npmjs.com/package/pg) npm package (version 7.0.0 or above). The module [pg-hstore](https://www.npmjs.com/package/pg-hstore) is also necessary.
-
-You can provide custom options to it using the `dialectOptions` in the Sequelize constructor:
-
-```js
-const sequelize = new Sequelize('database', 'username', 'password', {
- dialect: 'postgres',
- dialectOptions: {
- // Your pg options here
- }
-});
-```
-
-To connect over a unix domain socket, specify the path to the socket directory in the `host` option. The socket path must start with `/`.
-
-```js
-const sequelize = new Sequelize('database', 'username', 'password', {
- dialect: 'postgres',
- host: '/path/to/socket_directory'
-});
-```
-
-### MSSQL
-
-The underlying connector library used by Sequelize for MSSQL is the [tedious](https://www.npmjs.com/package/tedious) npm package (version 6.0.0 or above).
-
-You can provide custom options to it using `dialectOptions.options` in the Sequelize constructor:
-
-```js
-const sequelize = new Sequelize('database', 'username', 'password', {
- dialect: 'mssql',
- dialectOptions: {
- // Observe the need for this nested `options` field for MSSQL
- options: {
- // Your tedious options here
- useUTC: false,
- dateFirst: 1
- }
- }
-});
-```
-
-#### MSSQL Domain Account
-
-In order to connect with a domain account, use the following format.
-
-```js
-const sequelize = new Sequelize('database', null, null, {
- dialect: 'mssql',
- dialectOptions: {
- authentication: {
- type: 'ntlm',
- options: {
- domain: 'yourDomain',
- userName: 'username',
- password: 'password'
- }
- },
- options: {
- instanceName: 'SQLEXPRESS'
- }
- }
-})
-```
-
-## Data type: TIMESTAMP WITHOUT TIME ZONE - PostgreSQL only
-
-If you are working with the PostgreSQL `TIMESTAMP WITHOUT TIME ZONE` and you need to parse it to a different timezone, please use the pg library's own parser:
-
-```js
-require('pg').types.setTypeParser(1114, stringValue => {
- return new Date(stringValue + '+0000');
- // e.g., UTC offset. Use any offset that you would like.
-});
-```
-
-## Data type: ARRAY(ENUM) - PostgreSQL only
-
-Array(Enum) type requireS special treatment. Whenever Sequelize will talk to the database, it has to typecast array values with ENUM name.
-
-So this enum name must follow this pattern `enum__`. If you are using `sync` then correct name will automatically be generated.
-
-## Table Hints - MSSQL only
-
-The `tableHint` option can be used to define a table hint. The hint must be a value from `TableHints` and should only be used when absolutely necessary. Only a single table hint is currently supported per query.
-
-Table hints override the default behavior of MSSQL query optimizer by specifing certain options. They only affect the table or view referenced in that clause.
-
-```js
-const { TableHints } = require('sequelize');
-Project.findAll({
- // adding the table hint NOLOCK
- tableHint: TableHints.NOLOCK
- // this will generate the SQL 'WITH (NOLOCK)'
-})
-```
-
-## Index Hints - MySQL/MariaDB only
-
-The `indexHints` option can be used to define index hints. The hint type must be a value from `IndexHints` and the values should reference existing indexes.
-
-Index hints [override the default behavior of the MySQL query optimizer](https://dev.mysql.com/doc/refman/5.7/en/index-hints.html).
-
-```js
-const { IndexHints } = require("sequelize");
-Project.findAll({
- indexHints: [
- { type: IndexHints.USE, values: ['index_project_on_name'] }
- ],
- where: {
- id: {
- [Op.gt]: 623
- },
- name: {
- [Op.like]: 'Foo %'
- }
- }
-});
-```
-
-The above will generate a MySQL query that looks like this:
-
-```sql
-SELECT * FROM Project USE INDEX (index_project_on_name) WHERE name LIKE 'FOO %' AND id > 623;
-```
-
-`Sequelize.IndexHints` includes `USE`, `FORCE`, and `IGNORE`.
-
-See [Issue #9421](https://github.com/sequelize/sequelize/issues/9421) for the original API proposal.
-
-## Engines - MySQL/MariaDB only
-
-The default engine for a model is InnoDB.
-
-You can change the engine for a model with the `engine` option (e.g., to MyISAM):
-
-```js
-const Person = sequelize.define('person', { /* attributes */ }, {
- engine: 'MYISAM'
-});
-```
-
-Like every option for the definition of a model, this setting can also be changed globally with the `define` option of the Sequelize constructor:
-
-```js
-const sequelize = new Sequelize(db, user, pw, {
- define: { engine: 'MYISAM' }
-})
-```
-
-## Table comments - MySQL/MariaDB/PostgreSQL only
-
-You can specify a comment for a table when defining the model:
-
-```js
-class Person extends Model {}
-Person.init({ /* attributes */ }, {
- comment: "I'm a table comment!",
- sequelize
-})
-```
-
-The comment will be set when calling `sync()`.
diff --git a/docs/manual/other-topics/extending-data-types.md b/docs/manual/other-topics/extending-data-types.md
deleted file mode 100644
index 2e0938916faf..000000000000
--- a/docs/manual/other-topics/extending-data-types.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Extending Data Types
-
-Most likely the type you are trying to implement is already included in [DataTypes](data-types.html). If a new datatype is not included, this manual will show how to write it yourself.
-
-Sequelize doesn't create new datatypes in the database. This tutorial explains how to make Sequelize recognize new datatypes and assumes that those new datatypes are already created in the database.
-
-To extend Sequelize datatypes, do it before any Sequelize instance is created.
-
-## Example
-
-In this example, we will create a type called `SOMETYPE` that replicates the built-in datatype `DataTypes.INTEGER(11).ZEROFILL.UNSIGNED`.
-
-```js
-const { Sequelize, DataTypes, Utils } = require('Sequelize');
-createTheNewDataType();
-const sequelize = new Sequelize('sqlite::memory:');
-
-function createTheNewDataType() {
-
- class SOMETYPE extends DataTypes.ABSTRACT {
- // Mandatory: complete definition of the new type in the database
- toSql() {
- return 'INTEGER(11) UNSIGNED ZEROFILL'
- }
-
- // Optional: validator function
- validate(value, options) {
- return (typeof value === 'number') && (!Number.isNaN(value));
- }
-
- // Optional: sanitizer
- _sanitize(value) {
- // Force all numbers to be positive
- return value < 0 ? 0 : Math.round(value);
- }
-
- // Optional: value stringifier before sending to database
- _stringify(value) {
- return value.toString();
- }
-
- // Optional: parser for values received from the database
- static parse(value) {
- return Number.parseInt(value);
- }
- }
-
- // Mandatory: set the type key
- SOMETYPE.prototype.key = SOMETYPE.key = 'SOMETYPE';
-
- // Mandatory: add the new type to DataTypes. Optionally wrap it on `Utils.classToInvokable` to
- // be able to use this datatype directly without having to call `new` on it.
- DataTypes.SOMETYPE = Utils.classToInvokable(SOMETYPE);
-
- // Optional: disable escaping after stringifier. Do this at your own risk, since this opens opportunity for SQL injections.
- // DataTypes.SOMETYPE.escape = false;
-
-}
-```
-
-After creating this new datatype, you need to map this datatype in each database dialect and make some adjustments.
-
-## PostgreSQL
-
-Let's say the name of the new datatype is `pg_new_type` in the postgres database. That name has to be mapped to `DataTypes.SOMETYPE`. Additionally, it is required to create a child postgres-specific datatype.
-
-```js
-function createTheNewDataType() {
- // [...]
-
- const PgTypes = DataTypes.postgres;
-
- // Mandatory: map postgres datatype name
- DataTypes.SOMETYPE.types.postgres = ['pg_new_type'];
-
- // Mandatory: create a postgres-specific child datatype with its own parse
- // method. The parser will be dynamically mapped to the OID of pg_new_type.
- PgTypes.SOMETYPE = function SOMETYPE() {
- if (!(this instanceof PgTypes.SOMETYPE)) {
- return new PgTypes.SOMETYPE();
- }
- DataTypes.SOMETYPE.apply(this, arguments);
- }
- const util = require('util'); // Built-in Node package
- util.inherits(PgTypes.SOMETYPE, DataTypes.SOMETYPE);
-
- // Mandatory: create, override or reassign a postgres-specific parser
- // PgTypes.SOMETYPE.parse = value => value;
- PgTypes.SOMETYPE.parse = DataTypes.SOMETYPE.parse || x => x;
-
- // Optional: add or override methods of the postgres-specific datatype
- // like toSql, escape, validate, _stringify, _sanitize...
-
-}
-```
-
-### Ranges
-
-After a new range type has been [defined in postgres](https://www.postgresql.org/docs/current/static/rangetypes.html#RANGETYPES-DEFINING), it is trivial to add it to Sequelize.
-
-In this example the name of the postgres range type is `SOMETYPE_range` and the name of the underlying postgres datatype is `pg_new_type`. The key of `subtypes` and `castTypes` is the key of the Sequelize datatype `DataTypes.SOMETYPE.key`, in lower case.
-
-```js
-function createTheNewDataType() {
- // [...]
-
- // Add postgresql range, SOMETYPE comes from DataType.SOMETYPE.key in lower case
- DataTypes.RANGE.types.postgres.subtypes.SOMETYPE = 'SOMETYPE_range';
- DataTypes.RANGE.types.postgres.castTypes.SOMETYPE = 'pg_new_type';
-}
-```
-
-The new range can be used in model definitions as `DataTypes.RANGE(DataTypes.SOMETYPE)` or `DataTypes.RANGE(DataTypes.SOMETYPE)`.
diff --git a/docs/manual/other-topics/hooks.md b/docs/manual/other-topics/hooks.md
deleted file mode 100644
index 71791719bb4f..000000000000
--- a/docs/manual/other-topics/hooks.md
+++ /dev/null
@@ -1,385 +0,0 @@
-# Hooks
-
-Hooks (also known as 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.
-
-**Note:** _You can't use hooks with instances. Hooks are used with models._
-
-## Available hooks
-
-Sequelize provides a lot of hooks. The full list can be found in directly in the [source code - lib/hooks.js](https://github.com/sequelize/sequelize/blob/v6/lib/hooks.js#L7).
-
-## Hooks firing order
-
-The diagram below shows the firing order for the most common hooks.
-
-_**Note:** this list is not exhaustive._
-
-```text
-(1)
- beforeBulkCreate(instances, options)
- beforeBulkDestroy(options)
- beforeBulkUpdate(options)
-(2)
- beforeValidate(instance, options)
-
-[... validation happens ...]
-
-(3)
- afterValidate(instance, options)
- validationFailed(instance, options, error)
-(4)
- beforeCreate(instance, options)
- beforeDestroy(instance, options)
- beforeUpdate(instance, options)
- beforeSave(instance, options)
- beforeUpsert(values, options)
-
-[... creation/update/destruction happens ...]
-
-(5)
- afterCreate(instance, options)
- afterDestroy(instance, options)
- afterUpdate(instance, options)
- afterSave(instance, options)
- afterUpsert(created, options)
-(6)
- afterBulkCreate(instances, options)
- afterBulkDestroy(options)
- afterBulkUpdate(options)
-```
-
-## Declaring Hooks
-
-Arguments to hooks are passed by reference. This means, that you can change the values, and this will be reflected in the insert / update statement. A hook may contain async actions - in this case the hook function should return a promise.
-
-There are currently three ways to programmatically add hooks:
-
-```js
-// Method 1 via the .init() method
-class User extends Model {}
-User.init({
- username: DataTypes.STRING,
- mood: {
- type: DataTypes.ENUM,
- values: ['happy', 'sad', 'neutral']
- }
-}, {
- hooks: {
- beforeValidate: (user, options) => {
- user.mood = 'happy';
- },
- afterValidate: (user, options) => {
- user.username = 'Toni';
- }
- },
- sequelize
-});
-
-// Method 2 via the .addHook() method
-User.addHook('beforeValidate', (user, options) => {
- user.mood = 'happy';
-});
-
-User.addHook('afterValidate', 'someCustomName', (user, options) => {
- return Promise.reject(new Error("I'm afraid I can't let you do that!"));
-});
-
-// Method 3 via the direct method
-User.beforeCreate(async (user, options) => {
- const hashedPassword = await hashPassword(user.password);
- user.password = hashedPassword;
-});
-
-User.afterValidate('myHookAfter', (user, options) => {
- user.username = 'Toni';
-});
-```
-
-## Removing hooks
-
-Only a hook with name param can be removed.
-
-```js
-class Book extends Model {}
-Book.init({
- title: DataTypes.STRING
-}, { sequelize });
-
-Book.addHook('afterCreate', 'notifyUsers', (book, options) => {
- // ...
-});
-
-Book.removeHook('afterCreate', 'notifyUsers');
-```
-
-You can have many hooks with same name. Calling `.removeHook()` will remove all of them.
-
-## Global / universal hooks
-
-Global hooks are hooks which are run for all models. They can define behaviours that you want for all your models, and are especially useful for plugins. They can be defined in two ways, which have slightly different semantics:
-
-### Default Hooks (on Sequelize constructor options)
-
-```js
-const sequelize = new Sequelize(..., {
- define: {
- hooks: {
- beforeCreate() {
- // Do stuff
- }
- }
- }
-});
-```
-
-This adds a default hook to all models, which is run if the model does not define its own `beforeCreate` hook:
-
-```js
-const User = sequelize.define('User', {});
-const Project = sequelize.define('Project', {}, {
- hooks: {
- beforeCreate() {
- // Do other stuff
- }
- }
-});
-
-await User.create({}); // Runs the global hook
-await Project.create({}); // Runs its own hook (because the global hook is overwritten)
-```
-
-### Permanent Hooks (with `sequelize.addHook`)
-
-```js
-sequelize.addHook('beforeCreate', () => {
- // Do stuff
-});
-```
-
-This hook is always run, whether or not the model specifies its own `beforeCreate` hook. Local hooks are always run before global hooks:
-
-```js
-const User = sequelize.define('User', {});
-const Project = sequelize.define('Project', {}, {
- hooks: {
- beforeCreate() {
- // Do other stuff
- }
- }
-});
-
-await User.create({}); // Runs the global hook
-await Project.create({}); // Runs its own hook, followed by the global hook
-```
-
-Permanent hooks may also be defined in the options passed to the Sequelize constructor:
-
-```js
-new Sequelize(..., {
- hooks: {
- beforeCreate() {
- // do stuff
- }
- }
-});
-```
-
-Note that the above is not the same as the *Default Hooks* mentioned above. That one uses the `define` option of the constructor. This one does not.
-
-### Connection Hooks
-
-Sequelize provides four hooks that are executed immediately before and after a database connection is obtained or released:
-
-* `sequelize.beforeConnect(callback)`
- * The callback has the form `async (config) => /* ... */`
-* `sequelize.afterConnect(callback)`
- * The callback has the form `async (connection, config) => /* ... */`
-* `sequelize.beforeDisconnect(callback)`
- * The callback has the form `async (connection) => /* ... */`
-* `sequelize.afterDisconnect(callback)`
- * The callback has the form `async (connection) => /* ... */`
-
-These hooks can be useful if you need to asynchronously obtain database credentials, or need to directly access the low-level database connection after it has been created.
-
-For example, we can asynchronously obtain a database password from a rotating token store, and mutate Sequelize's configuration object with the new credentials:
-
-```js
-sequelize.beforeConnect(async (config) => {
- config.password = await getAuthToken();
-});
-```
-
-These hooks may *only* be declared as a permanent global hook, as the connection pool is shared by all models.
-
-## Instance hooks
-
-The following hooks will emit whenever you're editing a single object:
-
-* `beforeValidate`
-* `afterValidate` / `validationFailed`
-* `beforeCreate` / `beforeUpdate` / `beforeSave` / `beforeDestroy`
-* `afterCreate` / `afterUpdate` / `afterSave` / `afterDestroy`
-
-```js
-User.beforeCreate(user => {
- if (user.accessLevel > 10 && user.username !== "Boss") {
- throw new Error("You can't grant this user an access level above 10!");
- }
-});
-```
-
-The following example will throw an error:
-
-```js
-try {
- await User.create({ username: 'Not a Boss', accessLevel: 20 });
-} catch (error) {
- console.log(error); // You can't grant this user an access level above 10!
-};
-```
-
-The following example will be successful:
-
-```js
-const user = await User.create({ username: 'Boss', accessLevel: 20 });
-console.log(user); // user object with username 'Boss' and accessLevel of 20
-```
-
-### Model hooks
-
-Sometimes you'll be editing more than one record at a time by using methods like `bulkCreate`, `update` and `destroy`. The following hooks will emit whenever you're using one of those methods:
-
-* `YourModel.beforeBulkCreate(callback)`
- * The callback has the form `(instances, options) => /* ... */`
-* `YourModel.beforeBulkUpdate(callback)`
- * The callback has the form `(options) => /* ... */`
-* `YourModel.beforeBulkDestroy(callback)`
- * The callback has the form `(options) => /* ... */`
-* `YourModel.afterBulkCreate(callback)`
- * The callback has the form `(instances, options) => /* ... */`
-* `YourModel.afterBulkUpdate(callback)`
- * The callback has the form `(options) => /* ... */`
-* `YourModel.afterBulkDestroy(callback)`
- * The callback has the form `(options) => /* ... */`
-
-Note: methods like `bulkCreate` do not emit individual hooks by default - only the bulk hooks. However, if you want individual hooks to be emitted as well, you can pass the `{ individualHooks: true }` option to the query call. However, this can drastically impact performance, depending on the number of records involved (since, among other things, all instances will be loaded into memory). Examples:
-
-```js
-await Model.destroy({
- where: { accessLevel: 0 },
- individualHooks: true
-});
-// This will select all records that are about to be deleted and emit `beforeDestroy` and `afterDestroy` on each instance.
-
-await Model.update({ username: 'Tony' }, {
- where: { accessLevel: 0 },
- individualHooks: true
-});
-// This will select all records that are about to be updated and emit `beforeUpdate` and `afterUpdate` on each instance.
-```
-
-If you use `Model.bulkCreate(...)` with the `updateOnDuplicate` option, changes made in the hook to fields that aren't given in the `updateOnDuplicate` array will not be persisted to the database. However it is possible to change the `updateOnDuplicate` option inside the hook if this is what you want.
-
-```js
-User.beforeBulkCreate((users, options) => {
- for (const user of users) {
- if (user.isMember) {
- user.memberSince = new Date();
- }
- }
-
- // Add `memberSince` to updateOnDuplicate otherwise it won't be persisted
- if (options.updateOnDuplicate && !options.updateOnDuplicate.includes('memberSince')) {
- options.updateOnDuplicate.push('memberSince');
- }
-});
-
-// Bulk updating existing users with updateOnDuplicate option
-await Users.bulkCreate([
- { id: 1, isMember: true },
- { id: 2, isMember: false }
-], {
- updateOnDuplicate: ['isMember']
-});
-```
-
-## Associations
-
-For the most part hooks will work the same for instances when being associated.
-
-### One-to-One and One-to-Many associations
-
-* When using `add`/`set` mixin methods the `beforeUpdate` and `afterUpdate` hooks will run.
-
-* The `beforeDestroy` and `afterDestroy` hooks will only be called on associations that have `onDelete: 'CASCADE'` and `hooks: true`. For example:
-
-```js
-class Projects extends Model {}
-Projects.init({
- title: DataTypes.STRING
-}, { sequelize });
-
-class Tasks extends Model {}
-Tasks.init({
- title: DataTypes.STRING
-}, { sequelize });
-
-Projects.hasMany(Tasks, { onDelete: 'CASCADE', hooks: true });
-Tasks.belongsTo(Projects);
-```
-
-This code will run `beforeDestroy` and `afterDestroy` hooks on the Tasks model.
-
-Sequelize, by default, will try to optimize your queries as much as possible. When calling cascade on delete, Sequelize will simply execute:
-
-```sql
-DELETE FROM `table` WHERE associatedIdentifier = associatedIdentifier.primaryKey
-```
-
-However, adding `hooks: true` explicitly tells Sequelize that optimization is not of your concern. Then, Sequelize will first perform a `SELECT` on the associated objects and destroy each instance, one by one, in order to be able to properly call the hooks (with the right parameters).
-
-### Many-to-Many associations
-
-* When using `add` mixin methods for `belongsToMany` relationships (that will add one or more records to the junction table) the `beforeBulkCreate` and `afterBulkCreate` hooks in the junction model will run.
- * If `{ individualHooks: true }` was passed to the call, then each individual hook will also run.
-
-* When using `remove` mixin methods for `belongsToMany` relationships (that will remove one or more records to the junction table) the `beforeBulkDestroy` and `afterBulkDestroy` hooks in the junction model will run.
- * If `{ individualHooks: true }` was passed to the call, then each individual hook will also run.
-
-If your association is Many-to-Many, you may be interested in firing hooks on the through model when using the `remove` call. Internally, sequelize is using `Model.destroy` resulting in calling the `bulkDestroy` instead of the `before/afterDestroy` hooks on each through instance.
-
-## Hooks and Transactions
-
-Many model operations in Sequelize allow you to specify a transaction in the options parameter of the method. If a transaction *is* specified in the original call, it will be present in the options parameter passed to the hook function. For example, consider the following snippet:
-
-```js
-User.addHook('afterCreate', async (user, options) => {
- // We can use `options.transaction` to perform some other call
- // using the same transaction of the call that triggered this hook
- await User.update({ mood: 'sad' }, {
- where: {
- id: user.id
- },
- transaction: options.transaction
- });
-});
-
-await sequelize.transaction(async t => {
- await User.create({
- username: 'someguy',
- mood: 'happy',
- transaction: t
- });
-});
-```
-
-If we had not included the transaction option in our call to `User.update` in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.
-
-### Internal Transactions
-
-It is very important to recognize that sequelize may make use of transactions internally for certain operations such as `Model.findOrCreate`. If your hook functions execute read or write operations that rely on the object's presence in the database, or modify the object's stored values like the example in the preceding section, you should always specify `{ transaction: options.transaction }`:
-
-* If a transaction was used, then `{ transaction: options.transaction }` will ensure it is used again;
-* Otherwise, `{ transaction: options.transaction }` will be equivalent to `{ transaction: undefined }`, which won't use a transaction (which is ok).
-
-This way your hooks will always behave correctly.
diff --git a/docs/manual/other-topics/indexes.md b/docs/manual/other-topics/indexes.md
deleted file mode 100644
index 123ec878457e..000000000000
--- a/docs/manual/other-topics/indexes.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Indexes
-
-Sequelize supports adding indexes to the model definition which will be created on [`sequelize.sync()`](../class/lib/sequelize.js~Sequelize.html#instance-method-sync).
-
-```js
-const User = sequelize.define('User', { /* attributes */ }, {
- indexes: [
- // Create a unique index on email
- {
- unique: true,
- fields: ['email']
- },
-
- // Creates a gin index on data with the jsonb_path_ops operator
- {
- fields: ['data'],
- using: 'gin',
- operator: 'jsonb_path_ops'
- },
-
- // By default index name will be [table]_[fields]
- // Creates a multi column partial index
- {
- name: 'public_by_author',
- fields: ['author', 'status'],
- where: {
- status: 'public'
- }
- },
-
- // A BTREE index with an ordered field
- {
- name: 'title_index',
- using: 'BTREE',
- fields: [
- 'author',
- {
- attribute: 'title',
- collate: 'en_US',
- order: 'DESC',
- length: 5
- }
- ]
- }
- ]
-});
-```
\ No newline at end of file
diff --git a/docs/manual/other-topics/legacy.md b/docs/manual/other-topics/legacy.md
deleted file mode 100644
index 249f5a9638de..000000000000
--- a/docs/manual/other-topics/legacy.md
+++ /dev/null
@@ -1,71 +0,0 @@
-# Working with Legacy Tables
-
-While out of the box Sequelize will seem a bit opinionated it's easy to work legacy tables and forward proof your application by defining (otherwise generated) table and field names.
-
-## Tables
-
-```js
-class User extends Model {}
-User.init({
- // ...
-}, {
- modelName: 'user',
- tableName: 'users',
- sequelize,
-});
-```
-
-## Fields
-
-```js
-class MyModel extends Model {}
-MyModel.init({
- userId: {
- type: DataTypes.INTEGER,
- field: 'user_id'
- }
-}, { sequelize });
-```
-
-## Primary keys
-
-Sequelize will assume your table has a `id` primary key property by default.
-
-To define your own primary key:
-
-```js
-class Collection extends Model {}
-Collection.init({
- uid: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- autoIncrement: true // Automatically gets converted to SERIAL for postgres
- }
-}, { sequelize });
-
-class Collection extends Model {}
-Collection.init({
- uuid: {
- type: DataTypes.UUID,
- primaryKey: true
- }
-}, { sequelize });
-```
-
-And if your model has no primary key at all you can use `Model.removeAttribute('id');`
-
-## Foreign keys
-
-```js
-// 1:1
-Organization.belongsTo(User, { foreignKey: 'owner_id' });
-User.hasOne(Organization, { foreignKey: 'owner_id' });
-
-// 1:M
-Project.hasMany(Task, { foreignKey: 'tasks_pk' });
-Task.belongsTo(Project, { foreignKey: 'tasks_pk' });
-
-// N:M
-User.belongsToMany(Role, { through: 'user_has_roles', foreignKey: 'user_role_user_id' });
-Role.belongsToMany(User, { through: 'user_has_roles', foreignKey: 'roles_identifier' });
-```
diff --git a/docs/manual/other-topics/legal.md b/docs/manual/other-topics/legal.md
deleted file mode 100644
index 0d8d4b428b2a..000000000000
--- a/docs/manual/other-topics/legal.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# Legal Notice
-
-## License
-
-Sequelize library is distributed with MIT license. You can find original license [here.](https://github.com/sequelize/sequelize/blob/main/LICENSE)
-
-```text
-MIT License
-
-Copyright (c) 2014-present Sequelize contributors
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-```
-
-## AUTHOR(S)
-
-```text
-Main author:
-
-Sascha Depold
-Uhlandstr. 160
-10719 Berlin
-sascha [at] depold [dot] com
-[plus] 49 152 [slash] 03878582
-
-```
-
-## INHALTLICHE VERANTWORTUNG
-
-```text
-Ich übernehme keine Haftung für ausgehende Links.
-Daher musst du dich bei Problemen an deren Betreiber wenden!
-```
diff --git a/docs/manual/other-topics/migrations.md b/docs/manual/other-topics/migrations.md
deleted file mode 100644
index 7b869738146c..000000000000
--- a/docs/manual/other-topics/migrations.md
+++ /dev/null
@@ -1,565 +0,0 @@
-# Migrations
-
-Just like you use [version control](https://en.wikipedia.org/wiki/Version_control) systems such as [Git](https://en.wikipedia.org/wiki/Git) to manage changes in your source code, you can use **migrations** to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.
-
-You will need the [Sequelize Command-Line Interface (CLI)](https://github.com/sequelize/cli). The CLI ships support for migrations and project bootstrapping.
-
-A Migration in Sequelize is javascript file which exports two functions, `up` and `down`, that dictate how to perform the migration and undo it. You define those functions manually, but you don't call them manually; they will be called automatically by the CLI. In these functions, you should simply perform whatever queries you need, with the help of `sequelize.query` and whichever other methods Sequelize provides to you. There is no extra magic beyond that.
-
-## Installing the CLI
-
-To install the Sequelize CLI:
-
-```text
-npm install --save-dev sequelize-cli
-```
-
-For details see the [CLI GitHub repository](https://github.com/sequelize/cli).
-
-## Project bootstrapping
-
-To create an empty project you will need to execute `init` command
-
-```text
-npx sequelize-cli init
-```
-
-This will create following folders
-
-- `config`, contains config file, which tells CLI how to connect with database
-- `models`, contains all models for your project
-- `migrations`, contains all migration files
-- `seeders`, contains all seed files
-
-### Configuration
-
-Before continuing further we will need to tell the CLI how to connect to the database. To do that let's open default config file `config/config.json`. It looks something like this:
-
-```json
-{
- "development": {
- "username": "root",
- "password": null,
- "database": "database_development",
- "host": "127.0.0.1",
- "dialect": "mysql"
- },
- "test": {
- "username": "root",
- "password": null,
- "database": "database_test",
- "host": "127.0.0.1",
- "dialect": "mysql"
- },
- "production": {
- "username": "root",
- "password": null,
- "database": "database_production",
- "host": "127.0.0.1",
- "dialect": "mysql"
- }
-}
-```
-
-Note that the Sequelize CLI assumes mysql by default. If you're using another dialect, you need to change the content of the `"dialect"` option.
-
-Now edit this file and set correct database credentials and dialect. The keys of the objects (e.g. "development") are used on `model/index.js` for matching `process.env.NODE_ENV` (When undefined, "development" is a default value).
-
-Sequelize will use the default connection port for each dialect (for example, for postgres, it is port 5432). If you need to specify a different port, use the `"port"` field (it is not present by default in `config/config.js` but you can simply add it).
-
-**Note:** _If your database doesn't exist yet, you can just call `db:create` command. With proper access it will create that database for you._
-
-## Creating the first Model (and Migration)
-
-Once you have properly configured CLI config file you are ready to create your first migration. It's as simple as executing a simple command.
-
-We will use `model:generate` command. This command requires two options:
-
-- `name`: the name of the model;
-- `attributes`: the list of model attributes.
-
-Let's create a model named `User`.
-
-```text
-npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
-```
-
-This will:
-
-- Create a model file `user` in `models` folder;
-- Create a migration file with name like `XXXXXXXXXXXXXX-create-user.js` in `migrations` folder.
-
-**Note:** _Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database._
-
-## Running Migrations
-
-Until this step, we haven't inserted anything into the database. We have just created the required model and migration files for our first model, `User`. Now to actually create that table in the database you need to run `db:migrate` command.
-
-```text
-npx sequelize-cli db:migrate
-```
-
-This command will execute these steps:
-
-- Will ensure a table called `SequelizeMeta` in database. This table is used to record which migrations have run on the current database
-- Start looking for any migration files which haven't run yet. This is possible by checking `SequelizeMeta` table. In this case it will run `XXXXXXXXXXXXXX-create-user.js` migration, which we created in last step.
-- Creates a table called `Users` with all columns as specified in its migration file.
-
-## Undoing Migrations
-
-Now our table has been created and saved in the database. With migration you can revert to old state by just running a command.
-
-You can use `db:migrate:undo`, this command will revert most the recent migration.
-
-```text
-npx sequelize-cli db:migrate:undo
-```
-
-You can revert back to the initial state by undoing all migrations with the `db:migrate:undo:all` command. You can also revert back to a specific migration by passing its name with the `--to` option.
-
-```text
-npx sequelize-cli db:migrate:undo:all --to XXXXXXXXXXXXXX-create-posts.js
-```
-
-### Creating the first Seed
-
-Suppose we want to insert some data into a few tables by default. If we follow up on the previous example we can consider creating a demo user for the `User` table.
-
-To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database tables with sample or test data.
-
-Let's create a seed file which will add a demo user to our `User` table.
-
-```text
-npx sequelize-cli seed:generate --name demo-user
-```
-
-This command will create a seed file in `seeders` folder. File name will look something like `XXXXXXXXXXXXXX-demo-user.js`. It follows the same `up / down` semantics as the migration files.
-
-Now we should edit this file to insert demo user to `User` table.
-
-```js
-module.exports = {
- up: (queryInterface, Sequelize) => {
- return queryInterface.bulkInsert('Users', [{
- firstName: 'John',
- lastName: 'Doe',
- email: 'example@example.com',
- createdAt: new Date(),
- updatedAt: new Date()
- }]);
- },
- down: (queryInterface, Sequelize) => {
- return queryInterface.bulkDelete('Users', null, {});
- }
-};
-```
-
-## Running Seeds
-
-In last step you created a seed file; however, it has not been committed to the database. To do that we run a simple command.
-
-```text
-npx sequelize-cli db:seed:all
-```
-
-This will execute that seed file and a demo user will be inserted into the `User` table.
-
-**Note:** _Seeder execution history is not stored anywhere, unlike migrations, which use the `SequelizeMeta` table. If you wish to change this behavior, please read the `Storage` section._
-
-## Undoing Seeds
-
-Seeders can be undone if they are using any storage. There are two commands available for that:
-
-If you wish to undo the most recent seed:
-
-```text
-npx sequelize-cli db:seed:undo
-```
-
-If you wish to undo a specific seed:
-
-```text
-npx sequelize-cli db:seed:undo --seed name-of-seed-as-in-data
-```
-
-If you wish to undo all seeds:
-
-```text
-npx sequelize-cli db:seed:undo:all
-```
-
-## Migration Skeleton
-
-The following skeleton shows a typical migration file.
-
-```js
-module.exports = {
- up: (queryInterface, Sequelize) => {
- // logic for transforming into the new state
- },
- down: (queryInterface, Sequelize) => {
- // logic for reverting the changes
- }
-}
-```
-
-We can generate this file using `migration:generate`. This will create `xxx-migration-skeleton.js` in your migration folder.
-
-```text
-npx sequelize-cli migration:generate --name migration-skeleton
-```
-
-The passed `queryInterface` object can be used to modify the database. The `Sequelize` object stores the available data types such as `STRING` or `INTEGER`. Function `up` or `down` should return a `Promise`. Let's look at an example:
-
-```js
-module.exports = {
- up: (queryInterface, Sequelize) => {
- return queryInterface.createTable('Person', {
- name: Sequelize.DataTypes.STRING,
- isBetaMember: {
- type: Sequelize.DataTypes.BOOLEAN,
- defaultValue: false,
- allowNull: false
- }
- });
- },
- down: (queryInterface, Sequelize) => {
- return queryInterface.dropTable('Person');
- }
-};
-```
-
-The following is an example of a migration that performs two changes in the database, using an automatically-managed transaction to ensure that all instructions are successfully executed or rolled back in case of failure:
-
-```js
-module.exports = {
- up: (queryInterface, Sequelize) => {
- return queryInterface.sequelize.transaction(t => {
- return Promise.all([
- queryInterface.addColumn('Person', 'petName', {
- type: Sequelize.DataTypes.STRING
- }, { transaction: t }),
- queryInterface.addColumn('Person', 'favoriteColor', {
- type: Sequelize.DataTypes.STRING,
- }, { transaction: t })
- ]);
- });
- },
- down: (queryInterface, Sequelize) => {
- return queryInterface.sequelize.transaction(t => {
- return Promise.all([
- queryInterface.removeColumn('Person', 'petName', { transaction: t }),
- queryInterface.removeColumn('Person', 'favoriteColor', { transaction: t })
- ]);
- });
- }
-};
-```
-
-The next example is of a migration that has a foreign key. You can use references to specify a foreign key:
-
-```js
-module.exports = {
- up: (queryInterface, Sequelize) => {
- return queryInterface.createTable('Person', {
- name: Sequelize.DataTypes.STRING,
- isBetaMember: {
- type: Sequelize.DataTypes.BOOLEAN,
- defaultValue: false,
- allowNull: false
- },
- userId: {
- type: Sequelize.DataTypes.INTEGER,
- references: {
- model: {
- tableName: 'users',
- schema: 'schema'
- },
- key: 'id'
- },
- allowNull: false
- },
- });
- },
- down: (queryInterface, Sequelize) => {
- return queryInterface.dropTable('Person');
- }
-}
-```
-
-The next example is of a migration that uses async/await where you create an unique index on a new column, with a manually-managed transaction:
-
-```js
-module.exports = {
- async up(queryInterface, Sequelize) {
- const transaction = await queryInterface.sequelize.transaction();
- try {
- await queryInterface.addColumn(
- 'Person',
- 'petName',
- {
- type: Sequelize.DataTypes.STRING,
- },
- { transaction }
- );
- await queryInterface.addIndex(
- 'Person',
- 'petName',
- {
- fields: 'petName',
- unique: true,
- transaction,
- }
- );
- await transaction.commit();
- } catch (err) {
- await transaction.rollback();
- throw err;
- }
- },
- async down(queryInterface, Sequelize) {
- const transaction = await queryInterface.sequelize.transaction();
- try {
- await queryInterface.removeColumn('Person', 'petName', { transaction });
- await transaction.commit();
- } catch (err) {
- await transaction.rollback();
- throw err;
- }
- }
-};
-```
-
-The next example is of a migration that creates an unique index composed of multiple fields with a condition, which allows a relation to exist multiple times but only one can satisfy the condition:
-
-```js
-module.exports = {
- up: (queryInterface, Sequelize) => {
- queryInterface.createTable('Person', {
- name: Sequelize.DataTypes.STRING,
- bool: {
- type: Sequelize.DataTypes.BOOLEAN,
- defaultValue: false
- }
- }).then((queryInterface, Sequelize) => {
- queryInterface.addIndex(
- 'Person',
- ['name', 'bool'],
- {
- indicesType: 'UNIQUE',
- where: { bool : 'true' },
- }
- );
- });
- },
- down: (queryInterface, Sequelize) => {
- return queryInterface.dropTable('Person');
- }
-}
-```
-
-### The `.sequelizerc` file
-
-This is a special configuration file. It lets you specify the following options that you would usually pass as arguments to CLI:
-
-- `env`: The environment to run the command in
-- `config`: The path to the config file
-- `options-path`: The path to a JSON file with additional options
-- `migrations-path`: The path to the migrations folder
-- `seeders-path`: The path to the seeders folder
-- `models-path`: The path to the models folder
-- `url`: The database connection string to use. Alternative to using --config files
-- `debug`: When available show various debug information
-
-Some scenarios where you can use it:
-
-- You want to override default path to `migrations`, `models`, `seeders` or `config` folder.
-- You want to rename `config.json` to something else like `database.json`
-
-And a whole lot more. Let's see how you can use this file for custom configuration.
-
-To begin, let's create the `.sequelizerc` file in the root directory of your project, with the following content:
-
-```js
-// .sequelizerc
-
-const path = require('path');
-
-module.exports = {
- 'config': path.resolve('config', 'database.json'),
- 'models-path': path.resolve('db', 'models'),
- 'seeders-path': path.resolve('db', 'seeders'),
- 'migrations-path': path.resolve('db', 'migrations')
-};
-```
-
-With this config you are telling the CLI to:
-
-- Use `config/database.json` file for config settings;
-- Use `db/models` as models folder;
-- Use `db/seeders` as seeders folder;
-- Use `db/migrations` as migrations folder.
-
-### Dynamic configuration
-
-The configuration file is by default a JSON file called `config.json`. But sometimes you need a dynamic configuration, for example to access environment variables or execute some other code to determine the configuration.
-
-Thankfully, the Sequelize CLI can read from both `.json` and `.js` files. This can be setup with `.sequelizerc` file. You just have to provide the path to your `.js` file as the `config` option of your exported object:
-
-```js
-const path = require('path');
-
-module.exports = {
- 'config': path.resolve('config', 'config.js')
-}
-```
-
-Now the Sequelize CLI will load `config/config.js` for getting configuration options.
-
-An example of `config/config.js` file:
-
-```js
-const fs = require('fs');
-
-module.exports = {
- development: {
- username: 'database_dev',
- password: 'database_dev',
- database: 'database_dev',
- host: '127.0.0.1',
- port: 3306,
- dialect: 'mysql',
- dialectOptions: {
- bigNumberStrings: true
- }
- },
- test: {
- username: process.env.CI_DB_USERNAME,
- password: process.env.CI_DB_PASSWORD,
- database: process.env.CI_DB_NAME,
- host: '127.0.0.1',
- port: 3306,
- dialect: 'mysql',
- dialectOptions: {
- bigNumberStrings: true
- }
- },
- production: {
- username: process.env.PROD_DB_USERNAME,
- password: process.env.PROD_DB_PASSWORD,
- database: process.env.PROD_DB_NAME,
- host: process.env.PROD_DB_HOSTNAME,
- port: process.env.PROD_DB_PORT,
- dialect: 'mysql',
- dialectOptions: {
- bigNumberStrings: true,
- ssl: {
- ca: fs.readFileSync(__dirname + '/mysql-ca-main.crt')
- }
- }
- }
-};
-```
-
-The example above also shows how to add custom dialect options to the configuration.
-
-### Using Babel
-
-To enable more modern constructions in your migrations and seeders, you can simply install `babel-register` and require it at the beginning of `.sequelizerc`:
-
-```text
-npm i --save-dev babel-register
-```
-
-```js
-// .sequelizerc
-
-require("babel-register");
-
-const path = require('path');
-
-module.exports = {
- 'config': path.resolve('config', 'config.json'),
- 'models-path': path.resolve('models'),
- 'seeders-path': path.resolve('seeders'),
- 'migrations-path': path.resolve('migrations')
-}
-```
-
-Of course, the outcome will depend upon your babel configuration (such as in a `.babelrc` file). Learn more at [babeljs.io](https://babeljs.io).
-
-### Security tip
-
-Use environment variables for config settings. This is because secrets such as passwords should never be part of the source code (and especially not committed to version control).
-
-### Storage
-
-There are three types of storage that you can use: `sequelize`, `json`, and `none`.
-
-- `sequelize` : stores migrations and seeds in a table on the sequelize database
-- `json` : stores migrations and seeds on a json file
-- `none` : does not store any migration/seed
-
-#### Migration Storage
-
-By default the CLI will create a table in your database called `SequelizeMeta` containing an entry for each executed migration. To change this behavior, there are three options you can add to the configuration file. Using `migrationStorage`, you can choose the type of storage to be used for migrations. If you choose `json`, you can specify the path of the file using `migrationStoragePath` or the CLI will write to the file `sequelize-meta.json`. If you want to keep the information in the database, using `sequelize`, but want to use a different table, you can change the table name using `migrationStorageTableName`. Also you can define a different schema for the `SequelizeMeta` table by providing the `migrationStorageTableSchema` property.
-
-```json
-{
- "development": {
- "username": "root",
- "password": null,
- "database": "database_development",
- "host": "127.0.0.1",
- "dialect": "mysql",
-
- // Use a different storage type. Default: sequelize
- "migrationStorage": "json",
-
- // Use a different file name. Default: sequelize-meta.json
- "migrationStoragePath": "sequelizeMeta.json",
-
- // Use a different table name. Default: SequelizeMeta
- "migrationStorageTableName": "sequelize_meta",
-
- // Use a different schema for the SequelizeMeta table
- "migrationStorageTableSchema": "custom_schema"
- }
-}
-```
-
-**Note:** _The `none` storage is not recommended as a migration storage. If you decide to use it, be aware of the implications of having no record of what migrations did or didn't run._
-
-#### Seed Storage
-
-By default the CLI will not save any seed that is executed. If you choose to change this behavior (!), you can use `seederStorage` in the configuration file to change the storage type. If you choose `json`, you can specify the path of the file using `seederStoragePath` or the CLI will write to the file `sequelize-data.json`. If you want to keep the information in the database, using `sequelize`, you can specify the table name using `seederStorageTableName`, or it will default to `SequelizeData`.
-
-```json
-{
- "development": {
- "username": "root",
- "password": null,
- "database": "database_development",
- "host": "127.0.0.1",
- "dialect": "mysql",
- // Use a different storage. Default: none
- "seederStorage": "json",
- // Use a different file name. Default: sequelize-data.json
- "seederStoragePath": "sequelizeData.json",
- // Use a different table name. Default: SequelizeData
- "seederStorageTableName": "sequelize_data"
- }
-}
-```
-
-### Configuration Connection String
-
-As an alternative to the `--config` option with configuration files defining your database, you can use the `--url` option to pass in a connection string. For example:
-
-```text
-npx sequelize-cli db:migrate --url 'mysql://root:password@mysql_host.com/database_name'
-```
-
-### Programmatic usage
-
-Sequelize has a sister library called [umzug](https://github.com/sequelize/umzug) for programmatically handling execution and logging of migration tasks.
diff --git a/docs/manual/other-topics/naming-strategies.md b/docs/manual/other-topics/naming-strategies.md
deleted file mode 100644
index 9daf8b1a3567..000000000000
--- a/docs/manual/other-topics/naming-strategies.md
+++ /dev/null
@@ -1,157 +0,0 @@
-# Naming Strategies
-
-## The `underscored` option
-
-Sequelize provides the `underscored` option for a model. When `true`, this option will set the `field` option on all attributes to the [snake_case](https://en.wikipedia.org/wiki/Snake_case) version of its name. This also applies to foreign keys automatically generated by associations and other automatically generated fields. Example:
-
-```js
-const User = sequelize.define('user', { username: Sequelize.STRING }, {
- underscored: true
-});
-const Task = sequelize.define('task', { title: Sequelize.STRING }, {
- underscored: true
-});
-User.hasMany(Task);
-Task.belongsTo(User);
-```
-
-Above we have the models User and Task, both using the `underscored` option. We also have a One-to-Many relationship between them. Also, recall that since `timestamps` is true by default, we should expect the `createdAt` and `updatedAt` fields to be automatically created as well.
-
-Without the `underscored` option, Sequelize would automatically define:
-
-* A `createdAt` attribute for each model, pointing to a column named `createdAt` in each table
-* An `updatedAt` attribute for each model, pointing to a column named `updatedAt` in each table
-* A `userId` attribute in the `Task` model, pointing to a column named `userId` in the task table
-
-With the `underscored` option enabled, Sequelize will instead define:
-
-* A `createdAt` attribute for each model, pointing to a column named `created_at` in each table
-* An `updatedAt` attribute for each model, pointing to a column named `updated_at` in each table
-* A `userId` attribute in the `Task` model, pointing to a column named `user_id` in the task table
-
-Note that in both cases the fields are still [camelCase](https://en.wikipedia.org/wiki/Camel_case) in the JavaScript side; this option only changes how these fields are mapped to the database itself. The `field` option of every attribute is set to their snake_case version, but the attribute itself remains camelCase.
-
-This way, calling `sync()` on the above code will generate the following:
-
-```sql
-CREATE TABLE IF NOT EXISTS "users" (
- "id" SERIAL,
- "username" VARCHAR(255),
- "created_at" TIMESTAMP WITH TIME ZONE NOT NULL,
- "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL,
- PRIMARY KEY ("id")
-);
-CREATE TABLE IF NOT EXISTS "tasks" (
- "id" SERIAL,
- "title" VARCHAR(255),
- "created_at" TIMESTAMP WITH TIME ZONE NOT NULL,
- "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL,
- "user_id" INTEGER REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
- PRIMARY KEY ("id")
-);
-```
-
-## Singular vs. Plural
-
-At a first glance, it can be confusing whether the singular form or plural form of a name shall be used around in Sequelize. This section aims at clarifying that a bit.
-
-Recall that Sequelize uses a library called [inflection](https://www.npmjs.com/package/inflection) under the hood, so that irregular plurals (such as `person -> people`) are computed correctly. However, if you're working in another language, you may want to define the singular and plural forms of names directly; sequelize allows you to do this with some options.
-
-### When defining models
-
-Models should be defined with the singular form of a word. Example:
-
-```js
-sequelize.define('foo', { name: DataTypes.STRING });
-```
-
-Above, the model name is `foo` (singular), and the respective table name is `foos`, since Sequelize automatically gets the plural for the table name.
-
-### When defining a reference key in a model
-
-```js
-sequelize.define('foo', {
- name: DataTypes.STRING,
- barId: {
- type: DataTypes.INTEGER,
- allowNull: false,
- references: {
- model: "bars",
- key: "id"
- },
- onDelete: "CASCADE"
- },
-});
-```
-
-In the above example we are manually defining a key that references another model. It's not usual to do this, but if you have to, you should use the table name there. This is because the reference is created upon the referencced table name. In the example above, the plural form was used (`bars`), assuming that the `bar` model was created with the default settings (making its underlying table automatically pluralized).
-
-### When retrieving data from eager loading
-
-When you perform an `include` in a query, the included data will be added to an extra field in the returned objects, according to the following rules:
-
-* When including something from a single association (`hasOne` or `belongsTo`) - the field name will be the singular version of the model name;
-* When including something from a multiple association (`hasMany` or `belongsToMany`) - the field name will be the plural form of the model.
-
-In short, the name of the field will take the most logical form in each situation.
-
-Examples:
-
-```js
-// Assuming Foo.hasMany(Bar)
-const foo = Foo.findOne({ include: Bar });
-// foo.bars will be an array
-// foo.bar will not exist since it doens't make sense
-
-// Assuming Foo.hasOne(Bar)
-const foo = Foo.findOne({ include: Bar });
-// foo.bar will be an object (possibly null if there is no associated model)
-// foo.bars will not exist since it doens't make sense
-
-// And so on.
-```
-
-### Overriding singulars and plurals when defining aliases
-
-When defining an alias for an association, instead of using simply `{ as: 'myAlias' }`, you can pass an object to specify the singular and plural forms:
-
-```js
-Project.belongsToMany(User, {
- as: {
- singular: 'líder',
- plural: 'líderes'
- }
-});
-```
-
-If you know that a model will always use the same alias in associations, you can provide the singular and plural forms directly to the model itself:
-
-```js
-const User = sequelize.define('user', { /* ... */ }, {
- name: {
- singular: 'líder',
- plural: 'líderes',
- }
-});
-Project.belongsToMany(User);
-```
-
-The mixins added to the user instances will use the correct forms. For example, instead of `project.addUser()`, Sequelize will provide `project.getLíder()`. Also, instead of `project.setUsers()`, Sequelize will provide `project.setLíderes()`.
-
-Note: recall that using `as` to change the name of the association will also change the name of the foreign key. Therefore it is recommended to also specify the foreign key(s) involved directly in this case.
-
-```js
-// Example of possible mistake
-Invoice.belongsTo(Subscription, { as: 'TheSubscription' });
-Subscription.hasMany(Invoice);
-```
-
-The first call above will establish a foreign key called `theSubscriptionId` on `Invoice`. However, the second call will also establish a foreign key on `Invoice` (since as we know, `hasMany` calls places foreign keys in the target model) - however, it will be named `subscriptionId`. This way you will have both `subscriptionId` and `theSubscriptionId` columns.
-
-The best approach is to choose a name for the foreign key and place it explicitly in both calls. For example, if `subscription_id` was chosen:
-
-```js
-// Fixed example
-Invoice.belongsTo(Subscription, { as: 'TheSubscription', foreignKey: 'subscription_id' });
-Subscription.hasMany(Invoice, { foreignKey: 'subscription_id' });
-```
\ No newline at end of file
diff --git a/docs/manual/other-topics/optimistic-locking.md b/docs/manual/other-topics/optimistic-locking.md
deleted file mode 100644
index 7db529e43319..000000000000
--- a/docs/manual/other-topics/optimistic-locking.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Optimistic Locking
-
-Sequelize has built-in support for optimistic locking through a model instance version count.
-
-Optimistic locking is disabled by default and can be enabled by setting the `version` property to true in a specific model definition or global model configuration. See [model configuration](models-definition.html#configuration) for more details.
-
-Optimistic locking allows concurrent access to model records for edits and prevents conflicts from overwriting data. It does this by checking whether another process has made changes to a record since it was read and throws an OptimisticLockError when a conflict is detected.
\ No newline at end of file
diff --git a/docs/manual/other-topics/other-data-types.md b/docs/manual/other-topics/other-data-types.md
deleted file mode 100644
index fa0561385520..000000000000
--- a/docs/manual/other-topics/other-data-types.md
+++ /dev/null
@@ -1,192 +0,0 @@
-# Other Data Types
-
-Apart from the most common data types mentioned in the Model Basics guide, Sequelize provides several other data types.
-
-## Ranges (PostgreSQL only)
-
-```js
-DataTypes.RANGE(DataTypes.INTEGER) // int4range
-DataTypes.RANGE(DataTypes.BIGINT) // int8range
-DataTypes.RANGE(DataTypes.DATE) // tstzrange
-DataTypes.RANGE(DataTypes.DATEONLY) // daterange
-DataTypes.RANGE(DataTypes.DECIMAL) // numrange
-```
-
-Since range types have extra information for their bound inclusion/exclusion it's not very straightforward to just use a tuple to represent them in javascript.
-
-When supplying ranges as values you can choose from the following APIs:
-
-```js
-// defaults to inclusive lower bound, exclusive upper bound
-const range = [
- new Date(Date.UTC(2016, 0, 1)),
- new Date(Date.UTC(2016, 1, 1))
-];
-// '["2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")'
-
-// control inclusion
-const range = [
- { value: new Date(Date.UTC(2016, 0, 1)), inclusive: false },
- { value: new Date(Date.UTC(2016, 1, 1)), inclusive: true },
-];
-// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"]'
-
-// composite form
-const range = [
- { value: new Date(Date.UTC(2016, 0, 1)), inclusive: false },
- new Date(Date.UTC(2016, 1, 1)),
-];
-// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")'
-
-const Timeline = sequelize.define('Timeline', {
- range: DataTypes.RANGE(DataTypes.DATE)
-});
-
-await Timeline.create({ range });
-```
-
-However, retrieved range values always come in the form of an array of objects. For example, if the stored value is `("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"]`, after a finder query you will get:
-
-```js
-[
- { value: Date, inclusive: false },
- { value: Date, inclusive: true }
-]
-```
-
-You will need to call `reload()` after updating an instance with a range type or use the `returning: true` option.
-
-### Special Cases
-
-```js
-// empty range:
-Timeline.create({ range: [] }); // range = 'empty'
-
-// Unbounded range:
-Timeline.create({ range: [null, null] }); // range = '[,)'
-// range = '[,"2016-01-01 00:00:00+00:00")'
-Timeline.create({ range: [null, new Date(Date.UTC(2016, 0, 1))] });
-
-// Infinite range:
-// range = '[-infinity,"2016-01-01 00:00:00+00:00")'
-Timeline.create({ range: [-Infinity, new Date(Date.UTC(2016, 0, 1))] });
-```
-
-## BLOBs
-
-```js
-DataTypes.BLOB // BLOB (bytea for PostgreSQL)
-DataTypes.BLOB('tiny') // TINYBLOB (bytea for PostgreSQL)
-DataTypes.BLOB('medium') // MEDIUMBLOB (bytea for PostgreSQL)
-DataTypes.BLOB('long') // LONGBLOB (bytea for PostgreSQL)
-```
-
-The blob datatype allows you to insert data both as strings and as buffers. However, when a blob is retrieved from database with Sequelize, it will always be retrieved as a buffer.
-
-## ENUMs
-
-The ENUM is a data type that accepts only a few values, specified as a list.
-
-```js
-DataTypes.ENUM('foo', 'bar') // An ENUM with allowed values 'foo' and 'bar'
-```
-
-ENUMs can also be specified with the `values` field of the column definition, as follows:
-
-```js
-sequelize.define('foo', {
- states: {
- type: DataTypes.ENUM,
- values: ['active', 'pending', 'deleted']
- }
-});
-```
-
-## JSON (SQLite, MySQL, MariaDB and PostgreSQL only)
-
-The `DataTypes.JSON` data type is only supported for SQLite, MySQL, MariaDB and PostgreSQL. However, there is a minimum support for MSSQL (see below).
-
-### Note for PostgreSQL
-
-The JSON data type in PostgreSQL stores the value as plain text, as opposed to binary representation. If you simply want to store and retrieve a JSON representation, using JSON will take less disk space and less time to build from its input representation. However, if you want to do any operations on the JSON value, you should prefer the JSONB data type described below.
-
-### JSONB (PostgreSQL only)
-
-PostgreSQL also supports a JSONB data type: `DataTypes.JSONB`. It can be queried in three different ways:
-
-```js
-// Nested object
-await Foo.findOne({
- where: {
- meta: {
- video: {
- url: {
- [Op.ne]: null
- }
- }
- }
- }
-});
-
-// Nested key
-await Foo.findOne({
- where: {
- "meta.audio.length": {
- [Op.gt]: 20
- }
- }
-});
-
-// Containment
-await Foo.findOne({
- where: {
- meta: {
- [Op.contains]: {
- site: {
- url: 'http://google.com'
- }
- }
- }
- }
-});
-```
-
-### MSSQL
-
-MSSQL does not have a JSON data type, however it does provide some support for JSON stored as strings through certain functions since SQL Server 2016. Using these functions, you will be able to query the JSON stored in the string, but any returned values will need to be parsed seperately.
-
-```js
-// ISJSON - to test if a string contains valid JSON
-await User.findAll({
- where: sequelize.where(sequelize.fn('ISJSON', sequelize.col('userDetails')), 1)
-})
-
-// JSON_VALUE - extract a scalar value from a JSON string
-await User.findAll({
- attributes: [[ sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), 'address line 1']]
-})
-
-// JSON_VALUE - query a scalar value from a JSON string
-await User.findAll({
- where: sequelize.where(sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), '14, Foo Street')
-})
-
-// JSON_QUERY - extract an object or array
-await User.findAll({
- attributes: [[ sequelize.fn('JSON_QUERY', sequelize.col('userDetails'), '$.address'), 'full address']]
-})
-```
-
-## Others
-
-```js
-DataTypes.ARRAY(/* DataTypes.SOMETHING */) // Defines an array of DataTypes.SOMETHING. PostgreSQL only.
-
-DataTypes.CIDR // CIDR PostgreSQL only
-DataTypes.INET // INET PostgreSQL only
-DataTypes.MACADDR // MACADDR PostgreSQL only
-
-DataTypes.GEOMETRY // Spatial column. PostgreSQL (with PostGIS) or MySQL only.
-DataTypes.GEOMETRY('POINT') // Spatial column with geometry type. PostgreSQL (with PostGIS) or MySQL only.
-DataTypes.GEOMETRY('POINT', 4326) // Spatial column with geometry type and SRID. PostgreSQL (with PostGIS) or MySQL only.
-```
\ No newline at end of file
diff --git a/docs/manual/other-topics/query-interface.md b/docs/manual/other-topics/query-interface.md
deleted file mode 100644
index 5225d0adf1d3..000000000000
--- a/docs/manual/other-topics/query-interface.md
+++ /dev/null
@@ -1,152 +0,0 @@
-# Query Interface
-
-An instance of Sequelize uses something called **Query Interface** to communicate to the database in a dialect-agnostic way. Most of the methods you've learned in this manual are implemented with the help of several methods from the query interface.
-
-The methods from the query interface are therefore lower-level methods; you should use them only if you do not find another way to do it with higher-level APIs from Sequelize. They are, of course, still higher-level than running raw queries directly (i.e., writing SQL by hand).
-
-This guide shows a few examples, but for the full list of what it can do, and for detailed usage of each method, check the [QueryInterface API](../class/lib/dialects/abstract/query-interface.js~QueryInterface.html).
-
-## Obtaining the query interface
-
-From now on, we will call `queryInterface` the singleton instance of the [QueryInterface](../class/lib/dialects/abstract/query-interface.js~QueryInterface.html) class, which is available on your Sequelize instance:
-
-```js
-const { Sequelize, DataTypes } = require('sequelize');
-const sequelize = new Sequelize(/* ... */);
-const queryInterface = sequelize.getQueryInterface();
-```
-
-## Creating a table
-
-```js
-queryInterface.createTable('Person', {
- name: DataTypes.STRING,
- isBetaMember: {
- type: DataTypes.BOOLEAN,
- defaultValue: false,
- allowNull: false
- }
-});
-```
-
-Generated SQL (using SQLite):
-
-```SQL
-CREATE TABLE IF NOT EXISTS `Person` (
- `name` VARCHAR(255),
- `isBetaMember` TINYINT(1) NOT NULL DEFAULT 0
-);
-```
-
-**Note:** Consider defining a Model instead and calling `YourModel.sync()` instead, which is a higher-level approach.
-
-## Adding a column to a table
-
-```js
-queryInterface.addColumn('Person', 'petName', { type: DataTypes.STRING });
-```
-
-Generated SQL (using SQLite):
-
-```sql
-ALTER TABLE `Person` ADD `petName` VARCHAR(255);
-```
-
-## Changing the datatype of a column
-
-```js
-queryInterface.changeColumn('Person', 'foo', {
- type: DataTypes.FLOAT,
- defaultValue: 3.14,
- allowNull: false
-});
-```
-
-Generated SQL (using MySQL):
-
-```sql
-ALTER TABLE `Person` CHANGE `foo` `foo` FLOAT NOT NULL DEFAULT 3.14;
-```
-
-## Removing a column
-
-```js
-queryInterface.removeColumn('Person', 'petName', { /* query options */ });
-```
-
-Generated SQL (using PostgreSQL):
-
-```SQL
-ALTER TABLE "public"."Person" DROP COLUMN "petName";
-```
-
-## Changing and removing columns in SQLite
-
-SQLite does not support directly altering and removing columns. However, Sequelize will try to work around this by recreating the whole table with the help of a backup table, inspired by [these instructions](https://www.sqlite.org/lang_altertable.html#otheralter).
-
-For example:
-
-```js
-// Assuming we have a table in SQLite created as follows:
-queryInterface.createTable('Person', {
- name: DataTypes.STRING,
- isBetaMember: {
- type: DataTypes.BOOLEAN,
- defaultValue: false,
- allowNull: false
- },
- petName: DataTypes.STRING,
- foo: DataTypes.INTEGER
-});
-
-// And we change a column:
-queryInterface.changeColumn('Person', 'foo', {
- type: DataTypes.FLOAT,
- defaultValue: 3.14,
- allowNull: false
-});
-```
-
-The following SQL calls are generated for SQLite:
-
-```sql
-PRAGMA TABLE_INFO(`Person`);
-
-CREATE TABLE IF NOT EXISTS `Person_backup` (
- `name` VARCHAR(255),
- `isBetaMember` TINYINT(1) NOT NULL DEFAULT 0,
- `foo` FLOAT NOT NULL DEFAULT '3.14',
- `petName` VARCHAR(255)
-);
-
-INSERT INTO `Person_backup`
- SELECT
- `name`,
- `isBetaMember`,
- `foo`,
- `petName`
- FROM `Person`;
-
-DROP TABLE `Person`;
-
-CREATE TABLE IF NOT EXISTS `Person` (
- `name` VARCHAR(255),
- `isBetaMember` TINYINT(1) NOT NULL DEFAULT 0,
- `foo` FLOAT NOT NULL DEFAULT '3.14',
- `petName` VARCHAR(255)
-);
-
-INSERT INTO `Person`
- SELECT
- `name`,
- `isBetaMember`,
- `foo`,
- `petName`
- FROM `Person_backup`;
-
-DROP TABLE `Person_backup`;
-```
-
-## Other
-
-As mentioned in the beginning of this guide, there is a lot more to the Query Interface available in Sequelize! Check the [QueryInterface API](../class/lib/dialects/abstract/query-interface.js~QueryInterface.html) for a full list of what can be done.
\ No newline at end of file
diff --git a/docs/manual/other-topics/read-replication.md b/docs/manual/other-topics/read-replication.md
deleted file mode 100644
index 1c16fef1ad74..000000000000
--- a/docs/manual/other-topics/read-replication.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Read Replication
-
-Sequelize supports [read replication](https://en.wikipedia.org/wiki/Replication_%28computing%29#Database_replication), i.e. having multiple servers that you can connect to when you want to do a SELECT query. When you do read replication, you specify one or more servers to act as read replicas, and one server to act as the main writer, which handles all writes and updates and propagates them to the replicas (note that the actual replication process is **not** handled by Sequelize, but should be set up by database backend).
-
-```js
-const sequelize = new Sequelize('database', null, null, {
- dialect: 'mysql',
- port: 3306,
- replication: {
- read: [
- { host: '8.8.8.8', username: 'read-1-username', password: process.env.READ_DB_1_PW },
- { host: '9.9.9.9', username: 'read-2-username', password: process.env.READ_DB_2_PW }
- ],
- write: { host: '1.1.1.1', username: 'write-username', password: process.env.WRITE_DB_PW }
- },
- pool: { // If you want to override the options used for the read/write pool you can do so here
- max: 20,
- idle: 30000
- },
-})
-```
-
-If you have any general settings that apply to all replicas you do not need to provide them for each instance. In the code above, database name and port is propagated to all replicas. The same will happen for user and password, if you leave them out for any of the replicas. Each replica has the following options:`host`,`port`,`username`,`password`,`database`.
-
-Sequelize uses a pool to manage connections to your replicas. Internally Sequelize will maintain two pools created using `pool` configuration.
-
-If you want to modify these, you can pass pool as an options when instantiating Sequelize, as shown above.
-
-Each `write` or `useMaster: true` query will use write pool. For `SELECT` read pool will be used. Read replica are switched using a basic round robin scheduling.
diff --git a/docs/manual/other-topics/resources.md b/docs/manual/other-topics/resources.md
deleted file mode 100644
index 291f25712526..000000000000
--- a/docs/manual/other-topics/resources.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Resources
-
-## Addons & Plugins
-
-### ACL
-
-* [ssacl](https://github.com/pumpupapp/ssacl)
-* [ssacl-attribute-roles](https://github.com/mickhansen/ssacl-attribute-roles)
-* [SequelizeGuard](https://github.com/lotivo/sequelize-acl) - Role, Permission based Authorization for Sequelize.
-
-### Auto Code Generation & Scaffolding
-
-* [meteor modeler](https://www.datensen.com/) - Desktop tool for visual definition of Sequelize models and asssociations.
-* [sequelize-ui](https://github.com/tomjschuster/sequelize-ui) - Online tool for building models, relations and more.
-* [sequelizer](https://github.com/andyforever/sequelizer) - A GUI Desktop App for generating Sequelize models. Support for Mysql, Mariadb, Postgres, Sqlite, Mssql.
-* [sequelize-auto](https://github.com/sequelize/sequelize-auto) Generating models for SequelizeJS via the command line is another choice.
-* [pg-generator](http://www.pg-generator.com/builtin-templates/sequelize/) - Auto generate/scaffold Sequelize models for PostgreSQL database.
-* [sequelizejs-decorators](https://www.npmjs.com/package/sequelizejs-decorators) decorators for composing sequelize models
-
-### Autoloader
-
-* [sequelize-autoload](https://github.com/boxsnake-nodejs/sequelize-autoload) - An autoloader for Sequelize, inspired by [PSR-0](https://www.php-fig.org/psr/psr-0/) and [PSR-4](https://www.php-fig.org/psr/psr-4/).
-
-### Caching
-
-* [sequelize-transparent-cache](https://github.com/DanielHreben/sequelize-transparent-cache)
-
-### Filters
-
-* [sequelize-transforms](https://www.npmjs.com/package/sequelize-transforms) - Add configurable attribute transforms.
-
-### Fixtures / mock data
-
-* [Fixer](https://github.com/olalonde/fixer)
-* [Sequelize-fixtures](https://github.com/domasx2/sequelize-fixtures)
-* [Sequelize-fixture](https://github.com/xudejian/sequelize-fixture)
-
-### Hierarchies
-
-* [sequelize-hierarchy](https://www.npmjs.com/package/sequelize-hierarchy) - Nested hierarchies for Sequelize.
-
-### Historical records / Time travel
-
-* [sequelize-temporal](https://github.com/bonaval/sequelize-temporal) - Temporal tables (aka historical records)
-
-### Migrations
-
-* [umzug](https://github.com/sequelize/umzug)
-
-### Slugification
-
-* [sequelize-slugify](https://www.npmjs.com/package/sequelize-slugify) - Add slugs to sequelize models
-
-### Tokens
-
-* [sequelize-tokenify](https://github.com/pipll/sequelize-tokenify) - Add unique tokens to sequelize models
-
-### Miscellaneous
-
-* [sequelize-deep-update](https://www.npmjs.com/package/sequelize-deep-update) - Update a sequelize instance and its included associated instances with new properties.
-* [sequelize-noupdate-attributes](https://www.npmjs.com/package/sequelize-noupdate-attributes) - Adds no update/readonly attributes support to models.
-* [sequelize-joi](https://www.npmjs.com/package/sequelize-joi) - Allows specifying [Joi](https://github.com/hapijs/joi) validation schema for JSONB model attributes in Sequelize.
diff --git a/docs/manual/other-topics/scopes.md b/docs/manual/other-topics/scopes.md
deleted file mode 100644
index 73eb380364af..000000000000
--- a/docs/manual/other-topics/scopes.md
+++ /dev/null
@@ -1,284 +0,0 @@
-# Scopes
-
-Scopes are used to help you reuse code. You can define commonly used queries, specifying options such as `where`, `include`, `limit`, etc.
-
-This guide concerns model scopes. You might also be interested in the [guide for association scopes](association-scopes.html), which are similar but not the same thing.
-
-## 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
-class Project extends Model {}
-Project.init({
- // Attributes
-}, {
- defaultScope: {
- where: {
- active: true
- }
- },
- scopes: {
- deleted: {
- where: {
- deleted: true
- }
- },
- activeUsers: {
- include: [
- { model: User, where: { active: true } }
- ]
- },
- random() {
- return {
- where: {
- someNumber: Math.random()
- }
- }
- },
- accessLevel(value) {
- return {
- where: {
- accessLevel: {
- [Op.gte]: value
- }
- }
- }
- }
- sequelize,
- modelName: 'project'
- }
-});
-```
-
-You can also add scopes after a model has been defined by calling [`YourModel.addScope`](../class/lib/model.js~Model.html#static-method-addScope). This is especially useful for scopes with includes, where the model in the include might not be defined at the time the other model is being defined.
-
-The default scope is always applied. This means, that with the model definition above, `Project.findAll()` will create the following query:
-
-```sql
-SELECT * FROM projects WHERE active = true
-```
-
-The default scope can be removed by calling `.unscoped()`, `.scope(null)`, or by invoking another scope:
-
-```js
-await Project.scope('deleted').findAll(); // Removes the default scope
-```
-
-```sql
-SELECT * FROM projects WHERE deleted = true
-```
-
-It is also possible to include scoped models in a scope definition. This allows you to avoid duplicating `include`, `attributes` or `where` definitions. Using the above example, and invoking the `active` scope on the included User model (rather than specifying the condition directly in that include object):
-
-```js
-// The `activeUsers` scope defined in the example above could also have been defined this way:
-Project.addScope('activeUsers', {
- include: [
- { model: User.scope('active') }
- ]
-});
-```
-
-## 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
-const DeletedProjects = Project.scope('deleted');
-await DeletedProjects.findAll();
-
-// The above is equivalent to:
-await Project.findAll({
- where: {
- deleted: true
- }
-});
-```
-
-Scopes apply to `.find`, `.findAll`, `.count`, `.update`, `.increment` and `.destroy`.
-
-Scopes which are functions can be invoked in two ways. If the scope does not take any arguments it can be invoked as normally. If the scope takes arguments, pass an object:
-
-```js
-await Project.scope('random', { method: ['accessLevel', 19] }).findAll();
-```
-
-Generated SQL:
-
-```sql
-SELECT * FROM projects WHERE someNumber = 42 AND accessLevel >= 19
-```
-
-## Merging
-
-Several scopes can be applied simultaneously by passing an array of scopes to `.scope`, or by passing the scopes as consecutive arguments.
-
-```js
-// These two are equivalent
-await Project.scope('deleted', 'activeUsers').findAll();
-await Project.scope(['deleted', 'activeUsers']).findAll();
-```
-
-Generated SQL:
-
-```sql
-SELECT * FROM projects
-INNER JOIN users ON projects.userId = users.id
-WHERE projects.deleted = true
-AND users.active = true
-```
-
-If you want to apply another scope alongside the default scope, pass the key `defaultScope` to `.scope`:
-
-```js
-await Project.scope('defaultScope', 'deleted').findAll();
-```
-
-Generated SQL:
-
-```sql
-SELECT * FROM projects WHERE active = true AND deleted = true
-```
-
-When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similarly to [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)), except for `where` and `include`, which will be merged. Consider two scopes:
-
-```js
-YourMode.addScope('scope1', {
- where: {
- firstName: 'bob',
- age: {
- [Op.gt]: 20
- }
- },
- limit: 2
-});
-YourMode.addScope('scope2', {
- where: {
- age: {
- [Op.gt]: 30
- }
- },
- limit: 10
-});
-```
-
-Using `.scope('scope1', 'scope2')` will yield the following WHERE clause:
-
-```sql
-WHERE firstName = 'bob' AND age > 30 LIMIT 10
-```
-
-Note how `limit` and `age` are overwritten by `scope2`, while `firstName` is preserved. The `limit`, `offset`, `order`, `paranoid`, `lock` and `raw` fields are overwritten, while `where` is shallowly merged (meaning that identical keys will be overwritten). The merge strategy for `include` will be discussed later on.
-
-Note that `attributes` keys of multiple applied scopes are merged in such a way that `attributes.exclude` are always preserved. This allows merging several scopes and never leaking sensitive fields in final scope.
-
-The same merge logic applies when passing a find object directly to `findAll` (and similar finders) on a scoped model:
-
-```js
-Project.scope('deleted').findAll({
- where: {
- firstName: 'john'
- }
-})
-```
-
-Generated where clause:
-
-```sql
-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.
-
-### Merging includes
-
-Includes are merged recursively based on the models being included. This is a very powerful merge, added on v5, and is better understood with an example.
-
-Consider the models `Foo`, `Bar`, `Baz` and `Qux`, with One-to-Many associations as follows:
-
-```js
-const Foo = sequelize.define('Foo', { name: Sequelize.STRING });
-const Bar = sequelize.define('Bar', { name: Sequelize.STRING });
-const Baz = sequelize.define('Baz', { name: Sequelize.STRING });
-const Qux = sequelize.define('Qux', { name: Sequelize.STRING });
-Foo.hasMany(Bar, { foreignKey: 'fooId' });
-Bar.hasMany(Baz, { foreignKey: 'barId' });
-Baz.hasMany(Qux, { foreignKey: 'bazId' });
-```
-
-Now, consider the following four scopes defined on Foo:
-
-```js
-Foo.addScope('includeEverything', {
- include: {
- model: Bar,
- include: [{
- model: Baz,
- include: Qux
- }]
- }
-});
-
-Foo.addScope('limitedBars', {
- include: [{
- model: Bar,
- limit: 2
- }]
-});
-
-Foo.addScope('limitedBazs', {
- include: [{
- model: Bar,
- include: [{
- model: Baz,
- limit: 2
- }]
- }]
-});
-
-Foo.addScope('excludeBazName', {
- include: [{
- model: Bar,
- include: [{
- model: Baz,
- attributes: {
- exclude: ['name']
- }
- }]
- }]
-});
-```
-
-These four scopes can be deeply merged easily, for example by calling `Foo.scope('includeEverything', 'limitedBars', 'limitedBazs', 'excludeBazName').findAll()`, which would be entirely equivalent to calling the following:
-
-```js
-await Foo.findAll({
- include: {
- model: Bar,
- limit: 2,
- include: [{
- model: Baz,
- limit: 2,
- attributes: {
- exclude: ['name']
- },
- include: Qux
- }]
- }
-});
-
-// The above is equivalent to:
-await Foo.scope([
- 'includeEverything',
- 'limitedBars',
- 'limitedBazs',
- 'excludeBazName'
-]).findAll();
-```
-
-Observe how the four scopes were merged into one. The includes of scopes are merged based on the model being included. If one scope includes model A and another includes model B, the merged result will include both models A and B. On the other hand, if both scopes include the same model A, but with different options (such as nested includes or other attributes), those will be merged recursively, as shown above.
-
-The merge illustrated above works in the exact same way regardless of the order applied to the scopes. The order would only make a difference if a certain option was set by two different scopes - which is not the case of the above example, since each scope does a different thing.
-
-This merge strategy also works in the exact same way with options passed to `.findAll`, `.findOne` and the like.
\ No newline at end of file
diff --git a/docs/manual/other-topics/sub-queries.md b/docs/manual/other-topics/sub-queries.md
deleted file mode 100644
index 213e4ec3a1ab..000000000000
--- a/docs/manual/other-topics/sub-queries.md
+++ /dev/null
@@ -1,164 +0,0 @@
-# Sub Queries
-
-Consider you have two models, `Post` and `Reaction`, with a One-to-Many relationship set up, so that one post has many reactions:
-
-```js
-const Post = sequelize.define('post', {
- content: DataTypes.STRING
-}, { timestamps: false });
-
-const Reaction = sequelize.define('reaction', {
- type: DataTypes.STRING
-}, { timestamps: false });
-
-Post.hasMany(Reaction);
-Reaction.belongsTo(Post);
-```
-
-*Note: we have disabled timestamps just to have shorter queries for the next examples.*
-
-Let's fill our tables with some data:
-
-```js
-async function makePostWithReactions(content, reactionTypes) {
- const post = await Post.create({ content });
- await Reaction.bulkCreate(
- reactionTypes.map(type => ({ type, postId: post.id }))
- );
- return post;
-}
-
-await makePostWithReactions('Hello World', [
- 'Like', 'Angry', 'Laugh', 'Like', 'Like', 'Angry', 'Sad', 'Like'
-]);
-await makePostWithReactions('My Second Post', [
- 'Laugh', 'Laugh', 'Like', 'Laugh'
-]);
-```
-
-Now, we are ready for examples of the power of subqueries.
-
-Let's say we wanted to compute via SQL a `laughReactionsCount` for each post. We can achieve that with a sub-query, such as the following:
-
-```sql
-SELECT
- *,
- (
- SELECT COUNT(*)
- FROM reactions AS reaction
- WHERE
- reaction.postId = post.id
- AND
- reaction.type = "Laugh"
- ) AS laughReactionsCount
-FROM posts AS post
-```
-
-If we run the above raw SQL query through Sequelize, we get:
-
-```json
-[
- {
- "id": 1,
- "content": "Hello World",
- "laughReactionsCount": 1
- },
- {
- "id": 2,
- "content": "My Second Post",
- "laughReactionsCount": 3
- }
-]
-```
-
-So how can we achieve that with more help from Sequelize, without having to write the whole raw query by hand?
-
-The answer: by combining the `attributes` option of the finder methods (such as `findAll`) with the `sequelize.literal` utility function, that allows you to directly insert arbitrary content into the query without any automatic escaping.
-
-This means that Sequelize will help you with the main, larger query, but you will still have to write that sub-query by yourself:
-
-```js
-Post.findAll({
- attributes: {
- include: [
- [
- // Note the wrapping parentheses in the call below!
- sequelize.literal(`(
- SELECT COUNT(*)
- FROM reactions AS reaction
- WHERE
- reaction.postId = post.id
- AND
- reaction.type = "Laugh"
- )`),
- 'laughReactionsCount'
- ]
- ]
- }
-});
-```
-
-*Important Note: Since `sequelize.literal` inserts arbitrary content without escaping to the query, it deserves very special attention since it may be a source of (major) security vulnerabilities. It should not be used on user-generated content.* However, here, we are using `sequelize.literal` with a fixed string, carefully written by us (the coders). This is ok, since we know what we are doing.
-
-The above gives the following output:
-
-```json
-[
- {
- "id": 1,
- "content": "Hello World",
- "laughReactionsCount": 1
- },
- {
- "id": 2,
- "content": "My Second Post",
- "laughReactionsCount": 3
- }
-]
-```
-
-Success!
-
-## Using sub-queries for complex ordering
-
-This idea can be used to enable complex ordering, such as ordering posts by the number of laugh reactions they have:
-
-```js
-Post.findAll({
- attributes: {
- include: [
- [
- sequelize.literal(`(
- SELECT COUNT(*)
- FROM reactions AS reaction
- WHERE
- reaction.postId = post.id
- AND
- reaction.type = "Laugh"
- )`),
- 'laughReactionsCount'
- ]
- ]
- },
- order: [
- [sequelize.literal('laughReactionsCount'), 'DESC']
- ]
-});
-```
-
-Result:
-
-```json
-[
- {
- "id": 2,
- "content": "My Second Post",
- "laughReactionsCount": 3
- },
- {
- "id": 1,
- "content": "Hello World",
- "laughReactionsCount": 1
- }
-]
-```
\ No newline at end of file
diff --git a/docs/manual/other-topics/transactions.md b/docs/manual/other-topics/transactions.md
deleted file mode 100644
index e24f6d216781..000000000000
--- a/docs/manual/other-topics/transactions.md
+++ /dev/null
@@ -1,311 +0,0 @@
-# Transactions
-
-Sequelize does not use [transactions](https://en.wikipedia.org/wiki/Database_transaction) by default. However, for production-ready usage of Sequelize, you should definitely configure Sequelize to use transactions.
-
-Sequelize supports two ways of using transactions:
-
-1. **Unmanaged transactions:** Committing and rolling back the transaction should be done manually by the user (by calling the appropriate Sequelize methods).
-
-2. **Managed transactions**: Sequelize will automatically rollback the transaction if any error is thrown, or commit the transaction otherwise. Also, if CLS (Continuation Local Storage) is enabled, all queries within the transaction callback will automatically receive the transaction object.
-
-## Unmanaged transactions
-
-Let's start with an example:
-
-```js
-// First, we start a transaction and save it into a variable
-const t = await sequelize.transaction();
-
-try {
-
- // Then, we do some calls passing this transaction as an option:
-
- const user = await User.create({
- firstName: 'Bart',
- lastName: 'Simpson'
- }, { transaction: t });
-
- await user.addSibling({
- firstName: 'Lisa',
- lastName: 'Simpson'
- }, { transaction: t });
-
- // If the execution reaches this line, no errors were thrown.
- // We commit the transaction.
- await t.commit();
-
-} catch (error) {
-
- // If the execution reaches this line, an error was thrown.
- // We rollback the transaction.
- await t.rollback();
-
-}
-```
-
-As shown above, the *unmanaged transaction* approach requires that you commit and rollback the transaction manually, when necessary.
-
-## Managed transactions
-
-Managed transactions handle committing or rolling back the transaction automatically. You start a managed transaction by passing a callback to `sequelize.transaction`. This callback can be `async` (and usually is).
-
-The following will happen in this case:
-
-* Sequelize will automatically start a transaction and obtain a transaction object `t`
-* Then, Sequelize will execute the callback you provided, passing `t` into it
-* If your callback throws, Sequelize will automatically rollback the transaction
-* If your callback succeeds, Sequelize will automatically commit the transaction
-* Only then the `sequelize.transaction` call will settle:
- * Either resolving with the resolution of your callback
- * Or, if your callback throws, rejecting with the thrown error
-
-Example code:
-
-```js
-try {
-
- const result = await sequelize.transaction(async (t) => {
-
- const user = await User.create({
- firstName: 'Abraham',
- lastName: 'Lincoln'
- }, { transaction: t });
-
- await user.setShooter({
- firstName: 'John',
- lastName: 'Boothe'
- }, { transaction: t });
-
- return user;
-
- });
-
- // If the execution reaches this line, the transaction has been committed successfully
- // `result` is whatever was returned from the transaction callback (the `user`, in this case)
-
-} catch (error) {
-
- // If the execution reaches this line, an error occurred.
- // The transaction has already been rolled back automatically by Sequelize!
-
-}
-```
-
-Note that `t.commit()` and `t.rollback()` were not called directly (which is correct).
-
-### Throw errors to rollback
-
-When using the managed transaction you should *never* commit or rollback the transaction manually. If all queries are successful (in the sense of not throwing any error), but you still want to rollback the transaction, you should throw an error yourself:
-
-```js
-await sequelize.transaction(async t => {
- const user = await User.create({
- firstName: 'Abraham',
- lastName: 'Lincoln'
- }, { transaction: t });
-
- // Woops, the query was successful but we still want to roll back!
- // We throw an error manually, so that Sequelize handles everything automatically.
- throw new Error();
-});
-```
-
-### Automatically pass transactions to all queries
-
-In the examples above, the transaction is still manually passed, by passing `{ transaction: t }` as the second argument. To automatically pass the transaction to all queries you must install the [cls-hooked](https://github.com/Jeff-Lewis/cls-hooked) (CLS) module and instantiate a namespace in your own code:
-
-```js
-const cls = require('cls-hooked');
-const namespace = cls.createNamespace('my-very-own-namespace');
-```
-
-To enable CLS you must tell sequelize which namespace to use by using a static method of the sequelize constructor:
-
-```js
-const Sequelize = require('sequelize');
-Sequelize.useCLS(namespace);
-
-new Sequelize(....);
-```
-
-Notice, that the `useCLS()` method is on the *constructor*, not on an instance of sequelize. This means that all instances will share the same namespace, and that CLS is all-or-nothing - you cannot enable it only for some instances.
-
-CLS works like a thread-local storage for callbacks. What this means in practice is that different callback chains can access local variables by using the CLS namespace. When CLS is enabled sequelize will set the `transaction` property on the namespace when a new transaction is created. Since variables set within a callback chain are private to that chain several concurrent transactions can exist at the same time:
-
-```js
-sequelize.transaction((t1) => {
- namespace.get('transaction') === t1; // true
-});
-
-sequelize.transaction((t2) => {
- namespace.get('transaction') === t2; // true
-});
-```
-
-In most case you won't need to access `namespace.get('transaction')` directly, since all queries will automatically look for a transaction on the namespace:
-
-```js
-sequelize.transaction((t1) => {
- // With CLS enabled, the user will be created inside the transaction
- return User.create({ name: 'Alice' });
-});
-```
-
-## 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 belongs to:
-
-**Note:** *SQLite does not support more than one transaction at the same time.*
-
-### With CLS enabled
-
-```js
-sequelize.transaction((t1) => {
- return sequelize.transaction((t2) => {
- // With CLS enabled, queries here will by default use t2.
- // Pass in the `transaction` option to define/alter the transaction they belong to.
- return Promise.all([
- User.create({ name: 'Bob' }, { transaction: null }),
- User.create({ name: 'Mallory' }, { transaction: t1 }),
- User.create({ name: 'John' }) // this would default to t2
- ]);
- });
-});
-```
-
-## Passing options
-
-The `sequelize.transaction` method accepts options.
-
-For unmanaged transactions, just use `sequelize.transaction(options)`.
-
-For managed transactions, use `sequelize.transaction(options, callback)`.
-
-## Isolation levels
-
-The possible isolations levels to use when starting a transaction:
-
-```js
-const { Transaction } = require('sequelize');
-
-// The following are valid isolation levels:
-Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED // "READ UNCOMMITTED"
-Transaction.ISOLATION_LEVELS.READ_COMMITTED // "READ COMMITTED"
-Transaction.ISOLATION_LEVELS.REPEATABLE_READ // "REPEATABLE READ"
-Transaction.ISOLATION_LEVELS.SERIALIZABLE // "SERIALIZABLE"
-```
-
-By default, sequelize uses the isolation level of the database. If you want to use a different isolation level, pass in the desired level as the first argument:
-
-```js
-const { Transaction } = require('sequelize');
-
-await sequelize.transaction({
- isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE
-}, async (t) => {
- // Your code
-});
-```
-
-You can also overwrite the `isolationLevel` setting globally with an option in the Sequelize constructor:
-
-```js
-const { Sequelize, Transaction } = require('sequelize');
-
-const sequelize = new Sequelize('sqlite::memory:', {
- isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE
-});
-```
-
-**Note for MSSQL:** _The `SET ISOLATION LEVEL` queries are not logged since the specified `isolationLevel` is passed directly to `tedious`._
-
-## 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()`, etc. `transaction` should be passed to the option in the second argument.
-
-If unsure, refer to the API documentation for the method you are using to be sure of the signature.
-
-Examples:
-
-```js
-await User.create({ name: 'Foo Bar' }, { transaction: t });
-
-await User.findAll({
- where: {
- name: 'Foo Bar'
- },
- transaction: t
-});
-```
-
-## The `afterCommit` hook
-
-A `transaction` object allows tracking if and when it is committed.
-
-An `afterCommit` hook can be added to both managed and unmanaged transaction objects:
-
-```js
-// Managed transaction:
-await sequelize.transaction(async (t) => {
- t.afterCommit(() => {
- // Your logic
- });
-});
-
-// Unmanaged transaction:
-const t = await sequelize.transaction();
-t.afterCommit(() => {
- // Your logic
-});
-await t.commit();
-```
-
-The callback passed to `afterCommit` can be `async`. In this case:
-
-* For a managed transaction: the `sequelize.transaction` call will wait for it before settling;
-* For an unmanaged transaction: the `t.commit` call will wait for it before settling.
-
-Notes:
-
-* The `afterCommit` hook is not raised if the transaction is rolled back;
-* The `afterCommit` hook does not modify the return value of the transaction (unlike most hooks)
-
-You can use the `afterCommit` hook in conjunction with model hooks to know when a instance is saved and available outside of a transaction
-
-```js
-User.afterSave((instance, options) => {
- if (options.transaction) {
- // Save done within a transaction, wait until transaction is committed to
- // notify listeners the instance has been saved
- options.transaction.afterCommit(() => /* Notify */)
- return;
- }
- // Save done outside a transaction, safe for callers to fetch the updated model
- // Notify
-});
-```
-
-## Locks
-
-Queries within a `transaction` can be performed with locks:
-
-```js
-return User.findAll({
- limit: 1,
- lock: true,
- transaction: t1
-});
-```
-
-Queries within a transaction can skip locked rows:
-
-```js
-return User.findAll({
- limit: 1,
- lock: true,
- skipLocked: true,
- transaction: t2
-});
-```
diff --git a/docs/manual/other-topics/typescript.md b/docs/manual/other-topics/typescript.md
deleted file mode 100644
index 836963e20de6..000000000000
--- a/docs/manual/other-topics/typescript.md
+++ /dev/null
@@ -1,365 +0,0 @@
-# TypeScript
-
-Since v5, Sequelize provides its own TypeScript definitions. Please note that only TS >= 3.1 is supported.
-
-As Sequelize heavily relies on runtime property assignments, TypeScript won't be very useful out of the box. A decent amount of manual type declarations are needed to make models workable.
-
-## Installation
-
-In order to avoid installation bloat for non TS users, you must install the following typing packages manually:
-
-- `@types/node` (this is universally required in node projects)
-- `@types/validator`
-
-## Usage
-
-Example of a minimal TypeScript project with strict type-checking for attributes.
-
-**NOTE:** Keep the following code in sync with `/types/test/typescriptDocs/ModelInit.ts` to ensure it typechecks correctly.
-
-```ts
-import {
- Sequelize,
- Model,
- ModelDefined,
- DataTypes,
- HasManyGetAssociationsMixin,
- HasManyAddAssociationMixin,
- HasManyHasAssociationMixin,
- Association,
- HasManyCountAssociationsMixin,
- HasManyCreateAssociationMixin,
- Optional,
-} from "sequelize";
-
-const sequelize = new Sequelize("mysql://root:asd123@localhost:3306/mydb");
-
-// These are all the attributes in the User model
-interface UserAttributes {
- id: number;
- name: string;
- preferredName: string | null;
-}
-
-// Some attributes are optional in `User.build` and `User.create` calls
-interface UserCreationAttributes extends Optional {}
-
-class User extends Model
- implements UserAttributes {
- public id!: number; // Note that the `null assertion` `!` is required in strict mode.
- public name!: string;
- public preferredName!: string | null; // for nullable fields
-
- // timestamps!
- public readonly createdAt!: Date;
- public readonly updatedAt!: Date;
-
- // Since TS cannot determine model association at compile time
- // we have to declare them here purely virtually
- // these will not exist until `Model.init` was called.
- public getProjects!: HasManyGetAssociationsMixin; // Note the null assertions!
- public addProject!: HasManyAddAssociationMixin;
- public hasProject!: HasManyHasAssociationMixin;
- public countProjects!: HasManyCountAssociationsMixin;
- public createProject!: HasManyCreateAssociationMixin;
-
- // You can also pre-declare possible inclusions, these will only be populated if you
- // actively include a relation.
- public readonly projects?: Project[]; // Note this is optional since it's only populated when explicitly requested in code
-
- public static associations: {
- projects: Association;
- };
-}
-
-interface ProjectAttributes {
- id: number;
- ownerId: number;
- name: string;
-}
-
-interface ProjectCreationAttributes extends Optional {}
-
-class Project extends Model
- implements ProjectAttributes {
- public id!: number;
- public ownerId!: number;
- public name!: string;
-
- public readonly createdAt!: Date;
- public readonly updatedAt!: Date;
-}
-
-interface AddressAttributes {
- userId: number;
- address: string;
-}
-
-// You can write `extends Model` instead,
-// but that will do the exact same thing as below
-class Address extends Model implements AddressAttributes {
- public userId!: number;
- public address!: string;
-
- public readonly createdAt!: Date;
- public readonly updatedAt!: Date;
-}
-
-// You can also define modules in a functional way
-interface NoteAttributes {
- id: number;
- title: string;
- content: string;
-}
-
-// You can also set multiple attributes optional at once
-interface NoteCreationAttributes extends Optional {};
-
-Project.init(
- {
- id: {
- type: DataTypes.INTEGER.UNSIGNED,
- autoIncrement: true,
- primaryKey: true,
- },
- ownerId: {
- type: DataTypes.INTEGER.UNSIGNED,
- allowNull: false,
- },
- name: {
- type: new DataTypes.STRING(128),
- allowNull: false,
- },
- },
- {
- sequelize,
- tableName: "projects",
- }
-);
-
-User.init(
- {
- id: {
- type: DataTypes.INTEGER.UNSIGNED,
- autoIncrement: true,
- primaryKey: true,
- },
- name: {
- type: new DataTypes.STRING(128),
- allowNull: false,
- },
- preferredName: {
- type: new DataTypes.STRING(128),
- allowNull: true,
- },
- },
- {
- tableName: "users",
- sequelize, // passing the `sequelize` instance is required
- }
-);
-
-Address.init(
- {
- userId: {
- type: DataTypes.INTEGER.UNSIGNED,
- },
- address: {
- type: new DataTypes.STRING(128),
- allowNull: false,
- },
- },
- {
- tableName: "address",
- sequelize, // passing the `sequelize` instance is required
- }
-);
-
-// And with a functional approach defining a module looks like this
-const Note: ModelDefined<
- NoteAttributes,
- NoteCreationAttributes
-> = sequelize.define(
- 'Note',
- {
- id: {
- type: DataTypes.INTEGER.UNSIGNED,
- autoIncrement: true,
- primaryKey: true,
- },
- title: {
- type: new DataTypes.STRING(64),
- defaultValue: 'Unnamed Note',
- },
- content: {
- type: new DataTypes.STRING(4096),
- allowNull: false,
- },
- },
- {
- tableName: 'notes',
- }
-);
-
-// Here we associate which actually populates out pre-declared `association` static and other methods.
-User.hasMany(Project, {
- sourceKey: "id",
- foreignKey: "ownerId",
- as: "projects", // this determines the name in `associations`!
-});
-
-Address.belongsTo(User, { targetKey: "id" });
-User.hasOne(Address, { sourceKey: "id" });
-
-async function doStuffWithUser() {
- const newUser = await User.create({
- name: "Johnny",
- preferredName: "John",
- });
- console.log(newUser.id, newUser.name, newUser.preferredName);
-
- const project = await newUser.createProject({
- name: "first!",
- });
-
- const ourUser = await User.findByPk(1, {
- include: [User.associations.projects],
- rejectOnEmpty: true, // Specifying true here removes `null` from the return type!
- });
-
- // Note the `!` null assertion since TS can't know if we included
- // the model or not
- console.log(ourUser.projects![0].name);
-}
-```
-
-### Usage without strict types for attributes
-
-The typings for Sequelize v5 allowed you to define models without specifying types for the attributes. This is still possible for backwards compatibility and for cases where you feel strict typing for attributes isn't worth it.
-
-**NOTE:** Keep the following code in sync with `typescriptDocs/ModelInitNoAttributes.ts` to ensure
-it typechecks correctly.
-
-```ts
-import { Sequelize, Model, DataTypes } from "sequelize";
-
-const sequelize = new Sequelize("mysql://root:asd123@localhost:3306/mydb");
-
-class User extends Model {
- public id!: number; // Note that the `null assertion` `!` is required in strict mode.
- public name!: string;
- public preferredName!: string | null; // for nullable fields
-}
-
-User.init(
- {
- id: {
- type: DataTypes.INTEGER.UNSIGNED,
- autoIncrement: true,
- primaryKey: true,
- },
- name: {
- type: new DataTypes.STRING(128),
- allowNull: false,
- },
- preferredName: {
- type: new DataTypes.STRING(128),
- allowNull: true,
- },
- },
- {
- tableName: "users",
- sequelize, // passing the `sequelize` instance is required
- }
-);
-
-async function doStuffWithUserModel() {
- const newUser = await User.create({
- name: "Johnny",
- preferredName: "John",
- });
- console.log(newUser.id, newUser.name, newUser.preferredName);
-
- const foundUser = await User.findOne({ where: { name: "Johnny" } });
- if (foundUser === null) return;
- console.log(foundUser.name);
-}
-```
-
-## Usage of `sequelize.define`
-
-In Sequelize versions before v5, the default way of defining a model involved using `sequelize.define`. It's still possible to define models with that, and you can also add typings to these models using interfaces.
-
-**NOTE:** Keep the following code in sync with `typescriptDocs/Define.ts` to ensure
-it typechecks correctly.
-
-```ts
-import { Sequelize, Model, DataTypes, Optional } from "sequelize";
-
-const sequelize = new Sequelize("mysql://root:asd123@localhost:3306/mydb");
-
-// We recommend you declare an interface for the attributes, for stricter typechecking
-interface UserAttributes {
- id: number;
- name: string;
-}
-
-// Some fields are optional when calling UserModel.create() or UserModel.build()
-interface UserCreationAttributes extends Optional {}
-
-// We need to declare an interface for our model that is basically what our class would be
-interface UserInstance
- extends Model,
- UserAttributes {}
-
-const UserModel = sequelize.define("User", {
- id: {
- primaryKey: true,
- type: DataTypes.INTEGER.UNSIGNED,
- },
- name: {
- type: DataTypes.STRING,
- },
-});
-
-async function doStuff() {
- const instance = await UserModel.findByPk(1, {
- rejectOnEmpty: true,
- });
- console.log(instance.id);
-}
-```
-
-If you're comfortable with somewhat less strict typing for the attributes on a model, you can save some code by defining the Instance to just extend `Model` without any attributes in the generic types.
-
-**NOTE:** Keep the following code in sync with `typescriptDocs/DefineNoAttributes.ts` to ensure
-it typechecks correctly.
-
-```ts
-import { Sequelize, Model, DataTypes } from "sequelize";
-
-const sequelize = new Sequelize("mysql://root:asd123@localhost:3306/mydb");
-
-// We need to declare an interface for our model that is basically what our class would be
-interface UserInstance extends Model {
- id: number;
- name: string;
-}
-
-const UserModel = sequelize.define("User", {
- id: {
- primaryKey: true,
- type: DataTypes.INTEGER.UNSIGNED,
- },
- name: {
- type: DataTypes.STRING,
- },
-});
-
-async function doStuff() {
- const instance = await UserModel.findByPk(1, {
- rejectOnEmpty: true,
- });
- console.log(instance.id);
-}
-```
diff --git a/docs/manual/other-topics/upgrade-to-v6.md b/docs/manual/other-topics/upgrade-to-v6.md
deleted file mode 100644
index fd047d5cd694..000000000000
--- a/docs/manual/other-topics/upgrade-to-v6.md
+++ /dev/null
@@ -1,236 +0,0 @@
-# Upgrade to v6
-
-Sequelize v6 is the next major release after v5. Below is a list of breaking changes to help you upgrade.
-
-## Breaking Changes
-
-### Support for Node 10 and up
-
-Sequelize v6 will only support Node 10 and up [#10821](https://github.com/sequelize/sequelize/issues/10821).
-
-### CLS
-
-You should now use [cls-hooked](https://github.com/Jeff-Lewis/cls-hooked) package for CLS support.
-
-```js
-const cls = require("cls-hooked");
-const namespace = cls.createNamespace("....");
-const Sequelize = require("sequelize");
-
-Sequelize.useCLS(namespace);
-```
-
-### Database Engine Support
-
-We have updated our minimum supported database engine versions. Using older database engine will show `SEQUELIZE0006` deprecation warning. Please check [ENGINE.md](https://github.com/sequelize/sequelize/blob/main/ENGINE.md) for version table.
-
-### Sequelize
-
-- Bluebird has been removed. Internally all methods are now using async/await. Public API now returns native promises. Thanks to [Andy Edwards](https://github.com/jedwards1211) for this refactor work.
-- `Sequelize.Promise` is no longer available.
-- `sequelize.import` method has been removed. CLI users should update to `sequelize-cli@6`.
-- All instances of QueryInterface and QueryGenerator have been renamed to their lowerCamelCase variants eg. queryInterface and queryGenerator when used as property names on Model and Dialect, the class names remain the same.
-
-### Model
-
-#### `options.returning`
-
-Option `returning: true` will no longer return attributes that are not defined in the model. Old behavior can be achieved by using `returning: ['*']` instead.
-
-#### `Model.changed()`
-
-This method now tests for equality with [`_.isEqual`](https://lodash.com/docs/4.17.15#isEqual) and is now deep aware for JSON objects. Modifying a nested value for a JSON object won't mark it as changed (since it is still the same object).
-
-```js
-const instance = await MyModel.findOne();
-
-instance.myJsonField.someProperty = 12345; // Changed from something else to 12345
-console.log(instance.changed()); // false
-
-await instance.save(); // this will not save anything
-
-instance.changed("myJsonField", true);
-console.log(instance.changed()); // ['myJsonField']
-
-await instance.save(); // will save
-```
-
-#### `Model.bulkCreate()`
-
-This method now throws `Sequelize.AggregateError` instead of `Bluebird.AggregateError`. All errors are now exposed as `errors` key.
-
-#### `Model.upsert()`
-
-Native upsert is now supported for all dialects.
-
-```js
-const [instance, created] = await MyModel.upsert({});
-```
-
-Signature for this method has been changed to `Promise`. First index contains upserted `instance`, second index contains a boolean (or `null`) indicating if record was created or updated. For SQLite/Postgres, `created` value will always be `null`.
-
-- MySQL - Implemented with ON DUPLICATE KEY UPDATE
-- PostgreSQL - Implemented with ON CONFLICT DO UPDATE
-- SQLite - Implemented with ON CONFLICT DO UPDATE
-- MSSQL - Implemented with MERGE statement
-
-_Note for Postgres users:_ If upsert payload contains PK field, then PK will be used as the conflict target. Otherwise first unique constraint will be selected as the conflict key.
-
-### QueryInterface
-
-#### `addConstraint`
-
-This method now only takes 2 parameters, `tableName` and `options`. Previously the second parameter could be a list of column names to apply the constraint to, this list must now be passed as `options.fields` property.
-
-## Changelog
-
-### 6.0.0-beta.7
-
-- docs(associations): belongs to many create with through table
-- docs(query-interface): fix broken links [#12272](https://github.com/sequelize/sequelize/pull/12272)
-- docs(sequelize): omitNull only works for CREATE/UPDATE queries
-- docs: asyncify [#12297](https://github.com/sequelize/sequelize/pull/12297)
-- docs: responsive [#12308](https://github.com/sequelize/sequelize/pull/12308)
-- docs: update feature request template
-- feat(postgres): native upsert [#12301](https://github.com/sequelize/sequelize/pull/12301)
-- feat(sequelize): allow passing dialectOptions.options from url [#12404](https://github.com/sequelize/sequelize/pull/12404)
-- fix(include): check if attributes specified for included through model [#12316](https://github.com/sequelize/sequelize/pull/12316)
-- fix(model.destroy): return 0 with truncate [#12281](https://github.com/sequelize/sequelize/pull/12281)
-- fix(mssql): empty order array generates invalid FETCH statement [#12261](https://github.com/sequelize/sequelize/pull/12261)
-- fix(postgres): parse enums correctly when describing a table [#12409](https://github.com/sequelize/sequelize/pull/12409)
-- fix(query): ensure correct return signature for QueryTypes.RAW [#12305](https://github.com/sequelize/sequelize/pull/12305)
-- fix(query): preserve cls context for logger [#12328](https://github.com/sequelize/sequelize/pull/12328)
-- fix(query-generator): do not generate GROUP BY clause if options.group is empty [#12343](https://github.com/sequelize/sequelize/pull/12343)
-- fix(reload): include default scope [#12399](https://github.com/sequelize/sequelize/pull/12399)
-- fix(types): add Association into OrderItem type [#12332](https://github.com/sequelize/sequelize/pull/12332)
-- fix(types): add clientMinMessages to Options interface [#12375](https://github.com/sequelize/sequelize/pull/12375)
-- fix(types): transactionType in Options [#12377](https://github.com/sequelize/sequelize/pull/12377)
-- fix(types): add support for optional values in "where" clauses [#12337](https://github.com/sequelize/sequelize/pull/12337)
-- fix(types): add missing fields to 'FindOrCreateType' [#12338](https://github.com/sequelize/sequelize/pull/12338)
-- fix: add missing sql and parameters properties to some query errors [#12299](https://github.com/sequelize/sequelize/pull/12299)
-- fix: remove custom inspect [#12262](https://github.com/sequelize/sequelize/pull/12262)
-- refactor: cleanup query generators [#12304](https://github.com/sequelize/sequelize/pull/12304)
-
-### 6.0.0-beta.6
-
-- docs(add-constraint): options.fields support
-- docs(association): document uniqueKey for belongs to many [#12166](https://github.com/sequelize/sequelize/pull/12166)
-- docs(association): options.through.where support
-- docs(association): use and instead of 'a nd' [#12191](https://github.com/sequelize/sequelize/pull/12191)
-- docs(association): use correct scope name [#12204](https://github.com/sequelize/sequelize/pull/12204)
-- docs(manuals): avoid duplicate header ids [#12201](https://github.com/sequelize/sequelize/pull/12201)
-- docs(model): correct syntax error in example code [#12137](https://github.com/sequelize/sequelize/pull/12137)
-- docs(query-interface): removeIndex indexNameOrAttributes [#11947](https://github.com/sequelize/sequelize/pull/11947)
-- docs(resources): add sequelize-guard library [#12235](https://github.com/sequelize/sequelize/pull/12235)
-- docs(typescript): fix confusing comments [#12226](https://github.com/sequelize/sequelize/pull/12226)
-- docs(v6-guide): bluebird removal API changes
-- docs: database version support info [#12168](https://github.com/sequelize/sequelize/pull/12168)
-- docs: remove remaining bluebird references [#12167](https://github.com/sequelize/sequelize/pull/12167)
-- feat(belongs-to-many): allow creation of paranoid join tables [#12088](https://github.com/sequelize/sequelize/pull/12088)
-- feat(belongs-to-many): get/has/count for paranoid join table [#12256](https://github.com/sequelize/sequelize/pull/12256)
-- feat(pool): expose maxUses pool config option [#12101](https://github.com/sequelize/sequelize/pull/12101)
-- feat(postgres): minify include aliases over limit [#11940](https://github.com/sequelize/sequelize/pull/11940)
-- feat(sequelize): handle query string host value [#12041](https://github.com/sequelize/sequelize/pull/12041)
-- fix(associations): ensure correct schema on all generated attributes [#12258](https://github.com/sequelize/sequelize/pull/12258)
-- fix(docs/instances): use correct variable for increment [#12087](https://github.com/sequelize/sequelize/pull/12087)
-- fix(include): separate queries are not sub-queries [#12144](https://github.com/sequelize/sequelize/pull/12144)
-- fix(model): fix unchained promise in association logic in bulkCreate [#12163](https://github.com/sequelize/sequelize/pull/12163)
-- fix(model): updateOnDuplicate handles composite keys [#11984](https://github.com/sequelize/sequelize/pull/11984)
-- fix(model.count): distinct without any column generates invalid SQL [#11946](https://github.com/sequelize/sequelize/pull/11946)
-- fix(model.reload): ignore options.where and always use this.where() [#12211](https://github.com/sequelize/sequelize/pull/12211)
-- fix(mssql) insert record failure because of BOOLEAN column type [#12090](https://github.com/sequelize/sequelize/pull/12090)
-- fix(mssql): cast sql_variant in query generator [#11994](https://github.com/sequelize/sequelize/pull/11994)
-- fix(mssql): dont use OUTPUT INSERTED for update without returning [#12260](https://github.com/sequelize/sequelize/pull/12260)
-- fix(mssql): duplicate order in FETCH/NEXT queries [#12257](https://github.com/sequelize/sequelize/pull/12257)
-- fix(mssql): set correct scale for float [#11962](https://github.com/sequelize/sequelize/pull/11962)
-- fix(mssql): tedious v9 requires connect call [#12182](https://github.com/sequelize/sequelize/pull/12182)
-- fix(mssql): use uppercase for engine table and columns [#12212](https://github.com/sequelize/sequelize/pull/12212)
-- fix(pool): show deprecation when engine is not supported [#12218](https://github.com/sequelize/sequelize/pull/12218)
-- fix(postgres): addColumn support ARRAY(ENUM) [#12259](https://github.com/sequelize/sequelize/pull/12259)
-- fix(query): do not bind \$ used within a whole-word [#12250](https://github.com/sequelize/sequelize/pull/12250)
-- fix(query-generator): handle literal for substring based operators [#12210](https://github.com/sequelize/sequelize/pull/12210)
-- fix(query-interface): allow passing null for query interface insert [#11931](https://github.com/sequelize/sequelize/pull/11931)
-- fix(query-interface): allow sequelize.fn and sequelize.literal in fields of IndexesOptions [#12224](https://github.com/sequelize/sequelize/pull/12224)
-- fix(scope): don't modify original scope definition [#12207](https://github.com/sequelize/sequelize/pull/12207)
-- fix(sqlite): multiple primary keys results in syntax error [#12237](https://github.com/sequelize/sequelize/pull/12237)
-- fix(sync): pass options to all query methods [#12208](https://github.com/sequelize/sequelize/pull/12208)
-- fix(typings): add type_helpers to file list [#12000](https://github.com/sequelize/sequelize/pull/12000)
-- fix(typings): correct Model.init return type [#12148](https://github.com/sequelize/sequelize/pull/12148)
-- fix(typings): fn is assignable to where [#12040](https://github.com/sequelize/sequelize/pull/12040)
-- fix(typings): getForeignKeysForTables argument definition [#12084](https://github.com/sequelize/sequelize/pull/12084)
-- fix(typings): make between operator accept date ranges [#12162](https://github.com/sequelize/sequelize/pull/12162)
-- refactor(ci): improve database wait script [#12132](https://github.com/sequelize/sequelize/pull/12132)
-- refactor(tsd-test-setup): add & setup dtslint [#11879](https://github.com/sequelize/sequelize/pull/11879)
-- refactor: move all dialect conditional logic into subclass [#12217](https://github.com/sequelize/sequelize/pull/12217)
-- refactor: remove sequelize.import helper [#12175](https://github.com/sequelize/sequelize/pull/12175)
-- refactor: use native versions [#12159](https://github.com/sequelize/sequelize/pull/12159)
-- refactor: use object spread instead of Object.assign [#12213](https://github.com/sequelize/sequelize/pull/12213)
-
-### 6.0.0-beta.5
-
-- fix(find-all): throw on empty attributes [#11867](https://github.com/sequelize/sequelize/pull/11867)
-- fix(types): `queryInterface.addIndex` [#11844](https://github.com/sequelize/sequelize/pull/11844)
-- fix(types): `plain` option in `sequelize.query` [#11596](https://github.com/sequelize/sequelize/pull/11596)
-- fix(types): correct overloaded method order [#11727](https://github.com/sequelize/sequelize/pull/11727)
-- fix(types): `comparator` arg of `Sequelize.where` [#11843](https://github.com/sequelize/sequelize/pull/11843)
-- fix(types): fix BelongsToManyGetAssociationsMixinOptions [#11818](https://github.com/sequelize/sequelize/pull/11818)
-- fix(types): adds `hooks` to `CreateOptions` [#11736](https://github.com/sequelize/sequelize/pull/11736)
-- fix(increment): broken queries [#11852](https://github.com/sequelize/sequelize/pull/11852)
-- fix(associations): gets on many-to-many with non-primary target key [#11778](https://github.com/sequelize/sequelize11778/pull/)
-- fix: properly select SRID if present [#11763](https://github.com/sequelize/sequelize/pull/11763)
-- feat(sqlite): automatic path provision for `options.storage` [#11853](https://github.com/sequelize/sequelize/pull/11853)
-- feat(postgres): `idle_in_transaction_session_timeout` connection option [#11775](https://github.com/sequelize/sequelize11775/pull/)
-- feat(index): improve to support multiple fields with operator [#11934](https://github.com/sequelize/sequelize/pull/11934)
-- docs(transactions): fix addIndex example and grammar [#11759](https://github.com/sequelize/sequelize/pull/11759)
-- docs(raw-queries): remove outdated info [#11833](https://github.com/sequelize/sequelize/pull/11833)
-- docs(optimistic-locking): fix missing manual [#11850](https://github.com/sequelize/sequelize/pull/11850)
-- docs(model): findOne return value for empty result [#11762](https://github.com/sequelize/sequelize/pull/11762)
-- docs(model-querying-basics.md): add some commas [#11891](https://github.com/sequelize/sequelize/pull/11891)
-- docs(manuals): fix missing models-definition page [#11838](https://github.com/sequelize/sequelize/pull/11838)
-- docs(manuals): extensive rewrite [#11825](https://github.com/sequelize/sequelize/pull/11825)
-- docs(dialect-specific): add MSSQL domain auth example [#11799](https://github.com/sequelize/sequelize/pull/11799)
-- docs(associations): fix typos in assocs manual [#11888](https://github.com/sequelize/sequelize/pull/11888)
-- docs(associations): fix typo [#11869](https://github.com/sequelize/sequelize/pull/11869)
-
-### 6.0.0-beta.4
-
-- feat(sync): allow to bypass drop statements when sync with alter enabled [#11708](https://github.com/sequelize/sequelize/pull/11708)
-- fix(model): injectDependentVirtualAttrs on included models [#11713](https://github.com/sequelize/sequelize/pull/11713)
-- fix(model): generate ON CONFLICT ... DO UPDATE correctly [#11666](https://github.com/sequelize/sequelize/pull/11666)
-- fix(mssql): optimize formatError RegEx [#11725](https://github.com/sequelize/sequelize/pull/11725)
-- fix(types): add getForeignKeyReferencesForTable type [#11738](https://github.com/sequelize/sequelize/pull/11738)
-- fix(types): add 'restore' hooks to types [#11730](https://github.com/sequelize/sequelize/pull/11730)
-- fix(types): added 'fieldMaps' to QueryOptions typings [#11702](https://github.com/sequelize/sequelize/pull/11702)
-- fix(types): add isSoftDeleted to Model [#11628](https://github.com/sequelize/sequelize/pull/11628)
-- fix(types): fix upsert typing [#11674](https://github.com/sequelize/sequelize/pull/11674)
-- fix(types): specified 'this' for getters and setters in fields [#11648](https://github.com/sequelize/sequelize/pull/11648)
-- fix(types): add paranoid to UpdateOptions interface [#11647](https://github.com/sequelize/sequelize/pull/11647)
-- fix(types): include 'as' in IncludeThroughOptions definition [#11624](https://github.com/sequelize/sequelize/pull/11624)
-- fix(types): add Includeable to IncludeOptions.include type [#11622](https://github.com/sequelize/sequelize/pull/11622)
-- fix(types): transaction lock [#11620](https://github.com/sequelize/sequelize/pull/11620)
-- fix(sequelize.fn): escape dollarsign (#11533) [#11606](https://github.com/sequelize/sequelize/pull/11606)
-- fix(types): add nested to Includeable [#11354](https://github.com/sequelize/sequelize/pull/11354)
-- fix(types): add date to where [#11612](https://github.com/sequelize/sequelize/pull/11612)
-- fix(types): add getDatabaseName (#11431) [#11614](https://github.com/sequelize/sequelize/pull/11614)
-- fix(types): beforeDestroy [#11618](https://github.com/sequelize/sequelize/pull/11618)
-- fix(types): query-interface table schema [#11582](https://github.com/sequelize/sequelize/pull/11582)
-- docs: README.md [#11698](https://github.com/sequelize/sequelize/pull/11698)
-- docs(sequelize): detail options.retry usage [#11643](https://github.com/sequelize/sequelize/pull/11643)
-- docs: clarify logging option in Sequelize constructor [#11653](https://github.com/sequelize/sequelize/pull/11653)
-- docs(migrations): fix syntax error in example [#11626](https://github.com/sequelize/sequelize/pull/11626)
-- docs: describe logging option [#11654](https://github.com/sequelize/sequelize/pull/11654)
-- docs(transaction): fix typo [#11659](https://github.com/sequelize/sequelize/pull/11659)
-- docs(hooks): add info about belongs-to-many [#11601](https://github.com/sequelize/sequelize/pull/11601)
-- docs(associations): fix typo [#11592](https://github.com/sequelize/sequelize/pull/11592)
-
-### 6.0.0-beta.3
-
-- feat: support cls-hooked / tests [#11584](https://github.com/sequelize/sequelize/pull/11584)
-
-### 6.0.0-beta.2
-
-- feat(postgres): change returning option to only return model attributes [#11526](https://github.com/sequelize/sequelize/pull/11526)
-- fix(associations): allow binary key for belongs-to-many [#11578](https://github.com/sequelize/sequelize/pull/11578)
-- fix(postgres): always replace returning statement for upsertQuery
-- fix(model): make .changed() deep aware [#10851](https://github.com/sequelize/sequelize/pull/10851)
-- change: use node 10 [#11580](https://github.com/sequelize/sequelize/pull/11580)
diff --git a/docs/manual/other-topics/whos-using.md b/docs/manual/other-topics/whos-using.md
deleted file mode 100644
index b872943a7bac..000000000000
--- a/docs/manual/other-topics/whos-using.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Who's using sequelize?
-
-[](http://www.walmartlabs.com/)
-
-> ... we are avid users of sequelize (and have been for the past 18 months) (Feb 2017)
-
-
-
-[](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](http://github.com/mickhansen/graphql-sequelize)), and for all our background workers.
-
-
-
-[](https://connectedcars.io/)
-
-
-
-[](https://bitovi.com)
-
-> We have used Sequelize in enterprise projects for some of our Fortune 100 and Fortune 500 clients. It is used in deployments that are depended on by hundreds of millions of devices every year.
-
-
-
-[](https://www.ermeshotels.com)
-
-> Using Sequelize in production for two different apps with 30k+ daily users by 2 years. I doubt there is something better at this moment in terms of productivity and features.
diff --git a/docs/transforms/group-data-types.js b/docs/transforms/group-data-types.js
index 2aebe09b5c2e..b5fdd4411555 100644
--- a/docs/transforms/group-data-types.js
+++ b/docs/transforms/group-data-types.js
@@ -4,7 +4,7 @@ function groupDataTypes($, path) {
let firstLi;
$('nav a').each(function() {
/* eslint-disable no-invalid-this */
- if ($(this).attr('href').startsWith('class/lib/data-types.js~')) {
+ if ($(this).attr('href').startsWith('class/src/data-types.js~')) {
const li = $(this).closest('li');
if (!firstLi) {
firstLi = li;
@@ -19,7 +19,7 @@ function groupDataTypes($, path) {
if (path.endsWith('identifiers.html')) {
const rowsToDelete = [];
$('table.summary td a').each(function() {
- if ($(this).attr('href').startsWith('class/lib/data-types.js~')) {
+ if ($(this).attr('href').startsWith('class/src/data-types.js~')) {
rowsToDelete.push($(this).closest('tr'));
}
});
@@ -32,4 +32,4 @@ function groupDataTypes($, path) {
module.exports = function transform($, path) {
groupDataTypes($, path);
$('nav li[data-ice=doc]:first-child').css('margin-top', '15px');
-};
\ No newline at end of file
+};
diff --git a/docs/transforms/header-customization.js b/docs/transforms/header-customization.js
index 4f9dfcf1477b..26c320489ed8 100644
--- a/docs/transforms/header-customization.js
+++ b/docs/transforms/header-customization.js
@@ -5,19 +5,11 @@ module.exports = function transform($) {
const githubLogoImage = $('header a img[src="./image/github.png"]');
apiReferenceLink
- .text('API Reference')
+ .attr('href', '/docs/v6/intro/')
+ .text('Guides')
.addClass('api-reference-link');
githubLogoImage
.css('width', '30px')
.attr('width', '30px');
-
- githubLogoImage.closest('a')
- .css('position', '')
- .css('top', '')
- .after(`
-
-
-
- `);
};
diff --git a/esdoc-ts.js b/esdoc-ts.js
new file mode 100644
index 000000000000..ee3f1f691562
--- /dev/null
+++ b/esdoc-ts.js
@@ -0,0 +1,16 @@
+const path = require('path');
+const { transformSync } = require('esbuild');
+
+module.exports = {
+ onHandleCode({ data }) {
+ if (path.extname(data.filePath) === '.ts') {
+ // @preserve tells esbuild not to omit the comment. This is intended for legal comments,
+ // but works here too as a hack.
+ data.code = transformSync(data.code.replace(/\/\*\*/g, '/**@preserve'), {
+ target: 'node10',
+ format: 'cjs',
+ loader: 'ts'
+ }).code.replace(/\/\*\*@preserve/g, '/**');
+ }
+ }
+};
diff --git a/index.js b/index.js
index 31e6c23becdd..c41e6e3916a0 100644
--- a/index.js
+++ b/index.js
@@ -1,8 +1,12 @@
'use strict';
+// TODO [>=7]: remove me. I've been moved to 'exports' in package.json
+
/**
- * The entry point.
+ * A Sequelize module that contains the sequelize entry point.
*
- * @module Sequelize
+ * @module sequelize
*/
-module.exports = require('./lib/sequelize');
+
+/** Exports the sequelize entry point. */
+module.exports = require('./lib');
diff --git a/lib/dialects/abstract/query-generator/helpers/quote.js b/lib/dialects/abstract/query-generator/helpers/quote.js
deleted file mode 100644
index 19a1d983b5e5..000000000000
--- a/lib/dialects/abstract/query-generator/helpers/quote.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * Quote helpers implement quote ability for all dialects.
- * These are basic block of query building
- *
- * Its better to implement all dialect implementation together here. Which will allow
- * even abstract generator to use them by just specifying dialect type.
- *
- * Defining these helpers in each query dialect will leave
- * code in dual dependency of abstract <-> specific dialect
- */
-
-'use strict';
-
-const Utils = require('../../../../utils');
-
-/**
- * list of reserved words in PostgreSQL 10
- * source: https://www.postgresql.org/docs/10/static/sql-keywords-appendix.html
- *
- * @private
- */
-const postgresReservedWords = 'all,analyse,analyze,and,any,array,as,asc,asymmetric,authorization,binary,both,case,cast,check,collate,collation,column,concurrently,constraint,create,cross,current_catalog,current_date,current_role,current_schema,current_time,current_timestamp,current_user,default,deferrable,desc,distinct,do,else,end,except,false,fetch,for,foreign,freeze,from,full,grant,group,having,ilike,in,initially,inner,intersect,into,is,isnull,join,lateral,leading,left,like,limit,localtime,localtimestamp,natural,not,notnull,null,offset,on,only,or,order,outer,overlaps,placing,primary,references,returning,right,select,session_user,similar,some,symmetric,table,tablesample,then,to,trailing,true,union,unique,user,using,variadic,verbose,when,where,window,with'.split(',');
-
-/**
- *
- * @param {string} dialect Dialect name
- * @param {string} identifier Identifier to quote
- * @param {object} [options]
- * @param {boolean} [options.force=false]
- * @param {boolean} [options.quoteIdentifiers=true]
- *
- * @returns {string}
- * @private
- */
-function quoteIdentifier(dialect, identifier, options) {
- if (identifier === '*') return identifier;
-
- options = Utils.defaults(options || {}, {
- force: false,
- quoteIdentifiers: true
- });
-
- switch (dialect) {
- case 'sqlite':
- case 'mariadb':
- case 'mysql':
- return Utils.addTicks(Utils.removeTicks(identifier, '`'), '`');
-
- case 'postgres':
- const rawIdentifier = Utils.removeTicks(identifier, '"');
-
- if (
- options.force !== true &&
- options.quoteIdentifiers === false &&
- !identifier.includes('.') &&
- !identifier.includes('->') &&
- !postgresReservedWords.includes(rawIdentifier.toLowerCase())
- ) {
- // In Postgres, if tables or attributes are created double-quoted,
- // they are also case sensitive. If they contain any uppercase
- // characters, they must always be double-quoted. This makes it
- // impossible to write queries in portable SQL if tables are created in
- // this way. Hence, we strip quotes if we don't want case sensitivity.
- return rawIdentifier;
- }
- return Utils.addTicks(rawIdentifier, '"');
- case 'mssql':
- return `[${identifier.replace(/[[\]']+/g, '')}]`;
-
- default:
- throw new Error(`Dialect "${dialect}" is not supported`);
- }
-}
-module.exports.quoteIdentifier = quoteIdentifier;
-
-/**
- * Test if a give string is already quoted
- *
- * @param {string} identifier
- *
- * @returns {boolean}
- * @private
- */
-function isIdentifierQuoted(identifier) {
- return /^\s*(?:([`"'])(?:(?!\1).|\1{2})*\1\.?)+\s*$/i.test(identifier);
-}
-module.exports.isIdentifierQuoted = isIdentifierQuoted;
diff --git a/lib/dialects/mssql/async-queue.js b/lib/dialects/mssql/async-queue.js
deleted file mode 100644
index adebefc08a8d..000000000000
--- a/lib/dialects/mssql/async-queue.js
+++ /dev/null
@@ -1,46 +0,0 @@
-'use strict';
-
-const BaseError = require('../../errors/base-error');
-const ConnectionError = require('../../errors/connection-error');
-
-/**
- * Thrown when a connection to a database is closed while an operation is in progress
- */
-class AsyncQueueError extends BaseError {
- constructor(message) {
- super(message);
- this.name = 'SequelizeAsyncQueueError';
- }
-}
-
-exports.AsyncQueueError = AsyncQueueError;
-
-class AsyncQueue {
- constructor() {
- this.previous = Promise.resolve();
- this.closed = false;
- this.rejectCurrent = () => {};
- }
- close() {
- this.closed = true;
- this.rejectCurrent(new ConnectionError(new AsyncQueueError('the connection was closed before this query could finish executing')));
- }
- enqueue(asyncFunction) {
- // This outer promise might seems superflous since down below we return asyncFunction().then(resolve, reject).
- // However, this ensures that this.previous will never be a rejected promise so the queue will
- // always keep going, while still communicating rejection from asyncFunction to the user.
- return new Promise((resolve, reject) => {
- this.previous = this.previous.then(
- () => {
- this.rejectCurrent = reject;
- if (this.closed) {
- return reject(new ConnectionError(new AsyncQueueError('the connection was closed before this query could be executed')));
- }
- return asyncFunction().then(resolve, reject);
- }
- );
- });
- }
-}
-
-exports.default = AsyncQueue;
diff --git a/lib/dialects/postgres/index.js b/lib/dialects/postgres/index.js
deleted file mode 100644
index 3d23f6ed6c6d..000000000000
--- a/lib/dialects/postgres/index.js
+++ /dev/null
@@ -1,75 +0,0 @@
-'use strict';
-
-const _ = require('lodash');
-const AbstractDialect = require('../abstract');
-const ConnectionManager = require('./connection-manager');
-const Query = require('./query');
-const QueryGenerator = require('./query-generator');
-const DataTypes = require('../../data-types').postgres;
-const { PostgresQueryInterface } = require('./query-interface');
-
-class PostgresDialect extends AbstractDialect {
- constructor(sequelize) {
- super();
- this.sequelize = sequelize;
- this.connectionManager = new ConnectionManager(this, sequelize);
- this.queryGenerator = new QueryGenerator({
- _dialect: this,
- sequelize
- });
- this.queryInterface = new PostgresQueryInterface(sequelize, this.queryGenerator);
- }
-}
-
-PostgresDialect.prototype.supports = _.merge(_.cloneDeep(AbstractDialect.prototype.supports), {
- 'DEFAULT VALUES': true,
- 'EXCEPTION': true,
- 'ON DUPLICATE KEY': false,
- 'ORDER NULLS': true,
- returnValues: {
- returning: true
- },
- bulkDefault: true,
- schemas: true,
- lock: true,
- lockOf: true,
- lockKey: true,
- lockOuterJoinFailure: true,
- skipLocked: true,
- forShare: 'FOR SHARE',
- index: {
- concurrently: true,
- using: 2,
- where: true,
- functionBased: true,
- operator: true
- },
- inserts: {
- onConflictDoNothing: ' ON CONFLICT DO NOTHING',
- updateOnDuplicate: ' ON CONFLICT DO UPDATE SET'
- },
- NUMERIC: true,
- ARRAY: true,
- RANGE: true,
- GEOMETRY: true,
- REGEXP: true,
- GEOGRAPHY: true,
- JSON: true,
- JSONB: true,
- HSTORE: true,
- TSVECTOR: true,
- deferrableConstraints: true,
- searchPath: true
-});
-
-PostgresDialect.prototype.defaultVersion = '9.5.0';
-PostgresDialect.prototype.Query = Query;
-PostgresDialect.prototype.DataTypes = DataTypes;
-PostgresDialect.prototype.name = 'postgres';
-PostgresDialect.prototype.TICK_CHAR = '"';
-PostgresDialect.prototype.TICK_CHAR_LEFT = PostgresDialect.prototype.TICK_CHAR;
-PostgresDialect.prototype.TICK_CHAR_RIGHT = PostgresDialect.prototype.TICK_CHAR;
-
-module.exports = PostgresDialect;
-module.exports.default = PostgresDialect;
-module.exports.PostgresDialect = PostgresDialect;
diff --git a/lib/errors/aggregate-error.js b/lib/errors/aggregate-error.js
deleted file mode 100644
index 4a6eb94a4311..000000000000
--- a/lib/errors/aggregate-error.js
+++ /dev/null
@@ -1,34 +0,0 @@
-'use strict';
-
-const BaseError = require('./base-error');
-
-/**
- * A wrapper for multiple Errors
- *
- * @param {Error[]} [errors] Array of errors
- *
- * @property errors {Error[]}
- */
-class AggregateError extends BaseError {
- constructor(errors) {
- super();
- this.errors = errors;
- this.name = 'AggregateError';
- }
-
- toString() {
- const message = `AggregateError of:\n${
- this.errors.map(error =>
- error === this
- ? '[Circular AggregateError]'
- : error instanceof AggregateError
- ? String(error).replace(/\n$/, '').replace(/^/mg, ' ')
- : String(error).replace(/^/mg, ' ').substring(2)
-
- ).join('\n')
- }\n`;
- return message;
- }
-}
-
-module.exports = AggregateError;
diff --git a/lib/errors/database-error.js b/lib/errors/database-error.js
deleted file mode 100644
index c7059d3ba9e0..000000000000
--- a/lib/errors/database-error.js
+++ /dev/null
@@ -1,35 +0,0 @@
-'use strict';
-
-const BaseError = require('./base-error');
-
-/**
- * A base class for all database related errors.
- */
-class DatabaseError extends BaseError {
- constructor(parent) {
- super(parent.message);
- this.name = 'SequelizeDatabaseError';
- /**
- * @type {Error}
- */
- this.parent = parent;
- /**
- * @type {Error}
- */
- this.original = parent;
- /**
- * The SQL that triggered the error
- *
- * @type {string}
- */
- this.sql = parent.sql;
- /**
- * The parameters for the sql that triggered the error
- *
- * @type {Array}
- */
- this.parameters = parent.parameters;
- }
-}
-
-module.exports = DatabaseError;
diff --git a/lib/errors/database/exclusion-constraint-error.js b/lib/errors/database/exclusion-constraint-error.js
deleted file mode 100644
index f77e52aab3ea..000000000000
--- a/lib/errors/database/exclusion-constraint-error.js
+++ /dev/null
@@ -1,23 +0,0 @@
-'use strict';
-
-const DatabaseError = require('./../database-error');
-
-/**
- * Thrown when an exclusion constraint is violated in the database
- */
-class ExclusionConstraintError extends DatabaseError {
- constructor(options) {
- options = options || {};
- options.parent = options.parent || { sql: '' };
-
- super(options.parent);
- this.name = 'SequelizeExclusionConstraintError';
-
- this.message = options.message || options.parent.message || '';
- this.constraint = options.constraint;
- this.fields = options.fields;
- this.table = options.table;
- }
-}
-
-module.exports = ExclusionConstraintError;
diff --git a/lib/errors/database/foreign-key-constraint-error.js b/lib/errors/database/foreign-key-constraint-error.js
deleted file mode 100644
index 9bdf02ad0c14..000000000000
--- a/lib/errors/database/foreign-key-constraint-error.js
+++ /dev/null
@@ -1,25 +0,0 @@
-'use strict';
-
-const DatabaseError = require('./../database-error');
-
-/**
- * Thrown when a foreign key constraint is violated in the database
- */
-class ForeignKeyConstraintError extends DatabaseError {
- constructor(options) {
- options = options || {};
- options.parent = options.parent || { sql: '' };
-
- super(options.parent);
- this.name = 'SequelizeForeignKeyConstraintError';
-
- this.message = options.message || options.parent.message || 'Database Error';
- this.fields = options.fields;
- this.table = options.table;
- this.value = options.value;
- this.index = options.index;
- this.reltype = options.reltype;
- }
-}
-
-module.exports = ForeignKeyConstraintError;
diff --git a/lib/errors/database/timeout-error.js b/lib/errors/database/timeout-error.js
deleted file mode 100644
index b67933b50f77..000000000000
--- a/lib/errors/database/timeout-error.js
+++ /dev/null
@@ -1,15 +0,0 @@
-'use strict';
-
-const DatabaseError = require('./../database-error');
-
-/**
- * Thrown when a database query times out because of a deadlock
- */
-class TimeoutError extends DatabaseError {
- constructor(parent) {
- super(parent);
- this.name = 'SequelizeTimeoutError';
- }
-}
-
-module.exports = TimeoutError;
diff --git a/lib/errors/database/unknown-constraint-error.js b/lib/errors/database/unknown-constraint-error.js
deleted file mode 100644
index e11fa666c7ef..000000000000
--- a/lib/errors/database/unknown-constraint-error.js
+++ /dev/null
@@ -1,23 +0,0 @@
-'use strict';
-
-const DatabaseError = require('./../database-error');
-
-/**
- * Thrown when constraint name is not found in the database
- */
-class UnknownConstraintError extends DatabaseError {
- constructor(options) {
- options = options || {};
- options.parent = options.parent || { sql: '' };
-
- super(options.parent);
- this.name = 'SequelizeUnknownConstraintError';
-
- this.message = options.message || 'The specified constraint does not exist';
- this.constraint = options.constraint;
- this.fields = options.fields;
- this.table = options.table;
- }
-}
-
-module.exports = UnknownConstraintError;
diff --git a/lib/errors/index.js b/lib/errors/index.js
deleted file mode 100644
index 16316a5acad4..000000000000
--- a/lib/errors/index.js
+++ /dev/null
@@ -1,33 +0,0 @@
-'use strict';
-
-exports.BaseError = require('./base-error');
-
-exports.AggregateError = require('./aggregate-error');
-exports.AsyncQueueError = require('../dialects/mssql/async-queue').AsyncQueueError;
-exports.AssociationError = require('./association-error');
-exports.BulkRecordError = require('./bulk-record-error');
-exports.ConnectionError = require('./connection-error');
-exports.DatabaseError = require('./database-error');
-exports.EagerLoadingError = require('./eager-loading-error');
-exports.EmptyResultError = require('./empty-result-error');
-exports.InstanceError = require('./instance-error');
-exports.OptimisticLockError = require('./optimistic-lock-error');
-exports.QueryError = require('./query-error');
-exports.SequelizeScopeError = require('./sequelize-scope-error');
-exports.ValidationError = require('./validation-error');
-exports.ValidationErrorItem = exports.ValidationError.ValidationErrorItem;
-
-exports.AccessDeniedError = require('./connection/access-denied-error');
-exports.ConnectionAcquireTimeoutError = require('./connection/connection-acquire-timeout-error');
-exports.ConnectionRefusedError = require('./connection/connection-refused-error');
-exports.ConnectionTimedOutError = require('./connection/connection-timed-out-error');
-exports.HostNotFoundError = require('./connection/host-not-found-error');
-exports.HostNotReachableError = require('./connection/host-not-reachable-error');
-exports.InvalidConnectionError = require('./connection/invalid-connection-error');
-
-exports.ExclusionConstraintError = require('./database/exclusion-constraint-error');
-exports.ForeignKeyConstraintError = require('./database/foreign-key-constraint-error');
-exports.TimeoutError = require('./database/timeout-error');
-exports.UnknownConstraintError = require('./database/unknown-constraint-error');
-
-exports.UniqueConstraintError = require('./validation/unique-constraint-error');
diff --git a/lib/errors/optimistic-lock-error.js b/lib/errors/optimistic-lock-error.js
deleted file mode 100644
index 0c0ff3eb7db4..000000000000
--- a/lib/errors/optimistic-lock-error.js
+++ /dev/null
@@ -1,34 +0,0 @@
-'use strict';
-
-const BaseError = require('./base-error');
-
-/**
- * Thrown when attempting to update a stale model instance
- */
-class OptimisticLockError extends BaseError {
- constructor(options) {
- options = options || {};
- options.message = options.message || `Attempting to update a stale model instance: ${options.modelName}`;
- super(options.message);
- this.name = 'SequelizeOptimisticLockError';
- /**
- * The name of the model on which the update was attempted
- *
- * @type {string}
- */
- this.modelName = options.modelName;
- /**
- * The values of the attempted update
- *
- * @type {object}
- */
- this.values = options.values;
- /**
- *
- * @type {object}
- */
- this.where = options.where;
- }
-}
-
-module.exports = OptimisticLockError;
diff --git a/lib/errors/validation-error.js b/lib/errors/validation-error.js
deleted file mode 100644
index 4bb4c9817bc6..000000000000
--- a/lib/errors/validation-error.js
+++ /dev/null
@@ -1,208 +0,0 @@
-'use strict';
-
-const BaseError = require('./base-error');
-
-/**
- * Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
- * which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
- *
- * @param {string} message Error message
- * @param {Array} [errors] Array of ValidationErrorItem objects describing the validation errors
- *
- * @property errors {ValidationErrorItems[]}
- */
-class ValidationError extends BaseError {
- constructor(message, errors) {
- super(message);
- this.name = 'SequelizeValidationError';
- this.message = 'Validation Error';
- /**
- *
- * @type {ValidationErrorItem[]}
- */
- this.errors = errors || [];
-
- // Use provided error message if available...
- if (message) {
- this.message = message;
-
- // ... otherwise create a concatenated message out of existing errors.
- } else if (this.errors.length > 0 && this.errors[0].message) {
- this.message = this.errors.map(err => `${err.type || err.origin}: ${err.message}`).join(',\n');
- }
- }
-
- /**
- * Gets all validation error items for the path / field specified.
- *
- * @param {string} path The path to be checked for error items
- *
- * @returns {Array} Validation error items for the specified path
- */
- get(path) {
- return this.errors.reduce((reduced, error) => {
- if (error.path === path) {
- reduced.push(error);
- }
- return reduced;
- }, []);
- }
-}
-
-/**
- * Validation Error Item
- * Instances of this class are included in the `ValidationError.errors` property.
- */
-class ValidationErrorItem {
- /**
- * Creates a new ValidationError item. Instances of this class are included in the `ValidationError.errors` property.
- *
- * @param {string} [message] An error message
- * @param {string} [type] The type/origin of the validation error
- * @param {string} [path] The field that triggered the validation error
- * @param {string} [value] The value that generated the error
- * @param {Model} [instance] the DAO instance that caused the validation error
- * @param {string} [validatorKey] a validation "key", used for identification
- * @param {string} [fnName] property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
- * @param {Array} [fnArgs] parameters used with the BUILT-IN validator function, if applicable
- */
- constructor(message, type, path, value, instance, validatorKey, fnName, fnArgs) {
- /**
- * An error message
- *
- * @type {string} message
- */
- this.message = message || '';
-
- /**
- * The type/origin of the validation error
- *
- * @type {string | null}
- */
- this.type = null;
-
- /**
- * The field that triggered the validation error
- *
- * @type {string | null}
- */
- this.path = path || null;
-
- /**
- * The value that generated the error
- *
- * @type {string | null}
- */
- this.value = value !== undefined ? value : null;
-
- this.origin = null;
-
- /**
- * The DAO instance that caused the validation error
- *
- * @type {Model | null}
- */
- this.instance = instance || null;
-
- /**
- * A validation "key", used for identification
- *
- * @type {string | null}
- */
- this.validatorKey = validatorKey || null;
-
- /**
- * Property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
- *
- * @type {string | null}
- */
- this.validatorName = fnName || null;
-
- /**
- * Parameters used with the BUILT-IN validator function, if applicable
- *
- * @type {Array}
- */
- this.validatorArgs = fnArgs || [];
-
- if (type) {
- if (ValidationErrorItem.Origins[ type ]) {
- this.origin = type;
- } else {
- const lowercaseType = `${type}`.toLowerCase().trim();
- const realType = ValidationErrorItem.TypeStringMap[ lowercaseType ];
-
- if (realType && ValidationErrorItem.Origins[ realType ]) {
- this.origin = realType;
- this.type = type;
- }
- }
- }
-
- // This doesn't need captureStackTrace because it's not a subclass of Error
- }
-
- /**
- * return a lowercase, trimmed string "key" that identifies the validator.
- *
- * Note: the string will be empty if the instance has neither a valid `validatorKey` property nor a valid `validatorName` property
- *
- * @param {boolean} [useTypeAsNS=true] controls whether the returned value is "namespace",
- * this parameter is ignored if the validator's `type` is not one of ValidationErrorItem.Origins
- * @param {string} [NSSeparator='.'] a separator string for concatenating the namespace, must be not be empty,
- * defaults to "." (fullstop). only used and validated if useTypeAsNS is TRUE.
- * @throws {Error} thrown if NSSeparator is found to be invalid.
- * @returns {string}
- *
- * @private
- */
- getValidatorKey(useTypeAsNS, NSSeparator) {
- const useTANS = useTypeAsNS === undefined || !!useTypeAsNS;
- const NSSep = NSSeparator === undefined ? '.' : NSSeparator;
-
- const type = this.origin;
- const key = this.validatorKey || this.validatorName;
- const useNS = useTANS && type && ValidationErrorItem.Origins[ type ];
-
- if (useNS && (typeof NSSep !== 'string' || !NSSep.length)) {
- throw new Error('Invalid namespace separator given, must be a non-empty string');
- }
-
- if (!(typeof key === 'string' && key.length)) {
- return '';
- }
-
- return (useNS ? [type, key].join(NSSep) : key).toLowerCase().trim();
- }
-}
-
-/**
- * An enum that defines valid ValidationErrorItem `origin` values
- *
- * @type {object}
- * @property CORE {string} specifies errors that originate from the sequelize "core"
- * @property DB {string} specifies validation errors that originate from the storage engine
- * @property FUNCTION {string} specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
- */
-ValidationErrorItem.Origins = {
- CORE: 'CORE',
- DB: 'DB',
- FUNCTION: 'FUNCTION'
-};
-
-/**
- * An object that is used internally by the `ValidationErrorItem` class
- * that maps current `type` strings (as given to ValidationErrorItem.constructor()) to
- * our new `origin` values.
- *
- * @type {object}
- */
-ValidationErrorItem.TypeStringMap = {
- 'notnull violation': 'CORE',
- 'string violation': 'CORE',
- 'unique violation': 'DB',
- 'validation error': 'FUNCTION'
-};
-
-module.exports = ValidationError;
-module.exports.ValidationErrorItem = ValidationErrorItem;
diff --git a/lib/errors/validation/unique-constraint-error.js b/lib/errors/validation/unique-constraint-error.js
deleted file mode 100644
index a509e88ff4fb..000000000000
--- a/lib/errors/validation/unique-constraint-error.js
+++ /dev/null
@@ -1,25 +0,0 @@
-'use strict';
-
-const ValidationError = require('./../validation-error');
-
-/**
- * Thrown when a unique constraint is violated in the database
- */
-class UniqueConstraintError extends ValidationError {
- constructor(options) {
- options = options || {};
- options.parent = options.parent || { sql: '' };
- options.message = options.message || options.parent.message || 'Validation Error';
- options.errors = options.errors || {};
- super(options.message, options.errors);
-
- this.name = 'SequelizeUniqueConstraintError';
- this.errors = options.errors;
- this.fields = options.fields;
- this.parent = options.parent;
- this.original = options.parent;
- this.sql = options.parent.sql;
- }
-}
-
-module.exports = UniqueConstraintError;
diff --git a/lib/operators.js b/lib/operators.js
deleted file mode 100644
index 7e8bb7cf9cdb..000000000000
--- a/lib/operators.js
+++ /dev/null
@@ -1,91 +0,0 @@
-
-'use strict';
-/**
- * Operator symbols to be used when querying data
- *
- * @see {@link Model#where}
- *
- * @property eq
- * @property ne
- * @property gte
- * @property gt
- * @property lte
- * @property lt
- * @property not
- * @property is
- * @property in
- * @property notIn
- * @property like
- * @property notLike
- * @property iLike
- * @property notILike
- * @property startsWith
- * @property endsWith
- * @property substring
- * @property regexp
- * @property notRegexp
- * @property iRegexp
- * @property notIRegexp
- * @property between
- * @property notBetween
- * @property overlap
- * @property contains
- * @property contained
- * @property adjacent
- * @property strictLeft
- * @property strictRight
- * @property noExtendRight
- * @property noExtendLeft
- * @property and
- * @property or
- * @property any
- * @property all
- * @property values
- * @property col
- * @property placeholder
- * @property join
- */
-const Op = {
- eq: Symbol.for('eq'),
- ne: Symbol.for('ne'),
- gte: Symbol.for('gte'),
- gt: Symbol.for('gt'),
- lte: Symbol.for('lte'),
- lt: Symbol.for('lt'),
- not: Symbol.for('not'),
- is: Symbol.for('is'),
- in: Symbol.for('in'),
- notIn: Symbol.for('notIn'),
- like: Symbol.for('like'),
- notLike: Symbol.for('notLike'),
- iLike: Symbol.for('iLike'),
- notILike: Symbol.for('notILike'),
- startsWith: Symbol.for('startsWith'),
- endsWith: Symbol.for('endsWith'),
- substring: Symbol.for('substring'),
- regexp: Symbol.for('regexp'),
- notRegexp: Symbol.for('notRegexp'),
- iRegexp: Symbol.for('iRegexp'),
- notIRegexp: Symbol.for('notIRegexp'),
- between: Symbol.for('between'),
- notBetween: Symbol.for('notBetween'),
- overlap: Symbol.for('overlap'),
- contains: Symbol.for('contains'),
- contained: Symbol.for('contained'),
- adjacent: Symbol.for('adjacent'),
- strictLeft: Symbol.for('strictLeft'),
- strictRight: Symbol.for('strictRight'),
- noExtendRight: Symbol.for('noExtendRight'),
- noExtendLeft: Symbol.for('noExtendLeft'),
- and: Symbol.for('and'),
- or: Symbol.for('or'),
- any: Symbol.for('any'),
- all: Symbol.for('all'),
- values: Symbol.for('values'),
- col: Symbol.for('col'),
- placeholder: Symbol.for('placeholder'),
- join: Symbol.for('join'),
- match: Symbol.for('match')
-};
-
-module.exports = Op;
diff --git a/lib/sql-string.js b/lib/sql-string.js
deleted file mode 100644
index 2e334309d984..000000000000
--- a/lib/sql-string.js
+++ /dev/null
@@ -1,124 +0,0 @@
-'use strict';
-
-const dataTypes = require('./data-types');
-const { logger } = require('./utils/logger');
-
-function arrayToList(array, timeZone, dialect, format) {
- return array.reduce((sql, val, i) => {
- if (i !== 0) {
- sql += ', ';
- }
- if (Array.isArray(val)) {
- sql += `(${arrayToList(val, timeZone, dialect, format)})`;
- } else {
- sql += escape(val, timeZone, dialect, format);
- }
- return sql;
- }, '');
-}
-exports.arrayToList = arrayToList;
-
-function escape(val, timeZone, dialect, format) {
- let prependN = false;
- if (val === undefined || val === null) {
- return 'NULL';
- }
- switch (typeof val) {
- case 'boolean':
- // SQLite doesn't have true/false support. MySQL aliases true/false to 1/0
- // for us. Postgres actually has a boolean type with true/false literals,
- // but sequelize doesn't use it yet.
- if (dialect === 'sqlite' || dialect === 'mssql') {
- return +!!val;
- }
- return (!!val).toString();
- case 'number':
- return val.toString();
- case 'string':
- // In mssql, prepend N to all quoted vals which are originally a string (for
- // unicode compatibility)
- prependN = dialect === 'mssql';
- break;
- }
-
- if (val instanceof Date) {
- val = dataTypes[dialect].DATE.prototype.stringify(val, { timezone: timeZone });
- }
-
- if (Buffer.isBuffer(val)) {
- if (dataTypes[dialect].BLOB) {
- return dataTypes[dialect].BLOB.prototype.stringify(val);
- }
-
- return dataTypes.BLOB.prototype.stringify(val);
- }
-
- if (Array.isArray(val)) {
- const partialEscape = escVal => escape(escVal, timeZone, dialect, format);
- if (dialect === 'postgres' && !format) {
- return dataTypes.ARRAY.prototype.stringify(val, { escape: partialEscape });
- }
- return arrayToList(val, timeZone, dialect, format);
- }
-
- if (!val.replace) {
- throw new Error(`Invalid value ${logger.inspect(val)}`);
- }
-
- if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql') {
- // http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
- // http://stackoverflow.com/q/603572/130598
- val = val.replace(/'/g, "''");
-
- if (dialect === 'postgres') {
- // null character is not allowed in Postgres
- val = val.replace(/\0/g, '\\0');
- }
- } else {
- // eslint-disable-next-line no-control-regex
- val = val.replace(/[\0\n\r\b\t\\'"\x1a]/g, s => {
- switch (s) {
- case '\0': return '\\0';
- case '\n': return '\\n';
- case '\r': return '\\r';
- case '\b': return '\\b';
- case '\t': return '\\t';
- case '\x1a': return '\\Z';
- default: return `\\${s}`;
- }
- });
- }
- return `${(prependN ? "N'" : "'") + val}'`;
-}
-exports.escape = escape;
-
-function format(sql, values, timeZone, dialect) {
- values = [].concat(values);
-
- if (typeof sql !== 'string') {
- throw new Error(`Invalid SQL string provided: ${sql}`);
- }
-
- return sql.replace(/\?/g, match => {
- if (!values.length) {
- return match;
- }
-
- return escape(values.shift(), timeZone, dialect, true);
- });
-}
-exports.format = format;
-
-function formatNamedParameters(sql, values, timeZone, dialect) {
- return sql.replace(/:+(?!\d)(\w+)/g, (value, key) => {
- if ('postgres' === dialect && '::' === value.slice(0, 2)) {
- return value;
- }
-
- if (values[key] !== undefined) {
- return escape(values[key], timeZone, dialect, true);
- }
- throw new Error(`Named parameter "${value}" has no value in the given object.`);
- });
-}
-exports.formatNamedParameters = formatNamedParameters;
diff --git a/lib/utils/class-to-invokable.js b/lib/utils/class-to-invokable.js
deleted file mode 100644
index 0bc63c517d94..000000000000
--- a/lib/utils/class-to-invokable.js
+++ /dev/null
@@ -1,24 +0,0 @@
-'use strict';
-
-/**
- * Wraps a constructor to not need the `new` keyword using a proxy.
- * Only used for data types.
- *
- * @param {Function} Class The class instance to wrap as invocable.
- * @returns {Proxy} Wrapped class instance.
- * @private
- */
-function classToInvokable(Class) {
- return new Proxy(Class, {
- apply(Target, thisArg, args) {
- return new Target(...args);
- },
- construct(Target, args) {
- return new Target(...args);
- },
- get(target, p) {
- return target[p];
- }
- });
-}
-exports.classToInvokable = classToInvokable;
diff --git a/lib/utils/deprecations.js b/lib/utils/deprecations.js
deleted file mode 100644
index ac9d62216c71..000000000000
--- a/lib/utils/deprecations.js
+++ /dev/null
@@ -1,12 +0,0 @@
-'use strict';
-
-const { deprecate } = require('util');
-
-const noop = () => {};
-
-exports.noRawAttributes = deprecate(noop, 'Use sequelize.fn / sequelize.literal to construct attributes', 'SEQUELIZE0001');
-exports.noTrueLogging = deprecate(noop, 'The logging-option should be either a function or false. Default: console.log', 'SEQUELIZE0002');
-exports.noStringOperators = deprecate(noop, 'String based operators are deprecated. Please use Symbol based operators for better security, read more at https://sequelize.org/master/manual/querying.html#operators', 'SEQUELIZE0003');
-exports.noBoolOperatorAliases = deprecate(noop, 'A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.', 'SEQUELIZE0004');
-exports.noDoubleNestedGroup = deprecate(noop, 'Passing a double nested nested array to `group` is unsupported and will be removed in v6.', 'SEQUELIZE0005');
-exports.unsupportedEngine = deprecate(noop, 'This database engine version is not supported, please update your database server. More information https://github.com/sequelize/sequelize/blob/main/ENGINE.md', 'SEQUELIZE0006');
diff --git a/lib/utils/join-sql-fragments.js b/lib/utils/join-sql-fragments.js
deleted file mode 100644
index a53f61b8702f..000000000000
--- a/lib/utils/join-sql-fragments.js
+++ /dev/null
@@ -1,83 +0,0 @@
-'use strict';
-
-function doesNotWantLeadingSpace(str) {
- return /^[;,)]/.test(str);
-}
-function doesNotWantTrailingSpace(str) {
- return /\($/.test(str);
-}
-
-/**
- * Joins an array of strings with a single space between them,
- * except for:
- *
- * - Strings starting with ';', ',' and ')', which do not get a leading space.
- * - Strings ending with '(', which do not get a trailing space.
- *
- * @param {string[]} parts
- * @returns {string}
- * @private
- */
-function singleSpaceJoinHelper(parts) {
- return parts.reduce(({ skipNextLeadingSpace, result }, part) => {
- if (skipNextLeadingSpace || doesNotWantLeadingSpace(part)) {
- result += part.trim();
- } else {
- result += ` ${part.trim()}`;
- }
- return {
- skipNextLeadingSpace: doesNotWantTrailingSpace(part),
- result
- };
- }, {
- skipNextLeadingSpace: true,
- result: ''
- }).result;
-}
-
-/**
- * Joins an array with a single space, auto trimming when needed.
- *
- * Certain elements do not get leading/trailing spaces.
- *
- * @param {any[]} array The array to be joined. Falsy values are skipped. If an
- * element is another array, this function will be called recursively on that array.
- * Otherwise, if a non-string, non-falsy value is present, a TypeError will be thrown.
- *
- * @returns {string} The joined string.
- *
- * @private
- */
-function joinSQLFragments(array) {
- if (array.length === 0) return '';
-
- // Skip falsy fragments
- array = array.filter(x => x);
-
- // Resolve recursive calls
- array = array.map(fragment => {
- if (Array.isArray(fragment)) {
- return joinSQLFragments(fragment);
- }
- return fragment;
- });
-
- // Ensure strings
- for (const fragment of array) {
- if (fragment && typeof fragment !== 'string') {
- const error = new TypeError(`Tried to construct a SQL string with a non-string, non-falsy fragment (${fragment}).`);
- error.args = array;
- error.fragment = fragment;
- throw error;
- }
- }
-
- // Trim fragments
- array = array.map(x => x.trim());
-
- // Skip full-whitespace fragments (empty after the above trim)
- array = array.filter(x => x !== '');
-
- return singleSpaceJoinHelper(array);
-}
-exports.joinSQLFragments = joinSQLFragments;
diff --git a/lib/utils/logger.js b/lib/utils/logger.js
deleted file mode 100644
index 0b2ca26a53dd..000000000000
--- a/lib/utils/logger.js
+++ /dev/null
@@ -1,40 +0,0 @@
-'use strict';
-
-/**
- * Sequelize module for debug and deprecation messages.
- * It require a `context` for which messages will be printed.
- *
- * @module logging
- * @private
- */
-
-const debug = require('debug');
-const util = require('util');
-
-class Logger {
- constructor(config) {
-
- this.config = {
- context: 'sequelize',
- debug: true,
- ...config
- };
- }
-
- warn(message) {
- // eslint-disable-next-line no-console
- console.warn(`(${this.config.context}) Warning: ${message}`);
- }
-
- inspect(value) {
- return util.inspect(value, false, 3);
- }
-
- debugContext(name) {
- return debug(`${this.config.context}:${name}`);
- }
-}
-
-exports.logger = new Logger();
-
-exports.Logger = Logger;
diff --git a/logo.svg b/logo.svg
new file mode 100644
index 000000000000..0ee676a33cc8
--- /dev/null
+++ b/logo.svg
@@ -0,0 +1,41 @@
+
+
diff --git a/package-support.json b/package-support.json
new file mode 100644
index 000000000000..77ae7b83d775
--- /dev/null
+++ b/package-support.json
@@ -0,0 +1,13 @@
+{
+ "versions": [
+ {
+ "version": "*",
+ "target": {
+ "node": "supported"
+ },
+ "response": {
+ "type": "time-permitting"
+ }
+ }
+ ]
+}
diff --git a/package.json b/package.json
index a21320925b44..bc69e634ae69 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,12 @@
{
"name": "sequelize",
- "description": "Multi dialect ORM for Node.JS",
+ "description": "Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Amazon Redshift and Snowflake’s Data Cloud. It features solid transaction support, relations, eager and lazy loading, read replication and more.",
"version": "0.0.0-development",
- "maintainers": [
- "Pedro Augusto de Paula Barbosa "
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/sequelize"
+ }
],
"repository": {
"type": "git",
@@ -13,79 +16,116 @@
"url": "https://github.com/sequelize/sequelize/issues"
},
"homepage": "https://sequelize.org/",
- "main": "index.js",
- "types": "types",
+ "main": "./lib/index.js",
+ "types": "./types/index.d.ts",
+ "type": "commonjs",
+ "exports": {
+ ".": {
+ "types": "./types/index.d.ts",
+ "import": "./lib/index.mjs",
+ "require": "./lib/index.js"
+ },
+ "./lib/*": {
+ "types": "./types/*.d.ts",
+ "default": "./lib/*.js"
+ },
+ "./lib/errors": {
+ "types": "./types/errors/index.d.ts",
+ "default": "./lib/errors/index.js"
+ },
+ "./package.json": "./package.json",
+ "./types/*": {
+ "types": "./types/*.d.ts"
+ }
+ },
"engines": {
"node": ">=10.0.0"
},
"files": [
"lib",
- "types/index.d.ts",
- "types/lib",
- "types/type-helpers"
+ "types",
+ "index.js"
],
"license": "MIT",
"dependencies": {
- "debug": "^4.1.1",
- "dottie": "^2.0.0",
- "inflection": "1.13.1",
- "lodash": "^4.17.20",
- "moment": "^2.26.0",
- "moment-timezone": "^0.5.31",
- "retry-as-promised": "^3.2.0",
- "semver": "^7.3.2",
- "sequelize-pool": "^6.0.0",
+ "@types/debug": "^4.1.8",
+ "@types/validator": "^13.7.17",
+ "debug": "^4.3.4",
+ "dottie": "^2.0.6",
+ "inflection": "^1.13.4",
+ "lodash": "^4.17.21",
+ "moment": "^2.29.4",
+ "moment-timezone": "^0.5.43",
+ "pg-connection-string": "^2.6.1",
+ "retry-as-promised": "^7.0.4",
+ "semver": "^7.5.4",
+ "sequelize-pool": "^7.1.0",
"toposort-class": "^1.0.1",
- "uuid": "^8.1.0",
- "validator": "^13.6.0",
+ "uuid": "^8.3.2",
+ "validator": "^13.9.0",
"wkx": "^0.5.0"
},
"devDependencies": {
- "@commitlint/cli": "^11.0.0",
- "@commitlint/config-angular": "^11.0.0",
- "@types/node": "^12.12.42",
- "@types/validator": "^13.1.4",
- "acorn": "^8.0.4",
- "chai": "^4.x",
- "chai-as-promised": "^7.x",
- "chai-datetime": "^1.6.0",
- "cheerio": "^1.0.0-rc.3",
+ "@commitlint/cli": "^15.0.0",
+ "@commitlint/config-angular": "^15.0.0",
+ "@octokit/rest": "^18.12.0",
+ "@octokit/types": "^6.34.0",
+ "@types/chai": "^4.3.0",
+ "@types/lodash": "4.14.197",
+ "@types/mocha": "^9.0.0",
+ "@types/node": "^16.11.17",
+ "@types/sinon": "^10.0.6",
+ "@typescript-eslint/eslint-plugin": "^5.8.1",
+ "@typescript-eslint/parser": "^5.8.1",
+ "acorn": "^8.7.0",
+ "chai": "^4.3.7",
+ "chai-as-promised": "^7.1.1",
+ "chai-datetime": "^1.8.0",
+ "cheerio": "^1.0.0-rc.10",
"cls-hooked": "^4.2.2",
- "cross-env": "^7.0.2",
- "delay": "^4.3.0",
+ "copyfiles": "^2.4.1",
+ "cross-env": "^7.0.3",
+ "delay": "^5.0.0",
+ "esbuild": "0.14.3",
"esdoc": "^1.1.0",
"esdoc-ecmascript-proposal-plugin": "^1.0.0",
"esdoc-inject-style-plugin": "^1.0.0",
"esdoc-standard-plugin": "^1.0.0",
- "eslint": "^6.8.0",
- "eslint-plugin-jsdoc": "^20.4.0",
- "eslint-plugin-mocha": "^6.2.2",
- "expect-type": "^0.11.0",
- "fs-jetpack": "^4.1.0",
- "husky": "^4.2.5",
- "js-combinatorics": "^0.5.5",
- "lcov-result-merger": "^3.0.0",
- "lint-staged": "^10.2.6",
- "mariadb": "^2.3.1",
- "markdownlint-cli": "^0.26.0",
- "marked": "^1.1.0",
- "mocha": "^7.1.2",
- "mysql2": "^2.1.0",
- "nyc": "^15.0.0",
+ "eslint": "^8.5.0",
+ "eslint-plugin-jsdoc": "^37.4.0",
+ "eslint-plugin-mocha": "^9.0.0",
+ "expect-type": "^0.12.0",
+ "fast-glob": "^3.2.7",
+ "fs-jetpack": "^4.3.0",
+ "husky": "^7.0.4",
+ "ibm_db": "^2.8.1",
+ "js-combinatorics": "^0.6.1",
+ "lcov-result-merger": "^3.1.0",
+ "lint-staged": "^12.1.4",
+ "mariadb": "^2.5.5",
+ "markdownlint-cli": "^0.30.0",
+ "mocha": "^7.2.0",
+ "module-alias": "^2.2.2",
+ "mysql2": "^2.3.3",
+ "node-hook": "^1.0.0",
+ "nyc": "^15.1.0",
+ "oracledb": "^5.5.0",
"p-map": "^4.0.0",
"p-props": "^4.0.0",
"p-settle": "^4.1.1",
"p-timeout": "^4.0.0",
- "pg": "^8.2.1",
- "pg-hstore": "^2.x",
+ "pg": "^8.7.1",
+ "pg-hstore": "^2.3.4",
"rimraf": "^3.0.2",
- "semantic-release": "^17.3.0",
+ "semantic-release": "^18.0.1",
"semantic-release-fail-on-major-bump": "^1.0.0",
- "sinon": "^9.0.2",
- "sinon-chai": "^3.3.0",
- "sqlite3": "^4.2.0",
+ "sinon": "^12.0.1",
+ "sinon-chai": "^3.7.0",
+ "snowflake-sdk": "^1.6.6",
+ "source-map-support": "^0.5.21",
+ "sqlite3": "^5.1.6",
"tedious": "8.3.0",
- "typescript": "^4.1.3"
+ "typescript": "^4.5.4"
},
"peerDependenciesMeta": {
"pg": {
@@ -97,6 +137,12 @@
"mysql2": {
"optional": true
},
+ "ibm_db": {
+ "optional": true
+ },
+ "snowflake-sdk": {
+ "optional": true
+ },
"mariadb": {
"optional": true
},
@@ -105,6 +151,9 @@
},
"tedious": {
"optional": true
+ },
+ "oracledb": {
+ "optional": true
}
},
"keywords": [
@@ -115,8 +164,12 @@
"postgres",
"pg",
"mssql",
+ "db2",
+ "ibm_db",
"sql",
+ "oracledb",
"sqlserver",
+ "snowflake",
"orm",
"nodejs",
"object relational mapper",
@@ -148,13 +201,7 @@
}
},
"lint-staged": {
- "*.js": "eslint"
- },
- "husky": {
- "hooks": {
- "pre-commit": "lint-staged",
- "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
- }
+ "*!(d).[tj]s": "eslint"
},
"release": {
"plugins": [
@@ -165,7 +212,11 @@
"@semantic-release/github"
],
"branches": [
- "v6"
+ "v6",
+ {
+ "name": "v6-beta",
+ "prerelease": "beta"
+ }
]
},
"publishConfig": {
@@ -173,34 +224,46 @@
},
"scripts": {
"----------------------------------------- static analysis -----------------------------------------": "",
- "lint": "eslint lib test --quiet",
+ "lint": "eslint src test --quiet --fix",
"lint-docs": "markdownlint docs",
- "test-typings": "tsc -b types/tsconfig.json && tsc -b types/test/tsconfig.json",
+ "test-typings": "tsc --noEmit --emitDeclarationOnly false && tsc -b test/tsconfig.json",
"----------------------------------------- documentation -------------------------------------------": "",
- "docs": "rimraf esdoc && esdoc -c docs/esdoc-config.js && cp docs/favicon.ico esdoc/favicon.ico && cp docs/ROUTER.txt esdoc/ROUTER && node docs/run-docs-transforms.js && node docs/redirects/create-redirects.js && rimraf esdoc/file esdoc/source.html",
+ "docs": "sh docs.sh",
"----------------------------------------- tests ---------------------------------------------------": "",
- "test-unit": "mocha \"test/unit/**/*.test.js\"",
- "test-integration": "mocha \"test/integration/**/*.test.js\"",
+ "mocha": "mocha -r ./test/registerEsbuild",
+ "test-unit": "yarn mocha \"test/unit/**/*.test.[tj]s\"",
+ "test-integration": "yarn mocha \"test/integration/**/*.test.[tj]s\"",
"teaser": "node test/teaser.js",
- "test": "npm run teaser && npm run test-unit && npm run test-integration",
+ "test": "npm run prepare && npm run test-typings && npm run teaser && npm run test-unit && npm run test-integration",
"----------------------------------------- coverage ------------------------------------------------": "",
"cover": "rimraf coverage && npm run teaser && npm run cover-integration && npm run cover-unit && npm run merge-coverage",
- "cover-integration": "cross-env COVERAGE=true nyc --reporter=lcovonly mocha \"test/integration/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/integration.info')\"",
- "cover-unit": "cross-env COVERAGE=true nyc --reporter=lcovonly mocha \"test/unit/**/*.test.js\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/unit.info')\"",
+ "cover-integration": "cross-env COVERAGE=true nyc --reporter=lcovonly yarn mocha \"test/integration/**/*.test.[tj]s\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/integration.info')\"",
+ "cover-unit": "cross-env COVERAGE=true nyc --reporter=lcovonly yarn mocha \"test/unit/**/*.test.[tj]s\" && node -e \"require('fs').renameSync('coverage/lcov.info', 'coverage/unit.info')\"",
"merge-coverage": "lcov-result-merger \"coverage/*.info\" \"coverage/lcov.info\"",
"----------------------------------------- local test dbs ------------------------------------------": "",
"start-mariadb": "bash dev/mariadb/10.3/start.sh",
"start-mysql": "bash dev/mysql/5.7/start.sh",
+ "start-mysql-8": "bash dev/mysql/8.0/start.sh",
"start-postgres": "bash dev/postgres/10/start.sh",
"start-mssql": "bash dev/mssql/2019/start.sh",
+ "start-db2": "bash dev/db2/11.5/start.sh",
+ "start-oracle-oldest": "bash dev/oracle/18-slim/start.sh",
+ "start-oracle-latest": "bash dev/oracle/23-slim/start.sh",
"stop-mariadb": "bash dev/mariadb/10.3/stop.sh",
"stop-mysql": "bash dev/mysql/5.7/stop.sh",
+ "stop-mysql-8": "bash dev/mysql/8.0/stop.sh",
"stop-postgres": "bash dev/postgres/10/stop.sh",
"stop-mssql": "bash dev/mssql/2019/stop.sh",
+ "stop-db2": "bash dev/db2/11.5/stop.sh",
+ "stop-oracle-oldest": "bash dev/oracle/18-slim/stop.sh",
+ "stop-oracle-latest": "bash dev/oracle/23-slim/stop.sh",
"restart-mariadb": "npm run start-mariadb",
"restart-mysql": "npm run start-mysql",
"restart-postgres": "npm run start-postgres",
"restart-mssql": "npm run start-mssql",
+ "restart-db2": "npm run start-db2",
+ "restart-oracle-oldest": "npm run start-oracle-oldest",
+ "restart-oracle-latest": "npm run start-oracle-latest",
"----------------------------------------- local tests ---------------------------------------------": "",
"test-unit-mariadb": "cross-env DIALECT=mariadb npm run test-unit",
"test-unit-mysql": "cross-env DIALECT=mysql npm run test-unit",
@@ -208,18 +271,27 @@
"test-unit-postgres-native": "cross-env DIALECT=postgres-native npm run test-unit",
"test-unit-sqlite": "cross-env DIALECT=sqlite npm run test-unit",
"test-unit-mssql": "cross-env DIALECT=mssql npm run test-unit",
+ "test-unit-db2": "cross-env DIALECT=db2 npm run test-unit",
+ "test-unit-snowflake": "cross-env DIALECT=snowflake npm run test-unit",
+ "test-unit-oracle": "cross-env DIALECT=oracle npm run test-unit",
+ "test-unit-all": "npm run test-unit-mariadb && npm run test-unit-mysql && npm run test-unit-postgres && npm run test-unit-postgres-native && npm run test-unit-mssql && npm run test-unit-sqlite && npm run test-unit-snowflake && npm run test-unit-db2 && npm run test-unit-oracle",
"test-integration-mariadb": "cross-env DIALECT=mariadb npm run test-integration",
"test-integration-mysql": "cross-env DIALECT=mysql npm run test-integration",
"test-integration-postgres": "cross-env DIALECT=postgres npm run test-integration",
"test-integration-postgres-native": "cross-env DIALECT=postgres-native npm run test-integration",
"test-integration-sqlite": "cross-env DIALECT=sqlite npm run test-integration",
"test-integration-mssql": "cross-env DIALECT=mssql npm run test-integration",
+ "test-integration-db2": "cross-env DIALECT=db2 npm run test-integration",
+ "test-integration-snowflake": "cross-env DIALECT=snowflake npm run test-integration",
+ "test-integration-oracle": "cross-env LD_LIBRARY_PATH=\"$PWD/.oracle/instantclient/\" DIALECT=oracle UV_THREADPOOL_SIZE=128 npm run test-integration",
"test-mariadb": "cross-env DIALECT=mariadb npm test",
"test-mysql": "cross-env DIALECT=mysql npm test",
"test-sqlite": "cross-env DIALECT=sqlite npm test",
"test-postgres": "cross-env DIALECT=postgres npm test",
"test-postgres-native": "cross-env DIALECT=postgres-native npm test",
"test-mssql": "cross-env DIALECT=mssql npm test",
+ "test-db2": "cross-env DIALECT=db2 npm test",
+ "test-oracle": "cross-env LD_LIBRARY_PATH=\"$PWD/.oracle/instantclient/\" DIALECT=oracle UV_THREADPOOL_SIZE=128 npm test",
"----------------------------------------- development ---------------------------------------------": "",
"sscce": "node sscce.js",
"sscce-mariadb": "cross-env DIALECT=mariadb node sscce.js",
@@ -228,6 +300,11 @@
"sscce-postgres-native": "cross-env DIALECT=postgres-native node sscce.js",
"sscce-sqlite": "cross-env DIALECT=sqlite node sscce.js",
"sscce-mssql": "cross-env DIALECT=mssql node sscce.js",
+ "sscce-db2": "cross-env DIALECT=db2 node sscce.js",
+ "sscce-oracle": "cross-env LD_LIBRARY_PATH=\"$PWD/.oracle/instantclient/\" DIALECT=oracle UV_THREADPOOL_SIZE=128 node sscce.js",
+ "prepare": "npm run build && husky install",
+ "build": "node ./build.js",
"---------------------------------------------------------------------------------------------------": ""
- }
+ },
+ "support": true
}
diff --git a/types/lib/associations/base.d.ts b/src/associations/base.d.ts
similarity index 100%
rename from types/lib/associations/base.d.ts
rename to src/associations/base.d.ts
diff --git a/lib/associations/base.js b/src/associations/base.js
similarity index 100%
rename from lib/associations/base.js
rename to src/associations/base.js
diff --git a/types/lib/associations/belongs-to-many.d.ts b/src/associations/belongs-to-many.d.ts
similarity index 99%
rename from types/lib/associations/belongs-to-many.d.ts
rename to src/associations/belongs-to-many.d.ts
index b04a728af6ee..af3e3075cc86 100644
--- a/types/lib/associations/belongs-to-many.d.ts
+++ b/src/associations/belongs-to-many.d.ts
@@ -1,6 +1,7 @@
import {
BulkCreateOptions,
CreateOptions,
+ CreationAttributes,
Filterable,
FindAttributeOptions,
FindOptions,
@@ -10,7 +11,6 @@ import {
ModelCtor,
ModelType,
Transactionable,
- WhereOptions,
} from '../model';
import { Association, AssociationScope, ForeignKeyOptions, ManyToManyOptions, MultiAssociationAccessors } from './base';
@@ -303,8 +303,8 @@ export interface BelongsToManyCreateAssociationMixinOptions extends CreateOption
* @see https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
* @see Instance
*/
-export type BelongsToManyCreateAssociationMixin = (
- values?: { [attribute: string]: unknown },
+export type BelongsToManyCreateAssociationMixin = (
+ values?: CreationAttributes,
options?: BelongsToManyCreateAssociationMixinOptions
) => Promise;
diff --git a/lib/associations/belongs-to-many.js b/src/associations/belongs-to-many.js
similarity index 98%
rename from lib/associations/belongs-to-many.js
rename to src/associations/belongs-to-many.js
index 27f58701b052..a3d79cd7efb1 100644
--- a/lib/associations/belongs-to-many.js
+++ b/src/associations/belongs-to-many.js
@@ -48,7 +48,6 @@ const Op = require('../operators');
* const projects = await user.getProjects();
* const p1 = projects[0];
* p1.UserProjects.started // Is this project started yet?
- * })
* ```
*
* In the API reference below, add the name of the association to the method, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
@@ -265,7 +264,7 @@ class BelongsToMany extends Association {
// but ignore any keys that are part of this association (#5865)
_.each(this.through.model.rawAttributes, (attribute, attributeName) => {
if (attribute.primaryKey === true && attribute._autoGenerated === true) {
- if (attributeName === this.foreignKey || attributeName === this.otherKey) {
+ if ([this.foreignKey, this.otherKey].includes(attributeName)) {
// this key is still needed as it's part of the association
// so just set primaryKey to false
attribute.primaryKey = false;
@@ -342,6 +341,14 @@ class BelongsToMany extends Association {
this.identifierField = this.through.model.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignIdentifierField = this.through.model.rawAttributes[this.otherKey].field || this.otherKey;
+ // For Db2 server, a reference column of a FOREIGN KEY must be unique
+ // else, server throws SQL0573N error. Hence, setting it here explicitly
+ // for non primary columns.
+ if (this.options.sequelize.options.dialect === 'db2' &&
+ this.source.rawAttributes[this.sourceKey].primaryKey !== true) {
+ this.source.rawAttributes[this.sourceKey].unique = true;
+ }
+
if (this.paired && !this.paired.foreignIdentifierField) {
this.paired.foreignIdentifierField = this.through.model.rawAttributes[this.paired.otherKey].field || this.paired.otherKey;
}
diff --git a/types/lib/associations/belongs-to.d.ts b/src/associations/belongs-to.d.ts
similarity index 94%
rename from types/lib/associations/belongs-to.d.ts
rename to src/associations/belongs-to.d.ts
index 17754ac93775..19d50859290e 100644
--- a/types/lib/associations/belongs-to.d.ts
+++ b/src/associations/belongs-to.d.ts
@@ -1,5 +1,5 @@
import { DataType } from '../data-types';
-import { CreateOptions, FindOptions, Model, ModelCtor, SaveOptions } from '../model';
+import { CreateOptions, CreationAttributes, FindOptions, Model, ModelCtor, SaveOptions } from '../model';
import { Association, AssociationOptions, SingleAssociationAccessors } from './base';
// type ModelCtor = InstanceType;
@@ -116,8 +116,8 @@ export interface BelongsToCreateAssociationMixinOptions
* @see https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html
* @see Instance
*/
-export type BelongsToCreateAssociationMixin = (
- values?: { [attribute: string]: unknown },
+export type BelongsToCreateAssociationMixin = (
+ values?: CreationAttributes,
options?: BelongsToCreateAssociationMixinOptions
) => Promise;
diff --git a/lib/associations/belongs-to.js b/src/associations/belongs-to.js
similarity index 97%
rename from lib/associations/belongs-to.js
rename to src/associations/belongs-to.js
index cf78bd5b021c..a7ad48fa24bd 100644
--- a/lib/associations/belongs-to.js
+++ b/src/associations/belongs-to.js
@@ -185,7 +185,7 @@ class BelongsTo extends Association {
* Set the associated model.
*
* @param {Model} sourceInstance the source instance
- * @param {?|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
+ * @param {?Model|string|number} [associatedInstance] 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.
*
diff --git a/types/lib/associations/has-many.d.ts b/src/associations/has-many.d.ts
similarity index 97%
rename from types/lib/associations/has-many.d.ts
rename to src/associations/has-many.d.ts
index 802ad45a7181..ee83127b845a 100644
--- a/types/lib/associations/has-many.d.ts
+++ b/src/associations/has-many.d.ts
@@ -1,6 +1,7 @@
import { DataType } from '../data-types';
import {
CreateOptions,
+ CreationAttributes,
Filterable,
FindOptions,
InstanceUpdateOptions,
@@ -209,8 +210,12 @@ export interface HasManyCreateAssociationMixinOptions extends CreateOptions
* @see https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
* @see Instance
*/
-export type HasManyCreateAssociationMixin = (
- values?: { [attribute: string]: unknown },
+export type HasManyCreateAssociationMixin<
+ TModel extends Model,
+ TForeignKey extends keyof CreationAttributes = never,
+ TScope extends keyof CreationAttributes = never
+> = (
+ values?: Omit, TForeignKey | TScope>,
options?: HasManyCreateAssociationMixinOptions
) => Promise;
diff --git a/lib/associations/has-many.js b/src/associations/has-many.js
similarity index 100%
rename from lib/associations/has-many.js
rename to src/associations/has-many.js
diff --git a/types/lib/associations/has-one.d.ts b/src/associations/has-one.d.ts
similarity index 94%
rename from types/lib/associations/has-one.d.ts
rename to src/associations/has-one.d.ts
index 7b41fc05196e..692b9e1efcbf 100644
--- a/types/lib/associations/has-one.d.ts
+++ b/src/associations/has-one.d.ts
@@ -1,5 +1,5 @@
import { DataType } from '../data-types';
-import { CreateOptions, FindOptions, Model, ModelCtor, SaveOptions } from '../model';
+import { CreateOptions, CreationAttributes, FindOptions, Model, ModelCtor, SaveOptions } from '../model';
import { Association, AssociationOptions, SingleAssociationAccessors } from './base';
/**
@@ -113,7 +113,7 @@ export interface HasOneCreateAssociationMixinOptions extends HasOneSetAssociatio
* @see https://sequelize.org/master/class/lib/associations/has-one.js~HasOne.html
* @see Instance
*/
-export type HasOneCreateAssociationMixin = (
- values?: { [attribute: string]: unknown },
+export type HasOneCreateAssociationMixin = (
+ values?: CreationAttributes,
options?: HasOneCreateAssociationMixinOptions
) => Promise;
diff --git a/lib/associations/has-one.js b/src/associations/has-one.js
similarity index 97%
rename from lib/associations/has-one.js
rename to src/associations/has-one.js
index 6d19f4263c0a..df9d74fad649 100644
--- a/lib/associations/has-one.js
+++ b/src/associations/has-one.js
@@ -185,7 +185,7 @@ class HasOne extends Association {
* Set the associated model.
*
* @param {Model} sourceInstance the source instance
- * @param {?|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
+ * @param {?Model|string|number} [associatedInstance] 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 getAssociation and `target.save`
*
* @returns {Promise}
diff --git a/lib/associations/helpers.js b/src/associations/helpers.js
similarity index 100%
rename from lib/associations/helpers.js
rename to src/associations/helpers.js
diff --git a/types/lib/associations/index.d.ts b/src/associations/index.d.ts
similarity index 100%
rename from types/lib/associations/index.d.ts
rename to src/associations/index.d.ts
diff --git a/lib/associations/index.js b/src/associations/index.js
similarity index 100%
rename from lib/associations/index.js
rename to src/associations/index.js
diff --git a/lib/associations/mixin.js b/src/associations/mixin.js
similarity index 100%
rename from lib/associations/mixin.js
rename to src/associations/mixin.js
diff --git a/types/lib/data-types.d.ts b/src/data-types.d.ts
similarity index 98%
rename from types/lib/data-types.d.ts
rename to src/data-types.d.ts
index 617b01e84ec0..2eb62626a331 100644
--- a/types/lib/data-types.d.ts
+++ b/src/data-types.d.ts
@@ -52,6 +52,8 @@ export const ABSTRACT: AbstractDataTypeConstructor;
interface AbstractDataTypeConstructor {
key: string;
warn(link: string, text: string): void;
+ new (): AbstractDataType;
+ (): AbstractDataType;
}
export interface AbstractDataType {
@@ -102,7 +104,7 @@ export interface CharDataType extends StringDataType {
}
export interface CharDataTypeOptions extends StringDataTypeOptions {}
-
+
export type TextLength = 'tiny' | 'medium' | 'long';
/**
@@ -112,6 +114,8 @@ export const TEXT: TextDataTypeConstructor;
interface TextDataTypeConstructor extends AbstractDataTypeConstructor {
new (length?: TextLength): TextDataType;
+ new (options?: TextDataTypeOptions): TextDataType;
+ (length?: TextLength): TextDataType;
(options?: TextDataTypeOptions): TextDataType;
}
@@ -334,7 +338,7 @@ interface DateDataTypeConstructor extends AbstractDataTypeConstructor {
(options?: DateDataTypeOptions): DateDataType;
}
-export interface DateDataType extends AbstractDataTypeConstructor {
+export interface DateDataType extends AbstractDataType {
options: DateDataTypeOptions;
}
@@ -365,7 +369,6 @@ export const HSTORE: AbstractDataTypeConstructor;
* A JSON string column. Only available in postgres.
*/
export const JSON: AbstractDataTypeConstructor;
-
/**
* A pre-processed JSON data column. Only available in postgres.
*/
@@ -602,9 +605,14 @@ export const INET: AbstractDataTypeConstructor;
export const MACADDR: AbstractDataTypeConstructor;
/**
- * Case incenstive text
+ * Case-insensitive text
*/
export const CITEXT: AbstractDataTypeConstructor;
+/**
+ * Full text search vector. Only available in postgres.
+ */
+export const TSVECTOR: AbstractDataTypeConstructor;
+
// umzug compatibility
export type DataTypeAbstract = AbstractDataTypeConstructor;
diff --git a/lib/data-types.js b/src/data-types.js
similarity index 96%
rename from lib/data-types.js
rename to src/data-types.js
index e96e334180c7..f75ee2124ba7 100644
--- a/lib/data-types.js
+++ b/src/data-types.js
@@ -211,7 +211,7 @@ class NUMBER extends ABSTRACT {
return true;
}
_stringify(number) {
- if (typeof number === 'number' || typeof number === 'boolean' || number === null || number === undefined) {
+ if (typeof number === 'number' || typeof number === 'bigint' || typeof number === 'boolean' || number === null || number === undefined) {
return number;
}
if (typeof number.toString === 'function') {
@@ -469,7 +469,9 @@ class DATE extends ABSTRACT {
return momentTz(date);
}
_stringify(date, options) {
- date = this._applyTimezone(date, options);
+ if (!moment.isMoment(date)) {
+ date = this._applyTimezone(date, options);
+ }
// Z here means current timezone, _not_ UTC
return date.format('YYYY-MM-DD HH:mm:ss.SSS Z');
}
@@ -792,7 +794,7 @@ class ARRAY extends ABSTRACT {
* GeoJSON is accepted as input and returned as output.
*
* In PostGIS, the GeoJSON is parsed using the PostGIS function `ST_GeomFromGeoJSON`.
- * In MySQL it is parsed using the function `GeomFromText`.
+ * In MySQL it is parsed using the function `ST_GeomFromText`.
*
* Therefore, one can just follow the [GeoJSON spec](https://tools.ietf.org/html/rfc7946) for handling geometry objects. See the following examples:
*
@@ -802,7 +804,7 @@ class ARRAY extends ABSTRACT {
* DataTypes.GEOMETRY('POINT', 4326)
*
* @example