SlideShare a Scribd company logo
1 of 40
Download to read offline
Revenge of the ORMs
Why SQL skills still matter in 2015
Lightning strikes © flickr.com/photos/snowpeak CC-BY
First, An Intro
Megan Bowra-Dean !
• Rails/JS/Android/iOS/
kitchen sink developer
at Rabid Tech
• 2 years .NET
enterprise web dev
• 2 years C/C++
embedded dev
• Ruby NZ Committee
Member
–Roy Batty, Bladerunner
“I've seen things you people wouldn't believe.”
Reintroducing ORMs
ORMs
• “Object Relational Mappers”
• Translates and serialises objects to a relational
database
• Generally database agnostic
Cat.new(fur: 'calico', name: 'Ms Tibbles')
id fur name
1 calico Ms Tibbles
ms_tibbles.owner = Owner.new(name: 'Megan')
id fur name owner_id
1 calico Ms Tibbles 1
cats table
id name
1 Megan
owners table
Examples
Entity FrameworkActiveRecord django.db
The Good 👍
Saves development time & easier to maintain
SELECT
*
FROM
books
INNER JOIN
libraries ON
books.library_id =
libraries.id
WHERE
libraries.name = 'Wellington
City Library'
Book
.joins('libraries')
.where(libraries: { name:
'Wellington City Library' })
VS
Security
• Most ORMs stop SQL injection attacks 💉
• Some restrict columns that can be updated by
user input (e.g. Rails 4’s strong_params)
BUT $
When and How ORMs
Can Breakdown
Ultimately ORMs are an
Abstraction
• Simplified for specific use cases
• What happens when the relationships between
your models get more complex?
• What happens when you need data not tied to a
model’s fields? 📊
N+1 Problem
A book has an editor and magazines are a type of
book, how do we find all the editors belonging to
magazines to print them out?
📚'(
Naive Way
magazines = Book
.where(type: 'magazine')
magazines.each do |magazine|
puts magazine.editor
end
Resultant SQL
SELECT * FROM books WHERE type = 'magazine'
SELECT * FROM editors WHERE book_id = 1
SELECT * FROM editors WHERE book_id = 2
..
SELECT * FROM editors WHERE book_id = n
We end up with 1 + n queries, where n is the number
of magazines, hence the N+1 problem.
Optimised Way
magazines = Book
.includes('editor')
.where(type: 'magazine')
magazines.each do |magazine|
puts magazine.editor
end
Resultant SQL
SELECT * FROM books WHERE type = 'magazine'
SELECT * FROM editors WHERE (book_id IN (1,2,3..n))
• Not always as obvious as this
• Can have a lot of things happening between
fetching the parent model and the child models
• Still, (most) ORMs have the capability to help
Modern Scripting
Languages are SLOW* 🐢
* At handling large data sets
• Page load times can slow down noticeably with
just a few thousand instances of models.
• May expect to run operations on hundreds of
thousands.
• Is it WEBSCALE?
We Usually Deal With This
by Over-engineering
• Adding extra caching layers
• Load balancing with horizontal scaling
• Progressive page loading
Subverting Your ORM
for Fun and Profit
• We can wrest the raw database connection from
the ORM
• With this we can improve performance without
greatly increasing complexity
A real world example
• Web app for client that surveyed organisational
performance
• Produced an online report with several different
breakdowns of statistics from the survey
• Was surprisingly slow - hit web server timeout
Looking closer
Most of the time spent outside of the database
• 100,532 calls to Class#new ‼
• A simple page was only creating ~900 objects
• One suspect was a function calculating the
average of responses to a group of questions (a
“domain”)
sum = 0.0
count = 0.0
domain.questions.each do |q|
response = q.response_for(respondent)
sum += response.value
count += 1.0
end
if count > 0
return sum / count
else
return 1.0
end
conn = ActiveRecord::Base.connection
result = conn.execute <<-SQL
SELECT
SUM(responses.value) as sum,
COUNT(*) as count
FROM
domains
INNER JOIN
questions ON questions.domain_id = domains.id
INNER JOIN
responses ON responses.question_id = questions.id
AND responses.respondent_id = #{respondent.id}
WHERE
domains.id = #{domain.id}
SQL
score = 1.0
sum = result[0]['sum'].to_f
count = result[0]['count'].to_f
score = sum / count if count > 0
• Reduced page load time by more than a half
• Reduced number of objects created by 30%
Words of Caution ⚠
• Not as maintainable
• Need to keep an eye on security. 

