Sequelize is a promise-based ORM for Node.js that allows for modeling of database tables, querying, and synchronization between models and tables. It supports PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. Sequelize provides advantages like saving time and effort for developers by handling basic tasks and allowing a focus on business logic. Models can be defined and queried, validated, associated with other models, and synchronized with database tables. Raw SQL queries can also be executed through Sequelize.
2. What is Sequelize ?
▪ Sequelize is a promise-based ORM for Node.js.
▪ Sequelize is easy to learn and has dozens of cool features like
synchronization, association, validation, etc
▪ Supports Node v6 and above to use ES6 features.
▪ It also has support for PostgreSQL, MySQL, MariaDB, SQLite, and
MSSQL.
2
3. ORM
▪ ORM orObject Relation Mapping is a process of mapping between
objects and relation database systems.
▪ An ORM acts like an interface between two system.
▪ ORM provide advantages for developers from basic ones like saving
time and effort and rather focusing on business logic.
3
4. ORM
▪ ORM may be written to one or more database drivers, or have a storage
interface that allows databases, file systems, or other types of storage
mechanisms. Most ORMs require little or no SQL knowledge to work with
them.
$article = new Article(42);
if (!$article->fetch()) {throw new Exception("Article not found.");}
$article->title = “OneTitle for article";
$article->store();
4
5. Installation
▪ Sequelize is available via npm
npm install --save sequelize
▪ You also have to install manually the driver for the database of your choice:
# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2 # MYSQL
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
5
6. Setting up a connection
To connect to the database, you must create a Sequelize instance.This can be done
by passing the connection parameters separately to the Sequelize constructor or by
passing a single connection URI directly
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: Using a connection URI
const sequelize = new
Sequelize('postgres://user:pass@example.com:5432/dbname');
6
7. Testing the connection
You can use the .authenticate() function to test if the connection is OK:
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
})
7
8. Modeling a table/Model definition
▪ A model is a class that extends Sequelize.Model. Models can be
defined in two equivalent ways. The first,
with Sequelize.Model.init(attributes, options):
const Model = Sequelize.Model;
class User extends Model { }
User.init({
firstName: { type: Sequelize.STRING, allowNull: false },
lastName: { type: Sequelize.STRING}
}, { sequelize, modelName: 'user'});
8
9. Modeling a table/Model definition
▪ Altrnatively, using sequelize.define
const User = sequelize.define('user', {
firstName: {type: Sequelize.STRING, allowNull: false },
lastName: {type: Sequelize.STRING}
}, { // options });
▪ The above code tells Sequelize to expect a table named users in the
database with the fields firstName and lastName.The table name is
automatically pluralized by default.
9
10. Synchronizing the model with the
database
▪ If you want Sequelize to automatically create the table (or modify it
as needed) according to your model definition, you can use the sync
method, as follows:
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
return User.create({
firstName: ‘Tarek',
lastName: ‘Raihan'
});
});
10
11. Querying
▪ A few simple queries are shown below:
// Find all users
User.findAll().then(users => { console.log("All users:",JSON.stringify(users)); });
// Create a new user
User.create({ firstName: "Jane", lastName: "Doe" })
.then(res => { console.log("Jane's auto-generated ID:", res.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"); });
11
12. Datatypes
Below are some of the datatypes supported by sequelize
1. Sequelize.STRING //VARCHAR(255)
2. Sequelize.STRING(1234) //VARCHAR(1234)
3. Sequelize.STRING.BINARY //VARCHAR
BINARY
4. Sequelize.TEXT //TEXT
5. Sequelize.TEXT('tiny') //TINYTEXT
6. Sequelize.INTEGER // INTEGER
7. Sequelize.BIGINT // BIGINT
8. Sequelize.BIGINT(11) // BIGINT(11)
9. Sequelize.FLOAT // FLOAT
10. Sequelize.FLOAT(11) // FLOAT(11)
11. Sequelize.FLOAT(11, 10) // FLOAT(11,10)
12. Sequelize.DOUBLE // DOUBLE
13. Sequelize.DOUBLE(11) // DOUBLE(11)
14. Sequelize.DOUBLE(11, 10) // DOUBLE(11,10)
15. Sequelize.DECIMAL // DECIMAL
16. Sequelize.DECIMAL(10, 2) // DECIMAL(10,2)
17. Sequelize.DATE // DATETIME for mysql /
sqlite,
18. Sequelize.DATEONLY // DATE without
time.
19. Sequelize.BOOLEAN //TINYINT(1)
20. Sequelize.ENUM('value 1', 'value 2') // An ENUM
with allowed values 'value 1' and 'value 2'
12
13. Datatypes
Below are some of the datatypes supported by sequelize
1. Sequelize.STRING //VARCHAR(255)
2. Sequelize.STRING(1234) //VARCHAR(1234)
3. Sequelize.STRING.BINARY //VARCHAR
BINARY
4. Sequelize.TEXT //TEXT
5. Sequelize.TEXT('tiny') //TINYTEXT
6. Sequelize.INTEGER // INTEGER
7. Sequelize.BIGINT // BIGINT
8. Sequelize.BIGINT(11) // BIGINT(11)
9. Sequelize.FLOAT // FLOAT
10. Sequelize.FLOAT(11) // FLOAT(11)
11. Sequelize.FLOAT(11, 10) // FLOAT(11,10)
12. Sequelize.DOUBLE // DOUBLE
13. Sequelize.DOUBLE(11) // DOUBLE(11)
14. Sequelize.DOUBLE(11, 10) // DOUBLE(11,10)
15. Sequelize.DECIMAL // DECIMAL
16. Sequelize.DECIMAL(10, 2) // DECIMAL(10,2)
17. Sequelize.DATE // DATETIME for mysql /
sqlite,
18. Sequelize.DATEONLY // DATE without
time.
19. Sequelize.BOOLEAN //TINYINT(1)
20. Sequelize.ENUM('value 1', 'value 2') // An ENUM
with allowed values 'value 1' and 'value 2'
13
14. Validations
o Model validations allow you to specify format/content/inheritance validations for each
attribute of the model.
o Validations are automatically run on create, update and save
o You can define your custom validators or use several built-in validators, implemented
by validator.js
classValidateMe extends Model { }
ValidateMe.init({
bar: {
type: Sequelize.STRING,
validate: {
isEmail: true, // checks for email format (foo@bar.com)
isAlpha: true, // will only allow letters
isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail
isUUID: 4, // only allow uuids
max: 23, // only allow values <= 23
min: 23, // only allow values >= 23
}
}
}, { sequelize });
14
15. Model usage
▪ Data retrieval / Finders
1. find - Search for one specific element in the database
2. findOrCreate - Search for a specific element or create it if not available
3. findAndCountAll - Search for multiple elements in the database, returns both data and total
count
4. findAll - Search for multiple elements in the database
Project.findAll({ where: { id: [1,2,3] } }).then(projects => {
// projects will be an array of Projects having the id 1, 2 or 3
// this is actually doing an IN query
})
5. Manipulating the dataset with limit, offset, order and group
Project.findAll({ offset: 10, limit: 2 })
15
16. Model usage
▪ Data retrieval / Finders
1. max - Get the greatest value of a specific attribute within a specific table
Project.max('age').then(max => {
// this will return 40
})
2. min - Get the least value of a specific attribute within a specific table
3. sum - Sum the value of specific attributes
4. Eager loading
16
17. Model usage
Eager loading
When you are retrieving data from the database there is a fair chance that you also want to get
associations with the same query - this is called eager loading
classUser extends Model { }
User.init({ name: Sequelize.STRING }, { sequelize, modelName: 'user' })
classTask extends Model {}
Task.init({ name: Sequelize.STRING }, { sequelize, modelName: 'task' })
classTool extends Model {}
Tool.init({ name: Sequelize.STRING }, { sequelize, modelName: 'tool' })
Task.belongsTo(User)
User.hasMany(Task)
User.hasMany(Tool, { as: 'Instruments' })
17
18. Model usage
Eager loading
So, first of all, let's load all tasks with their associated user.
Task.findAll({ include: [ User ] }).then(tasks => {
console.log(JSON.stringify(tasks))
/*
[{
"name": "ATask",
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"userId": 1,
"user": {
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z"
}
}]
*/
})
18
19. Model usage
Eager loading
Notice that the accessor (the User property in the resulting instance) is singular because the
association is one-to-something.
Next thing: Loading of data with many-to-something associations!
User.findAll({ include: [Task ] }).then(users => {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"tasks": [{
"name": "ATask",
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"userId": 1
}]
}]
*/
})
19
20. Raw queries
As there are often use cases in which it is just easier to
execute raw / already prepared SQL queries, you can utilize
the function sequelize.query
sequelize.query("SELECT * FROM `users`", { type:
sequelize.QueryTypes.SELECT})
.then(users => {
//We don't need spread here, since only the results will be
returned for select queries
})
20
21. Replacements
Replacements in a query can be done in two different ways, either using
named parameters (starting with :), or unnamed, represented by a ?.
Replacements are passed in the options object.
▪ If an array is passed, ? will be replaced in the order that they appear in the
array
▪ If an object is passed, :key will be replaced with the keys from that object. If
the object contains keys not found in the query or vice versa, an exception
will be thrown
21