SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
Maarten van Vliet
Backend developer @ Awkward
Email: maarten@awkward.co
Github: maartenvanvliet
Recursive
Common Table Expressions
and Ecto
PRESENTATION
By Maarten van Vliet
First:
an introduction to the problem
What is Sketch?
An intuitive vector editor for the
Mac. It’s used primarily by screen
designers who create websites,
icons, and user interfaces for
desktop and mobile devices.
Sketch Cloud
Sketch Cloud is a platform that allows
you to share documents easily and with
everyone. Many more features are
coming!
Sketch Cloud uses a GraphQL API built in
Elixir, we call it SketchQL
Prototyping
Sketch’s Prototyping features makes
it easy to create interactive
workflows and preview your designs
as your users will see them.
Released last year in Sketch and
Sketch Cloud
A user can now create a prototype in
the Sketch, upload it to Cloud and
interactively play with it
Prototyping Cloud
Building prototyping was challenging
• Fluent transitions across browsers
• Converting Sketch Prototypes to the
web
• And, there are simple prototypes such
as this one
And complex prototypes…
Problems
We needed to fluently transition from
one screen to the next for prototyping in
the browser.
This meant: (deep) preloading the
relations of one screen (artboard) with
all other artboards
So, when A is loaded, we need to load B
and C, but also D!
Simplest solution
Recursively query database for related
artboards from application
1. First query for artboard A
2. Query for artboards directly related to
A, returns [B, C]
3. Query for artboards directly related to
[B, C], but leave out already found
artboards [A], this returns [D]
4. Query for artboards directly related to
[D], but leave out already found
artboards [A, B, C], returns []
5. We stop when an empty set is
returned.
Problem:lots of queries
Solution:
Recursive Common
Table Expressions!
• Last year we migrated Sketch Cloud to
Mariadb 10.2

• Introduced support for (Recursive) Common
Table Expressions

• (R)CTE's are also available in Mysql 8.0
(since 2018), and Postgres 8.4 (since 2009)