Never insert user provided values into raw SQL.
• Not as portable.
XKCD #327 https://xkcd.com/327/
sql = Cat.where(name: 'Ms Tibbles').to_sql
ActiveRecord::Base.connection.execute sql
Can sometimes get ORM
to help you defeat itself
Cool Things Beyond
Performance 😎
• Database functions
• Common table expressions
• Views
• GIS extensions for geographical data 🌏
• Non-standard data types
Finally:
Remember your
indexes!
To Summarise
• ORMs bring great benefits much of the time
• However being aware of what they’re doing is
essential
• If need be, it is possible to work around them.
• Databases are your friend.

More Related Content

Viewers also liked

No money? No matter - Improve your website with next to no cash
No money? No matter - Improve your website with next to no cashNo money? No matter - Improve your website with next to no cash
No money? No matter - Improve your website with next to no cashIWMW
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeWim Godden
 
Is having no limits a limitation [distilled version]
Is having no limits a limitation [distilled version]Is having no limits a limitation [distilled version]
Is having no limits a limitation [distilled version]Ben Brignell
 
Coordinating Senior Care with Intuit's Weave
Coordinating Senior Care with Intuit's Weave Coordinating Senior Care with Intuit's Weave
Coordinating Senior Care with Intuit's Weave Ted Drake
 
Scrum and Kanban applicability
Scrum and Kanban applicabilityScrum and Kanban applicability
Scrum and Kanban applicabilityKirill Klimov
 
Combining Context with Signals in the IoT (longer version)
Combining Context with Signals in the IoT (longer version)Combining Context with Signals in the IoT (longer version)
Combining Context with Signals in the IoT (longer version)Andy Piper
 
Play the Customer Development Game
Play the Customer Development GamePlay the Customer Development Game
Play the Customer Development GameAdrian Howard
 
Morgan e xt_062811
Morgan e xt_062811Morgan e xt_062811
Morgan e xt_062811kimorgan613
 
Varnish in action phpuk11
Varnish in action phpuk11Varnish in action phpuk11
Varnish in action phpuk11Combell NV
 
Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...
Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...
Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...Cindy Pao
 
Arquillian: Helping web developers and QA get along
Arquillian: Helping web developers and QA get alongArquillian: Helping web developers and QA get along
Arquillian: Helping web developers and QA get alongLukáš Fryč
 
Martijn van Exel - Collaborate to compete: Regain your Competitive Edge with osm
Martijn van Exel - Collaborate to compete: Regain your Competitive Edge with osmMartijn van Exel - Collaborate to compete: Regain your Competitive Edge with osm
Martijn van Exel - Collaborate to compete: Regain your Competitive Edge with osmOSMFstateofthemap
 
Conquering The Context Conundrum
Conquering The Context ConundrumConquering The Context Conundrum
Conquering The Context ConundrumDaniel Eizans
 
Lançando versões em um clique - deploy contínuo
Lançando versões em um clique - deploy contínuoLançando versões em um clique - deploy contínuo
Lançando versões em um clique - deploy contínuoHélio Medeiros
 

Viewers also liked (20)

Lynne Cazaly - Insights & Connections
Lynne Cazaly - Insights & ConnectionsLynne Cazaly - Insights & Connections
Lynne Cazaly - Insights & Connections
 
No money? No matter - Improve your website with next to no cash
No money? No matter - Improve your website with next to no cashNo money? No matter - Improve your website with next to no cash
No money? No matter - Improve your website with next to no cash
 
[OTA15] Back to binary !
[OTA15] Back to binary ![OTA15] Back to binary !
[OTA15] Back to binary !
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
 
How releasing faster changes testing
How releasing faster changes testingHow releasing faster changes testing
How releasing faster changes testing
 
Is having no limits a limitation [distilled version]
Is having no limits a limitation [distilled version]Is having no limits a limitation [distilled version]
Is having no limits a limitation [distilled version]
 
Coordinating Senior Care with Intuit's Weave
Coordinating Senior Care with Intuit's Weave Coordinating Senior Care with Intuit's Weave
Coordinating Senior Care with Intuit's Weave
 
Scrum and Kanban applicability
Scrum and Kanban applicabilityScrum and Kanban applicability
Scrum and Kanban applicability
 
Combining Context with Signals in the IoT (longer version)
Combining Context with Signals in the IoT (longer version)Combining Context with Signals in the IoT (longer version)
Combining Context with Signals in the IoT (longer version)
 
ChemSpider – disseminating data and enabling an abundance of chemistry platforms
ChemSpider – disseminating data and enabling an abundance of chemistry platformsChemSpider – disseminating data and enabling an abundance of chemistry platforms
ChemSpider – disseminating data and enabling an abundance of chemistry platforms
 
HTTP 2
HTTP 2HTTP 2
HTTP 2
 
Play the Customer Development Game
Play the Customer Development GamePlay the Customer Development Game
Play the Customer Development Game
 
Surge2012
Surge2012Surge2012
Surge2012
 
