SlideShare a Scribd company logo
1 of 23
Sequelize
models, migrations, oh my
Ryan M Harrison Jan 24, 2019
Agenda
• Three-schema approach
• DEMO: Express w/ SQL
• What good is an “ORM”?
• DEMO: Express w/ Sequelize (models)
• What good are migrations?
• DEMO: Express w/ Sequelize (migrations)
Follow along in Github:
https://github.com/rmharrison/prez-sequelize
2
Three-schema approach
• Conceptual Data Model
• Logical Data Model
• Physical Data Model
3
Three-schema approach
4
Three-schema approach
5
DEMO: Express w/ SQL
• Run postgres in docker
• psql to create table
• psql to seed table
6
DEMO: Express w/ SQL
• full_name → first_name, last_name
7
Web Framework express, hapi, restify
ORM sequelize, bookshelf
Migration tool umzug (sequelize-cli), knex
(bookshelf)
Query builder sequelize, knex
(Data access object)
Client pg
ORM: Object Relational Mapper (postgres)
8
ORM: Object Relational Mapper
9
SQL
CREATE TABLE Person (
id bigserial primary key,
full_name varchar(100) NOT NULL,
created_at timestamp default
CURRENT_TIMESTAMP
updated_at timestamp default
CURRENT_TIMESTAMP
);
Sequelize ORM (javascript)
module.exports = (sequelize, DataTypes) => {
const person = sequelize.define('person', {
full_name: DataTypes.STRING,
}, {
underscored: true,
});
return person;
};
ORM: Object Relational Mapper
• Virtual Object
• Abstracts (some) implementation details, e.g. associations.
10
SQL
SELECT * FROM people;
SELECT * FROM people
LIMIT 1;
SELECT COUNT(*) FROM people;
SELECT * FROM people WHERE id = 1
Sequelize ORM (javascript)
Person.findAll()
Person.findOne()
Person.findAndCountAll()
Person.findById(1)
ORM: Object Relational Mapper
• Virtual Object
• Abstracts (some) implementation details, e.g. associations.
11
Sequelize, One-To-Many associations (hasMany)
const City = sequelize.define('city', { countryCode: Sequelize.STRING });
const Country = sequelize.define('country', { isoCode: Sequelize.STRING });
// Here we can connect countries and cities base on country code
Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'});
City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});
Web Framework express, hapi, restify
ORM mongoose
Migration tool migrate-mongoose
Query Builder mongodb
Client mongodb-core
ORM: Object Relational Mapper (mongo)
12
DEMO: Express w/ Sequelize (models)
• Sequelize CLI
• Generate models from CLI
13
Migrations: Define schema
14
demodb=# d people
Table "public.people"
Column | Type | Collation | Nullable | Default
------------+--------------------------+-----------+----------+-----------------------------------
id | integer | | not null |
nextval('people_id_seq'::regclass)
created_at | timestamp with time zone | | not null | now()
updated_at | timestamp with time zone | | not null | now()
full_name | character varying(255) | | |
Indexes:
"people_pkey" PRIMARY KEY, btree (id)
Migrations: Define schema
15
demodb=# d people
Table "public.people"
Column | Type | Collation | Nullable | Default
------------+--------------------------+-----------+----------+-----------------------------------
id | integer | | not null |
nextval('people_id_seq'::regclass)
created_at | timestamp with time zone | | not null | now()
updated_at | timestamp with time zone | | not null | now()
first_name | character varying(255) | | |
last_name | character varying(255) | | |
Indexes:
"people_pkey" PRIMARY KEY, btree (id)
Migrations: Define schema
16
Time Jan 2018 Feb 2018 Mar 2018
release v0.1.0 v0.2.0 v0.3.0
models sales.js
product.js
sales.js
product.js (13 ++++++-----)
store.js
sales.js (100 +++---)
product.js (50 ++++)
store.js (20 +-----)
migrations 201801-migration.js 201802-migration.js
201801-migration.js
201803-migration.js
201802-migration.js
201801-migration.js
Seeds: Define data
17
demodb=# SELECT * FROM people;
id | created_at | updated_at | first_name |
last_name
----+----------------------------+----------------------------+------------+-----------
1 | 2019-01-25 09:20:11.392+00 | 2019-01-25 09:20:11.392+00 | John | Watts
2 | 2019-01-25 09:20:11.392+00 | 2019-01-25 09:20:11.392+00 | Charles | Ingram
DEMO: Express w/ Sequelize (migrations)
• full_name → first_name, last_name
• Generate migrations and seeds from CLI
18
Strengths
● Model-driven development
● Sequelize Models are Javascript classes
○ all the goodies available, inc. Prototype, extends, etc.
● Life-cycle hooks
○ beforeSave, afterValidate, et al.
19
Weaknesses addressed ecosystem
● Generate models from existing DB schema
○ npm:sequelize-auto (1400+ stars; officially supported)
● Generate migrations from models
○ Long-standing known issue: https://github.com/sequelize/cli/issues/157
○ npm:sequelize-auto-migrations (incomplete, only handles up)
● Model versioning
○ npm:sequelize-version (low adoption)
● Nested hierarchies
○ npm:sequelize-hierarchy
● Fixtures
○ npm:sequelize-fixtures (maintainer wants to abandon)
20
Gotchas
● Cannot link a seed with a specific migration
○ Convention: Assume “latest” for seed data
○ Check SequelizeMeta in seed script
● “Version” is not what you think
○ NB: version in Sequelize is for OptimisticLocking [PR] not model versions
● Poor error messages in migrations
21
== 20190125055636-full-to-first-last: migrating =======
ERROR: Unexpected identifier
Resources
● SQL Naming Conventions
22
Questions?

