SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
Getting to know Arel
Active Record's nerdy little brother
What is Arel?
Arel is a SQL AST manager for Ruby
Active Record uses Arel to build queries
It adapts to various RDBMSes
It is intended to be a framework framework
Active Record is pretty good...
Dog.where(name: 'Fido')
# WHERE "dogs"."name" = 'Fido'
Dog.where(name: nil)
# WHERE "dogs"."name" IS NULL
Dog.where(name: ['Fido', 'Jeff'])
# WHERE "dogs"."name" IN ('Fido', 'Jeff')
Dog.where(name: ['Fido', 'Jeff', nil])
# WHERE (
# "dogs"."name" IN ('Fido', 'Jeff') OR
# "dogs"."name" IS NULL
# )
Active Record is pretty good,
until it isn't.
It only supports equality
Dog.where('age > ?', 5)
# WHERE age > 5
No support for OR (until 5.0.0)
Dog.where('age = ? OR name = ?', 5, 'Fido')
# WHERE age = 5 OR name = 'Fido'
No support for explicit joins
Dog.joins(
'INNER JOIN owners o ON o.id = dogs.owner_id'
)
No outer joins (without loading everything into memory)
Dog.joins(
'LEFT OUTER JOIN owners ON owners.id = dogs.owner_id'
)
Composability goes out the window
class Dog < ActiveRecord::Base
scope :old, -> { where('age > ?', 5) }
scope :named_fido, -> { where(name: 'Fido') }
def self.named_fido_or_old
where('age > ? OR name = ?', 5, 'Fido')
end
end
Not to mention...
Not database agnostic
No syntax checking
Question marks can be tough to track down
What ever happened to the 80 characters/line?
Model
.joins('LEFT JOIN candidacies as search_candidates on search_candidates.contact_id = contacts.id'
.joins('LEFT JOIN searches as contact_searches on search_candidates.search_id = contact_searches.id'
.where('(lower(contact_searches.name) like ? AND search_candidates.deleted=?)', "%#{name}%".downcase
Arel to the rescue!
Arel::Table
Arel::Table.new(:dogs)
Arel::Table.new(:dogs)[:name] # an Arel::Attribute
Dog.arel_table
Dog.arel_table[:name] # an Arel::Attribute
Predications
age = Dog.arel_table[:age]
name = Dog.arel_table[:name]
Dog.where age.gt(5)
# WHERE "dogs"."age" > 5
Dog.where age.not_eq(5)
# WHERE "dogs"."age" != 5
Dog.where name.matches('%ido')
# WHERE "dogs"."name" LIKE '%ido'
Grouping
id = Dog.arel_table[:id]
age = Dog.arel_table[:age]
name = Dog.arel_table[:name]
Dog.where id.gt(5).and(
name.eq('Ronald').or(
age.eq(3)
)
)
# WHERE (
# "dogs"."id" > 5 AND (
# "dogs"."name" = 'Ronald' OR
# "dogs"."age" = 3
# )
# )
Inner Join
dogs = Dog.arel_table
owners = Owner.arel_table
join = dogs.inner_join(owners).on(
dogs[:owner_id].eq(owners[:id])
)
Dog.joins join.join_sources
# SELECT "dogs".* FROM "dogs"
# INNER JOIN "owners"
# ON "dogs"."owner_id" = "owners"."id"
Outer Join
dogs = Dog.arel_table
owners = Owner.arel_table
join = dogs.outer_join(owners).on(
dogs[:owner_id].eq(owners[:id])
)
Dog.joins join.join_sources
# SELECT "dogs".* FROM "dogs"
# LEFT OUTER JOIN "owners"
# ON "dogs"."owner_id" = "owners"."id"
Composability
class Dog < ActiveRecord::Base
scope :old, -> { where(old_arel) }
scope :named_fido, -> { where(named_fido_arel) }
def self.old_or_named_fido
where named_fido_arel.or(old_arel)
end
def self.old_arel
arel_table[:age].gt(5)
end
def self.named_fido_arel
arel_table[:name].eq('Fido')
end
end
Arel can do anything!
Aggregates
Dog.select Dog.arel_table[:age].maximum
# SELECT MAX("dogs"."age") FROM "dogs"
Functions
Dog.select(
Arel::Nodes::NamedFunction.new('COALESCE', [
Dog.arel_table[:name],
Arel::Nodes.build_quoted('Ronald')
])
)
# SELECT COALESCE("dogs"."name", 'Ronald')
# FROM "dogs"
Infix
Dog.select(
Arel::Nodes::InfixOperation.new('||',
Dog.arel_table[:name],
Arel::Nodes.build_quoted('diddly')
)
)
# SELECT "dogs"."name" || 'diddly'
# FROM "dogs"
Dog.select("name || 'diddly'")
# SELECT.... nevermind...
Am I just wasting your time?
(this Arel stuff is pretty verbose)
Introducing Baby Squeel
Extremely similar to Squeel
Under 500 LOC
No core exts
No monkey patches!
As conservative as possible
Predications
Dog.where.has { age > 5 }
# WHERE ("dogs"."age" > 5)
Dog.where.has { name != 'Jeff' }
# WHERE ("dogs"."name" != 'Jeff')
Dog.where.has { name =~ '%ido' }
# WHERE ("name" LIKE '%ido')
Grouping
Dog.where.has {
(id > 5).and(
(name == 'Ronald').or(age == 3)
)
}
# WHERE (
# "dogs"."id" > 5 AND (
# "dogs"."name" = 'Ronald' OR
# "dogs"."age" = 3
# )
# )
Dog.selecting { age.maximum }
# SELECT MAX("dogs"."age") FROM "dogs"
Dog.selecting { (id + 100) / 20 }
# SELECT ("dogs"."id" + 100) / 20 FROM "dogs"
Dog.selecting { coalesce(name, quoted('Ronald')) }
# SELECT coalesce("dogs"."name", 'Ronald') FROM "dogs"
Dog.selecting { name.op('||', quoted('diddly')) }
# SELECT "dogs"."name" || 'diddly' FROM "dogs"
Explicit Joins
Dog.joining { owner.on(owner_id == owner.id) }
# INNER JOIN "owners"
# ON "dogs"."owner_id" = "owners"."id"
Dog.joining { owner.outer.on(owner.id == owner_id) }
# LEFT OUTER JOIN "owners"
# ON "dogs"."owner_id" = "owners"."id"
Implicit Joins
class Dog < ActiveRecord::Base
belongs_to :owner
end
Dog.joining { owner }
# INNER JOIN "owners"
# ON "owners"."id" = "dogs"."owner_id"
Dog.joining { owner.outer }
# LEFT OUTER JOIN "owners"
# ON "owners"."id" = "dogs"."owner_id"
Join like a BO$$
Dog.joining { owner.dog.outer.owner.dog }
# SELECT "dogs".* FROM "dogs"
# INNER JOIN "owners"
# ON "owners"."id" = "dogs"."owner_id"
# LEFT OUTER JOIN "dogs" "dogs_owners"
# ON "dogs_owners"."owner_id" = "owners"."id"
# INNER JOIN "owners" "owners_dogs"
# ON "owners_dogs"."id" = "dogs_owners"."owner_id"
# INNER JOIN "dogs" "dogs_owners_2"
# ON "dogs_owners_2"."owner_id" = "owners_dogs"."id"
Composability
class Dog < ActiveRecord::Base
sifter(:old) { age > 5 }
sifter(:named_fido) { name == 'Fido' }
scope :old, -> { where.has { sift(:old) } }
scope :named_fido, -> { where.has { sift(:named_fido) } }
def self.old_or_named_fido
where.has { sift(:old) | sift(:named_fido) }
end
end
Thanks.
Now, please stop using strings to generate SQL.

Weitere ähnliche Inhalte

Was ist angesagt?

Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyGautam Rege
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4Kevin Chun-Hsien Hsu
 
Search Engines: How They Work and Why You Need Them
Search Engines: How They Work and Why You Need ThemSearch Engines: How They Work and Why You Need Them
Search Engines: How They Work and Why You Need ThemToria Gibbs
 
03 Php Array String Functions
03 Php Array String Functions03 Php Array String Functions
03 Php Array String FunctionsGeshan Manandhar
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arraysKumar
 
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDBLisa Roth, PMP
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP ArraysAhmed Swilam
 
Iterators, Hashes, and Arrays
Iterators, Hashes, and ArraysIterators, Hashes, and Arrays
Iterators, Hashes, and ArraysBlazing Cloud
 
Collections
CollectionsCollections
CollectionsSV.CO
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slidesaiclub_slides
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsDavid Golden
 

Was ist angesagt? (20)

Php array
Php arrayPhp array
Php array
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Php array
Php arrayPhp array
Php array
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of ruby
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
 
Search Engines: How They Work and Why You Need Them
Search Engines: How They Work and Why You Need ThemSearch Engines: How They Work and Why You Need Them
Search Engines: How They Work and Why You Need Them
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
03 Php Array String Functions
03 Php Array String Functions03 Php Array String Functions
03 Php Array String Functions
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
 
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Baabtra.com little coder chapter - 3
Baabtra.com little coder   chapter - 3Baabtra.com little coder   chapter - 3
Baabtra.com little coder chapter - 3
 
Iterators, Hashes, and Arrays
Iterators, Hashes, and ArraysIterators, Hashes, and Arrays
Iterators, Hashes, and Arrays
 
Collections
CollectionsCollections
Collections
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 

Andere mochten auch

Andere mochten auch (15)

Script Supervising Resume
Script Supervising ResumeScript Supervising Resume
Script Supervising Resume
 
Tecnologia
TecnologiaTecnologia
Tecnologia
 
Tecnologia
TecnologiaTecnologia
Tecnologia
 
Social Media Hacking 102 - WGA KeyNotes
Social Media Hacking 102 - WGA KeyNotesSocial Media Hacking 102 - WGA KeyNotes
Social Media Hacking 102 - WGA KeyNotes
 
250 пр
250 пр250 пр
250 пр
 
Insight№43
Insight№43Insight№43
Insight№43
 
Insight№45
Insight№45Insight№45
Insight№45
 
Portfolio
PortfolioPortfolio
Portfolio
 
Insights №39
Insights №39Insights №39
Insights №39
 
Run your way fashion show GMEvents 2016
Run your way fashion show GMEvents 2016Run your way fashion show GMEvents 2016
Run your way fashion show GMEvents 2016
 
Plataformas virtuales
Plataformas virtualesPlataformas virtuales
Plataformas virtuales
 
Actividades y estrategias
Actividades y estrategiasActividades y estrategias
Actividades y estrategias
 
New microsoft-office-power point-presentation
New microsoft-office-power point-presentationNew microsoft-office-power point-presentation
New microsoft-office-power point-presentation
 
neurobiology of stress
neurobiology of stress neurobiology of stress
neurobiology of stress
 
Kuluttajien mielikuvat, odotukset ja maksuhalukkuus - Eija Pouta, Luke
Kuluttajien mielikuvat, odotukset ja maksuhalukkuus - Eija Pouta, LukeKuluttajien mielikuvat, odotukset ja maksuhalukkuus - Eija Pouta, Luke
Kuluttajien mielikuvat, odotukset ja maksuhalukkuus - Eija Pouta, Luke
 

Ähnlich wie Getting to know Arel

Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)brian d foy
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)Kerry Buckley
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6 brian d foy
 
Gigigo Ruby Workshop
Gigigo Ruby WorkshopGigigo Ruby Workshop
Gigigo Ruby WorkshopAlex Rupérez
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of RubyTom Crinson
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎anzhong70
 
Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Pamela Fox
 
Seven Languages in Seven Days: Ruby
Seven Languages in Seven Days: RubySeven Languages in Seven Days: Ruby
Seven Languages in Seven Days: RubyZach Leatherman
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubyJason Yeo Jie Shun
 
Introduction to R
Introduction to RIntroduction to R
Introduction to Rvpletap
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 

Ähnlich wie Getting to know Arel (20)

Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Gigigo Ruby Workshop
Gigigo Ruby WorkshopGigigo Ruby Workshop
Gigigo Ruby Workshop
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
My First Ruby
My First RubyMy First Ruby
My First Ruby
 
MIPS Merge Sort
MIPS Merge SortMIPS Merge Sort
MIPS Merge Sort
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)
 
