### Install Sequelize and Database Drivers (npm) Source: https://sequelize.org/v5/manual/getting-started Installs the Sequelize ORM and the necessary driver for your chosen database using npm. Ensure you install only one database driver per project. ```bash npm install --save sequelize # 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 ``` -------------------------------- ### Quick Sequelize Setup and User Creation (JavaScript) Source: https://sequelize.org/v5/index Demonstrates a quick setup of Sequelize with an in-memory SQLite database, defines a User model, synchronizes the database, creates a user, and logs the user's JSON representation. Requires Sequelize. ```javascript 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' }); sequelize.sync() .then(() => User.create({ username: 'janedoe', birthday: new Date(1980, 6, 20) })) .then(jane => { console.log(jane.toJSON()); }); ``` -------------------------------- ### Perform Basic Queries in Sequelize Source: https://sequelize.org/v5/manual/getting-started Illustrates common Sequelize query operations including finding all records, creating a new record, deleting records based on criteria, and updating records. ```javascript // Find all users User.findAll().then(users => { console.log("All users:", JSON.stringify(users, null, 4)); }); // Create a new user User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => { console.log("Jane's auto-generated ID:", jane.id); }); // Delete everyone named "Jane" User.destroy({ where: { firstName: "Jane" } }).then(() => { console.log("Done"); }); // Change everyone without a last name to "Doe" User.update({ lastName: "Doe" }, { where: { lastName: null } }).then(() => { console.log("Done"); }); ``` -------------------------------- ### Dynamic Configuration File Example (Node.js) Source: https://sequelize.org/v5/manual/migrations An example of a dynamic configuration file (`config/config.js`) that exports different database connection settings for development, test, and production environments. It demonstrates accessing environment variables and using file system operations. ```javascript const fs = require('fs'); module.exports = { development: { username: 'database_dev', password: 'database_dev', database: 'database_dev', host: '127.0.0.1', dialect: 'mysql' }, test: { username: 'database_test', password: null, database: 'database_test', host: '127.0.0.1', dialect: 'mysql' }, production: { username: process.env.DB_USERNAME, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, host: process.env.DB_HOSTNAME, dialect: 'mysql', dialectOptions: { ssl: { ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt') } } } }; ``` -------------------------------- ### Connect to Database using Sequelize (JavaScript) Source: https://sequelize.org/v5/manual/getting-started Demonstrates two methods for establishing a database connection with Sequelize: passing connection parameters separately or using a connection URI. The `dialect` option specifies the database type. ```javascript const Sequelize = require('sequelize'); // Option 1: Passing parameters separately const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */ }); // Option 2: Passing a connection URI const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname'); ``` -------------------------------- ### Sequelize Configuration Example Source: https://sequelize.org/v5/manual/migrations Example JSON configuration file for Sequelize CLI. This file specifies database connection details for different environments (development, test, production), including username, password, database name, host, and dialect. ```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" } } ``` -------------------------------- ### Sequelize SQLite Connection Setup (JavaScript) Source: https://sequelize.org/v5/index Illustrates how to configure Sequelize for SQLite databases by specifying the dialect and storage path. Requires Sequelize. ```javascript const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'path/to/database.sqlite' }); ``` -------------------------------- ### Sequelize Configuration File Example Source: https://sequelize.org/v5/index An example of the `config/config.json` file used by Sequelize CLI to define database connection details for different environments (development, test, production). Users should update this file with their specific database credentials and dialect. ```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" } } ``` -------------------------------- ### Synchronize Model with Database in Sequelize Source: https://sequelize.org/v5/manual/getting-started Shows how to use the `sync` method to automatically create or modify database tables based on model definitions. The example includes using `force: true` to drop and recreate the table, followed by creating a new user. ```javascript // Note: using `force: true` will drop the table if it already exists User.sync({ force: true }).then(() => { // Now the `users` table in the database corresponds to the model definition return User.create({ firstName: 'John', lastName: 'Hancock' }); }); ``` -------------------------------- ### Example dynamic config.js for Sequelize CLI (JavaScript) Source: https://sequelize.org/v5/index This example JavaScript file provides dynamic configuration for Sequelize CLI across different environments (development, test, production). It demonstrates accessing environment variables for production settings and includes dialect-specific options. ```javascript const fs = require('fs'); module.exports = { development: { username: 'database_dev', password: 'database_dev', database: 'database_dev', host: '127.0.0.1', dialect: 'mysql' }, test: { username: 'database_test', password: null, database: 'database_test', host: '127.0.0.1', dialect: 'mysql' }, production: { username: process.env.DB_USERNAME, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, host: process.env.DB_HOSTNAME, dialect: 'mysql', dialectOptions: { ssl: { ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt') } } } }; ``` -------------------------------- ### Install Sequelize CLI Source: https://sequelize.org/v5/manual/migrations Installs the Sequelize CLI package locally in your project using npm. This command adds the sequelize-cli to your project's dependencies. ```bash npm install --save sequelize-cli ``` -------------------------------- ### Define a Sequelize Model using `Sequelize.Model.init` (JavaScript) Source: https://sequelize.org/v5/manual/getting-started Shows how to define a Sequelize model by extending `Sequelize.Model` and using the `init` method. This approach requires defining attributes and options separately. ```javascript const Model = Sequelize.Model; class User extends Model {} User.init({ // attributes firstName: { type: Sequelize.STRING, allowNull: false }, lastName: { type: Sequelize.STRING // allowNull defaults to true } }, { sequelize, modelName: 'user' // options }); ``` -------------------------------- ### Sequelize Database Connection Setup (JavaScript) Source: https://sequelize.org/v5/index Shows two methods for setting up a Sequelize database connection: passing parameters separately to the constructor or using a single connection URI. Supports multiple SQL dialects. Requires Sequelize. ```javascript const Sequelize = require('sequelize'); // Option 1: Passing parameters separately const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */ }); // Option 2: Passing a connection URI const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname'); ``` -------------------------------- ### Install Sequelize and Database Drivers (Shell) Source: https://sequelize.org/v5/index Provides shell commands to install the Sequelize ORM and specific database drivers for PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server. Requires npm. ```shell npm install --save sequelize # 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 ``` -------------------------------- ### Configure Connection Pool (JavaScript) Source: https://sequelize.org/v5/manual/getting-started Illustrates how to configure the connection pool settings for a Sequelize instance. The `pool` object within the options allows customization of `max`, `min`, `acquire`, and `idle` connection parameters for production environments. ```javascript const sequelize = new Sequelize(/* ... */, { // ... pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } }); ``` -------------------------------- ### Connect using a Connection String CLI Argument Source: https://sequelize.org/v5/manual/migrations This command-line example shows how to use the `--url` option with the Sequelize CLI to provide database connection details via a single connection string, simplifying the command for migrations. ```bash $ npx sequelize-cli db:migrate --url 'mysql://root:password@mysql_host.com/database_name' ``` -------------------------------- ### Create and Drop Table Migration with Sequelize Source: https://sequelize.org/v5/manual/migrations Provides an example of a Sequelize migration that creates a 'Person' table with specific columns and their data types, and a corresponding `down` function to drop the table. ```javascript module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Person', { name: Sequelize.STRING, isBetaMember: { type: Sequelize.BOOLEAN, defaultValue: false, allowNull: false } }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('Person'); } } ``` -------------------------------- ### Example dynamic config.js with environment variables (JavaScript) Source: https://sequelize.org/v5/index This JavaScript configuration file demonstrates how to use environment variables for database credentials across different environments. It's designed to be used with Sequelize CLI when dynamic configuration is enabled via .sequelizerc. ```javascript module.exports = { development: { username: 'database_dev', password: 'database_dev', database: 'database_dev', host: '127.0.0.1', dialect: 'mysql' }, test: { username: process.env.CI_DB_USERNAME, password: process.env.CI_DB_PASSWORD, database: process.env.CI_DB_NAME, host: '127.0.0.1', dialect: 'mysql' }, 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, dialect: 'mysql' } }; ``` -------------------------------- ### Configure .sequelizerc for Custom Paths (Node.js) Source: https://sequelize.org/v5/manual/migrations An example of a .sequelizerc file written in Node.js. It specifies custom paths for the configuration file, models, seeders, and migrations folders using `path.resolve`. ```javascript 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') } ``` -------------------------------- ### Install babel-register for ES6/ES7 migrations (Bash) Source: https://sequelize.org/v5/index This command installs the `babel-register` package as a development dependency. This package allows you to transpile ES6/ES7 code on the fly, enabling the use of modern JavaScript syntax in Sequelize migrations and seeders. ```bash $ npm i --save-dev babel-register ``` -------------------------------- ### Perform Basic Sequelize Queries Source: https://sequelize.org/v5/index Provides examples of common Sequelize operations: finding all records, creating a new record, deleting records based on a condition, and updating records. ```javascript // Find all users User.findAll().then(users => { console.log("All users:", JSON.stringify(users, null, 4)); }); // Create a new user User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => { console.log("Jane's auto-generated ID:", jane.id); }); // Delete everyone named "Jane" User.destroy({ where: { firstName: "Jane" } }).then(() => { console.log("Done"); }); // Change everyone without a last name to "Doe" User.update({ lastName: "Doe" }, { where: { lastName: null } }).then(() => { console.log("Done"); }); ``` -------------------------------- ### Sequelize v5 Hook Argument Examples Source: https://sequelize.org/v5/index Illustrates the arguments passed to Sequelize v5 bulk hook methods, showing how to access records, options, fields, attributes, and where clauses. This helps in understanding how to interact with the data being processed by the hooks. ```javascript Model.beforeBulkCreate((records, {fields}) => { // records = the first argument sent to .bulkCreate // fields = one of the second argument fields sent to .bulkCreate }) Model.bulkCreate([ {username: 'Toni'}, // part of records argument {username: 'Tobi'} // part of records argument ], {fields: ['username']} // options parameter ) Model.beforeBulkUpdate(({attributes, where}) => { // where - in one of the fields of the clone of second argument sent to .update // attributes - is one of the fields that the clone of second argument of .update would be extended with }) Model.update({gender: 'Male'} /*attributes argument*/, { where: {username: 'Tom'}} /*where argument*/) Model.beforeBulkDestroy(({where, individualHooks}) => { // individualHooks - default of overridden value of extended clone of second argument sent to Model.destroy // where - in one of the fields of the clone of second argument sent to Model.destroy }) Model.destroy({ where: {username: 'Tom'}} /*where argument*/) ``` -------------------------------- ### Model Definition Example Source: https://sequelize.org/v5/class/lib/sequelize.js~Sequelize An example demonstrating how to define a Sequelize model with various column types, validations, and field mappings. ```APIDOC ## Model Definition Example ### Description This example shows how to define a Sequelize model named 'modelName' with attributes 'columnA', 'columnB', and 'columnC'. It includes examples of data types, validation rules, and custom field names. ### Method `Sequelize.define()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (This is a code example, not an API endpoint) ### Request Example ```javascript sequelize.define('modelName', { columnA: { type: Sequelize.BOOLEAN, validate: { is: ["[a-z]",'i'], // will only allow letters max: 23, // only allow values <= 23 isIn: { args: [['en', 'zh']], msg: "Must be English or Chinese" } }, field: 'column_a' }, columnB: Sequelize.STRING, columnC: 'MY VERY OWN COLUMN TYPE' }); sequelize.models.modelName // The model will now be available in models under the name given to define ``` ### Response None (This is a code example) ### See: * Model.init for a more comprehensive specification of the `options` and `attributes` objects. * Model definition Manual related to model definition * DataTypes For a list of possible data types ``` -------------------------------- ### Paginate Query Results in Sequelize Source: https://sequelize.org/v5/index Provides examples of how to implement pagination in Sequelize queries using `limit` and `offset`. It shows fetching a specific number of records and skipping a certain number before fetching. ```javascript // 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 }) ``` -------------------------------- ### Sequelize CLS Namespace Setup Source: https://sequelize.org/v5/manual/transactions Shows the setup for using Continuation Local Storage (CLS) with Sequelize. It involves requiring the 'continuation-local-storage' module, creating a namespace, and then telling Sequelize to use this namespace via `Sequelize.useCLS()`. ```javascript const cls = require('continuation-local-storage'); const namespace = cls.createNamespace('my-very-own-namespace'); ``` ```javascript const Sequelize = require('sequelize'); Sequelize.useCLS(namespace); new Sequelize(....); ``` -------------------------------- ### Environment Variables in Config (Node.js) Source: https://sequelize.org/v5/manual/migrations An example of a dynamic configuration file (`config/config.js`) that utilizes environment variables for database credentials and connection details across different environments (development, test, production). ```javascript module.exports = { development: { username: 'database_dev', password: 'database_dev', database: 'database_dev', host: '127.0.0.1', dialect: 'mysql' }, test: { username: process.env.CI_DB_USERNAME, password: process.env.CI_DB_PASSWORD, database: process.env.CI_DB_NAME, host: '127.0.0.1', dialect: 'mysql' }, 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, dialect: 'mysql' } }; ``` -------------------------------- ### Seed File for Inserting Demo User (JavaScript) Source: https://sequelize.org/v5/index An example of a Sequelize seed file written in JavaScript. The `up` method uses `queryInterface.bulkInsert` to add a demo user to the 'Users' table. The `down` method uses `queryInterface.bulkDelete` to remove the user. ```javascript 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Users', [{ firstName: 'John', lastName: 'Doe', email: 'demo@demo.com', createdAt: new Date(), updatedAt: new Date() }], {}); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('Users', null, {}); } }; ``` -------------------------------- ### Change Default Model Options in Sequelize Source: https://sequelize.org/v5/manual/getting-started Demonstrates how to change default options for all defined models using the `define` option in the Sequelize constructor. This example specifically shows how to disable timestamps for all models by default. ```javascript const sequelize = new Sequelize(connectionURI, { define: { // The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created. // This was true by default, but now is false by default timestamps: false } }); // Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created. class Foo extends Model {} Foo.init({ /* ... */ }, { sequelize }); // Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created. class Bar extends Model {} Bar.init({ /* ... */ }, { sequelize, timestamps: true }); ``` -------------------------------- ### Initialize Sequelize v5 Connection Source: https://sequelize.org/v5/class/lib/sequelize Demonstrates various ways to initialize a Sequelize v5 instance. Supports connection without password, with password, using options object, and via a database URI. Includes examples of common Sequelize options like dialect, host, port, logging, dialect-specific options, storage, omitNull, native, define, sync, pool configuration, and transaction isolation levels. ```javascript const { Sequelize, Transaction } = require('sequelize'); // without password / with blank password const sequelize1 = new Sequelize('database', 'username', null, { dialect: 'mysql' }); // with password and options const sequelize2 = new Sequelize('my_database', 'john', 'doe', { dialect: 'postgres' }); // with database, username, and password in the options object const sequelize3 = new Sequelize({ database: 'db_name', username: 'user', password: 'pw', dialect: 'mssql' }); // with uri const sequelize4 = new Sequelize('mysql://localhost:3306/database', {}); // option examples const sequelize5 = new Sequelize('database', 'username', 'password', { // the sql dialect of the database // currently supported: 'mysql', 'sqlite', 'postgres', 'mssql' dialect: 'mysql', // custom host; default: localhost host: 'my.server.tld', // for postgres, you can also specify an absolute path to a directory // containing a UNIX socket to connect over // host: '/sockets/psql_sockets'. // custom port; default: dialect default port: 12345, // custom protocol; default: 'tcp' // postgres only, useful for Heroku protocol: null, // disable logging or provide a custom logging function; default: console.log logging: false, // you can also pass any dialect options to the underlying dialect library // - default is empty // - currently supported: 'mysql', 'postgres', 'mssql' dialectOptions: { socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock', supportBigNumbers: true, bigNumberStrings: true }, // the storage engine for sqlite // - default ':memory:' storage: 'path/to/database.sqlite', // disable inserting undefined values as NULL // - default: false omitNull: true, // a flag for using a native library or not. // in the case of 'pg' -- set this to true will allow SSL support // - default: false native: true, // Specify options, which are used when sequelize.define is called. // The following example: // define: { timestamps: false } // is basically the same as: // Model.init(attributes, { timestamps: false }); // sequelize.define(name, attributes, { timestamps: false }); // so defining the timestamps for each model will be not necessary define: { underscored: false, freezeTableName: false, charset: 'utf8', dialectOptions: { collate: 'utf8_general_ci' }, timestamps: true }, // similar for sync: you can define this to always force sync for models sync: { force: true }, // pool configuration used to pool database connections pool: { max: 5, idle: 30000, acquire: 60000, }, // isolation level of each transaction // defaults to dialect default isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ }); ``` -------------------------------- ### Test Database Connection (JavaScript) Source: https://sequelize.org/v5/manual/getting-started Uses the `.authenticate()` method to verify the database connection established by Sequelize. It logs a success message or an error if the connection fails. ```javascript sequelize .authenticate() .then(() => { console.log('Connection has been established successfully.'); }) .catch(err => { console.error('Unable to connect to the database:', err); }); ``` -------------------------------- ### Configure SQLite Connection (JavaScript) Source: https://sequelize.org/v5/manual/getting-started Provides the specific configuration for connecting to an SQLite database using Sequelize. This method utilizes a `storage` option to specify the database file path. ```javascript const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'path/to/database.sqlite' }); ``` -------------------------------- ### Define a Sequelize Model using `sequelize.define` (JavaScript) Source: https://sequelize.org/v5/manual/getting-started Demonstrates an alternative method for defining a Sequelize model using the `sequelize.define` function. This is a more concise way to define models and internally calls `Model.init`. ```javascript const User = sequelize.define('user', { // attributes firstName: { type: Sequelize.STRING, allowNull: false }, lastName: { type: Sequelize.STRING // allowNull defaults to true } }, { // options }); ``` -------------------------------- ### Sequelize Constructor Source: https://sequelize.org/v5/class/lib/sequelize Instantiate sequelize with name of database, username and password. ```APIDOC ## POST /websites/sequelize_v5/constructor ### Description Instantiate sequelize with name of database, username and password. ### Method POST ### Endpoint /websites/sequelize_v5/constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **database** (string) - Required - The name of the database. - **username** (string) - Required - The username for database access. - **password** (string) - Required - The password for database access. - **options** (Object) - Optional - Additional configuration options. ### Request Example ```json { "database": "my_database", "username": "my_user", "password": "my_password", "options": {"host": "localhost"} } ``` ### Response #### Success Response (200) - **SequelizeInstance** (object) - An instance of Sequelize. #### Response Example ```json { "message": "Sequelize instance created successfully." } ``` ``` -------------------------------- ### Initialize Sequelize Project Source: https://sequelize.org/v5/index Initializes a new Sequelize project structure, creating essential folders like 'config', 'models', 'migrations', and 'seeders'. This command sets up the basic file structure for your Sequelize application. ```bash npx sequelize-cli init ``` -------------------------------- ### Install Babel Register (npm) Source: https://sequelize.org/v5/manual/migrations Installs the `babel-register` package as a development dependency. This package allows you to use ES6/ES7 syntax in your Node.js code, including Sequelize migrations and seeders. ```bash $ npm i --save-dev babel-register ``` -------------------------------- ### Initialize Sequelize Project Source: https://sequelize.org/v5/manual/migrations Initializes a new Sequelize project structure. This command creates essential folders like 'config', 'models', 'migrations', and 'seeders' for your project. ```bash npx sequelize-cli init ``` -------------------------------- ### Define Sequelize Models with Columns Source: https://sequelize.org/v5/index Demonstrates how to define Sequelize models and their columns using the `init` method. It shows basic string and text datatypes for project and task models. ```javascript class Project extends Model {} Project.init({ title: Sequelize.STRING, description: Sequelize.TEXT }, { sequelize, modelName: 'project' }); class Task extends Model {} Task.init({ title: Sequelize.STRING, description: Sequelize.TEXT, deadline: Sequelize.DATE }, { sequelize, modelName: 'task' }) ``` -------------------------------- ### Implement Connection Hooks (beforeConnect, afterConnect, beforeDisconnect, afterDisconnect) Source: https://sequelize.org/v5/index Shows how to use connection hooks to execute logic before and after establishing or releasing a database connection. These hooks are useful for dynamic credential management or direct connection access. ```javascript beforeConnect(config) afterConnect(connection, config) beforeDisconnect(connection) afterDisconnect(connection) ``` ```javascript sequelize.beforeConnect((config) => { return getAuthToken() .then((token) => { config.password = token; }); }); ``` -------------------------------- ### Initialize Sequelize v5 Connection Source: https://sequelize.org/v5/class/lib/sequelize.js~Sequelize Demonstrates various ways to initialize a Sequelize v5 connection, including with and without passwords, using options objects, and connecting via a database URI. It covers different SQL dialects like MySQL, PostgreSQL, and MSSQL. ```javascript const { Sequelize, Transaction } = require('sequelize'); // without password / with blank password const sequelize1 = new Sequelize('database', 'username', null, { dialect: 'mysql' }); // with password and options const sequelize2 = new Sequelize('my_database', 'john', 'doe', { dialect: 'postgres' }); // with database, username, and password in the options object const sequelize3 = new Sequelize({ database: 'db_name', username: 'user', password: 'pw', dialect: 'mssql' }); // with uri const sequelize4 = new Sequelize('mysql://localhost:3306/database', {}); // option examples const sequelize5 = new Sequelize('database', 'username', 'password', { // the sql dialect of the database // currently supported: 'mysql', 'sqlite', 'postgres', 'mssql' dialect: 'mysql', // custom host; default: localhost host: 'my.server.tld', // for postgres, you can also specify an absolute path to a directory // containing a UNIX socket to connect over // host: '/sockets/psql_sockets'. // custom port; default: dialect default port: 12345, // custom protocol; default: 'tcp' // postgres only, useful for Heroku protocol: null, // disable logging or provide a custom logging function; default: console.log logging: false, // you can also pass any dialect options to the underlying dialect library // - default is empty // - currently supported: 'mysql', 'postgres', 'mssql' dialectOptions: { socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock', supportBigNumbers: true, bigNumberStrings: true }, // the storage engine for sqlite // - default ':memory:' storage: 'path/to/database.sqlite', // disable inserting undefined values as NULL // - default: false omitNull: true, // a flag for using a native library or not. // in the case of 'pg' -- set this to true will allow SSL support // - default: false native: true, // Specify options, which are used when sequelize.define is called. // The following example: // define: { timestamps: false } // is basically the same as: // Model.init(attributes, { timestamps: false }); // sequelize.define(name, attributes, { timestamps: false }); // so defining the timestamps for each model will be not necessary define: { underscored: false, freezeTableName: false, charset: 'utf8', dialectOptions: { collate: 'utf8_general_ci' }, timestamps: true }, // similar for sync: you can define this to always force sync for models sync: { force: true }, // pool configuration used to pool database connections pool: { max: 5, idle: 30000, acquire: 60000, }, // isolation level of each transaction // defaults to dialect default isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ }); ``` -------------------------------- ### Async/Await Migration with Unique Index and Sequelize Source: https://sequelize.org/v5/manual/migrations An example of a Sequelize migration using async/await syntax to add a column and create a unique index on it within a transaction. ```javascript module.exports = { async up(queryInterface, Sequelize) { const transaction = await queryInterface.sequelize.transaction(); try { await queryInterface.addColumn( 'Person', 'petName', { type: Sequelize.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; } }, }; ``` -------------------------------- ### Database Synchronization with Sequelize v5 Source: https://sequelize.org/v5/index Demonstrates how to synchronize Sequelize models with the database, including creating, dropping, and forcing table creation. It also covers event handling for these operations and the use of the 'match' option for safety. ```javascript // Create the tables: Project.sync() Task.sync() // Force the creation! Project.sync({force: true}) // this will drop the table first and re-create it afterwards // drop the tables: Project.drop() Task.drop() // event handling: Project.[sync|drop]().then(() => { // ok ... everything is nice! }).catch(error => { // oooh, did you enter wrong database credentials? }) ``` ```javascript // Sync all models that aren't already in the database sequelize.sync() // Force sync all models sequelize.sync({force: true}) // Drop all tables sequelize.drop() // emit handling: sequelize.[sync|drop]().then(() => { // woot woot }).catch(error => { // whooops }) ``` ```javascript // This will run .sync() only if database name ends with '_test' sequelize.sync({ force: true, match: /_test$/ }); ``` -------------------------------- ### Query JSONB Data with Nested Objects Source: https://sequelize.org/v5/index Shows how to query JSONB data in Sequelize when dealing with nested objects. This example filters for records where a specific nested field is not null. ```json { meta: { video: { url: { [Op.ne]: null } } } } ``` -------------------------------- ### Sequelize: Define User and Project Models Source: https://sequelize.org/v5/index Initializes User and Project models, preparing for the definition of a one-to-many association. ```javascript class User extends Model {} User.init({/* ... */}, { sequelize, modelName: 'user' }) class Project extends Model {} Project.init({/* ... */}, { sequelize, modelName: 'project' }) ``` -------------------------------- ### Find Projects with Matching Task State Source: https://sequelize.org/v5/index Example of using Sequelize associations to find projects that have at least one associated task with a matching state. It utilizes `Sequelize.col` for cross-table comparisons. ```javascript // Find all projects with a least one task where task.state === project.state Project.findAll({ include: [{ model: Task, where: { state: Sequelize.col('project.state') } }] }) ``` -------------------------------- ### Query JSONB Data with Nested Keys Source: https://sequelize.org/v5/index Demonstrates querying JSONB data in Sequelize using nested keys. This example filters records based on a condition applied to a deeply nested key. ```json { "meta.audio.length": { [Op.gt]: 20 } } ``` -------------------------------- ### Data Retrieval with Sequelize Finders Source: https://sequelize.org/v5/index Explains how to use Sequelize finder methods like `findByPk` and `findOne` to query data from the database. These methods return model instances, allowing further interaction with the retrieved data. ```javascript // search for known ids Project.findByPk(123).then(project => { // project will be an instance of Project and stores the content of the table entry // with id 123. if such an entry is not defined you will get null }) // search for attributes Project.findOne({ where: {title: 'aProject'} }).then(project => { // project will be the first entry of the Projects table with the title 'aProject' || null }) ``` ```javascript Project.findOne({ where: {title: 'aProject'}, attributes: ['id', ['name', 'title']] }).then(project => { // project will be the first entry of the Projects table with the title 'aProject' || null // project.get('title') will contain the name of the project }) ``` -------------------------------- ### Query JSONB Data with Containment Source: https://sequelize.org/v5/index Illustrates how to query JSONB data in Sequelize using the containment operator. This example checks if a nested object within the JSONB field contains specific key-value pairs. ```json { "meta": { [Op.contains]: { site: { url: 'http://google.com' } } } } ``` -------------------------------- ### Sequelize v5 Operator Combinations Source: https://sequelize.org/v5/index Provides examples of combining Sequelize operators to form more complex query conditions. This includes using OR for multiple conditions on the same field or different fields, and AND for time-based range queries. ```javascript const Op = Sequelize.Op; { 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%' ``` -------------------------------- ### Order Eager Loaded Associations (JavaScript) Source: https://sequelize.org/v5/index Provides examples of ordering eager-loaded associations in Sequelize v5 for both one-to-many and many-to-many relationships. It demonstrates ordering by attributes in the main model, associated models, and through tables. ```javascript // One-to-many relationship ordering Company.findAll({ include: [ Division ], order: [ [ Division, 'name' ] ] }); Company.findAll({ include: [ Division ], order: [ [ Division, 'name', 'DESC' ] ] }); Company.findAll({ include: [ { model: Division, as: 'Div' } ], order: [ [ { model: Division, as: 'Div' }, 'name' ] ] }); Company.findAll({ include: [ { model: Division, as: 'Div' } ], order: [ [ { model: Division, as: 'Div' }, 'name', 'DESC' ] ] }); Company.findAll({ include: [ { model: Division, include: [ Department ] } ], order: [ [ Division, Department, 'name' ] ] }); // Many-to-many relationship ordering by through table Company.findAll({ include: [ { model: Division, include: [ Department ] } ], order: [ [ Division, DepartmentDivision, 'name' ] ] }); ``` -------------------------------- ### Sequelize v5 Public Methods: authenticate, close, createSchema, define Source: https://sequelize.org/v5/class/lib/sequelize Documentation for essential Sequelize v5 public methods. `authenticate` tests the database connection. `close` terminates all connections. `createSchema` creates a new schema (PostgreSQL specific). `define` defines a new model representing a database table. ```javascript // Test the connection sequelize.authenticate() .then(() => { console.log('Connection has been established successfully.'); }) .catch(err => { console.error('Unable to connect to the database:', err); }); // Close all connections sequelize.close() .then(() => { console.log('Connection closed.'); }); // Create a schema (PostgreSQL specific) sequelize.createSchema('my_schema', { logging: console.log }) .then(schema => { console.log(`Schema 'my_schema' created.`); }); // Define a new model const User = sequelize.define('User', { firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING, allowNull: false } }, { // Other model options timestamps: false }); ``` -------------------------------- ### Change Default Model Options with Sequelize Constructor Source: https://sequelize.org/v5/index Illustrates how to modify default options for all Sequelize models by passing a 'define' object to the Sequelize constructor. This example disables timestamps (createdAt, updatedAt) by default. ```javascript const Sequelize = require('sequelize'); const sequelize = new Sequelize(connectionURI, { define: { // The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created. // This was true by default, but now is false by default timestamps: false } }); // Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created. class Foo extends Sequelize.Model {} Foo.init({ /* ... */ }, { sequelize }); // Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created. class Bar extends Sequelize.Model {} Bar.init({ /* ... */ }, { sequelize, timestamps: true }); ``` -------------------------------- ### Sequelize.useCLS() Source: https://sequelize.org/v5/class/lib/sequelize Use CLS with Sequelize. CLS namespace provided is stored as `Sequelize._cls` and bluebird Promise is patched to use the namespace. ```APIDOC ## POST /websites/sequelize_v5/useCLS ### Description Use CLS with Sequelize. CLS namespace provided is stored as `Sequelize._cls` and bluebird Promise is patched to use the namespace, using `cls-bluebird` module. ### Method POST ### Endpoint /websites/sequelize_v5/useCLS ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ns** (Object) - Required - CLS namespace ### Request Example ```json { "ns": {} } ``` ### Response #### Success Response (200) - **Object** (Object) - Sequelize constructor or the CLS namespace #### Response Example ```json { "message": "CLS namespace applied successfully." } ``` ``` -------------------------------- ### Merging Multiple Scopes Source: https://sequelize.org/v5/index Illustrates how to apply multiple scopes simultaneously to a model. Scopes can be passed as an array of scope names or as consecutive arguments to the .scope() method. The example shows merging 'deleted' and 'activeUsers' scopes. ```javascript // These two are equivalent Project.scope('deleted', 'activeUsers').findAll(); Project.scope(['deleted', 'activeUsers']).findAll(); ``` -------------------------------- ### Creating Persistent Instances Source: https://sequelize.org/v5/manual/instances Explains how to create instances that are automatically saved to the database upon creation using the `.create()` method. It also covers restricting attributes that can be set. ```APIDOC ## Creating Persistent Instances ### Description Use the `create` method to instantiate a model and immediately save it to the database in a single step. You can also specify which attributes are allowed to be set during creation. ### Method `create(values, options)` ### Endpoint N/A (Model method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **values** (object) - Required - An object containing the attributes to set for the new instance. - **options** (object) - Optional - An object that can contain `fields` to specify which attributes are allowed to be set. - **fields** (array) - Optional - An array of strings representing the attribute names that can be set. ### Request Example ```javascript // Create a task and save it Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task => { // Access the newly created task }); // Create a user, restricting settable fields User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user => { // isAdmin will be false if its default is false }); ``` ### Response #### Success Response (Created Instance) - **instance** (object) - The newly created and saved instance of the model. #### Response Example ```json { "username": "barfooz", "isAdmin": false } ``` ``` -------------------------------- ### Get Minimum Value with Sequelize v5 Source: https://sequelize.org/v5/index Retrieves the least value of a specified attribute from a database table. Similar to `max`, this method allows filtering records using a `where` clause. The result is returned via a Promise. ```javascript /* Let's assume 3 person objects with an attribute age. The first one is 10 years old, the second one is 5 years old, the third one is 40 years old. */ Project.min('age').then(min => { // this will return 5 }) Project.min('age', { where: { age: { [Op.gt]: 5 } } }).then(min => { // will be 10 }) ``` -------------------------------- ### Generate Migration Skeleton using Sequelize CLI Source: https://sequelize.org/v5/manual/migrations Demonstrates how to generate a basic migration file skeleton using the Sequelize CLI. This file contains the `up` and `down` functions for database schema changes. ```bash npx sequelize-cli migration:generate --name migration-skeleton ```