More Related Content

Similar to 2019-01-24 Sequelize ORM (Object Relational Mapper): models, migrations, oh my

A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScriptDenis Voituron
 
The openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query LanguageThe openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query LanguageNeo4j
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youShrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youSHRUG GIS
 
ActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in JavaActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in Javaipolevoy
 
The Quest for an Open Source Data Science Platform
 The Quest for an Open Source Data Science Platform The Quest for an Open Source Data Science Platform
The Quest for an Open Source Data Science PlatformQAware GmbH
 
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...jaxLondonConference
 
PostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databasePostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databaseBarry Jones
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB
 
Retaining globally distributed high availability
Retaining globally distributed high availabilityRetaining globally distributed high availability
Retaining globally distributed high availabilityspil-engineering
 
Drilling into Data with Apache Drill
Drilling into Data with Apache DrillDrilling into Data with Apache Drill
Drilling into Data with Apache DrillDataWorks Summit
 
Drilling into Data with Apache Drill
Drilling into Data with Apache DrillDrilling into Data with Apache Drill
Drilling into Data with Apache DrillMapR Technologies
 
Flume HBase
Flume HBaseFlume HBase
Flume HBaseirayan
 
Working with MongoDB as MySQL DBA
Working with MongoDB as MySQL DBAWorking with MongoDB as MySQL DBA
Working with MongoDB as MySQL DBAIgor Donchovski
 
You got schema in my json
You got schema in my jsonYou got schema in my json
You got schema in my jsonPhilipp Fehre
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)Jerome Eteve
 
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...apidays
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...NoSQLmatters
 
Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Neo4j
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonMax Klymyshyn
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQLjeykottalam
 

Similar to 2019-01-24 Sequelize ORM (Object Relational Mapper): models, migrations, oh my (20)

A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
 
The openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query LanguageThe openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query Language
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youShrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_you
 
ActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in JavaActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in Java
 
The Quest for an Open Source Data Science Platform
 The Quest for an Open Source Data Science Platform The Quest for an Open Source Data Science Platform
The Quest for an Open Source Data Science Platform
 
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
 
PostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databasePostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty database
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
 
Retaining globally distributed high availability
Retaining globally distributed high availabilityRetaining globally distributed high availability
Retaining globally distributed high availability
 
Drilling into Data with Apache Drill
Drilling into Data with Apache DrillDrilling into Data with Apache Drill
Drilling into Data with Apache Drill
 
Drilling into Data with Apache Drill
Drilling into Data with Apache DrillDrilling into Data with Apache Drill
Drilling into Data with Apache Drill
 
Flume HBase
Flume HBaseFlume HBase
Flume HBase
 
Working with MongoDB as MySQL DBA
Working with MongoDB as MySQL DBAWorking with MongoDB as MySQL DBA
Working with MongoDB as MySQL DBA
 
You got schema in my json
You got schema in my jsonYou got schema in my json
You got schema in my json
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)
 
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
 
Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 

More from Ryan M Harrison

2020-11-13 Anatomy of a FHIR Implementation Guide
2020-11-13 Anatomy of a FHIR Implementation Guide2020-11-13 Anatomy of a FHIR Implementation Guide
2020-11-13 Anatomy of a FHIR Implementation GuideRyan M Harrison
 