Seven Languages in Seven Days: Ruby
Seven Languages in Seven Days: RubySeven Languages in Seven Days: Ruby
Seven Languages in Seven Days: Ruby
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
PHP 101
PHP 101 PHP 101
PHP 101
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 

Kürzlich hochgeladen

Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...SUHANI PANDEY
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Delhi Call girls
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusTimothy Spann
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceBDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceDelhi Call girls
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxMohammedJunaid861692
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Delhi Call girls
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...amitlee9823
 

Kürzlich hochgeladen (20)

Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceBDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 

Getting to know Arel

  • 1. Getting to know Arel Active Record's nerdy little brother
  • 2. What is Arel? Arel is a SQL AST manager for Ruby Active Record uses Arel to build queries It adapts to various RDBMSes It is intended to be a framework framework
  • 3. Active Record is pretty good...
  • 4. Dog.where(name: 'Fido') # WHERE "dogs"."name" = 'Fido'
  • 5. Dog.where(name: nil) # WHERE "dogs"."name" IS NULL
  • 6. Dog.where(name: ['Fido', 'Jeff']) # WHERE "dogs"."name" IN ('Fido', 'Jeff')
  • 7. Dog.where(name: ['Fido', 'Jeff', nil]) # WHERE ( # "dogs"."name" IN ('Fido', 'Jeff') OR # "dogs"."name" IS NULL # )
  • 8. Active Record is pretty good, until it isn't.
  • 9. It only supports equality Dog.where('age > ?', 5) # WHERE age > 5
  • 10. No support for OR (until 5.0.0) Dog.where('age = ? OR name = ?', 5, 'Fido') # WHERE age = 5 OR name = 'Fido'
  • 11. No support for explicit joins Dog.joins( 'INNER JOIN owners o ON o.id = dogs.owner_id' )
  • 12. No outer joins (without loading everything into memory) Dog.joins( 'LEFT OUTER JOIN owners ON owners.id = dogs.owner_id' )
  • 13. Composability goes out the window class Dog < ActiveRecord::Base scope :old, -> { where('age > ?', 5) } scope :named_fido, -> { where(name: 'Fido') } def self.named_fido_or_old where('age > ? OR name = ?', 5, 'Fido') end end
  • 14. Not to mention... Not database agnostic No syntax checking Question marks can be tough to track down What ever happened to the 80 characters/line? Model .joins('LEFT JOIN candidacies as search_candidates on search_candidates.contact_id = contacts.id' .joins('LEFT JOIN searches as contact_searches on search_candidates.search_id = contact_searches.id' .where('(lower(contact_searches.name) like ? AND search_candidates.deleted=?)', "%#{name}%".downcase
  • 15. Arel to the rescue!
  • 16. Arel::Table Arel::Table.new(:dogs) Arel::Table.new(:dogs)[:name] # an Arel::Attribute Dog.arel_table Dog.arel_table[:name] # an Arel::Attribute
  • 17. Predications age = Dog.arel_table[:age] name = Dog.arel_table[:name] Dog.where age.gt(5) # WHERE "dogs"."age" > 5 Dog.where age.not_eq(5) # WHERE "dogs"."age" != 5 Dog.where name.matches('%ido') # WHERE "dogs"."name" LIKE '%ido'
  • 18. Grouping id = Dog.arel_table[:id] age = Dog.arel_table[:age] name = Dog.arel_table[:name] Dog.where id.gt(5).and( name.eq('Ronald').or( age.eq(3) ) ) # WHERE ( # "dogs"."id" > 5 AND ( # "dogs"."name" = 'Ronald' OR # "dogs"."age" = 3 # ) # )
  • 19. Inner Join dogs = Dog.arel_table owners = Owner.arel_table join = dogs.inner_join(owners).on( dogs[:owner_id].eq(owners[:id]) ) Dog.joins join.join_sources # SELECT "dogs".* FROM "dogs" # INNER JOIN "owners" # ON "dogs"."owner_id" = "owners"."id"
  • 20. Outer Join dogs = Dog.arel_table owners = Owner.arel_table join = dogs.outer_join(owners).on( dogs[:owner_id].eq(owners[:id]) ) Dog.joins join.join_sources # SELECT "dogs".* FROM "dogs" # LEFT OUTER JOIN "owners" # ON "dogs"."owner_id" = "owners"."id"
  • 21. Composability class Dog < ActiveRecord::Base scope :old, -> { where(old_arel) } scope :named_fido, -> { where(named_fido_arel) } def self.old_or_named_fido where named_fido_arel.or(old_arel) end def self.old_arel arel_table[:age].gt(5) end def self.named_fido_arel arel_table[:name].eq('Fido') end end
  • 22. Arel can do anything!
  • 26. Am I just wasting your time? (this Arel stuff is pretty verbose)
  • 28. Extremely similar to Squeel Under 500 LOC No core exts No monkey patches! As conservative as possible
  • 29. Predications Dog.where.has { age > 5 } # WHERE ("dogs"."age" > 5) Dog.where.has { name != 'Jeff' } # WHERE ("dogs"."name" != 'Jeff') Dog.where.has { name =~ '%ido' } # WHERE ("name" LIKE '%ido')
  • 30. Grouping Dog.where.has { (id > 5).and( (name == 'Ronald').or(age == 3) ) } # WHERE ( # "dogs"."id" > 5 AND ( # "dogs"."name" = 'Ronald' OR # "dogs"."age" = 3 # ) # )
  • 31. Dog.selecting { age.maximum } # SELECT MAX("dogs"."age") FROM "dogs" Dog.selecting { (id + 100) / 20 } # SELECT ("dogs"."id" + 100) / 20 FROM "dogs" Dog.selecting { coalesce(name, quoted('Ronald')) } # SELECT coalesce("dogs"."name", 'Ronald') FROM "dogs" Dog.selecting { name.op('||', quoted('diddly')) } # SELECT "dogs"."name" || 'diddly' FROM "dogs"
  • 32. Explicit Joins Dog.joining { owner.on(owner_id == owner.id) } # INNER JOIN "owners" # ON "dogs"."owner_id" = "owners"."id" Dog.joining { owner.outer.on(owner.id == owner_id) } # LEFT OUTER JOIN "owners" # ON "dogs"."owner_id" = "owners"."id"
  • 33. Implicit Joins class Dog < ActiveRecord::Base belongs_to :owner end Dog.joining { owner } # INNER JOIN "owners" # ON "owners"."id" = "dogs"."owner_id" Dog.joining { owner.outer } # LEFT OUTER JOIN "owners" # ON "owners"."id" = "dogs"."owner_id"
  • 34. Join like a BO$$ Dog.joining { owner.dog.outer.owner.dog } # SELECT "dogs".* FROM "dogs" # INNER JOIN "owners" # ON "owners"."id" = "dogs"."owner_id" # LEFT OUTER JOIN "dogs" "dogs_owners" # ON "dogs_owners"."owner_id" = "owners"."id" # INNER JOIN "owners" "owners_dogs" # ON "owners_dogs"."id" = "dogs_owners"."owner_id" # INNER JOIN "dogs" "dogs_owners_2" # ON "dogs_owners_2"."owner_id" = "owners_dogs"."id"
  • 35. Composability class Dog < ActiveRecord::Base sifter(:old) { age > 5 } sifter(:named_fido) { name == 'Fido' } scope :old, -> { where.has { sift(:old) } } scope :named_fido, -> { where.has { sift(:named_fido) } } def self.old_or_named_fido where.has { sift(:old) | sift(:named_fido) } end end
  • 36. Thanks. Now, please stop using strings to generate SQL.