Morgan e xt_062811
Morgan e xt_062811Morgan e xt_062811
Morgan e xt_062811
 
Varnish in action phpuk11
Varnish in action phpuk11Varnish in action phpuk11
Varnish in action phpuk11
 
Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...
Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...
Innovative Fund-Raising, Orlando Central Florida Chapter Initiatives to Gener...
 
Arquillian: Helping web developers and QA get along
Arquillian: Helping web developers and QA get alongArquillian: Helping web developers and QA get along
Arquillian: Helping web developers and QA get along
 
Martijn van Exel - Collaborate to compete: Regain your Competitive Edge with osm
Martijn van Exel - Collaborate to compete: Regain your Competitive Edge with osmMartijn van Exel - Collaborate to compete: Regain your Competitive Edge with osm
Martijn van Exel - Collaborate to compete: Regain your Competitive Edge with osm
 
Conquering The Context Conundrum
Conquering The Context ConundrumConquering The Context Conundrum
Conquering The Context Conundrum
 
Lançando versões em um clique - deploy contínuo
Lançando versões em um clique - deploy contínuoLançando versões em um clique - deploy contínuo
Lançando versões em um clique - deploy contínuo
 

Similar to Revenge of the ORMs

How to use the new Domino Query Language
How to use the new Domino Query LanguageHow to use the new Domino Query Language
How to use the new Domino Query LanguageTim Davis
 
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?DATAVERSITY
 
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013Amazon Web Services
 
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxPythian
 
A tale of 3 databases
A tale of 3 databasesA tale of 3 databases
A tale of 3 databasesChris Skardon
 
CQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architectureCQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architectureThomas Jaskula
 
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails AppSrijan Technologies
 
Building DSLs with Scala
Building DSLs with ScalaBuilding DSLs with Scala
Building DSLs with ScalaMohit Jaggi
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
Dapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDavide Mauri
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Jan Helke
 
Boosting the Performance of your Rails Apps
Boosting the Performance of your Rails AppsBoosting the Performance of your Rails Apps
Boosting the Performance of your Rails AppsMatt Kuklinski
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverMongoDB
 
Getting started with Spark & Cassandra by Jon Haddad of Datastax
Getting started with Spark & Cassandra by Jon Haddad of DatastaxGetting started with Spark & Cassandra by Jon Haddad of Datastax
Getting started with Spark & Cassandra by Jon Haddad of DatastaxData Con LA
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable CodeBaidu, Inc.
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & TricksMongoDB
 
Cloud brew cloudcamp
Cloud brew cloudcampCloud brew cloudcamp
Cloud brew cloudcampHenry Been
 
Spring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_dataSpring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_dataRoger Xia
 
Writing Space and the Cassandra NoSQL DBMS
Writing Space and the Cassandra NoSQL DBMSWriting Space and the Cassandra NoSQL DBMS
Writing Space and the Cassandra NoSQL DBMSDataStax Academy
 

Similar to Revenge of the ORMs (20)

MongoDB
MongoDBMongoDB
MongoDB
 
How to use the new Domino Query Language
How to use the new Domino Query LanguageHow to use the new Domino Query Language
How to use the new Domino Query Language
 
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
 
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
 
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
 
A tale of 3 databases
A tale of 3 databasesA tale of 3 databases
A tale of 3 databases
 
CQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architectureCQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architecture
 
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
 
Building DSLs with Scala
Building DSLs with ScalaBuilding DSLs with Scala
Building DSLs with Scala
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Dapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDapper: the microORM that will change your life
Dapper: the microORM that will change your life
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
 
Boosting the Performance of your Rails Apps
Boosting the Performance of your Rails AppsBoosting the Performance of your Rails Apps
Boosting the Performance of your Rails Apps
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
Getting started with Spark & Cassandra by Jon Haddad of Datastax
Getting started with Spark & Cassandra by Jon Haddad of DatastaxGetting started with Spark & Cassandra by Jon Haddad of Datastax
Getting started with Spark & Cassandra by Jon Haddad of Datastax
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & Tricks
 
Cloud brew cloudcamp
Cloud brew cloudcampCloud brew cloudcamp
Cloud brew cloudcamp
 
Spring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_dataSpring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_data
 
Writing Space and the Cassandra NoSQL DBMS
Writing Space and the Cassandra NoSQL DBMSWriting Space and the Cassandra NoSQL DBMS
Writing Space and the Cassandra NoSQL DBMS
 

Recently uploaded

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
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
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
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
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
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 

Recently uploaded (20)

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
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
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
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
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...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 