2021 12-03 TOGAF for Developers
2021 12-03 TOGAF for Developers2021 12-03 TOGAF for Developers
2021 12-03 TOGAF for DevelopersRyan M Harrison
 
Positioning yourself for success in technical careers
Positioning yourself for success in technical careersPositioning yourself for success in technical careers
Positioning yourself for success in technical careersRyan M Harrison
 
2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with DreddRyan M Harrison
 
Breaking a monolith: In-place refactoring with service-oriented architecture ...
Breaking a monolith: In-place refactoring with service-oriented architecture ...Breaking a monolith: In-place refactoring with service-oriented architecture ...
Breaking a monolith: In-place refactoring with service-oriented architecture ...Ryan M Harrison
 
End-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-Rest
End-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-RestEnd-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-Rest
End-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-RestRyan M Harrison
 
Nest v. Flat with EmberData
Nest v. Flat with EmberDataNest v. Flat with EmberData
Nest v. Flat with EmberDataRyan M Harrison
 
DEF CON 24: Reverse engineering biomedical equipment for fun and open science
DEF CON 24: Reverse engineering biomedical equipment for fun and open scienceDEF CON 24: Reverse engineering biomedical equipment for fun and open science
DEF CON 24: Reverse engineering biomedical equipment for fun and open scienceRyan M Harrison
 

More from Ryan M Harrison (8)

2020-11-13 Anatomy of a FHIR Implementation Guide
2020-11-13 Anatomy of a FHIR Implementation Guide2020-11-13 Anatomy of a FHIR Implementation Guide
2020-11-13 Anatomy of a FHIR Implementation Guide
 
2021 12-03 TOGAF for Developers
2021 12-03 TOGAF for Developers2021 12-03 TOGAF for Developers
2021 12-03 TOGAF for Developers
 
Positioning yourself for success in technical careers
Positioning yourself for success in technical careersPositioning yourself for success in technical careers
Positioning yourself for success in technical careers
 
2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd
 
Breaking a monolith: In-place refactoring with service-oriented architecture ...
Breaking a monolith: In-place refactoring with service-oriented architecture ...Breaking a monolith: In-place refactoring with service-oriented architecture ...
Breaking a monolith: In-place refactoring with service-oriented architecture ...
 
End-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-Rest
End-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-RestEnd-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-Rest
End-To-End Asymmetric Encryption of Biomedical Data In-Transit and At-Rest
 
Nest v. Flat with EmberData
Nest v. Flat with EmberDataNest v. Flat with EmberData
Nest v. Flat with EmberData
 
DEF CON 24: Reverse engineering biomedical equipment for fun and open science
DEF CON 24: Reverse engineering biomedical equipment for fun and open scienceDEF CON 24: Reverse engineering biomedical equipment for fun and open science
DEF CON 24: Reverse engineering biomedical equipment for fun and open science
 

Recently uploaded

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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 WorkerThousandEyes
 
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.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
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 ApplicationsAlberto González Trastoy
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
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 CCTVshikhaohhpro
 
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...ICS
 
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...panagenda
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
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
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
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
 
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...
 
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...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 

