SlideShare uma empresa Scribd logo
1 de 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

Mais conteĂșdo relacionado

Mais procurados

Mais procurados (20)

JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Cookie and session
Cookie and sessionCookie and session
Cookie and session
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
 
Express JS
Express JSExpress JS
Express JS
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Java script array
Java script arrayJava script array
Java script array
 
Express js
Express jsExpress js
Express js
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | Edureka
 

Semelhante a 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
 

Semelhante a 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
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Bert Jan Schrijver
 

Último (20)

WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%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
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 

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