Sequelize

Command Line

Initialize Project

 npm install sequelize sequelize-cli pg
npx sequelize-cli init

Create Database

 npx sequelize-cli db:create

Seeds

Generate a new seed file

 npx sequelize-cli seed:generate --name <descriptiveName>

Run all pending seeds

 npx sequelize-cli db:seed:all

Rollback Seeds

Migrations

Generate a model and its migration

 npx sequelize-cli model:generate --name <ModelName> --attributes<column1>:<type>,<column2>:<type>,...

Run all pending migrations

 npx sequelize-cli db:migrate

Rollback Migrations

Javascript SQL Functions

Connecting to a Database

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 2a: Passing parameters separately (sqlite)
const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: 'path/to/database.sqlite'
});
// Option 2b: Passing parameters separately (other dialects)
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});

Testing the Connection

try {
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

Create a Table

return queryInterface.createTable(<TableName>, {
  <columnName>: {
    type: Sequelize.<type>,
    allowNull: <true|false>,
    unique: <true|false>,
    references: {
      model: {
        tableName: <TableName>
      }
    }
  }
});

Delete Table

return queryInterface.dropTable(<TableName>);

Adding a column

return queryInteface.addColumn(<TableName>, <columnName>: {
  type: Sequelize.<type>,
  allowNull: <true|false>,
  unique: <true|false>,
  references: {
    model: <TableName>
    },
});

Removing a column

return queryInterface.removeColumn(<TableName>, <columnName>);

Models

Model Basics

Naming Models

Defining a Model

Using sequelize.define
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

Synchronizing a Model

Function Action
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.
Promises and async/ await

Model Instances

Queries

INSERT queries

// Create a new user
const jane = await User.create({ firstName: "Jane", lastName: "Doe" });
console.log("Jane's auto-generated ID:", jane.id);

SELECT queries

// 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));
 SELECT * FROM ...

UPDATE queries

// Change everyone without a last name to "Doe"
await User.update({ lastName: "Doe" }, {
  where: {
    lastName: null
  }
});

DELETE queries

// Delete everyone named "Jane"
await User.destroy({
  where: {
    firstName: "Jane"
  }
});

Ordering Results

Model.findAll({
  order: [
    // Will escape name and validate DESC | ASC against a list of valid direction parameters
    ['name', 'DESC' | 'ASC']
  ]
})
Model.findOne({
  order: [
    // will return `name` DESC or ASC
    ['name', `DESC` | `ASC`],
    // will return max('age')
    sequelize.fn('max', sequelize.col('age')),
    // will return max('age') DESC
    [sequelize.fn('max', sequelize.col('age')), 'DESC'],
  ]
});

The elements of the order array can be the following:

Limits and Offset

// 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 });

Grouping Results

Model.findAll({
  group: 'name'
});
// yields 'GROUP BY name'
Public Methods
Action Method
Add a new column to a table async addColumn(table: string, key: string, attribute: object, options: object): Promise
Add a constraint to a table async addConstraint(tableName: string, options: object): Promise
Add an index to a column async addIndex(tableName: string \| object, attributes: Array, options: object, rawTablename: string): Promise
Delete multiple records from a table async bulkDelete(tableName: string, where: object, options: object, model: Model): Promise
Insert multiple records into a table async bulkInsert(tableName: string, records: Array, options: object, attributes: object): Promise
Update multiple records of a table async bulkUpdate(tableName: string, values: object, identifier: object, options: object, attributes: object): Promise
Change a column definition async changeColumn(tableName: string, attributeName: string, dataTypeOrOptions: object, options: object): *
Create a database async createDatabase(database: string, options: object): Promise
Create an SQL function async createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, optionsArray: Array, options: object): Promise
Create a schema async createSchema(schema: string, options: object): Promise
Create a table with given set of attributes async createTable(tableName: string, attributes: object, options: object, model: Model): Promise
Describe a table structure async describeTable(tableName: string, options: object): Promise<object>
Drop all schemas async dropAllSchemas(options: object): Promise
Drop all tables from database async dropAllTables(options: object): Promise
Drop a database async dropDatabase(database: string, options: object): Promise
Drop an SQL function async dropFunction(functionName: string, params: Array, options: object): Promise
Drop a schema async dropSchema(schema: string, options: object): Promise
Drop a table from database async dropTable(tableName: string, options: object): Promise
Get foreign key references details for the table async getForeignKeyReferencesForTable(tableName: string, options: object): *
Returns all foreign key constraints of requested tables async getForeignKeysForTables(tableNames: string[], options: object): Promise
Remove a column from a table async removeColumn(tableName: string, attributeName: string, options: object): *
Remove a constraint from a table async removeConstraint(tableName: string, constraintName: string, options: object): *
Remove an already existing index from a table async removeIndex(tableName: string, indexNameOrAttributes: string \| string[], options: object): Promise
Rename a column async renameColumn(tableName: string, attrNameBefore: string, attrNameAfter: string, options: object): Promise
Rename an SQL function async renameFunction(oldFunctionName: string, params: Array, newFunctionName: string, options: object): Promise
Rename a table async renameTable(before: string, after: string, options: object): Promise
Show all schemas async showAllSchemas(options: object): Promise<Array>
Upsert async upsert(tableName: string, insertValues: object, updateValues: object, where: object, options: object): Promise<boolean, ?number>

Utility Methods

Count

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

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
Validations and Constraints

END