2019-01-24 Sequelize ORM (Object Relational Mapper): models, migrations, oh my

  • 1. Sequelize models, migrations, oh my Ryan M Harrison Jan 24, 2019
  • 2. Agenda • Three-schema approach • DEMO: Express w/ SQL • What good is an “ORM”? • DEMO: Express w/ Sequelize (models) • What good are migrations? • DEMO: Express w/ Sequelize (migrations) Follow along in Github: https://github.com/rmharrison/prez-sequelize 2
  • 3. Three-schema approach • Conceptual Data Model • Logical Data Model • Physical Data Model 3
  • 6. DEMO: Express w/ SQL • Run postgres in docker • psql to create table • psql to seed table 6
  • 7. DEMO: Express w/ SQL • full_name → first_name, last_name 7
  • 8. Web Framework express, hapi, restify ORM sequelize, bookshelf Migration tool umzug (sequelize-cli), knex (bookshelf) Query builder sequelize, knex (Data access object) Client pg ORM: Object Relational Mapper (postgres) 8
  • 9. ORM: Object Relational Mapper 9 SQL CREATE TABLE Person ( id bigserial primary key, full_name varchar(100) NOT NULL, created_at timestamp default CURRENT_TIMESTAMP updated_at timestamp default CURRENT_TIMESTAMP ); Sequelize ORM (javascript) module.exports = (sequelize, DataTypes) => { const person = sequelize.define('person', { full_name: DataTypes.STRING, }, { underscored: true, }); return person; };
  • 10. ORM: Object Relational Mapper • Virtual Object • Abstracts (some) implementation details, e.g. associations. 10 SQL SELECT * FROM people; SELECT * FROM people LIMIT 1; SELECT COUNT(*) FROM people; SELECT * FROM people WHERE id = 1 Sequelize ORM (javascript) Person.findAll() Person.findOne() Person.findAndCountAll() Person.findById(1)
  • 11. ORM: Object Relational Mapper • Virtual Object • Abstracts (some) implementation details, e.g. associations. 11 Sequelize, One-To-Many associations (hasMany) const City = sequelize.define('city', { countryCode: Sequelize.STRING }); const Country = sequelize.define('country', { isoCode: Sequelize.STRING }); // Here we can connect countries and cities base on country code Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'}); City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});
  • 12. Web Framework express, hapi, restify ORM mongoose Migration tool migrate-mongoose Query Builder mongodb Client mongodb-core ORM: Object Relational Mapper (mongo) 12
  • 13. DEMO: Express w/ Sequelize (models) • Sequelize CLI • Generate models from CLI 13
  • 14. Migrations: Define schema 14 demodb=# d people Table "public.people" Column | Type | Collation | Nullable | Default ------------+--------------------------+-----------+----------+----------------------------------- id | integer | | not null | nextval('people_id_seq'::regclass) created_at | timestamp with time zone | | not null | now() updated_at | timestamp with time zone | | not null | now() full_name | character varying(255) | | | Indexes: "people_pkey" PRIMARY KEY, btree (id)
  • 15. Migrations: Define schema 15 demodb=# d people Table "public.people" Column | Type | Collation | Nullable | Default ------------+--------------------------+-----------+----------+----------------------------------- id | integer | | not null | nextval('people_id_seq'::regclass) created_at | timestamp with time zone | | not null | now() updated_at | timestamp with time zone | | not null | now() first_name | character varying(255) | | | last_name | character varying(255) | | | Indexes: "people_pkey" PRIMARY KEY, btree (id)
  • 16. Migrations: Define schema 16 Time Jan 2018 Feb 2018 Mar 2018 release v0.1.0 v0.2.0 v0.3.0 models sales.js product.js sales.js product.js (13 ++++++-----) store.js sales.js (100 +++---) product.js (50 ++++) store.js (20 +-----) migrations 201801-migration.js 201802-migration.js 201801-migration.js 201803-migration.js 201802-migration.js 201801-migration.js
  • 17. Seeds: Define data 17 demodb=# SELECT * FROM people; id | created_at | updated_at | first_name | last_name ----+----------------------------+----------------------------+------------+----------- 1 | 2019-01-25 09:20:11.392+00 | 2019-01-25 09:20:11.392+00 | John | Watts 2 | 2019-01-25 09:20:11.392+00 | 2019-01-25 09:20:11.392+00 | Charles | Ingram
  • 18. DEMO: Express w/ Sequelize (migrations) • full_name → first_name, last_name • Generate migrations and seeds from CLI 18
  • 19. Strengths ● Model-driven development ● Sequelize Models are Javascript classes ○ all the goodies available, inc. Prototype, extends, etc. ● Life-cycle hooks ○ beforeSave, afterValidate, et al. 19
  • 20. Weaknesses addressed ecosystem ● Generate models from existing DB schema ○ npm:sequelize-auto (1400+ stars; officially supported) ● Generate migrations from models ○ Long-standing known issue: https://github.com/sequelize/cli/issues/157 ○ npm:sequelize-auto-migrations (incomplete, only handles up) ● Model versioning ○ npm:sequelize-version (low adoption) ● Nested hierarchies ○ npm:sequelize-hierarchy ● Fixtures ○ npm:sequelize-fixtures (maintainer wants to abandon) 20
  • 21. Gotchas ● Cannot link a seed with a specific migration ○ Convention: Assume “latest” for seed data ○ Check SequelizeMeta in seed script ● “Version” is not what you think ○ NB: version in Sequelize is for OptimisticLocking [PR] not model versions ● Poor error messages in migrations 21 == 20190125055636-full-to-first-last: migrating ======= ERROR: Unexpected identifier
  • 22. Resources ● SQL Naming Conventions 22