### Quick Start with Sequelize Source: https://sequelize.org/docs/v6 A basic example demonstrating how to set up a Sequelize model, synchronize it with the database, and create a new record. Requires Node.js and Sequelize installed. ```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' }, ); (async () => { await sequelize.sync(); const jane = await User.create({ username: 'janedoe', birthday: new Date(1980, 6, 20), }); console.log(jane.toJSON()); })(); ``` -------------------------------- ### Full Runnable Example: Many-to-Many-to-Many Setup Source: https://sequelize.org/docs/v6/advanced-association-concepts/advanced-many-to-many A complete, runnable example demonstrating the setup of three models (Player, Team, Game) and their complex many-to-many-to-many relationships using Sequelize. Includes model definitions, junction tables, and bulk data creation. ```javascript 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.STRING }); // 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' }, ``` -------------------------------- ### Setup One-To-One Association for Query Examples Source: https://sequelize.org/docs/v6/core-concepts/assocs This code sets up the `Ship` and `Captain` models with a one-to-one relationship, allowing null foreign keys, which is the default behavior. This setup is used for demonstrating association queries. ```javascript // 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); ``` -------------------------------- ### Install Sequelize Source: https://sequelize.org/docs/v6/getting-started Install Sequelize using npm. You will also need to install a database driver separately. ```bash npm install --save sequelize ``` ```bash # 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 $ npm install --save oracledb # Oracle ``` -------------------------------- ### Install and Instantiate CLS Namespace Source: https://sequelize.org/docs/v6/other-topics/transactions Install the `cls-hooked` module and create a namespace for managing context. This is the first step to enabling automatic transaction passing. ```javascript const cls = require('cls-hooked'); const namespace = cls.createNamespace('my-very-own-namespace'); ``` -------------------------------- ### Install Sequelize CLI Source: https://sequelize.org/docs/v6/other-topics/migrations Install the Sequelize Command-Line Interface (CLI) as a development dependency. ```bash npm install --save-dev sequelize-cli ``` -------------------------------- ### Minimal Strict TypeScript Sequelize Project Setup Source: https://sequelize.org/docs/v6/other-topics/typescript An example of a minimal TypeScript project setup for Sequelize with strict type checking. It includes necessary imports for associations, model definition, and attribute typing, along with a Sequelize instance initialization. ```typescript import type { Association, HasManyAddAssociationMixin, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin, HasManyGetAssociationsMixin, HasManyHasAssociationMixin, HasManySetAssociationsMixin, HasManyAddAssociationsMixin, HasManyHasAssociationsMixin, HasManyRemoveAssociationMixin, HasManyRemoveAssociationsMixin, ModelDefined, Optional, InferAttributes, InferCreationAttributes, CreationOptional, NonAttribute, ForeignKey, } from 'sequelize'; import { DataTypes, Model, Sequelize } from 'sequelize'; const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb'); // 'projects' is excluded as it's not an attribute, it's an association. class User extends Model< InferAttributes, InferCreationAttributes > { // id can be undefined during creation when using `autoIncrement` declare id: CreationOptional; declare name: string; declare preferredName: string | null; // for nullable fields // timestamps! // createdAt can be undefined during creation declare createdAt: CreationOptional; // updatedAt can be undefined during creation declare updatedAt: CreationOptional; // 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. declare getProjects: HasManyGetAssociationsMixin; // Note the null assertions! ``` -------------------------------- ### Default Association Setup and Eager/Lazy Loading Source: https://sequelize.org/docs/v6/core-concepts/assocs Shows the default `belongsTo` association setup and how to perform Eager Loading with `include` and Lazy Loading with `getCaptain()` instance method. ```javascript 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()); ``` -------------------------------- ### Associations Setup Source: https://sequelize.org/docs/v6/other-topics/typescript Demonstrates how to set up associations between Sequelize models, including one-to-many, one-to-one, and many-to-one relationships. ```APIDOC ## Sequelize Associations ### Description This section details the setup of associations between different Sequelize models, defining how they relate to each other. ### User hasMany Project - **Description**: A User can have multiple Projects. - **Configuration**: `User.hasMany(Project, { sourceKey: 'id', foreignKey: 'ownerId', as: 'projects' });` ### Address belongsTo User - **Description**: An Address belongs to a User. - **Configuration**: `Address.belongsTo(User, { targetKey: 'id' });` ### User hasOne Address - **Description**: A User can have one Address. - **Configuration**: `User.hasOne(Address, { sourceKey: 'id' });` ### Example Usage (Conceptual) ```typescript // Fetching a user and their associated projects const userWithProjects = await User.findByPk(1, { include: [{ model: Project, as: 'projects' }] }); console.log(userWithProjects.projects); // Fetching an address and its associated user const addressWithUser = await Address.findByPk(1, { include: [{ model: User }] }); console.log(addressWithUser.user); ``` ``` -------------------------------- ### Sequelize Configuration File Source: https://sequelize.org/docs/v6/other-topics/migrations Example configuration file for Sequelize, defining database connection details for different environments. ```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" } } ``` -------------------------------- ### Example Dynamic Configuration File (config.js) Source: https://sequelize.org/docs/v6/other-topics/migrations Provides development, test, and production database configurations, including environment variable usage and custom dialect options. ```javascript 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'), }, }, }, }; ``` -------------------------------- ### npm Script Usage Example Source: https://sequelize.org/docs/v6/other-topics/migrations Illustrates how to run an npm script that executes a Sequelize migration command, including passing a connection string URL. ```bash npm run migrate:up -- --url ``` -------------------------------- ### Setup One-to-Many Relationships for Grant Model Source: https://sequelize.org/docs/v6/advanced-association-concepts/advanced-many-to-many Configures two One-to-Many relationships: one between User and Grant, and another between Profile and Grant. This approach results in similar database table structures as the Many-to-Many setup. ```javascript // 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); ``` -------------------------------- ### Example Output of Polymorphic Eager Loading Source: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations This is an example of the output you might see after successfully performing polymorphic eager loading and logging the commentable data. ```javascript 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 } ``` -------------------------------- ### Sequelize One-to-One Association Setup Source: https://sequelize.org/docs/v6/core-concepts/assocs Sets up a One-to-One relationship where Bar gets a fooId column. Sequelize infers the foreign key name from the model names. ```javascript Foo.hasOne(Bar); Bar.belongsTo(Foo); ``` -------------------------------- ### Define Isolation Levels for Transactions Source: https://sequelize.org/docs/v6/other-topics/transactions Shows how to specify isolation levels when starting a transaction using the `isolationLevel` option. This example uses `SERIALIZABLE`. ```javascript const { Transaction } = require('sequelize'); await sequelize.transaction( { isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE, }, async t => { // Your code }, ); ``` -------------------------------- ### Enabling Babel for Migrations/Seeders Source: https://sequelize.org/docs/v6/other-topics/migrations Install babel-register and require it in .sequelizerc to use modern JavaScript syntax in migrations and seeders. ```bash npm i --save-dev babel-register ``` ```javascript // .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'), }; ``` -------------------------------- ### Configure Connection Pool Options Source: https://sequelize.org/docs/v6/category/other-topics Configure the connection pool settings when initializing a Sequelize instance. This example shows how to set options for the pool. ```javascript const sequelize = new Sequelize({ // ... other options pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } }); ``` -------------------------------- ### Populate Post and Reaction Data Source: https://sequelize.org/docs/v6/other-topics/sub-queries Helper function to create posts and associate reactions, used for setting up data for subquery examples. ```javascript 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']); ``` -------------------------------- ### Sequelize Initialization with Imports Source: https://sequelize.org/docs/v6/getting-started Initialize Sequelize with necessary imports for common operations. This example uses an in-memory SQLite database for quick local testing. ```javascript const { Sequelize, Op, Model, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); // Code here! It works! ``` -------------------------------- ### Successful Instance Creation with Hook Source: https://sequelize.org/docs/v6/other-topics/hooks Example showing a successful user creation where the instance hook's validation passes. The user 'Boss' can have an access level of 20. ```javascript const user = await User.create({ username: 'Boss', accessLevel: 20 }); console.log(user); // user object with username 'Boss' and accessLevel of 20 ``` -------------------------------- ### Eager Loading Example Source: https://sequelize.org/docs/v6/core-concepts/assocs Fetches associated models in the same query as the primary model using the `include` option. This is efficient when you know you will need the associated data. ```javascript 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); ``` -------------------------------- ### Create Table Migration Source: https://sequelize.org/docs/v6/other-topics/migrations Example of a migration that creates a 'Person' table with string and boolean columns. The 'up' function creates the table, and the 'down' function drops it. ```javascript 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'); }, }; ``` -------------------------------- ### Raw SQL Subquery Example Source: https://sequelize.org/docs/v6/other-topics/sub-queries A raw SQL query demonstrating how to count 'Laugh' reactions for each post using a subquery. ```sql SELECT *, ( SELECT COUNT(*) FROM reactions AS reaction WHERE reaction.postId = post.id AND reaction.type = "Laugh" ) AS laughReactionsCount FROM posts AS post ``` -------------------------------- ### SQL Query for Creating an Image Comment Source: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations Example SQL for `image.createComment({ title: 'Awesome!' })`, showing the insertion of a new comment with the correct `commentableType` and `commentableId`. ```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 *; ``` -------------------------------- ### Nested Eager Loading Example Source: https://sequelize.org/docs/v6/advanced-association-concepts/eager-loading Demonstrates how to load all related models of a related model using nested eager loading. This typically results in an outer join. ```javascript const users = await User.findAll({ include: { model: Tool, as: 'Instruments', include: { model: Teacher, include: [ /* etc */ ], }, }, }); console.log(JSON.stringify(users, null, 2)); ``` -------------------------------- ### Instance Methods for hasOne Association Source: https://sequelize.org/docs/v6/core-concepts/assocs Demonstrates the special methods (`get`, `set`, `create`) added to instances when a `hasOne` association is defined. These methods allow for retrieving, updating, and creating associated records. ```javascript 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 ``` -------------------------------- ### Seed File Implementation for User Data Source: https://sequelize.org/docs/v6/other-topics/migrations Example implementation of a seed file using Sequelize's query interface to insert a demo user into the 'Users' table and a corresponding down method to delete the user. ```javascript 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, {}); }, }; ``` -------------------------------- ### Initialize Sequelize Project Source: https://sequelize.org/docs/v6/other-topics/migrations Bootstrap a new Sequelize project, creating essential configuration and directory structures. ```bash npx sequelize-cli init ``` -------------------------------- ### Polymorphic Eager Loading Setup Source: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations Use this structure to eager load associated commentables for one or more comments. Ensure an `afterFind` hook is defined to correctly populate the `commentable` field. ```javascript const comment = await Comment.findOne({ include: [ /* What to put here? */ ], }); console.log(comment.commentable); // This is our goal ``` -------------------------------- ### Create and Associate User and Project Models Source: https://sequelize.org/docs/v6/other-topics/typescript Demonstrates creating a new user, associating a project with that user, and then fetching the user with their associated projects. Uses `rejectOnEmpty` to ensure a user is found. ```javascript 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); } (async () => { await sequelize.sync(); await doStuffWithUser(); })(); ``` -------------------------------- ### Create Table with Multi-field Unique Index and Condition Source: https://sequelize.org/docs/v6/other-topics/migrations Example of creating a table and adding a unique index composed of multiple fields ('name', 'bool') with a condition. This allows multiple entries if the condition is not met. ```javascript 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'], { ``` -------------------------------- ### Use Index Hint in Sequelize Query Source: https://sequelize.org/docs/v6/other-topics/dialect-specific-things Apply index hints to guide the MySQL query optimizer. Ensure the specified index exists in your database. This example uses the USE index hint. ```javascript const { IndexHints } = require('sequelize'); Project.findAll({ indexHints: [{ type: IndexHints.USE, values: ['index_project_on_name'] }], where: { id: { [Op.gt]: 623, }, name: { [Op.like]: 'Foo %', }, }, }); ``` ```sql SELECT * FROM Project USE INDEX (index_project_on_name) WHERE name LIKE 'FOO %' AND id > 623; ``` -------------------------------- ### Lazy Loading Example Source: https://sequelize.org/docs/v6/core-concepts/assocs Fetches an associated model only when explicitly requested using an instance method like `getShip()`. This is useful when the associated data might not always be needed, saving resources. ```javascript 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); ``` -------------------------------- ### Create and Save a Model Instance (Shortcut) Source: https://sequelize.org/docs/v6/core-concepts/model-instances Combines the `build` and `save` operations into a single asynchronous method. Use `create` for a more concise way to instantiate and persist a model record. ```javascript const jane = await User.create({ name: 'Jane' }); // Jane exists in the database now! console.log(jane instanceof User); // true console.log(jane.name); // "Jane" ``` -------------------------------- ### Validation Result Example Source: https://sequelize.org/docs/v6/core-concepts/validations-and-constraints An example of a validation result object that might be returned when a model fails validation, showing errors for both a field and a model-wide validator. ```json { 'latitude': ['Invalid number: latitude'], 'bothCoordsOrNone': ['Either both latitude and longitude, or neither!'] } ``` -------------------------------- ### Create Product with Nested User and Addresses Source: https://sequelize.org/docs/v6/advanced-association-concepts/creating-with-associations Create a new Product instance along with its associated User and Addresses in a single step. The `include` option is required to specify which associations to create. ```javascript 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], }, ], }, ); ``` -------------------------------- ### Create a new user record Source: https://sequelize.org/docs/v6/core-concepts/model-querying-basics Use `Model.create()` to build and save a new instance. This is a shorthand for `Model.build()` followed by `instance.save()`. ```javascript const jane = await User.create({ firstName: 'Jane', lastName: 'Doe' }); console.log("Jane's auto-generated ID:", jane.id); ``` -------------------------------- ### Combining Getters and Setters for Content Compression Source: https://sequelize.org/docs/v6/core-concepts/getters-setters-virtuals This example demonstrates how to combine getters and setters to automatically compress and decompress text content using gzip and base64 encoding. It's useful for optimizing memory usage when storing large text fields. ```javascript 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')); }, }, }); ``` ```javascript const post = await Post.create({ content: 'Hello everyone!' }); console.log(post.content); // 'Hello everyone!' // However, if we are really curious, we can get the 'raw' data... console.log(post.getDataValue('content')); // Output: 'H4sIAAAAAAAACvNIzcnJV0gtSy2qzM9LVQQAUuk9jQ8AAAA=' ``` -------------------------------- ### Generated SQL for Scoped Query Source: https://sequelize.org/docs/v6/other-topics/scopes Example of the SQL query generated when applying scopes with arguments. ```sql SELECT * FROM projects WHERE someNumber = 42 AND accessLevel >= 19 ``` -------------------------------- ### Generated SQL for Removing a Column (PostgreSQL) Source: https://sequelize.org/docs/v6/other-topics/query-interface Example of the SQL generated by Sequelize's queryInterface.removeColumn for PostgreSQL. ```sql ALTER TABLE "public"."Person" DROP COLUMN "petName"; ``` -------------------------------- ### Generated SQL for Changing a Column (MySQL) Source: https://sequelize.org/docs/v6/other-topics/query-interface Example of the SQL generated by Sequelize's queryInterface.changeColumn for MySQL. ```sql ALTER TABLE `Person` CHANGE `foo` `foo` FLOAT NOT NULL DEFAULT 3.14; ``` -------------------------------- ### Configure Sequelize with Read Replication Source: https://sequelize.org/docs/v6/other-topics/read-replication Set up Sequelize with read and write database configurations. Use environment variables for sensitive credentials like passwords. Pool options can be overridden for read/write pools. ```javascript 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, }, }); ``` -------------------------------- ### Generated SQL for Adding a Column (SQLite) Source: https://sequelize.org/docs/v6/other-topics/query-interface Example of the SQL generated by Sequelize's queryInterface.addColumn for SQLite. ```sql ALTER TABLE `Person` ADD `petName` VARCHAR(255); ``` -------------------------------- ### Generated SQL for Creating a Table (SQLite) Source: https://sequelize.org/docs/v6/other-topics/query-interface Example of the SQL generated by Sequelize's queryInterface.createTable for SQLite. ```sql CREATE TABLE IF NOT EXISTS `Person` ( `name` VARCHAR(255), `isBetaMember` TINYINT(1) NOT NULL DEFAULT 0 ); ``` -------------------------------- ### Connect to a Database with Sequelize Source: https://sequelize.org/docs/v6/getting-started Create a Sequelize instance by providing connection parameters either as a URI or separate arguments. Supports various dialects like SQLite and PostgreSQL. ```javascript 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' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */ }); ``` -------------------------------- ### Dynamic Configuration with .sequelizerc Source: https://sequelize.org/docs/v6/other-topics/migrations Specify a JavaScript file for dynamic configuration loading in Sequelize CLI. ```javascript const path = require('path'); module.exports = { config: path.resolve('config', 'config.js'), }; ``` -------------------------------- ### Test Database Connection Source: https://sequelize.org/docs/v6/getting-started Use the `.authenticate()` method to verify that the connection to the database is established successfully. Handles potential errors during authentication. ```javascript try { await sequelize.authenticate(); console.log('Connection has been established successfully.'); } catch (error) { console.error('Unable to connect to the database:', error); } ``` -------------------------------- ### Apply Deleted Scope in Sequelize Source: https://sequelize.org/docs/v6/other-topics/scopes Example of applying the 'deleted' scope to find projects where the 'deleted' attribute is true. ```javascript await Project.scope('deleted').findAll(); ``` -------------------------------- ### Create Product with Multiple Tags Source: https://sequelize.org/docs/v6/advanced-association-concepts/creating-with-associations Create a Product instance and associate it with multiple Tag instances in a single operation. The `include` option specifies the Tag association. ```javascript Product.create( { id: 1, title: 'Chair', tags: [{ name: 'Alpha' }, { name: 'Beta' }], }, { include: [Tag], }, ); ``` -------------------------------- ### Sequelize CLI Configuration with .sequelizerc Source: https://sequelize.org/docs/v6/other-topics/migrations Configure paths for config, models, seeders, and migrations using a .sequelizerc file. ```javascript // .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'), }; ``` -------------------------------- ### SQL Query for Image Comments Source: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations Example SQL generated by `image.getComments()`, demonstrating how the `commentableType` scope is automatically added to the WHERE clause. ```sql SELECT "id", "title", "commentableType", "commentableId", "createdAt", "updatedAt" FROM "comments" AS "comment" WHERE "comment"."commentableType" = 'image' AND "comment"."commentableId" = 1; ``` -------------------------------- ### Run Migrations with Connection String Source: https://sequelize.org/docs/v6/other-topics/migrations Execute Sequelize migrations using a connection string URL instead of a configuration file. Ensure proper URL encoding for special characters. ```bash npx sequelize-cli db:migrate --url 'mysql://root:password@mysql_host.com/database_name' ``` -------------------------------- ### Define Post and Reaction Models Source: https://sequelize.org/docs/v6/other-topics/sub-queries Defines the Sequelize models for 'Post' and 'Reaction' with a one-to-many relationship. Timestamps are disabled for brevity in examples. ```javascript 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); ``` -------------------------------- ### Delete Records with WHERE Clause Source: https://sequelize.org/docs/v6/core-concepts/model-querying-basics Use the `destroy` method with a `where` option to remove specific records. This example deletes all users named 'Jane'. ```javascript await User.destroy({ where: { firstName: 'Jane', }, }); ``` -------------------------------- ### Set Storage Engine for a Model Source: https://sequelize.org/docs/v6/other-topics/dialect-specific-things Define a custom storage engine for a Sequelize model. The default is InnoDB; this example sets it to 'MYISAM'. ```javascript const Person = sequelize.define( 'person', { /* attributes */ }, { engine: 'MYISAM', }, ); ``` -------------------------------- ### Configure PostgreSQL Connector Options Source: https://sequelize.org/docs/v6/other-topics/dialect-specific-things Provide custom options to the pg package for PostgreSQL connections using `dialectOptions`. This includes settings like `application_name`, `ssl`, `client_encoding`, `keepAlive`, `statement_timeout`, and `idle_in_transaction_session_timeout`. ```javascript const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'postgres', dialectOptions: { // Your pg options here }, }); ``` -------------------------------- ### Postgres Range Operators Source: https://sequelize.org/docs/v6/core-concepts/model-querying-basics Examples of using Sequelize's operators for PostgreSQL-specific range types, including containment, overlap, and adjacency. ```javascript [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) ``` -------------------------------- ### Initialize Project Model Source: https://sequelize.org/docs/v6/other-topics/typescript Initializes the Project model with its attributes, table name, and Sequelize instance. ```typescript Project.init( { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, }, name: { type: new DataTypes.STRING(128), allowNull: false, }, createdAt: DataTypes.DATE, updatedAt: DataTypes.DATE, }, { sequelize, tableName: 'projects', }, ); ``` -------------------------------- ### Sequelize One-to-One Association SQL Output Source: https://sequelize.org/docs/v6/core-concepts/assocs Example SQL generated by Sequelize for a One-to-One association, showing the 'fooId' column in the 'bars' table. ```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 /* ... */ ); ``` -------------------------------- ### Define Self-Referential Many-to-Many Association Source: https://sequelize.org/docs/v6/advanced-association-concepts/advanced-many-to-many Supports self-referential Many-to-Many relationships by associating a model with itself. This example defines a 'Children' association for the Person model. ```javascript Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' }); ``` -------------------------------- ### Find the first project matching a title Source: https://sequelize.org/docs/v6/core-concepts/model-querying-finders Use `findOne` to retrieve the first entry that matches the provided query options. Returns an instance of the model or null if no match is found. ```javascript 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' } ``` -------------------------------- ### SQL Query for Adding a Comment to an Image Source: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations Example SQL for `image.addComment(comment)`, illustrating the update of an existing comment's `commentableId` and `commentableType`. ```sql UPDATE "comments" SET "commentableId"=1, "commentableType"='image', "updatedAt"='2018-04-17 05:38:43.948 +00:00' WHERE "id" IN (1) ``` -------------------------------- ### Instance Methods for belongsTo Association Source: https://sequelize.org/docs/v6/core-concepts/assocs Details the instance methods (`get`, `set`, `create`) available for `belongsTo` associations, which are identical to those for `hasOne` associations. ```javascript * `fooInstance.getBar()` * `fooInstance.setBar()` * `fooInstance.createBar()` ``` -------------------------------- ### Creating and Retrieving Data with Target Key Association Source: https://sequelize.org/docs/v6/core-concepts/assocs Demonstrates creating instances and retrieving associated data when a `belongsTo` association uses a `targetKey` other than the primary key. ```javascript 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" ``` -------------------------------- ### Configure SQLite Connector Options Source: https://sequelize.org/docs/v6/other-topics/dialect-specific-things Configure the sqlite3 npm package with custom options using `dialectOptions`. The `storage` option specifies the database file or ':memory:' for an in-memory instance. Ensure you are using a compatible version of sqlite3 or its recommended fork. ```javascript import { Sequelize } from 'sequelize'; import SQLite from 'sqlite3'; const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'sqlite', storage: 'path/to/database.sqlite', // or ':memory:' dialectOptions: { // Your sqlite3 options here // for instance, this is how you can configure the database opening mode: mode: SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE | SQLite.OPEN_FULLMUTEX, }, }); ``` -------------------------------- ### Configure Oracle Connection (Connect String) Source: https://sequelize.org/docs/v6/other-topics/dialect-specific-things Connect to an Oracle database using a connect string via `dialectOptions.connectString`. This method overrides host and port settings. ```javascript const sequelize = new Sequelize({ dialect: 'oracle', username: 'user', password: 'password', dialectOptions: { connectString: 'inst1', }, }); ``` -------------------------------- ### Update Records with WHERE Clause Source: https://sequelize.org/docs/v6/core-concepts/model-querying-basics Use the `update` method with a `where` option to modify specific records. This example changes users without a last name to 'Doe'. ```javascript await User.update( { lastName: 'Doe' }, { where: { lastName: null, }, } ); ``` -------------------------------- ### Obtain Sequelize Query Interface Source: https://sequelize.org/docs/v6/other-topics/query-interface Get the singleton instance of the QueryInterface class from your Sequelize instance. This is the entry point for using lower-level database operations. ```javascript const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize(/* ... */); const queryInterface = sequelize.getQueryInterface(); ``` -------------------------------- ### Run Sequelize Migrations Source: https://sequelize.org/docs/v6/other-topics/migrations Execute pending database migrations to create or update tables according to the migration files. ```bash npx sequelize-cli db:migrate ``` -------------------------------- ### Sequelize One-to-Many Association SQL Output Source: https://sequelize.org/docs/v6/core-concepts/assocs Example SQL generated for a One-to-Many association between Team and Player, showing the 'TeamId' foreign key in the 'Players' table. ```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, /* ... */ ); ``` -------------------------------- ### Setup Sequelize and Define User Model Source: https://sequelize.org/docs/v6/core-concepts/validations-and-constraints Initializes Sequelize with an in-memory SQLite database and defines a User model with username and hashedPassword attributes. The username has a unique constraint and cannot be null. The hashedPassword has a format validation. ```javascript 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 })(); ``` -------------------------------- ### Define Models for Associations Source: https://sequelize.org/docs/v6/advanced-association-concepts/creating-with-associations Define the Product, User, and Address models for demonstrating associations. Ensure models are initialized with Sequelize. ```javascript 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` ``` -------------------------------- ### Configure Oracle Connection (Standard) Source: https://sequelize.org/docs/v6/other-topics/dialect-specific-things Connect to an Oracle database using standard Sequelize constructor parameters including dialect, host, and port. ```javascript const sequelize = new Sequelize('servicename', 'username', 'password', { dialect: 'oracle', host: 'hostname', port: 'port number', }); ``` -------------------------------- ### Pass Transaction to Create Method Source: https://sequelize.org/docs/v6/other-topics/transactions Example of passing an active transaction `t` to the `User.create` method. The `transaction` option is typically the second argument for methods like `create`. ```javascript await User.create({ name: 'Foo Bar' }, { transaction: t }); ``` -------------------------------- ### Generated SQL for Association Scope Source: https://sequelize.org/docs/v6/advanced-association-concepts/association-scopes Illustrates the SQL query generated when calling the 'getOpenBars()' mixin on a Foo instance, demonstrating the automatic application of the association scope. ```sql SELECT `id`, `status`, `createdAt`, `updatedAt`, `fooId` FROM `bars` AS `bar` WHERE `bar`.`status` = 'open' AND `bar`.`fooId` = 1; ``` -------------------------------- ### Create Image and Associated Comment Source: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations Demonstrates creating an Image instance and then creating a Comment associated with that Image using an instance method. The `commentableId` and `commentableType` are automatically set. ```javascript const image = await Image.create({ url: 'https://placekitten.com/408/287' }); const comment = await image.createComment({ content: 'Awesome!' }); ```