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

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
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.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
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 ...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

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