Revenge of the ORMs

  • 1. Revenge of the ORMs Why SQL skills still matter in 2015 Lightning strikes © flickr.com/photos/snowpeak CC-BY
  • 3. Megan Bowra-Dean ! • Rails/JS/Android/iOS/ kitchen sink developer at Rabid Tech • 2 years .NET enterprise web dev • 2 years C/C++ embedded dev • Ruby NZ Committee Member
  • 4. –Roy Batty, Bladerunner “I've seen things you people wouldn't believe.”
  • 6. ORMs • “Object Relational Mappers” • Translates and serialises objects to a relational database • Generally database agnostic
  • 7. Cat.new(fur: 'calico', name: 'Ms Tibbles') id fur name 1 calico Ms Tibbles
  • 8. ms_tibbles.owner = Owner.new(name: 'Megan') id fur name owner_id 1 calico Ms Tibbles 1 cats table id name 1 Megan owners table
  • 11. Saves development time & easier to maintain SELECT * FROM books INNER JOIN libraries ON books.library_id = libraries.id WHERE libraries.name = 'Wellington City Library' Book .joins('libraries') .where(libraries: { name: 'Wellington City Library' }) VS
  • 12. Security • Most ORMs stop SQL injection attacks 💉 • Some restrict columns that can be updated by user input (e.g. Rails 4’s strong_params)
  • 13. BUT $
  • 14. When and How ORMs Can Breakdown
  • 15. Ultimately ORMs are an Abstraction • Simplified for specific use cases • What happens when the relationships between your models get more complex? • What happens when you need data not tied to a model’s fields? 📊
  • 16. N+1 Problem A book has an editor and magazines are a type of book, how do we find all the editors belonging to magazines to print them out? 📚'(
  • 17. Naive Way magazines = Book .where(type: 'magazine') magazines.each do |magazine| puts magazine.editor end
  • 18. Resultant SQL SELECT * FROM books WHERE type = 'magazine' SELECT * FROM editors WHERE book_id = 1 SELECT * FROM editors WHERE book_id = 2 .. SELECT * FROM editors WHERE book_id = n
  • 19. We end up with 1 + n queries, where n is the number of magazines, hence the N+1 problem.
  • 20. Optimised Way magazines = Book .includes('editor') .where(type: 'magazine') magazines.each do |magazine| puts magazine.editor end
  • 21. Resultant SQL SELECT * FROM books WHERE type = 'magazine' SELECT * FROM editors WHERE (book_id IN (1,2,3..n))
  • 22. • Not always as obvious as this • Can have a lot of things happening between fetching the parent model and the child models • Still, (most) ORMs have the capability to help
  • 23. Modern Scripting Languages are SLOW* 🐢 * At handling large data sets
  • 24. • Page load times can slow down noticeably with just a few thousand instances of models. • May expect to run operations on hundreds of thousands. • Is it WEBSCALE?
  • 25. We Usually Deal With This by Over-engineering • Adding extra caching layers • Load balancing with horizontal scaling • Progressive page loading
  • 26. Subverting Your ORM for Fun and Profit
  • 27. • We can wrest the raw database connection from the ORM • With this we can improve performance without greatly increasing complexity
  • 28. A real world example • Web app for client that surveyed organisational performance • Produced an online report with several different breakdowns of statistics from the survey • Was surprisingly slow - hit web server timeout
  • 29. Looking closer Most of the time spent outside of the database
  • 30. • 100,532 calls to Class#new ‼ • A simple page was only creating ~900 objects • One suspect was a function calculating the average of responses to a group of questions (a “domain”)
  • 31. sum = 0.0 count = 0.0 domain.questions.each do |q| response = q.response_for(respondent) sum += response.value count += 1.0 end if count > 0 return sum / count else return 1.0 end
  • 32. conn = ActiveRecord::Base.connection result = conn.execute <<-SQL SELECT SUM(responses.value) as sum, COUNT(*) as count FROM domains INNER JOIN questions ON questions.domain_id = domains.id INNER JOIN responses ON responses.question_id = questions.id AND responses.respondent_id = #{respondent.id} WHERE domains.id = #{domain.id} SQL score = 1.0 sum = result[0]['sum'].to_f count = result[0]['count'].to_f score = sum / count if count > 0
  • 33. • Reduced page load time by more than a half • Reduced number of objects created by 30%
  • 35. • Not as maintainable • Need to keep an eye on security. 
 Never insert user provided values into raw SQL. • Not as portable. XKCD #327 https://xkcd.com/327/
  • 36. sql = Cat.where(name: 'Ms Tibbles').to_sql ActiveRecord::Base.connection.execute sql Can sometimes get ORM to help you defeat itself
  • 38. • Database functions • Common table expressions • Views • GIS extensions for geographical data 🌏 • Non-standard data types
  • 40. To Summarise • ORMs bring great benefits much of the time • However being aware of what they’re doing is essential • If need be, it is possible to work around them. • Databases are your friend.