[](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), [DB2](https://en.wikipedia.org/wiki/IBM_Db2_Family) 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
-## Supporting the project
+### 🤝 How to Get Involved
+Interested? Join our Slack and reach out to **@WikiRik** or **@sdepold**:
+➡️ **[sequelize.org/slack](https://sequelize.org/slack)**
-Do you like Sequelize and would like to give back to the engineering team behind it?
+We’d love to have you on board! 🚀
-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. ❤️
+## :computer: Getting Started
+
+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
-$ npm i ibm_db #DB2
-```
+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) (Official)
+- [中文文档](https://github.com/demopark/sequelize-docs-Zh-CN) (Unofficial)
-- [English](https://sequelize.org/master) (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/build.js b/build.js
index 2302c47949b2..a8b1f4604749 100644
--- a/build.js
+++ b/build.js
@@ -13,22 +13,23 @@ const copyFile = promisify(fs.copyFile);
// if this script is moved, this will need to be adjusted
const rootDir = __dirname;
-const outdir = path.join(rootDir, 'dist');
+const outdir = path.join(rootDir, 'lib');
+const typesDir = path.join(rootDir, 'types');
const nodeMajorVersion = Number(process.version.match(/(?<=^v)\d+/));
-async function rmDistDir() {
+async function rmDir(dirName) {
try {
- await stat(outdir);
+ await stat(dirName);
if (nodeMajorVersion >= 14) {
const rm = promisify(fs.rm);
- await rm(outdir, { recursive: true });
+ await rm(dirName, { recursive: true });
} else {
const rmdir = promisify(fs.rmdir);
if (nodeMajorVersion >= 12) {
- await rmdir(outdir, { recursive: true });
+ await rmdir(dirName, { recursive: true });
} else {
- await rmdir(outdir);
+ await rmdir(dirName);
}}
} catch {
/* no-op */
@@ -37,23 +38,46 @@ async function rmDistDir() {
async function main() {
console.log('Compiling sequelize...');
- const [declarationFiles, filesToCompile] = await Promise.all([
- // Find all .d.ts files from types/
- glob('./types/**/*.d.ts', { onlyFiles: true, absolute: false }),
- // Find all .js and .ts files from lib/
- glob('./lib/**/*.[tj]s', { onlyFiles: true, absolute: false }),
- // Delete dist/ for a full rebuild.
- rmDistDir()
+ 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(outdir),
+ 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
@@ -65,13 +89,9 @@ async function main() {
outdir,
entryPoints: filesToCompile
- .concat('./index.js')
.map(file => path.resolve(file))
}),
- // not passed to "build" because we need this file to stay as ESM instead of CJS
- copyFile('./index.mjs', path.resolve(outdir, './index.mjs')),
-
exec('tsc', {
env: {
// binaries installed from modules have symlinks in
diff --git a/dev/mariadb/10.3/start.sh b/dev/mariadb/10.3/start.sh
index 30af181cb667..492b19bca12e 100755
--- a/dev/mariadb/10.3/start.sh
+++ b/dev/mariadb/10.3/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-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
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/start.sh b/dev/mysql/8.0/start.sh
index d3b0aaab912c..046ba95d145b 100755
--- a/dev/mysql/8.0/start.sh
+++ b/dev/mysql/8.0/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-80 down --remove-orphans
-docker-compose -p sequelize-mysql-80 up -d
+docker compose -p sequelize-mysql-80 down --remove-orphans
+docker compose -p sequelize-mysql-80 up -d
./../../wait-until-healthy.sh sequelize-mysql-80
diff --git a/dev/mysql/8.0/stop.sh b/dev/mysql/8.0/stop.sh
index a5a6492ca0f7..8bcf3da8323e 100755
--- a/dev/mysql/8.0/stop.sh
+++ b/dev/mysql/8.0/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-80 down --remove-orphans
+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 5e3c8b469438..4c931cc131f2 100644
--- a/docs/css/style.css
+++ b/docs/css/style.css
@@ -181,6 +181,6 @@ header a {
}
a[href="source.html"],
-a[href^="file/lib/"] {
+a[href^="file/src/"] {
display: none;
}
diff --git a/docs/esdoc-config.js b/docs/esdoc-config.js
index 36b3a867ccc0..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: ['\\.[tj]s$'],
+ excludes: ['\\.d.ts$'],
plugins: [
{
name: 'esdoc-ecmascript-proposal-plugin',
@@ -45,10 +43,8 @@ module.exports = {
site: 'https://sequelize.org/master/'
},
manual: {
- index: './docs/index.md',
- globalIndex: true,
asset: './docs/images',
- files: getDeclaredManuals()
+ files: []
}
}
},
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-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/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 7d8ebf948bfa..1ff71d06b0ae 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,52 +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://opencollective.com/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), [Microsoft SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server), [Amazon Redshift](https://docs.aws.amazon.com/redshift/index.html) and [Snowflake’s Data Cloud](https://docs.snowflake.com/en/user-guide/intro-key-concepts.html). 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).
-
-## Supporting the project
-
-Do you like Sequelize and would like to give back to the engineering team behind it?
-
-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. ❤️
+Click on an entry in the sidebar to open its API Reference.
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 70370ce1536d..000000000000
--- a/docs/manual/advanced-association-concepts/eager-loading.md
+++ /dev/null
@@ -1,666 +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 = await 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 inside the `through` option of the `include` option, and in this case nothing will be fetched and the extra property will not even be created:
-
-```js
-Foo.findOne({
- include: {
- model: Bar,
- through: {
- 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.
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 2a1ade8f216b..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 junction 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.
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 5940095eee02..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 to create custom attributes which also could simplify your 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'
-```
-
-## Deprecated in Sequelize v7: `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'
-})();
-```
diff --git a/docs/manual/core-concepts/getting-started.md b/docs/manual/core-concepts/getting-started.md
deleted file mode 100644
index 94bd14933049..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 3: 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 is still empty, 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 ca2733f6d7d9..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 `DataTypes.NOW`, are also accepted:
-
-```js
-sequelize.define('Foo', {
- bar: {
- type: DataTypes.DATETIME,
- defaultValue: DataTypes.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 `DataTypes.UUIDV1` or `DataTypes.UUIDV4` as the default value:
-
-```js
-{
- type: DataTypes.UUID,
- defaultValue: DataTypes.UUIDV4 // Or DataTypes.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 8c47810ddffb..000000000000
--- a/docs/manual/core-concepts/model-instances.md
+++ /dev/null
@@ -1,197 +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!
-```
-
-You can update several fields at once with the [`set`](../class/lib/model.js~Model.html#instance-method-set) method:
-
-```js
-const jane = await User.create({ name: "Jane" });
-
-jane.set({
- name: "Ada",
- favoriteColor: "blue"
-});
-// As above, the database still has "Jane" and "green"
-await jane.save();
-// The database now has "Ada" and "blue" for name and favorite color
-```
-
-Note that the `save()` here will also persist any other changes that have been made on this instance, not just those in the previous `set` call. If you want to update a specific set of fields, you can use [`update`](../class/lib/model.js~Model.html#instance-method-update):
-
-```js
-const jane = await User.create({ name: "Jane" });
-jane.favoriteColor = "blue"
-await jane.update({ name: "Ada" })
-// The database now has "Ada" for name, but still has the default "green" for favorite color
-await jane.save()
-// Now the database has "Ada" for name and "blue" for favorite color
-```
-
-## 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 91a890208982..000000000000
--- a/docs/manual/core-concepts/model-querying-basics.md
+++ /dev/null
@@ -1,712 +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
-```
-
-### `increment`, `decrement`
-
-Sequelize also provides the `increment` convenience method.
-
-Let's assume we have a user, whose age is 10.
-
-```js
-await User.increment({age: 5}, { where: { id: 1 } }) // Will increase age to 15
-await User.increment({age: -5}, { where: { id: 1 } }) // Will decrease age to 5
-```
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 fed749072ed7..000000000000
--- a/docs/manual/core-concepts/validations-and-constraints.md
+++ /dev/null
@@ -1,272 +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),
- validate: {
- 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 `` `username` 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/aws-lambda.md b/docs/manual/other-topics/aws-lambda.md
deleted file mode 100644
index 002d9b277cf7..000000000000
--- a/docs/manual/other-topics/aws-lambda.md
+++ /dev/null
@@ -1,730 +0,0 @@
-# Using sequelize in AWS Lambda
-
-[AWS Lambda](https://aws.amazon.com/lambda/) is a serverless computing service that allows customers
-to run code without having to worry about the underlying servers. Using `sequelize` in AWS Lambda
-can be tricky if certain concepts are not properly understood and an appropriate configuration is
-not used. This guide seeks to clarify some of these concepts so users of the library can properly
-configure `sequelize` for AWS Lambda and troubleshoot issues.
-
-## TL;DR
-
-If you just want to learn how to properly configure `sequelize`
-[connection pooling](./connection-pool.html) for AWS Lambda, all you need to know is that
-`sequelize` connection pooling does not get along well with AWS Lambda's Node.js runtime and it ends
-up causing more problems than it solves. Therefore, the most appropriate configuration is to **use
-pooling within the same invocation** and **avoid pooling across invocations** (i.e. close all
-connections at the end):
-
-```js
-const { Sequelize } = require("sequelize");
-
-let sequelize = null;
-
-async function loadSequelize() {
- const sequelize = new Sequelize(/* (...) */, {
- // (...)
- pool: {
- /*
- * Lambda functions process one request at a time but your code may issue multiple queries
- * concurrently. Be wary that `sequelize` has methods that issue 2 queries concurrently
- * (e.g. `Model.findAndCountAll()`). Using a value higher than 1 allows concurrent queries to
- * be executed in parallel rather than serialized. Careful with executing too many queries in
- * parallel per Lambda function execution since that can bring down your database with an
- * excessive number of connections.
- *
- * Ideally you want to choose a `max` number where this holds true:
- * max * EXPECTED_MAX_CONCURRENT_LAMBDA_INVOCATIONS < MAX_ALLOWED_DATABASE_CONNECTIONS * 0.8
- */
- max: 2,
- /*
- * Set this value to 0 so connection pool eviction logic eventually cleans up all connections
- * in the event of a Lambda function timeout.
- */
- min: 0,
- /*
- * Set this value to 0 so connections are eligible for cleanup immediately after they're
- * returned to the pool.
- */
- idle: 0,
- // Choose a small enough value that fails fast if a connection takes too long to be established.
- acquire: 3000,
- /*
- * Ensures the connection pool attempts to be cleaned up automatically on the next Lambda
- * function invocation, if the previous invocation timed out.
- */
- evict: CURRENT_LAMBDA_FUNCTION_TIMEOUT
- }
- });
-
- // or `sequelize.sync()`
- await sequelize.authenticate();
-
- return sequelize;
-}
-
-module.exports.handler = async function (event, callback) {
- // re-use the sequelize instance across invocations to improve performance
- if (!sequelize) {
- sequelize = await loadSequelize();
- } else {
- // restart connection pool to ensure connections are not re-used across invocations
- sequelize.connectionManager.initPools();
-
- // restore `getConnection()` if it has been overwritten by `close()`
- if (sequelize.connectionManager.hasOwnProperty("getConnection")) {
- delete sequelize.connectionManager.getConnection;
- }
- }
-
- try {
- return await doSomethingWithSequelize(sequelize);
- } finally {
- // close any opened connections during the invocation
- // this will wait for any in-progress queries to finish before closing the connections
- await sequelize.connectionManager.close();
- }
-};
-```
-
-### Using AWS RDS Proxy
-
-If your are using [AWS RDS](https://aws.amazon.com/rds/) and you are using
-[Aurora](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy.html) or a
-[supported database engine](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy.html),
-then connect to your database using [AWS RDS Proxy](https://aws.amazon.com/rds/proxy/). This will
-make sure that opening/closing connections on each invocation is not an expensive operation for
-your underlying database server.
-
----
-
-If you want to understand why you must use sequelize this way in AWS Lambda, continue reading the
-rest of this document:
-
-## The Node.js event loop
-
-The [Node.js event loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/) is:
-
-> what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is
-> single-threaded —
-
-While the event loop implementation is in C++, here's a simplified JavaScript pseudo-implementation
-that illustrates how Node.js would execute a script named `index.js`:
-
-```js
-// see: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
-// see: https://www.youtube.com/watch?v=P9csgxBgaZ8
-// see: https://www.youtube.com/watch?v=PNa9OMajw9w
-const process = require('process');
-
-/*
- * counter of pending events
- *
- * reference counter is increased for every:
- *
- * 1. scheduled timer: `setTimeout()`, `setInterval()`, etc.
- * 2. scheduled immediate: `setImmediate()`.
- * 3. syscall of non-blocking IO: `require('net').Server.listen()`, etc.
- * 4. scheduled task to the thread pool: `require('fs').WriteStream.write()`, etc.
- *
- * reference counter is decreased for every:
- *
- * 1. elapsed timer
- * 2. executed immediate
- * 3. completed non-blocking IO
- * 4. completed thread pool task
- *
- * references can be explicitly decreased by invoking `.unref()` on some
- * objects like: `require('net').Socket.unref()`
- */
-let refs = 0;
-
-/*
- * a heap of timers, sorted by next ocurrence
- *
- * whenever `setTimeout()` or `setInterval()` is invoked, a timer gets added here
- */
-const timersHeap = /* (...) */;
-
-/*
- * a FIFO queue of immediates
- *
- * whenever `setImmediate()` is invoked, it gets added here
- */
-const immediates = /* (...) */;
-
-/*
- * a FIFO queue of next tick callbacks
- *
- * whenever `require('process').nextTick()` is invoked, the callback gets added here
- */
-const nextTickCallbacks = [];
-
-/*
- * a heap of Promise-related callbacks, sorted by promise constructors callbacks first,
- * and then resolved/rejected callbacks
- *
- * whenever a new Promise instance is created via `new Promise` or a promise resolves/rejects
- * the appropriate callback (if any) gets added here
- */
-const promiseCallbacksHeap = /* ... */;
-
-function execTicksAndPromises() {
- while (nextTickCallbacks.length || promiseCallbacksHeap.size()) {
- // execute all callbacks scheduled with `process.nextTick()`
- while (nextTickCallbacks.length) {
- const callback = nextTickCallbacks.shift();
- callback();
- }
-
- // execute all promise-related callbacks
- while (promiseCallbacksHeap.size()) {
- const callback = promiseCallbacksHeap.pop();
- callback();
- }
- }
-}
-
-try {
- // execute index.js
- require('./index');
- execTicksAndPromises();
-
- do {
- // timers phase: executes all elapsed timers
- getElapsedTimerCallbacks(timersHeap).forEach(callback => {
- callback();
- execTicksAndPromises();
- });
-
- // pending callbacks phase: executes some system operations (like `TCP errors`) that are not
- // executed in the poll phase
- getPendingCallbacks().forEach(callback => {
- callback();
- execTicksAndPromises();
- })
-
- // poll phase: gets completed non-blocking I/O events or thread pool tasks and invokes the
- // corresponding callbacks; if there are none and there's no pending immediates,
- // it blocks waiting for events/completed tasks for a maximum of `maxWait`
- const maxWait = computeWhenNextTimerElapses(timersHeap);
- pollForEventsFromKernelOrThreadPool(maxWait, immediates).forEach(callback => {
- callback();
- execTicksAndPromises();
- });
-
- // check phase: execute available immediates; if an immediate callback invokes `setImmediate()`
- // it will be invoked on the next event loop iteration
- getImmediateCallbacks(immediates).forEach(callback => {
- callback();
- execTicksAndPromises();
- });
-
- // close callbacks phase: execute special `.on('close')` callbacks
- getCloseCallbacks().forEach(callback => {
- callback();
- execTicksAndPromises();
- });
-
- if (refs === 0) {
- // listeners of this event may execute code that increments `refs`
- process.emit('beforeExit');
- }
- } while (refs > 0);
-} catch (err) {
- if (!process.listenerCount('uncaughtException')) {
- // default behavior: print stack and exit with status code 1
- console.error(err.stack);
- process.exit(1);
- } else {
- // there are listeners: emit the event and exit using `process.exitCode || 0`
- process.emit('uncaughtException');
- process.exit();
- }
-}
-```
-
-## AWS Lambda function handler types in Node.js
-
-AWS Lambda handlers come in two flavors in Node.js:
-
-[Non-async handlers](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html#nodejs-handler-sync)
-(i.e. `callback`):
-
-```js
-module.exports.handler = function (event, context, callback) {
- try {
- doSomething();
- callback(null, "Hello World!"); // Lambda returns "Hello World!"
- } catch (err) {
- // try/catch is not required, uncaught exceptions invoke `callback(err)` implicitly
- callback(err); // Lambda fails with `err`
- }
-};
-```
-
-[Async handlers](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html#nodejs-handler-async)
-(i.e. use `async`/`await` or `Promise`s):
-
-```js
-// async/await
-module.exports.handler = async function (event, context) {
- try {
- await doSomethingAsync();
- return "Hello World!"; // equivalent of: callback(null, "Hello World!");
- } catch (err) {
- // try/cath is not required, async functions always return a Promise
- throw err; // equivalent of: callback(err);
- }
-};
-
-// Promise
-module.exports.handler = function (event, context) {
- /*
- * must return a `Promise` to be considered an async handler
- *
- * an uncaught exception that prevents a `Promise` to be returned
- * by the handler will "downgrade" the handler to non-async
- */
- return Promise.resolve()
- .then(() => doSomethingAsync())
- .then(() => "Hello World!");
-};
-```
-
-While at first glance it seems like async VS non-async handlers are simply a code styling choice,
-there is a fundamental difference between the two:
-
-- In async handlers, a Lambda function execution finishes when the `Promise` returned by the handler
- resolves or rejects, regardless of whether the event loop is empty or not.
-- In non-async handlers, a Lambda function execution finishes when one of the following conditions
- occur:
- - The event loop is empty
- ([process `'beforeExit'` event](https://nodejs.org/dist/latest-v12.x/docs/api/process.html#process_event_beforeexit)
- is used to detect this).
- - The `callback` argument is invoked and
- [`context.callbackWaitsForEmptyEventLoop`](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html)
- is set to `false`.
-
-This fundamental difference is very important to understand in order to rationalize how `sequelize`
-may be affected by it. Here are a few examples to illustrate the difference:
-
-```js
-// no callback invoked
-module.exports.handler = function () {
- // Lambda finishes AFTER `doSomething()` is invoked
- setTimeout(() => doSomething(), 1000);
-};
-
-// callback invoked
-module.exports.handler = function (event, context, callback) {
- // Lambda finishes AFTER `doSomething()` is invoked
- setTimeout(() => doSomething(), 1000);
- callback(null, "Hello World!");
-};
-
-// callback invoked, context.callbackWaitsForEmptyEventLoop = false
-module.exports.handler = function (event, context, callback) {
- // Lambda finishes BEFORE `doSomething()` is invoked
- context.callbackWaitsForEmptyEventLoop = false;
- setTimeout(() => doSomething(), 2000);
- setTimeout(() => callback(null, "Hello World!"), 1000);
-};
-
-// async/await
-module.exports.handler = async function () {
- // Lambda finishes BEFORE `doSomething()` is invoked
- setTimeout(() => doSomething(), 1000);
- return "Hello World!";
-};
-
-// Promise
-module.exports.handler = function () {
- // Lambda finishes BEFORE `doSomething()` is invoked
- setTimeout(() => doSomething(), 1000);
- return Promise.resolve("Hello World!");
-};
-```
-
-## AWS Lambda execution environments (i.e. containers)
-
-AWS Lambda function handlers are invoked by built-in or custom
-[runtimes](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) which run in
-execution environments (i.e. containers) that
-[may or may not be re-used](https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/)
-across invocations. Containers can only process
-[one request at a time](https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html).
-Concurrent invocations of a Lambda function means that a container instance will be created for each
-concurrent request.
-
-In practice, this means that Lambda functions should be designed to be stateless but developers can
-use state for caching purposes:
-
-```js
-let sequelize = null;
-
-module.exports.handler = async function () {
- /*
- * sequelize will already be loaded if the container is re-used
- *
- * containers are never re-used when a Lambda function's code change
- *
- * while the time elapsed between Lambda invocations is used as a factor to determine whether
- * a container is re-used, no assumptions should be made of when a container is actually re-used
- *
- * AWS does not publicly document the rules of container re-use "by design" since containers
- * can be recycled in response to internal AWS Lambda events (e.g. a Lambda function container
- * may be recycled even if the function is constanly invoked)
- */
- if (!sequelize) {
- sequelize = await loadSequelize();
- }
-
- return await doSomethingWithSequelize(sequelize);
-};
-```
-
-When a Lambda function doesn't wait for the event loop to be empty and a container is re-used,
-the event loop will be "paused" until the next invocation occurs. For example:
-
-```js
-let counter = 0;
-
-module.exports.handler = function (event, context, callback) {
- /*
- * The first invocation (i.e. container initialized) will:
- * - log:
- * - Fast timeout invoked. Request id: 00000000-0000-0000-0000-000000000000 | Elapsed ms: 5XX
- * - return: 1
- *
- * Wait 3 seconds and invoke the Lambda again. The invocation (i.e. container re-used) will:
- * - log:
- * - Slow timeout invoked. Request id: 00000000-0000-0000-0000-000000000000 | Elapsed ms: 3XXX
- * - Fast timeout invoked. Request id: 11111111-1111-1111-1111-111111111111 | Elapsed ms: 5XX
- * - return: 3
- */
- const now = Date.now();
-
- context.callbackWaitsForEmptyEventLoop = false;
-
- setTimeout(() => {
- console.log(
- "Slow timeout invoked. Request id:",
- context.awsRequestId,
- "| Elapsed ms:",
- Date.now() - now
- );
- counter++;
- }, 1000);
-
- setTimeout(() => {
- console.log(
- "Fast timeout invoked. Request id:",
- context.awsRequestId,
- "| Elapsed ms:",
- Date.now() - now
- );
- counter++;
- callback(null, counter);
- }, 500);
-};
-```
-
-## Sequelize connection pooling in AWS Lambda
-
-`sequelize` uses connection pooling for optimizing usage of database connections. The connection
-pool used by `sequelize` is implemented using `setTimeout()` callbacks (which are processed by the
-Node.js event loop).
-
-Given the fact that AWS Lambda containers process one request at a time, one would be tempted to
-configure `sequelize` as follows:
-
-```js
-const { Sequelize } = require('sequelize');
-
-const sequelize = new Sequelize(/* (...) */, {
- // (...)
- pool: { min: 1, max: 1 }
-});
-```
-
-This configuration prevents Lambda containers from overwhelming the database server with an
-excessive number of connections (since each container takes at most 1 connection). It also makes
-sure that the container's connection is not garbage collected when idle so the connection does not
-need to be re-established when the Lambda container is re-used. Unfortunately, this configuration
-presents a set of issues:
-
-1. Lambdas that wait for the event loop to be empty will always time out. `sequelize` connection
- pools schedule a `setTimeout` every
- [`options.pool.evict`](../class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor)
- ms until **all idle connections have been closed**. However, since `min` is set to `1`, there
- will always be at least one idle connection in the pool, resulting in an infinite event loop.
-1. Some operations like
- [`Model.findAndCountAll()`](../class/lib/model.js~Model.html#static-method-findAndCountAll)
- execute multiple queries asynchronously (e.g.
- [`Model.count()`](..class/lib/model.js~Model.html#static-method-count) and
- [`Model.findAll()`](../class/lib/model.js~Model.html#static-method-findAll)). Using a maximum of
- one connection forces the queries to be exectued serially (rather than in parallel using two
- connections). While this may be an acceptable performance compromise in order to
- maintain a manageable number of database connections, long running queries may result in
- [`ConnectionAcquireTimeoutError`](../class/lib/errors/connection/connection-acquire-timeout-error.js~ConnectionAcquireTimeoutError.html)
- if a query takes more than the default or configured
- [`options.pool.acquire`](../class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor)
- timeout to complete. This is because the serialized query will be stuck waiting on the pool until
- the connection used by the other query is released.
-1. If the AWS Lambda function times out (i.e. the configured AWS Lambda timeout is exceeded), the
- Node.js event loop will be "paused" regardless of its state. This can cause race conditions that
- result in connection errors. For example, you may encounter situations where a very expensive
- query causes a Lambda function to time out, the event loop is "paused" before the expensive query
- finishes and the connection is released back to the pool, and subsequent Lambda invocations fail
- with a `ConnectionAcquireTimeoutError` if the container is re-used and the connection has not
- been returned after `options.pool.acquire` ms.
-
-You can attempt to mitigate issue **#2** by using `{ min: 1, max: 2 }`. However, this will still
-suffer from issues **#1** and **#3** whilst introducing additional ones:
-
-1. Race conditions may occur where the even loop "pauses" before a connection pool eviction callback
- executes or more than `options.pool.evict` time elapses between Lambda invocations. This can
- result in timeout errors, handshake errors, and other connection-related errors.
-1. If you use an operation like `Model.findAndCountAll()` and either the underlying `Model.count()`
- or `Model.findAll()` queries fail, you won't be able to ensure that the other query has finished
- executing (and the connection is put back into the pool) before the Lambda function execution
- finishes and the event loop is "paused". This can leave connections in a stale state which can
- result in prematurely closed TCP connections and other connection-related errors.
-
-Using `{ min: 2, max: 2 }` mitigates additional issue **#1**. However, the configuration still
-suffers from all the other issues (original **#1**, **#3**, and additional **#2**).
-
-### Detailed race condition example
-
-In order to make sense of the example, you'll need a bit more context of how certain parts of
-Lambda and `sequelize` are implemented.
-
-The built-in AWS Lambda runtime for `nodejs.12x` is implemented in Node.js. You can access the
-entire source code of the runtime by reading the contents of `/var/runtime/` inside a Node.js Lambda
-function. The relevant subset of the code is as follows:
-
-**runtime/Runtime.js**
-
-```js
-class Runtime {
- // (...)
-
- // each iteration is executed in the event loop `check` phase
- scheduleIteration() {
- setImmediate(() => this.handleOnce().then(/* (...) */));
- }
-
- async handleOnce() {
- // get next invocation. see: https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next
- let { bodyJson, headers } = await this.client.nextInvocation();
-
- // prepare `context` handler parameter
- let invokeContext = new InvokeContext(headers);
- invokeContext.updateLoggingContext();
-
- // prepare `callback` handler parameter
- let [callback, callbackContext] = CallbackContext.build(
- this.client,
- invokeContext.invokeId,
- this.scheduleIteration.bind(this)
- );
-
- try {
- // this listener is subscribed to process.on('beforeExit')
- // so that when when `context.callbackWaitsForEmptyEventLoop === true`
- // the Lambda execution finishes after the event loop is empty
- this._setDefaultExitListener(invokeContext.invokeId);
-
- // execute handler
- const result = this.handler(
- JSON.parse(bodyJson),
- invokeContext.attachEnvironmentData(callbackContext),
- callback
- );
-
- // finish the execution if the handler is async
- if (_isPromise(result)) {
- result
- .then(callbackContext.succeed, callbackContext.fail)
- .catch(callbackContext.fail);
- }
- } catch (err) {
- callback(err);
- }
- }
-}
-```
-
-The runtime schedules an iteration at the end of the initialization code:
-
-**runtime/index.js**
-
-```js
-// (...)
-
-new Runtime(client, handler, errorCallbacks).scheduleIteration();
-```
-
-All SQL queries invoked by a Lambda handler using `sequelize` are ultimately executed using
-[Sequelize.prototype.query()](../class/lib/sequelize.js~Sequelize.html#instance-method-query).
-This method is responsible for obtaining a connection from the pool, executing the query, and
-releasing the connection back to the pool when the query completes. The following snippet shows
-a simplification of the method's logic for queries without transactions:
-
-**sequelize.js**
-
-```js
-class Sequelize {
- // (...)
-
- query(sql, options) {
- // (...)
-
- const connection = await this.connectionManager.getConnection(options);
- const query = new this.dialect.Query(connection, this, options);
-
- try {
- return await query.run(sql, bindParameters);
- } finally {
- await this.connectionManager.releaseConnection(connection);
- }
- }
-}
-```
-
-The field `this.connectionManager` is an instance of a dialect-specific `ConnectionManager` class.
-All dialect-specific managers inherit from an abstract `ConnectionManager` class which initializes
-the connection pool and configures it to invoke the dialect-specific class' `connect()` method
-everytime a new connection needs to be created. The following snippet shows a simplification of the
-`mysql` dialect `connect()` method:
-
-**mysql/connection-manager.js**
-
-```js
-class ConnectionManager {
- // (...)
-
- async connect(config) {
- // (...)
- return await new Promise((resolve, reject) => {
- // uses mysql2's `new Connection()`
- const connection = this.lib.createConnection(connectionConfig);
-
- const errorHandler = (e) => {
- connection.removeListener("connect", connectHandler);
- connection.removeListener("error", connectHandler);
- reject(e);
- };
-
- const connectHandler = () => {
- connection.removeListener("error", errorHandler);
- resolve(connection);
- };
-
- connection.on("error", errorHandler);
- connection.once("connect", connectHandler);
- });
- }
-}
-```
-
-The field `this.lib` refers to [`mysql2`](https://www.npmjs.com/package/mysql2) and the function
-`createConnection()` creates a connection by creating an instance of a `Connection` class. The
-relevant subset of this class is as follows:
-
-**mysql2/connection.js**
-
-```js
-class Connection extends EventEmitter {
- constructor(opts) {
- // (...)
-
- // create Socket
- this.stream = /* (...) */;
-
- // when data is received, clear timeout
- this.stream.on('data', data => {
- if (this.connectTimeout) {
- Timers.clearTimeout(this.connectTimeout);
- this.connectTimeout = null;
- }
- this.packetParser.execute(data);
- });
-
- // (...)
-
- // when handshake is completed, emit the 'connect' event
- handshakeCommand.on('end', () => {
- this.emit('connect', handshakeCommand.handshake);
- });
-
- // set a timeout to trigger if no data is received on the socket
- if (this.config.connectTimeout) {
- const timeoutHandler = this._handleTimeoutError.bind(this);
- this.connectTimeout = Timers.setTimeout(
- timeoutHandler,
- this.config.connectTimeout
- );
- }
- }
-
- // (...)
-
- _handleTimeoutError() {
- if (this.connectTimeout) {
- Timers.clearTimeout(this.connectTimeout);
- this.connectTimeout = null;
- }
- this.stream.destroy && this.stream.destroy();
- const err = new Error('connect ETIMEDOUT');
- err.errorno = 'ETIMEDOUT';
- err.code = 'ETIMEDOUT';
- err.syscall = 'connect';
-
- // this will emit the 'error' event
- this._handleNetworkError(err);
- }
-}
-```
-
-Based on the previous code, the following sequence of events shows how a connection pooling
-race condition with `{ min: 1, max: 1 }` can result with in a `ETIMEDOUT` error:
-
-1. A Lambda invocation is received (new container):
- 1. The event loop enters the `check` phase and `runtime/Runtime.js`'s `handleOnce()` method is
- invoked.
- 1. The `handleOnce()` method invokes `await this.client.nextInvocation()` and waits.
- 1. The event loop skips the `timers` phase since there no pending timers.
- 1. The event loop enters the `poll` phase and the `handleOnce()` method continues.
- 1. The Lambda handler is invoked.
- 1. The Lambda handler invokes `Model.count()` which invokes `sequelize.js`'s `query()` which
- invokes `connectionManager.getConnection()`.
- 1. The connection pool initializes a `setTimeout(..., config.pool.acquire)` for `Model.count()`
- and invokes `mysql/connection-manager.js`'s `connect()` to create a new connection.
- 1. `mysql2/connection.js` creates the TCP socket and initializes a `setTimeout()` for failing
- the connection with `ETIMEDOUT`.
- 1. The promise returned by the handler rejects (for reasons not detailed here) so the Lambda
- function execution finishes and the Node.js event loop is "paused".
-1. Enough time elapses beween invocations so that:
- 1. `config.pool.acquire` timer elapses.
- 1. `mysql2` connection timer has not elapsed yet but has almost elapsed (i.e. race condition).
-1. A second Lambda invocation is received (container re-used):
- 1. The event loop is "resumed".
- 1. The event loop enters the `check` phase and `runtime/Runtime.js`'s `handleOnce()` method is
- invoked.
- 1. The event loop enters the `timers` phase and the `config.pool.acquire` timer elapses, causing
- the previous invocation's `Model.count()` promise to reject with
- `ConnectionAcquireTimeoutError`.
- 1. The event loop enters the `poll` phase and the `handleOnce()` method continues.
- 1. The Lambda handler is invoked.
- 1. The Lambda handler invokes `Model.count()` which invokes `sequelize.js`'s `query()` which
- invokes `connectionManager.getConnection()`.
- 1. The connection pool initializes a `setTimeout(..., config.pool.acquire)` for `Model.count()`
- and since `{ max : 1 }` it waits for the pending `connect()` promise to complete.
- 1. The event loop skips the `check` phase since there are no pending immediates.
- 1. **Race condition:** The event loop enters the `timers` phase and the `mysql2` connection
- timeout elapses, resulting in a `ETIMEDOUT` error that is emitted using
- `connection.emit('error')`.
- 1. The emitted event rejects the promise in `mysql/connection-manager.js`'s `connect()` which
- in turn forwards the rejected promise to the `Model.count()` query's promise.
- 1. The lambda function fails with an `ETIMEDOUT` error.
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 2eac0d1cc8de..000000000000
--- a/docs/manual/other-topics/dialect-specific-things.md
+++ /dev/null
@@ -1,270 +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'
-});
-```
-
-The default `client_min_messages` config in sequelize is `WARNING`.
-
-### Redshift
-
-Most configuration is same as PostgreSQL above.
-
-Redshift doesn't support `client_min_messages`, 'ignore' is needed to skip the configuration:
-
-```js
-const sequelize = new Sequelize('database', 'username', 'password', {
- dialect: 'postgres',
- dialectOptions: {
- // Your pg options here
- // ...
- clientMinMessages: 'ignore' // case insensitive
- }
-});
-```
-
-### 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'
- }
- }
-})
-```
-
-### Snowflake (Experiment)
-
-The underlying connector library used by Sequelize for Snowflake is the [snowflake-sdk](https://www.npmjs.com/package/snowflake-sdk) npm package.
-
-In order to connect with an account, use the following format:
-
-```js
-const sequelize = new Sequelize('database', null, null, {
- dialect: 'snowflake',
- dialectOptions: {
- // put your snowflake account here,
- account: 'myAccount', // my-app.us-east-1
-
- // below option should be optional
- role: 'myRole',
- warehouse: 'myWarehouse',
- schema: 'mySchema'
- },
- // same as other dialect
- username: 'myUserName',
- password: 'myPassword',
- database: 'myDatabaseName'
-})
-```
-
-**NOTE** There is no test sandbox provided so the snowflake integration test is not part of the pipeline. Also it is difficult for core team to triage and debug. This dialect needs to be maintained by the snowflake user/community for now.
-
-For running integration test:
-
-```sh
-SEQ_ACCOUNT=myAccount SEQ_USER=myUser SEQ_PW=myPassword SEQ_ROLE=myRole SEQ_DB=myDatabaseName SEQ_SCHEMA=mySchema SEQ_WH=myWareHouse npm run test-integration-snowflake
-```
-
-## 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 682b6cda7ac9..000000000000
--- a/docs/manual/other-topics/hooks.md
+++ /dev/null
@@ -1,403 +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 that are run for all models. They are especially useful for plugins and can define behaviours that you want for all your models, for example to allow customization on timestamps using `sequelize.define` on your models:
-
-```js
-const User = sequelize.define('User', {}, {
- tableName: 'users',
- hooks : {
- beforeCreate : (record, options) => {
- record.dataValues.createdAt = new Date().toISOString().replace(/T/, ' ').replace(/\..+/g, '');
- record.dataValues.updatedAt = new Date().toISOString().replace(/T/, ' ').replace(/\..+/g, '');
- },
- beforeUpdate : (record, options) => {
- record.dataValues.updatedAt = new Date().toISOString().replace(/T/, ' ').replace(/\..+/g, '');
- }
- }
-});
-```
-
-They can be defined in many 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 c5ae37d5c28d..000000000000
--- a/docs/manual/other-topics/resources.md
+++ /dev/null
@@ -1,70 +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/).
-
-### Bcrypt
-
-* [sequelize-bcrypt](https://github.com/mattiamalonni/sequelize-bcrypt) - Utility to integrate bcrypt into sequelize models
-
-### 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)
-
-### Joi
-
-* [sequelize-joi](https://github.com/mattiamalonni/sequelize-joi) - Allows specifying [Joi](https://github.com/sideway/joi) validation schema for model attributes in Sequelize.
-
-### 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.
-* [sqlcommenter-sequelize](https://github.com/google/sqlcommenter/tree/master/nodejs/sqlcommenter-nodejs/packages/sqlcommenter-sequelize) A [sqlcommenter](https://google.github.io/sqlcommenter/) plugin with [support for Sequelize](https://google.github.io/sqlcommenter/node/sequelize/) to augment SQL statements with comments that can be used later to correlate application code with SQL statements.
diff --git a/docs/manual/other-topics/scopes.md b/docs/manual/other-topics/scopes.md
deleted file mode 100644
index 96a531115122..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.
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/index.js b/index.js
index 942290085172..c41e6e3916a0 100644
--- a/index.js
+++ b/index.js
@@ -1,5 +1,7 @@
'use strict';
+// TODO [>=7]: remove me. I've been moved to 'exports' in package.json
+
/**
* A Sequelize module that contains the sequelize entry point.
*
@@ -7,4 +9,4 @@
*/
/** Exports the sequelize entry point. */
-module.exports = require('./lib/sequelize');
+module.exports = require('./lib');
diff --git a/lib/sql-string.js b/lib/sql-string.js
deleted file mode 100644
index d56c0468b300..000000000000
--- a/lib/sql-string.js
+++ /dev/null
@@ -1,125 +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 (['sqlite', 'mssql'].includes(dialect)) {
- 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 (['postgres', 'sqlite', 'mssql', 'snowflake', 'db2'].includes(dialect)) {
- // 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/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.json b/package.json
index 587743e241f0..bc69e634ae69 100644
--- a/package.json
+++ b/package.json
@@ -16,59 +16,69 @@
"url": "https://github.com/sequelize/sequelize/issues"
},
"homepage": "https://sequelize.org/",
- "main": "./dist/index.js",
- "types": "./dist",
+ "main": "./lib/index.js",
+ "types": "./types/index.d.ts",
"type": "commonjs",
"exports": {
".": {
- "import": "./dist/index.mjs",
- "require": "./dist/index.js"
+ "types": "./types/index.d.ts",
+ "import": "./lib/index.mjs",
+ "require": "./lib/index.js"
},
- "./lib/*": "./dist/lib/*.js",
- "./lib/errors": "./dist/lib/errors/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": [
- "dist",
"lib",
- "index.js",
- "types/index.d.ts",
- "types/lib",
- "types/type-helpers"
+ "types",
+ "index.js"
],
"license": "MIT",
"dependencies": {
- "@types/debug": "^4.1.7",
- "debug": "^4.3.3",
- "dottie": "^2.0.2",
- "inflection": "^1.13.1",
+ "@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.1",
- "moment-timezone": "^0.5.34",
- "pg-connection-string": "^2.5.0",
- "retry-as-promised": "^5.0.0",
- "semver": "^7.3.5",
+ "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.3.2",
- "validator": "^13.7.0",
+ "validator": "^13.9.0",
"wkx": "^0.5.0"
},
"devDependencies": {
"@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",
- "@types/validator": "^13.7.1",
"@typescript-eslint/eslint-plugin": "^5.8.1",
"@typescript-eslint/parser": "^5.8.1",
"acorn": "^8.7.0",
- "chai": "^4.3.4",
+ "chai": "^4.3.7",
"chai-as-promised": "^7.1.1",
"chai-datetime": "^1.8.0",
"cheerio": "^1.0.0-rc.10",
@@ -88,6 +98,7 @@
"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",
@@ -95,10 +106,10 @@
"markdownlint-cli": "^0.30.0",
"mocha": "^7.2.0",
"module-alias": "^2.2.2",
- "ibm_db": "^2.8.1",
"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",
@@ -112,7 +123,7 @@
"sinon-chai": "^3.7.0",
"snowflake-sdk": "^1.6.6",
"source-map-support": "^0.5.21",
- "sqlite3": "npm:@vscode/sqlite3@^5.0.7",
+ "sqlite3": "^5.1.6",
"tedious": "8.3.0",
"typescript": "^4.5.4"
},
@@ -140,6 +151,9 @@
},
"tedious": {
"optional": true
+ },
+ "oracledb": {
+ "optional": true
}
},
"keywords": [
@@ -153,6 +167,7 @@
"db2",
"ibm_db",
"sql",
+ "oracledb",
"sqlserver",
"snowflake",
"orm",
@@ -209,11 +224,11 @@
},
"scripts": {
"----------------------------------------- static analysis -----------------------------------------": "",
- "lint": "eslint lib test --quiet --fix",
+ "lint": "eslint src test --quiet --fix",
"lint-docs": "markdownlint docs",
- "test-typings": "tsc -b types/tsconfig.json && tsc -b types/test/tsconfig.json && tsc --noEmit --emitDeclarationOnly false && tsc -b 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 ---------------------------------------------------": "",
"mocha": "mocha -r ./test/registerEsbuild",
"test-unit": "yarn mocha \"test/unit/**/*.test.[tj]s\"",
@@ -232,16 +247,23 @@
"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",
@@ -251,7 +273,8 @@
"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-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",
+ "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",
@@ -260,6 +283,7 @@
"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",
@@ -267,6 +291,7 @@
"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",
@@ -276,6 +301,7 @@
"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",
"---------------------------------------------------------------------------------------------------": ""
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 b7106ffb197b..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,
@@ -9,7 +10,7 @@ import {
Model,
ModelCtor,
ModelType,
- Transactionable
+ Transactionable,
} from '../model';
import { Association, AssociationScope, ForeignKeyOptions, ManyToManyOptions, MultiAssociationAccessors } from './base';
@@ -303,7 +304,7 @@ export interface BelongsToManyCreateAssociationMixinOptions extends CreateOption
* @see Instance
*/
export type BelongsToManyCreateAssociationMixin = (
- values?: TModel['_creationAttributes'],
+ values?: CreationAttributes,
options?: BelongsToManyCreateAssociationMixinOptions
) => Promise;
diff --git a/lib/associations/belongs-to-many.js b/src/associations/belongs-to-many.js
similarity index 100%
rename from lib/associations/belongs-to-many.js
rename to src/associations/belongs-to-many.js
diff --git a/types/lib/associations/belongs-to.d.ts b/src/associations/belongs-to.d.ts
similarity index 96%
rename from types/lib/associations/belongs-to.d.ts
rename to src/associations/belongs-to.d.ts
index fd2a5e356b2a..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;
@@ -117,7 +117,7 @@ export interface BelongsToCreateAssociationMixinOptions
* @see Instance
*/
export type BelongsToCreateAssociationMixin = (
- values?: TModel['_creationAttributes'],
+ values?: CreationAttributes,
options?: BelongsToCreateAssociationMixinOptions
) => Promise;
diff --git a/lib/associations/belongs-to.js b/src/associations/belongs-to.js
similarity index 100%
rename from lib/associations/belongs-to.js
rename to src/associations/belongs-to.js
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 26b62444b13f..ee83127b845a 100644
--- a/types/lib/associations/has-many.d.ts
+++ b/src/associations/has-many.d.ts
@@ -1,12 +1,13 @@
import { DataType } from '../data-types';
import {
CreateOptions,
+ CreationAttributes,
Filterable,
FindOptions,
InstanceUpdateOptions,
Model,
ModelCtor,
- Transactionable
+ Transactionable,
} from '../model';
import { Association, ManyToManyOptions, MultiAssociationAccessors } from './base';
@@ -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?: TModel['_creationAttributes'],
+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 96%
rename from types/lib/associations/has-one.d.ts
rename to src/associations/has-one.d.ts
index e81784b3d88a..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';
/**
@@ -114,6 +114,6 @@ export interface HasOneCreateAssociationMixinOptions extends HasOneSetAssociatio
* @see Instance
*/
export type HasOneCreateAssociationMixin = (
- values?: TModel['_creationAttributes'],
+ values?: CreationAttributes,
options?: HasOneCreateAssociationMixinOptions
) => Promise;
diff --git a/lib/associations/has-one.js b/src/associations/has-one.js
similarity index 100%
rename from lib/associations/has-one.js
rename to src/associations/has-one.js
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 d95f78d83dfd..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';
/**
@@ -336,7 +338,7 @@ interface DateDataTypeConstructor extends AbstractDataTypeConstructor {
(options?: DateDataTypeOptions): DateDataType;
}
-export interface DateDataType extends AbstractDataTypeConstructor {
+export interface DateDataType extends AbstractDataType {
options: DateDataTypeOptions;
}
@@ -367,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.
*/
@@ -604,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 99%
rename from lib/data-types.js
rename to src/data-types.js
index 371652be60f9..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') {
@@ -1060,6 +1060,7 @@ dialectMap.sqlite = require('./dialects/sqlite/data-types')(DataTypes);
dialectMap.mssql = require('./dialects/mssql/data-types')(DataTypes);
dialectMap.db2 = require('./dialects/db2/data-types')(DataTypes);
dialectMap.snowflake = require('./dialects/snowflake/data-types')(DataTypes);
+dialectMap.oracle = require('./dialects/oracle/data-types')(DataTypes);
const dialectList = Object.values(dialectMap);
diff --git a/types/lib/deferrable.d.ts b/src/deferrable.d.ts
similarity index 100%
rename from types/lib/deferrable.d.ts
rename to src/deferrable.d.ts
diff --git a/lib/deferrable.js b/src/deferrable.js
similarity index 100%
rename from lib/deferrable.js
rename to src/deferrable.js
diff --git a/types/lib/connection-manager.d.ts b/src/dialects/abstract/connection-manager.d.ts
similarity index 76%
rename from types/lib/connection-manager.d.ts
rename to src/dialects/abstract/connection-manager.d.ts
index 8bb7674918b9..b3b0907a033d 100644
--- a/types/lib/connection-manager.d.ts
+++ b/src/dialects/abstract/connection-manager.d.ts
@@ -28,7 +28,12 @@ export interface ConnectionManager {
*/
getConnection(opts: GetConnectionOptions): Promise;
/**
- * Release a pooled connection so it can be utilized by other connection requests
+ * Release a pooled connection, so it can be utilized by other connection requests
*/
- releaseConnection(conn: Connection): Promise;
+ releaseConnection(conn: Connection): void;
+
+ /**
+ * Destroys a pooled connection and removes it from the pool.
+ */
+ destroyConnection(conn: Connection): Promise;
}
diff --git a/lib/dialects/abstract/connection-manager.js b/src/dialects/abstract/connection-manager.js
similarity index 96%
rename from lib/dialects/abstract/connection-manager.js
rename to src/dialects/abstract/connection-manager.js
index 8f6ee9f44f99..5d58ea134938 100644
--- a/lib/dialects/abstract/connection-manager.js
+++ b/src/dialects/abstract/connection-manager.js
@@ -283,7 +283,13 @@ class ConnectionManager {
let result;
try {
+
+ await this.sequelize.runHooks('beforePoolAcquire', options);
+
result = await this.pool.acquire(options.type, options.useMaster);
+
+ await this.sequelize.runHooks('afterPoolAcquire', result, options);
+
} catch (error) {
if (error instanceof TimeoutError) throw new errors.ConnectionAcquireTimeoutError(error);
throw error;
@@ -298,14 +304,22 @@ class ConnectionManager {
* Release a pooled connection so it can be utilized by other connection requests
*
* @param {Connection} connection
- *
- * @returns {Promise}
*/
- async releaseConnection(connection) {
+ releaseConnection(connection) {
this.pool.release(connection);
debug('connection released');
}
+ /**
+ * Destroys a pooled connection and removes it from the pool.
+ *
+ * @param {Connection} connection
+ */
+ async destroyConnection(connection) {
+ await this.pool.destroy(connection);
+ debug(`connection ${connection.uuid} destroyed`);
+ }
+
/**
* Call dialect library to get connection
*
diff --git a/src/dialects/abstract/index.d.ts b/src/dialects/abstract/index.d.ts
new file mode 100644
index 000000000000..878efebb83d3
--- /dev/null
+++ b/src/dialects/abstract/index.d.ts
@@ -0,0 +1,109 @@
+import type { Dialect } from '../../sequelize.js';
+import type { AbstractQuery } from './query.js';
+
+export declare type DialectSupports = {
+ 'DEFAULT': boolean;
+ 'DEFAULT VALUES': boolean;
+ 'VALUES ()': boolean;
+ 'LIMIT ON UPDATE': boolean;
+ 'ON DUPLICATE KEY': boolean;
+ 'ORDER NULLS': boolean;
+ 'UNION': boolean;
+ 'UNION ALL': boolean;
+ 'RIGHT JOIN': boolean;
+ EXCEPTION: boolean;
+ forShare?: 'LOCK IN SHARE MODE' | 'FOR SHARE' | undefined;
+ lock: boolean;
+ lockOf: boolean;
+ lockKey: boolean;
+ lockOuterJoinFailure: boolean;
+ skipLocked: boolean;
+ finalTable: boolean;
+ returnValues: false | {
+ output: boolean;
+ returning: boolean;
+ };
+ autoIncrement: {
+ identityInsert: boolean;
+ defaultValue: boolean;
+ update: boolean;
+ };
+ bulkDefault: boolean;
+ schemas: boolean;
+ transactions: boolean;
+ settingIsolationLevelDuringTransaction: boolean;
+ transactionOptions: {
+ type: boolean;
+ };
+ migrations: boolean;
+ upserts: boolean;
+ inserts: {
+ ignoreDuplicates: string;
+ updateOnDuplicate: boolean | string;
+ onConflictDoNothing: string;
+ onConflictWhere: boolean,
+ conflictFields: boolean;
+ };
+ constraints: {
+ restrict: boolean;
+ addConstraint: boolean;
+ dropConstraint: boolean;
+ unique: boolean;
+ default: boolean;
+ check: boolean;
+ foreignKey: boolean;
+ primaryKey: boolean;
+ onUpdate: boolean;
+ };
+ index: {
+ collate: boolean;
+ length: boolean;
+ parser: boolean;
+ concurrently: boolean;
+ type: boolean;
+ using: boolean | number;
+ functionBased: boolean;
+ operator: boolean;
+ where: boolean;
+ };
+ groupedLimit: boolean;
+ indexViaAlter: boolean;
+ JSON: boolean;
+ JSONB: boolean;
+ ARRAY: boolean;
+ RANGE: boolean;
+ NUMERIC: boolean;
+ GEOMETRY: boolean;
+ GEOGRAPHY: boolean;
+ REGEXP: boolean;
+ /**
+ * Case-insensitive regexp operator support ('~*' in postgres).
+ */
+ IREGEXP: boolean;
+ HSTORE: boolean;
+ TSVECTOR: boolean;
+ deferrableConstraints: boolean;
+ tmpTableTrigger: boolean;
+ indexHints: boolean;
+ searchPath: boolean;
+ escapeStringConstants: boolean;
+};
+
+export declare abstract class AbstractDialect {
+ /**
+ * List of features this dialect supports.
+ *
+ * Important: Dialect implementations inherit these values.
+ * When changing a default, ensure the implementations still properly declare which feature they support.
+ */
+ static readonly supports: DialectSupports;
+ readonly defaultVersion: string;
+ readonly Query: typeof AbstractQuery;
+ readonly name: Dialect;
+ readonly TICK_CHAR: string;
+ readonly TICK_CHAR_LEFT: string;
+ readonly TICK_CHAR_RIGHT: string;
+ readonly queryGenerator: unknown;
+ get supports(): DialectSupports;
+ canBackslashEscape(): boolean;
+}
diff --git a/lib/dialects/abstract/index.js b/src/dialects/abstract/index.js
similarity index 80%
rename from lib/dialects/abstract/index.js
rename to src/dialects/abstract/index.js
index 5d2c13808166..e2d715695de0 100644
--- a/lib/dialects/abstract/index.js
+++ b/src/dialects/abstract/index.js
@@ -1,6 +1,15 @@
'use strict';
-class AbstractDialect {}
+class AbstractDialect {
+ /**
+ * Whether this dialect can use \ in strings to escape string delimiters.
+ *
+ * @returns {boolean}
+ */
+ canBackslashEscape() {
+ return false;
+ }
+}
AbstractDialect.prototype.supports = {
'DEFAULT': true,
@@ -41,6 +50,7 @@ AbstractDialect.prototype.supports = {
ignoreDuplicates: '', /* dialect specific words for INSERT IGNORE or DO NOTHING */
updateOnDuplicate: false, /* whether dialect supports ON DUPLICATE KEY UPDATE */
onConflictDoNothing: '', /* dialect specific words for ON CONFLICT DO NOTHING */
+ onConflictWhere: false, /* whether dialect supports ON CONFLICT WHERE */
conflictFields: false /* whether the dialect supports specifying conflict fields or not */
},
constraints: {
@@ -66,7 +76,12 @@ AbstractDialect.prototype.supports = {
groupedLimit: true,
indexViaAlter: false,
JSON: false,
- deferrableConstraints: false
+ /**
+ * This dialect supports marking a column's constraints as deferrable.
+ * e.g. 'DEFERRABLE' and 'INITIALLY DEFERRED'
+ */
+ deferrableConstraints: false,
+ escapeStringConstants: false
};
module.exports = AbstractDialect;
diff --git a/lib/dialects/abstract/query-generator.js b/src/dialects/abstract/query-generator.js
similarity index 91%
rename from lib/dialects/abstract/query-generator.js
rename to src/dialects/abstract/query-generator.js
index 98773e213584..56f777090018 100644
--- a/lib/dialects/abstract/query-generator.js
+++ b/src/dialects/abstract/query-generator.js
@@ -17,6 +17,35 @@ const Op = require('../../operators');
const sequelizeError = require('../../errors');
const IndexHints = require('../../index-hints');
+/**
+ * Whitelist of SQL data types allowed in JSON key cast notation (e.g. "key::integer").
+ * This prevents SQL injection via user-controlled cast types in _traverseJSON.
+ * Includes types produced by _getJsonCast() and types transformed by dialect overrides.
+ */
+const ALLOWED_CAST_TYPES = new Set([
+ 'integer',
+ 'int',
+ 'smallint',
+ 'bigint',
+ 'float',
+ 'real',
+ 'double precision',
+ 'decimal',
+ 'numeric',
+ 'boolean',
+ 'text',
+ 'char',
+ 'varchar',
+ 'nvarchar',
+ 'date',
+ 'timestamp',
+ 'timestamptz',
+ 'datetime',
+ 'json',
+ 'jsonb',
+ 'signed',
+ 'unsigned'
+]);
/**
* Abstract Query Generator
@@ -43,7 +72,7 @@ class QueryGenerator {
options = options || {};
tableName = tableName || {};
return {
- schema: tableName.schema || options.schema || 'public',
+ schema: tableName.schema || options.schema || this.options.schema || 'public',
tableName: _.isPlainObject(tableName) ? tableName.tableName : tableName,
delimiter: tableName.delimiter || options.delimiter || '.'
};
@@ -88,6 +117,16 @@ class QueryGenerator {
return `ALTER TABLE ${this.quoteTable(before)} RENAME TO ${this.quoteTable(after)};`;
}
+ /**
+ * Helper method for populating the returning into bind information
+ * that is needed by some dialects (currently Oracle)
+ *
+ * @private
+ */
+ populateInsertQueryReturnIntoBinds() {
+ // noop by default
+ }
+
/**
* Returns an insert into command
*
@@ -103,12 +142,14 @@ class QueryGenerator {
_.defaults(options, this.options);
const modelAttributeMap = {};
- const bind = [];
+ const bind = options.bind || [];
const fields = [];
const returningModelAttributes = [];
+ const returnTypes = [];
const values = [];
const quotedTable = this.quoteTable(table);
const bindParam = options.bindParam === undefined ? this.bindParam(bind) : options.bindParam;
+ const returnAttributes = [];
let query;
let valueQuery = '';
let emptyQuery = '';
@@ -132,10 +173,14 @@ class QueryGenerator {
emptyQuery += ' VALUES ()';
}
- if (this._dialect.supports.returnValues && options.returning) {
+ if ((this._dialect.supports.returnValues || this._dialect.supports.returnIntoValues) && options.returning) {
const returnValues = this.generateReturnValues(modelAttributes, options);
returningModelAttributes.push(...returnValues.returnFields);
+ // Storing the returnTypes for dialects that need to have returning into bind information for outbinds
+ if (this._dialect.supports.returnIntoValues) {
+ returnTypes.push(...returnValues.returnTypes);
+ }
returningFragment = returnValues.returningFragment;
tmpTable = returnValues.tmpTable || '';
outputFragment = returnValues.outputFragment || '';
@@ -182,6 +227,13 @@ class QueryGenerator {
let onDuplicateKeyUpdate = '';
+ if (
+ !_.isEmpty(options.conflictWhere)
+ && !this._dialect.supports.inserts.onConflictWhere
+ ) {
+ throw new Error('missing dialect support for conflictWhere option');
+ }
+
// `options.updateOnDuplicate` is the list of field names to update if a duplicate key is hit during the insert. It
// contains just the field names. This option is _usually_ explicitly set by the corresponding query-interface
// upsert function.
@@ -190,10 +242,28 @@ class QueryGenerator {
// If no conflict target columns were specified, use the primary key names from options.upsertKeys
const conflictKeys = options.upsertKeys.map(attr => this.quoteIdentifier(attr));
const updateKeys = options.updateOnDuplicate.map(attr => `${this.quoteIdentifier(attr)}=EXCLUDED.${this.quoteIdentifier(attr)}`);
- onDuplicateKeyUpdate = ` ON CONFLICT (${conflictKeys.join(',')})`;
+
+ const fragments = [
+ 'ON CONFLICT',
+ '(',
+ conflictKeys.join(','),
+ ')'
+ ];
+
+ if (!_.isEmpty(options.conflictWhere)) {
+ fragments.push(this.whereQuery(options.conflictWhere, options));
+ }
+
// if update keys are provided, then apply them here. if there are no updateKeys provided, then do not try to
// do an update. Instead, fall back to DO NOTHING.
- onDuplicateKeyUpdate += _.isEmpty(updateKeys) ? ' DO NOTHING ' : ` DO UPDATE SET ${updateKeys.join(',')}`;
+ if (_.isEmpty(updateKeys)) {
+ fragments.push('DO NOTHING');
+ } else {
+ fragments.push('DO UPDATE SET', updateKeys.join(','));
+ }
+
+ onDuplicateKeyUpdate = ` ${Utils.joinSQLFragments(fragments)}`;
+
} else {
const valueKeys = options.updateOnDuplicate.map(attr => `${this.quoteIdentifier(attr)}=VALUES(${this.quoteIdentifier(attr)})`);
// the rough equivalent to ON CONFLICT DO NOTHING in mysql, etc is ON DUPLICATE KEY UPDATE id = id
@@ -244,7 +314,12 @@ class QueryGenerator {
emptyQuery += returningFragment;
}
- query = `${replacements.attributes.length ? valueQuery : emptyQuery};`;
+ if (this._dialect.supports.returnIntoValues && options.returning) {
+ // Populating the returnAttributes array and performing operations needed for output binds of insertQuery
+ this.populateInsertQueryReturnIntoBinds(returningModelAttributes, returnTypes, bind.length, returnAttributes, options);
+ }
+
+ query = `${replacements.attributes.length ? valueQuery : emptyQuery}${returnAttributes.join(',')};`;
if (this._dialect.supports.finalTable) {
query = `SELECT * FROM FINAL TABLE(${ replacements.attributes.length ? valueQuery : emptyQuery });`;
}
@@ -318,8 +393,31 @@ class QueryGenerator {
// If no conflict target columns were specified, use the primary key names from options.upsertKeys
const conflictKeys = options.upsertKeys.map(attr => this.quoteIdentifier(attr));
const updateKeys = options.updateOnDuplicate.map(attr => `${this.quoteIdentifier(attr)}=EXCLUDED.${this.quoteIdentifier(attr)}`);
- onDuplicateKeyUpdate = ` ON CONFLICT (${conflictKeys.join(',')}) DO UPDATE SET ${updateKeys.join(',')}`;
+
+ let whereClause = false;
+ if (options.conflictWhere) {
+ if (!this._dialect.supports.inserts.onConflictWhere) {
+ throw new Error(`conflictWhere not supported for dialect ${this._dialect.name}`);
+ }
+
+ whereClause = this.whereQuery(options.conflictWhere, options);
+ }
+
+ // The Utils.joinSQLFragments later on will join this as it handles nested arrays.
+ onDuplicateKeyUpdate = [
+ 'ON CONFLICT',
+ '(',
+ conflictKeys.join(','),
+ ')',
+ whereClause,
+ 'DO UPDATE SET',
+ updateKeys.join(',')
+ ];
} else { // mysql / maria
+ if (options.conflictWhere) {
+ throw new Error(`conflictWhere not supported for dialect ${this._dialect.name}`);
+ }
+
const valueKeys = options.updateOnDuplicate.map(attr => `${this.quoteIdentifier(attr)}=VALUES(${this.quoteIdentifier(attr)})`);
onDuplicateKeyUpdate = `${this._dialect.supports.inserts.updateOnDuplicate} ${valueKeys.join(',')}`;
}
@@ -383,8 +481,18 @@ class QueryGenerator {
const bindParam = options.bindParam === undefined ? this.bindParam(bind) : options.bindParam;
if (this._dialect.supports['LIMIT ON UPDATE'] && options.limit) {
- if (this.dialect !== 'mssql' && this.dialect !== 'db2') {
+ if (!['mssql', 'db2', 'oracle'].includes(this.dialect)) {
suffix = ` LIMIT ${this.escape(options.limit)} `;
+ } else if (this.dialect === 'oracle') {
+ // This cannot be setted in where because rownum will be quoted
+ if (where && (where.length && where.length > 0 || Object.keys(where).length > 0)) {
+ // If we have a where clause, we add AND
+ suffix += ' AND ';
+ } else {
+ // No where clause, we add where
+ suffix += ' WHERE ';
+ }
+ suffix += `rownum <= ${this.escape(options.limit)} `;
}
}
@@ -676,7 +784,7 @@ class QueryGenerator {
break;
case 'DEFAULT':
if (options.defaultValue === undefined) {
- throw new Error('Default value must be specifed for DEFAULT CONSTRAINT');
+ throw new Error('Default value must be specified for DEFAULT CONSTRAINT');
}
if (this._dialect.name !== 'mssql') {
@@ -939,8 +1047,8 @@ class QueryGenerator {
/**
* Split a list of identifiers by "." and quote each part.
*
- * @param {string} identifiers
- *
+ * @param {string} identifiers
+ *
* @returns {string}
*/
quoteIdentifiers(identifiers) {
@@ -963,6 +1071,15 @@ class QueryGenerator {
return this.quoteIdentifiers(attribute);
}
+ /**
+ * Returns the alias token
+ *
+ * @returns {string}
+ */
+ getAliasToken() {
+ return 'AS';
+ }
+
/**
* Quote table name with optional alias and schema attribution
*
@@ -998,7 +1115,7 @@ class QueryGenerator {
}
if (alias) {
- table += ` AS ${this.quoteIdentifier(alias)}`;
+ table += ` ${this.getAliasToken()} ${this.quoteIdentifier(alias)}`;
}
return table;
@@ -1016,6 +1133,12 @@ class QueryGenerator {
return this.handleSequelizeMethod(value);
}
if (field && field.type) {
+ if (field.type instanceof DataTypes.STRING
+ && ['mysql', 'mariadb'].includes(this.dialect)
+ && ['number', 'boolean'].includes(typeof value)) {
+ value = String(Number(value));
+ }
+
this.validate(value, field, options);
if (field.type.stringify) {
@@ -1312,7 +1435,12 @@ class QueryGenerator {
} else {
// Ordering is handled by the subqueries, so ordering the UNION'ed result is not needed
groupedLimitOrder = options.order;
- delete options.order;
+
+ // For the Oracle dialect, the result of a select is a set, not a sequence, and so is the result of UNION.
+ // So the top level ORDER BY is required
+ if (!this._dialect.supports.topLevelOrderByRequired) {
+ delete options.order;
+ }
where[Op.placeholder] = true;
}
@@ -1332,7 +1460,7 @@ class QueryGenerator {
model
},
model
- ).replace(/;$/, '')}) AS sub`; // Every derived table must have its own alias
+ ).replace(/;$/, '')}) ${this.getAliasToken()} sub`; // Every derived table must have its own alias
const placeHolder = this.whereItemQuery(Op.placeholder, true, { model });
const splicePos = baseQuery.indexOf(placeHolder);
@@ -1426,7 +1554,7 @@ class QueryGenerator {
if (subQuery) {
this._throwOnEmptyAttributes(attributes.main, { modelName: model && model.name, as: mainTable.as });
- query = `SELECT ${attributes.main.join(', ')} FROM (${subQueryItems.join('')}) AS ${mainTable.as}${mainJoinQueries.join('')}${mainQueryItems.join('')}`;
+ query = `SELECT ${attributes.main.join(', ')} FROM (${subQueryItems.join('')}) ${this.getAliasToken()} ${mainTable.as}${mainJoinQueries.join('')}${mainQueryItems.join('')}`;
} else {
query = mainQueryItems.join('');
}
@@ -1476,11 +1604,24 @@ class QueryGenerator {
if (attr[0] instanceof Utils.SequelizeMethod) {
attr[0] = this.handleSequelizeMethod(attr[0]);
addTable = false;
- } else if (!attr[0].includes('(') && !attr[0].includes(')')) {
+ } else if (this.options.attributeBehavior === 'escape' || !attr[0].includes('(') && !attr[0].includes(')')) {
attr[0] = this.quoteIdentifier(attr[0]);
- } else {
- deprecations.noRawAttributes();
+ } else if (this.options.attributeBehavior !== 'unsafe-legacy') {
+ throw new Error(`Attributes cannot include parentheses in Sequelize 6:
+In order to fix the vulnerability CVE-2023-22578, we had to remove support for treating attributes as raw SQL if they included parentheses.
+Sequelize 7 escapes all attributes, even if they include parentheses.
+For Sequelize 6, because we're introducing this change in a minor release, we've opted for throwing an error instead of silently escaping the attribute as a way to warn you about this change.
+
+Here is what you can do to fix this error:
+- Wrap the attribute in a literal() call. This will make Sequelize treat it as raw SQL.
+- Set the "attributeBehavior" sequelize option to "escape" to make Sequelize escape the attribute, like in Sequelize v7. We highly recommend this option.
+- Set the "attributeBehavior" sequelize option to "unsafe-legacy" to make Sequelize escape the attribute, like in Sequelize v5.
+
+We sincerely apologize for the inconvenience this may cause you. You can find more information on the following threads:
+https://github.com/sequelize/sequelize/security/advisories/GHSA-f598-mfpv-gmfx
+https://github.com/sequelize/sequelize/discussions/15694`);
}
+
let alias = attr[1];
if (this.options.minifyAliases) {
@@ -1566,6 +1707,8 @@ class QueryGenerator {
prefix = `(${this.quoteIdentifier(includeAs.internalAs)}.${attr.replace(/\(|\)/g, '')})`;
} else if (/json_extract\(/.test(attr)) {
prefix = attr.replace(/json_extract\(/i, `json_extract(${this.quoteIdentifier(includeAs.internalAs)}.`);
+ } else if (/json_value\(/.test(attr)) {
+ prefix = attr.replace(/json_value\(/i, `json_value(${this.quoteIdentifier(includeAs.internalAs)}.`);
} else {
prefix = `${this.quoteIdentifier(includeAs.internalAs)}.${this.quoteIdentifier(attr)}`;
}
@@ -1773,11 +1916,7 @@ class QueryGenerator {
}
}
- if (this.options.minifyAliases && asRight.length > 63) {
- const alias = `%${topLevelInfo.options.includeAliases.size}`;
-
- topLevelInfo.options.includeAliases.set(alias, asRight);
- }
+ this.aliasAs(asRight, topLevelInfo);
return {
join: include.required ? 'INNER JOIN' : include.right && this._dialect.supports['RIGHT JOIN'] ? 'RIGHT OUTER JOIN' : 'LEFT OUTER JOIN',
@@ -1822,6 +1961,8 @@ class QueryGenerator {
if (this._dialect.supports.returnValues.returning) {
returningFragment = ` RETURNING ${returnFields.join(',')}`;
+ } else if (this._dialect.supports.returnIntoValues) {
+ returningFragment = ` RETURNING ${returnFields.join(',')} INTO `;
} else if (this._dialect.supports.returnValues.output) {
outputFragment = ` OUTPUT ${returnFields.map(field => `INSERTED.${field}`).join(',')}`;
@@ -1835,7 +1976,7 @@ class QueryGenerator {
}
}
- return { outputFragment, returnFields, returningFragment, tmpTable };
+ return { outputFragment, returnFields, returnTypes, returningFragment, tmpTable };
}
generateThroughJoin(include, includeAs, parentTableName, topLevelInfo) {
@@ -1917,6 +2058,8 @@ class QueryGenerator {
throughWhere = this.getWhereConditions(through.where, this.sequelize.literal(this.quoteIdentifier(throughAs)), through.model);
}
+ this.aliasAs(includeAs.internalAs, topLevelInfo);
+
// Generate a wrapped join so that the through table join can be dependent on the target join
joinBody = `( ${this.quoteTable(throughTable, throughAs)} INNER JOIN ${this.quoteTable(include.model.getTableName(), includeAs.internalAs)} ON ${targetJoinOn}`;
if (throughWhere) {
@@ -1944,6 +2087,18 @@ class QueryGenerator {
};
}
+ /*
+ * Appends to the alias cache if the alias 64+ characters long and minifyAliases is true.
+ * This helps to avoid character limits in PostgreSQL.
+ */
+ aliasAs(as, topLevelInfo) {
+ if (this.options.minifyAliases && as.length >= 64) {
+ const alias = `%${topLevelInfo.options.includeAliases.size}`;
+
+ topLevelInfo.options.includeAliases.set(alias, as);
+ }
+ }
+
/*
* Generates subQueryFilter - a select nested in the where clause of the subQuery.
* For a given include a query is generated that contains all the way from the subQuery
@@ -2083,17 +2238,39 @@ class QueryGenerator {
&& !(typeof order[0].model === 'function' && order[0].model.prototype instanceof Model)
&& !(typeof order[0] === 'string' && model && model.associations !== undefined && model.associations[order[0]])
) {
- subQueryOrder.push(this.quote(order, model, '->'));
+ const field = model.rawAttributes[order[0]] ? model.rawAttributes[order[0]].field : order[0];
+ const subQueryAlias = this._getAliasForField(this.quoteIdentifier(model.name), field, options);
+
+ let parent = null;
+ let orderToQuote = [];
+
+ // we need to ensure that the parent is null if we use the subquery alias, else we'll get an exception since
+ // "model_name"."alias" doesn't exist - only "alias" does. we also need to ensure that we preserve order direction
+ // by pushing order[1] to the subQueryOrder as well - in case it doesn't exist, we want to push "ASC"
+ if (subQueryAlias === null) {
+ orderToQuote = order;
+ parent = model;
+ } else {
+ orderToQuote = [subQueryAlias, order.length > 1 ? order[1] : 'ASC'];
+ parent = null;
+ }
+
+ subQueryOrder.push(this.quote(orderToQuote, parent, '->'));
}
- if (subQuery) {
- // Handle case where sub-query renames attribute we want to order by,
- // see https://github.com/sequelize/sequelize/issues/8739
- const subQueryAttribute = options.attributes.find(a => Array.isArray(a) && a[0] === order[0] && a[1]);
- if (subQueryAttribute) {
+ // Handle case where renamed attributes are used to order by,
+ // see https://github.com/sequelize/sequelize/issues/8739
+ // need to check if either of the attribute options match the order
+ if (options.attributes && model) {
+ const aliasedAttribute = options.attributes.find(attr => Array.isArray(attr)
+ && attr[1]
+ && (attr[0] === order[0] || attr[1] === order[0]));
+
+ if (aliasedAttribute) {
const modelName = this.quoteIdentifier(model.name);
+ const alias = this._getAliasForField(modelName, aliasedAttribute[1], options);
- order[0] = new Utils.Col(this._getAliasForField(modelName, subQueryAttribute[1], options) || subQueryAttribute[1]);
+ order[0] = new Utils.Col(alias || aliasedAttribute[1]);
}
}
@@ -2126,7 +2303,7 @@ class QueryGenerator {
let fragment = `SELECT ${attributes.join(', ')} FROM ${tables}`;
if (mainTableAs) {
- fragment += ` AS ${mainTableAs}`;
+ fragment += ` ${this.getAliasToken()} ${mainTableAs}`;
}
if (options.indexHints && this._dialect.supports.indexHints) {
@@ -2243,7 +2420,7 @@ class QueryGenerator {
if (_.isPlainObject(arg)) {
return this.whereItemsQuery(arg);
}
- return this.escape(typeof arg === 'string' ? arg.replace('$', '$$$') : arg);
+ return this.escape(typeof arg === 'string' ? arg.replace(/\$/g, '$$$') : arg);
}).join(', ')
})`;
}
@@ -2491,6 +2668,8 @@ class QueryGenerator {
const tmp = path[path.length - 1].split('::');
cast = tmp[1];
path[path.length - 1] = tmp[0];
+
+ this._validateCastType(cast);
}
let pathKey = this.jsonPathExtractionQuery(baseKey, path);
@@ -2547,6 +2726,12 @@ class QueryGenerator {
return;
}
+ _validateCastType(cast) {
+ if (!ALLOWED_CAST_TYPES.has(cast.toLowerCase())) {
+ throw new Error(`Invalid cast type: ${cast}`);
+ }
+ }
+
_joinKeyValue(key, value, comparator, prefix) {
if (!key) {
return value;
@@ -2721,7 +2906,7 @@ class QueryGenerator {
type: options.type
});
}
- if (typeof smth === 'number') {
+ if (typeof smth === 'number' || typeof smth === 'bigint') {
let primaryKeys = factory ? Object.keys(factory.primaryKeys) : [];
if (primaryKeys.length > 0) {
@@ -2755,14 +2940,14 @@ class QueryGenerator {
}
throw new Error('Support for literal replacements in the `where` object has been removed.');
}
- if (smth === null) {
+ if (smth == null) {
return this.whereItemsQuery(smth, {
model: factory,
prefix: prepend && tableName
});
}
- return '1=1';
+ throw new Error(`Unsupported where option value: ${util.inspect(smth)}. Please refer to the Sequelize documentation to learn more about which values are accepted as part of the where option.`);
}
// A recursive parser for nested where conditions
@@ -2780,6 +2965,13 @@ class QueryGenerator {
booleanValue(value) {
return value;
}
+
+ /**
+ * Returns the authenticate test query string
+ */
+ authTestQuery() {
+ return 'SELECT 1+1 AS result';
+ }
}
Object.assign(QueryGenerator.prototype, require('./query-generator/operators'));
diff --git a/lib/dialects/abstract/query-generator/operators.js b/src/dialects/abstract/query-generator/operators.js
similarity index 100%
rename from lib/dialects/abstract/query-generator/operators.js
rename to src/dialects/abstract/query-generator/operators.js
diff --git a/lib/dialects/abstract/query-generator/transaction.js b/src/dialects/abstract/query-generator/transaction.js
similarity index 100%
rename from lib/dialects/abstract/query-generator/transaction.js
rename to src/dialects/abstract/query-generator/transaction.js
diff --git a/types/lib/query-interface.d.ts b/src/dialects/abstract/query-interface.d.ts
similarity index 94%
rename from types/lib/query-interface.d.ts
rename to src/dialects/abstract/query-interface.d.ts
index 0f230c5df138..dafa19cac579 100644
--- a/types/lib/query-interface.d.ts
+++ b/src/dialects/abstract/query-interface.d.ts
@@ -1,4 +1,4 @@
-import { DataType } from './data-types';
+import { DataType } from '../../data-types';
import {
Logging,
Model,
@@ -8,14 +8,18 @@ import {
WhereOptions,
Filterable,
Poolable,
- ModelCtor, ModelStatic, ModelType
-} from './model';
-import QueryTypes = require('./query-types');
-import { Sequelize, RetryOptions } from './sequelize';
-import { Transaction } from './transaction';
-import { SetRequired } from './../type-helpers/set-required';
-import { Fn, Literal } from './utils';
-import { Deferrable } from './deferrable';
+ ModelCtor,
+ ModelStatic,
+ ModelType,
+ CreationAttributes,
+ Attributes
+} from '../../model';
+import QueryTypes = require('../../query-types');
+import { Sequelize, RetryOptions } from '../../sequelize';
+import { Transaction } from '../../transaction';
+import { SetRequired } from '../../utils/set-required';
+import { Fn, Literal } from '../../utils';
+import { Deferrable } from '../../deferrable';
type BindOrReplacements = { [key: string]: unknown } | unknown[];
type FieldMap = { [key: string]: string };
@@ -337,7 +341,7 @@ export class QueryInterface {
*/
public createTable(
tableName: TableName,
- attributes: ModelAttributes,
+ attributes: ModelAttributes>,
options?: QueryInterfaceCreateTableOptions
): Promise;
@@ -373,6 +377,14 @@ export class QueryInterface {
*/
public showAllTables(options?: QueryOptions): Promise;
+ /**
+ * Returns a promise that resolves to true if the table exists in the database, false otherwise.
+ *
+ * @param tableName The name of the table
+ * @param options Options passed to {@link Sequelize#query}
+ */
+ public tableExists(tableName: TableName, options?: QueryOptions): Promise;
+
/**
* Describe a table
*/
@@ -482,13 +494,12 @@ export class QueryInterface {
/**
* Inserts or Updates a record in the database
*/
- public upsert(
+ public upsert(
tableName: TableName,
insertValues: object,
updateValues: object,
where: object,
- model: ModelType,
- options?: QueryOptions
+ options?: QueryOptionsWithModel
): Promise