SlideShare a Scribd company logo
1 of 23
Sequelize
BYTAREK RAIHAN
Email : tarekraihan@yahoo.com
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Replacements
sequelize.query('SELECT * FROM projectsWHERE status = ?',
{ replacements: ['active'], type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
sequelize.query('SELECT * FROM projectsWHERE status = :status ',
{ replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
22
THANK YOU
23

More Related Content

What's hot

What's hot (20)

Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
JAVASCRIPT.pdf
JAVASCRIPT.pdfJAVASCRIPT.pdf
JAVASCRIPT.pdf
 
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
 
Postgresql tutorial
Postgresql tutorialPostgresql tutorial
Postgresql tutorial
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Express node js
Express node jsExpress node js
Express node js
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
MongoDB
MongoDBMongoDB
MongoDB
 
JPA and Hibernate Performance Tips
JPA and Hibernate Performance TipsJPA and Hibernate Performance Tips
JPA and Hibernate Performance Tips
 
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자
[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자
[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
Spring Core
Spring CoreSpring Core
Spring Core
 

Similar to Sequelize

case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
tidwellveronique
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentation
SAIL_QU
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
PostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, StructuredPostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, Structured
priya951125
 
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
MARRY7
 

Similar to Sequelize (20)

Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
 
Apache Utilities At Work V5
Apache Utilities At Work   V5Apache Utilities At Work   V5
Apache Utilities At Work V5
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Rails and alternative ORMs
Rails and alternative ORMsRails and alternative ORMs
Rails and alternative ORMs
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentation
 
Local Storage
Local StorageLocal Storage
Local Storage
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Php summary
Php summaryPhp summary
Php summary
 
PostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, StructuredPostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, Structured
 
Html web sql database
Html web sql databaseHtml web sql database
Html web sql database
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
 
MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019
MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019
MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019
 
Data handling in r
Data handling in rData handling in r
Data handling in r
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascript
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 

Sequelize

  • 1. Sequelize BYTAREK RAIHAN Email : tarekraihan@yahoo.com
  • 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
  • 22. Replacements sequelize.query('SELECT * FROM projectsWHERE status = ?', { replacements: ['active'], type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) }) sequelize.query('SELECT * FROM projectsWHERE status = :status ', { replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) }) 22