• But what are they?
Common Table Expressions
A CTE is a temporary resultset
Think of it as a database view only
created and visible for one query.
Useful for making subqueries easier
to read
You can have multiple in one query
WITH FirstUser AS (
  SELECT * FROM Users WHERE id = 1
)
SELECT * FROM FirstUser
— Equivalent to query with subquery
SELECT * FROM
(SELECT * FROM Users WHERE id = 1) AS F;
CTE’s can also do
recursion!
Recursive CTE’s are useful for querying
hierarchies, e.g. tables with a parent_id
column, so a row has can have a parent
or children
E.g. a CMS with pages, where a page can
have children
Pages:
WITH RECURSIVE PageGraph AS (
SELECT
P.id,
P.parent_id
FROM
Pages P
WHERE
P.parent_id IS NULL —start id
UNION
SELECT
P.id,
P.parent_id
FROM
Pages P
JOIN PageGraph PG
ON P.parent_id = PG.id
)
SELECT * FROM PageGraph
Id parent_id Name
1 NULL Page 1
2 1 Subpage 1
3 1 Subpage 2
4 2 Subpage 3
Dealing with cycles
How to deal with cycles? Hierarchies
with “loops” in them. E.g. page A has
page B as a parent, and page B has page
A as a parent
WITH RECURSIVE PageGraph AS (
SELECT
P.id,
P.parent_id
FROM
Pages P
WHERE
P.id = 1 #start id
UNION
SELECT
P.id,
P.parent_id
FROM
Pages P
JOIN PageGraph PG
ON P.parent_id = PG.id
)
SELECT * FROM PageGraph
Id parent_id Name
1 2 Page 1
2 1 Page 2
Union removes duplicates!
Back to the problem
In steps:
• First get artboards related to A, and
store them in “to”, returns [B, C]
• UNION this with the artboards where
the id matches those of [B, C]
• Get related artboards of [B, C], returns
[D]
• Again, UNION and get related
artboards of [D], returns [A].
• Nothing new found, so stop
WITH RECURSIVE RelatedArtboards AS (
SELECT
— A.id AS "from",
F.DestinationArtboardId AS "to"
FROM
Artboards A
JOIN Layers L ON L.ArtboardId = A.id
JOIN Flows F ON F.id = L.FlowId
WHERE
A.id = #Start ID, in this case Artboard A
UNION
SELECT
— A.id AS "from",
F.DestinationArtboardId AS "to"
FROM
Artboards A
JOIN Layers L ON L.ArtboardId = A.id
JOIN Flows F ON F.id = L.FlowId
JOIN RelatedArtboards ON A.id = RelatedArtboards.to
WHERE
A.id = RelatedArtboards.to
)
SELECT
R.to
FROM
RelatedArtboards R
From To
A B
A C
B D
C D
D A
Now we only need one query to load
all artboards for a prototype!
But how to use this in Elixir/Ecto?
Not supported in the query builder, yet…
Still open 😢
Once merged:
page_tree_initial_query =
Page
|> where([p], is_nil(p.parent_id))
page_tree_recursion_query =
Page
|> join(:inner, [p], pt in "page_tree", on: p.parent_id == pt.id)
page_tree_query =
page_tree_initial_queryv
|> union(^page_tree_recursion_query)
Page
|> recursive_ctes(true)
|> with_cte("page_tree", as: ^page_tree_query)
|> Repo.all
Until then…
Fragments gives us the
ability to extend Ecto
defmacro with_related_artboards(artboard_id) do
quote do
fragment(
"""
(
WITH RECURSIVE RelatedArtboards AS (
SELECT
F.DestinationArtboardId AS "to"
FROM
Artboards A
JOIN Layers L ON L.ArtboardId = A.id
JOIN Flows F ON F.id = L.FlowId
WHERE
A.id = ?
UNION
SELECT
F.DestinationArtboardId AS "to"
FROM
Artboards A
JOIN Layers L ON L.ArtboardId = A.id
JOIN Flows F ON F.id = L.FlowId
JOIN RelatedArtboards ON A.id = RelatedArtboards.to
WHERE
A.id = RelatedArtboards.to
)
SELECT
RelatedArtboards.to
FROM
RelatedArtboards
WHERE RelatedArtboards.to IS NOT NULL
)
""",
unquote(artboard_id)
)
end
end
import Sketchql.Utils.RelatedArtboards
artboard_id = 1
Artboard
|> join(:inner, [a], ra in with_related_artboards(^artboard_id)
|> Repo.all()
So, this will return a list of
%Artboard{} Ecto.Schema structs
related to the artboard with id 1.
• Keep composability of queries
🎉 Conclusion
• With one query leveraging Ecto and
RCTE ’s we can query all artboards
related to the current one, no matter
how deep.
• In the app we also paginate these
calls. This way we can render much
larger prototypes in Sketch Cloud
• It really pays off to dive deep into the
tools your database can provide such
as RCTE’s.
• Ecto’s extensibility is great! Where we
could not use its native features we
could use SQL to make up for it

Mais conteúdo relacionado

Mais procurados

PostgreSQL Advanced Queries
PostgreSQL Advanced QueriesPostgreSQL Advanced Queries
PostgreSQL Advanced QueriesNur Hidayat
 
All about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdfAll about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdfAltinity Ltd
 
Rules to Hack By - Offensivecon 2022 keynote
Rules to Hack By - Offensivecon 2022 keynoteRules to Hack By - Offensivecon 2022 keynote
Rules to Hack By - Offensivecon 2022 keynoteMarkDowd13
 
Apache Calcite: One Frontend to Rule Them All
Apache Calcite: One Frontend to Rule Them AllApache Calcite: One Frontend to Rule Them All
Apache Calcite: One Frontend to Rule Them AllMichael Mior
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to DockerLuong Vo
 
MySQL Timeout Variables Explained
MySQL Timeout Variables Explained MySQL Timeout Variables Explained
MySQL Timeout Variables Explained Mydbops
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
Finding Evil In DNS Traffic
Finding  Evil In DNS TrafficFinding  Evil In DNS Traffic
Finding Evil In DNS Trafficreal_slacker007
 
Docker introduction
Docker introductionDocker introduction
Docker introductiondotCloud
 
MySQL Performance for DevOps
MySQL Performance for DevOpsMySQL Performance for DevOps
MySQL Performance for DevOpsSveta Smirnova
 
introduction to trees,graphs,hashing
introduction to trees,graphs,hashingintroduction to trees,graphs,hashing
introduction to trees,graphs,hashingAkhil Prem
 
Evolution of containers to kubernetes
Evolution of containers to kubernetesEvolution of containers to kubernetes
Evolution of containers to kubernetesKrishna-Kumar
 
ClickHouse Materialized Views: The Magic Continues
ClickHouse Materialized Views: The Magic ContinuesClickHouse Materialized Views: The Magic Continues
ClickHouse Materialized Views: The Magic ContinuesAltinity Ltd
 
NoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросовNoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросовCodeFest
 

Mais procurados (20)

What is Docker
What is DockerWhat is Docker
What is Docker
 
PostgreSQL Advanced Queries
PostgreSQL Advanced QueriesPostgreSQL Advanced Queries
PostgreSQL Advanced Queries
 
All about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdfAll about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdf
 
Matplotlib
MatplotlibMatplotlib
Matplotlib
 
Rules to Hack By - Offensivecon 2022 keynote
Rules to Hack By - Offensivecon 2022 keynoteRules to Hack By - Offensivecon 2022 keynote
Rules to Hack By - Offensivecon 2022 keynote
 
Apache Calcite: One Frontend to Rule Them All
Apache Calcite: One Frontend to Rule Them AllApache Calcite: One Frontend to Rule Them All
Apache Calcite: One Frontend to Rule Them All
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
MySQL Timeout Variables Explained
MySQL Timeout Variables Explained MySQL Timeout Variables Explained
MySQL Timeout Variables Explained
 
Pro Postgres 9
Pro Postgres 9Pro Postgres 9
Pro Postgres 9
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Finding Evil In DNS Traffic
Finding  Evil In DNS TrafficFinding  Evil In DNS Traffic
Finding Evil In DNS Traffic
 
Docker introduction
Docker introductionDocker introduction
Docker introduction
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
MySQL Performance for DevOps
MySQL Performance for DevOpsMySQL Performance for DevOps
MySQL Performance for DevOps
 
introduction to trees,graphs,hashing
introduction to trees,graphs,hashingintroduction to trees,graphs,hashing
introduction to trees,graphs,hashing
 
Evolution of containers to kubernetes
Evolution of containers to kubernetesEvolution of containers to kubernetes
Evolution of containers to kubernetes
 
ClickHouse Materialized Views: The Magic Continues
ClickHouse Materialized Views: The Magic ContinuesClickHouse Materialized Views: The Magic Continues
ClickHouse Materialized Views: The Magic Continues
 
NoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросовNoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросов
 
Log Structured Merge Tree
Log Structured Merge TreeLog Structured Merge Tree
Log Structured Merge Tree
 

Semelhante a Using Recursive Common Table Expressions with Ecto

Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#Talbott Crowell
 
MapInfo Professional 12.0 and SQL Server 2008
MapInfo Professional 12.0 and SQL Server 2008MapInfo Professional 12.0 and SQL Server 2008
MapInfo Professional 12.0 and SQL Server 2008Peter Horsbøll Møller
 
Intro to-html-backbone-angular
Intro to-html-backbone-angularIntro to-html-backbone-angular
Intro to-html-backbone-angularzonathen
 
Plone For Developers - World Plone Day, 2009
Plone For Developers - World Plone Day, 2009Plone For Developers - World Plone Day, 2009
Plone For Developers - World Plone Day, 2009Core Software Group
 
F# for functional enthusiasts
F# for functional enthusiastsF# for functional enthusiasts
F# for functional enthusiastsJack Fox
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan
 
Designing well known websites with ADF Rich Faces
Designing well known websites with ADF Rich FacesDesigning well known websites with ADF Rich Faces
Designing well known websites with ADF Rich Facesmaikorocha
 
Android | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardAndroid | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardJAX London
 
Evolve Your Code
Evolve Your CodeEvolve Your Code
Evolve Your CodeRookieOne
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Developmentjoelabrahamsson
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introductionshaojung
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introductionshaojung
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introductionshaojung
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Pythongturnquist
 
iOS App Development with F# and Xamarin
iOS App Development with F# and XamariniOS App Development with F# and Xamarin
iOS App Development with F# and XamarinRachel Reese
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectureselliando dias
 

Semelhante a Using Recursive Common Table Expressions with Ecto (20)

Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
 
MapInfo Professional 12.0 and SQL Server 2008
MapInfo Professional 12.0 and SQL Server 2008MapInfo Professional 12.0 and SQL Server 2008
MapInfo Professional 12.0 and SQL Server 2008
 
Intro to-html-backbone-angular
Intro to-html-backbone-angularIntro to-html-backbone-angular
Intro to-html-backbone-angular
 
Web+Dev+Syllabus.pdf
Web+Dev+Syllabus.pdfWeb+Dev+Syllabus.pdf
Web+Dev+Syllabus.pdf
 
Plone For Developers - World Plone Day, 2009
Plone For Developers - World Plone Day, 2009Plone For Developers - World Plone Day, 2009
Plone For Developers - World Plone Day, 2009
 
Hexagonal architecture in PHP
Hexagonal architecture in PHPHexagonal architecture in PHP
Hexagonal architecture in PHP
 
F# for functional enthusiasts
F# for functional enthusiastsF# for functional enthusiasts
F# for functional enthusiasts
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
 
Designing well known websites with ADF Rich Faces
Designing well known websites with ADF Rich FacesDesigning well known websites with ADF Rich Faces
Designing well known websites with ADF Rich Faces
 
Android | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardAndroid | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted Neward
 
Evolve Your Code
Evolve Your CodeEvolve Your Code
Evolve Your Code
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Development
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
Automating SolidWorks with Excel
Automating SolidWorks with ExcelAutomating SolidWorks with Excel
Automating SolidWorks with Excel
 
iOS App Development with F# and Xamarin
iOS App Development with F# and XamariniOS App Development with F# and Xamarin
iOS App Development with F# and Xamarin
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectures
 

Último

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Último (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Using Recursive Common Table Expressions with Ecto

  • 1. Maarten van Vliet Backend developer @ Awkward Email: maarten@awkward.co Github: maartenvanvliet
  • 2. Recursive Common Table Expressions and Ecto PRESENTATION By Maarten van Vliet
  • 4. What is Sketch? An intuitive vector editor for the Mac. It’s used primarily by screen designers who create websites, icons, and user interfaces for desktop and mobile devices.
  • 5. Sketch Cloud Sketch Cloud is a platform that allows you to share documents easily and with everyone. Many more features are coming! Sketch Cloud uses a GraphQL API built in Elixir, we call it SketchQL
  • 6. Prototyping Sketch’s Prototyping features makes it easy to create interactive workflows and preview your designs as your users will see them. Released last year in Sketch and Sketch Cloud A user can now create a prototype in the Sketch, upload it to Cloud and interactively play with it
  • 7. Prototyping Cloud Building prototyping was challenging • Fluent transitions across browsers • Converting Sketch Prototypes to the web • And, there are simple prototypes such as this one
  • 9. Problems We needed to fluently transition from one screen to the next for prototyping in the browser. This meant: (deep) preloading the relations of one screen (artboard) with all other artboards So, when A is loaded, we need to load B and C, but also D!
  • 10. Simplest solution Recursively query database for related artboards from application 1. First query for artboard A 2. Query for artboards directly related to A, returns [B, C] 3. Query for artboards directly related to [B, C], but leave out already found artboards [A], this returns [D] 4. Query for artboards directly related to [D], but leave out already found artboards [A, B, C], returns [] 5. We stop when an empty set is returned. Problem:lots of queries
  • 11. Solution: Recursive Common Table Expressions! • Last year we migrated Sketch Cloud to Mariadb 10.2 • Introduced support for (Recursive) Common Table Expressions • (R)CTE's are also available in Mysql 8.0 (since 2018), and Postgres 8.4 (since 2009) • But what are they?
  • 12. Common Table Expressions A CTE is a temporary resultset Think of it as a database view only created and visible for one query. Useful for making subqueries easier to read You can have multiple in one query WITH FirstUser AS (   SELECT * FROM Users WHERE id = 1 ) SELECT * FROM FirstUser — Equivalent to query with subquery SELECT * FROM (SELECT * FROM Users WHERE id = 1) AS F;
  • 13. CTE’s can also do recursion! Recursive CTE’s are useful for querying hierarchies, e.g. tables with a parent_id column, so a row has can have a parent or children E.g. a CMS with pages, where a page can have children Pages: WITH RECURSIVE PageGraph AS ( SELECT P.id, P.parent_id FROM Pages P WHERE P.parent_id IS NULL —start id UNION SELECT P.id, P.parent_id FROM Pages P JOIN PageGraph PG ON P.parent_id = PG.id ) SELECT * FROM PageGraph Id parent_id Name 1 NULL Page 1 2 1 Subpage 1 3 1 Subpage 2 4 2 Subpage 3
  • 14. Dealing with cycles How to deal with cycles? Hierarchies with “loops” in them. E.g. page A has page B as a parent, and page B has page A as a parent WITH RECURSIVE PageGraph AS ( SELECT P.id, P.parent_id FROM Pages P WHERE P.id = 1 #start id UNION SELECT P.id, P.parent_id FROM Pages P JOIN PageGraph PG ON P.parent_id = PG.id ) SELECT * FROM PageGraph Id parent_id Name 1 2 Page 1 2 1 Page 2 Union removes duplicates!
  • 15. Back to the problem In steps: • First get artboards related to A, and store them in “to”, returns [B, C] • UNION this with the artboards where the id matches those of [B, C] • Get related artboards of [B, C], returns [D] • Again, UNION and get related artboards of [D], returns [A]. • Nothing new found, so stop WITH RECURSIVE RelatedArtboards AS ( SELECT — A.id AS "from", F.DestinationArtboardId AS "to" FROM Artboards A JOIN Layers L ON L.ArtboardId = A.id JOIN Flows F ON F.id = L.FlowId WHERE A.id = #Start ID, in this case Artboard A UNION SELECT — A.id AS "from", F.DestinationArtboardId AS "to" FROM Artboards A JOIN Layers L ON L.ArtboardId = A.id JOIN Flows F ON F.id = L.FlowId JOIN RelatedArtboards ON A.id = RelatedArtboards.to WHERE A.id = RelatedArtboards.to ) SELECT R.to FROM RelatedArtboards R From To A B A C B D C D D A
  • 16. Now we only need one query to load all artboards for a prototype! But how to use this in Elixir/Ecto?
  • 17. Not supported in the query builder, yet… Still open 😢
  • 18. Once merged: page_tree_initial_query = Page |> where([p], is_nil(p.parent_id)) page_tree_recursion_query = Page |> join(:inner, [p], pt in "page_tree", on: p.parent_id == pt.id) page_tree_query = page_tree_initial_queryv |> union(^page_tree_recursion_query) Page |> recursive_ctes(true) |> with_cte("page_tree", as: ^page_tree_query) |> Repo.all
  • 19. Until then… Fragments gives us the ability to extend Ecto defmacro with_related_artboards(artboard_id) do quote do fragment( """ ( WITH RECURSIVE RelatedArtboards AS ( SELECT F.DestinationArtboardId AS "to" FROM Artboards A JOIN Layers L ON L.ArtboardId = A.id JOIN Flows F ON F.id = L.FlowId WHERE A.id = ? UNION SELECT F.DestinationArtboardId AS "to" FROM Artboards A JOIN Layers L ON L.ArtboardId = A.id JOIN Flows F ON F.id = L.FlowId JOIN RelatedArtboards ON A.id = RelatedArtboards.to WHERE A.id = RelatedArtboards.to ) SELECT RelatedArtboards.to FROM RelatedArtboards WHERE RelatedArtboards.to IS NOT NULL ) """, unquote(artboard_id) ) end end import Sketchql.Utils.RelatedArtboards artboard_id = 1 Artboard |> join(:inner, [a], ra in with_related_artboards(^artboard_id) |> Repo.all() So, this will return a list of %Artboard{} Ecto.Schema structs related to the artboard with id 1. • Keep composability of queries
  • 20. 🎉 Conclusion • With one query leveraging Ecto and RCTE ’s we can query all artboards related to the current one, no matter how deep. • In the app we also paginate these calls. This way we can render much larger prototypes in Sketch Cloud • It really pays off to dive deep into the tools your database can provide such as RCTE’s. • Ecto’s extensibility is great! Where we could not use its native features we could use SQL to make up for it