SlideShare a Scribd company logo
1 of 20
Download to read 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

More Related Content

What's hot

Apache Arrow: High Performance Columnar Data Framework
Apache Arrow: High Performance Columnar Data FrameworkApache Arrow: High Performance Columnar Data Framework
Apache Arrow: High Performance Columnar Data FrameworkWes McKinney
 
Building Reliable Lakehouses with Apache Flink and Delta Lake
Building Reliable Lakehouses with Apache Flink and Delta LakeBuilding Reliable Lakehouses with Apache Flink and Delta Lake
Building Reliable Lakehouses with Apache Flink and Delta LakeFlink Forward
 
SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...
SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...
SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...HostedbyConfluent
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven DesignAndriy Buday
 
Data modeling for Elasticsearch
Data modeling for ElasticsearchData modeling for Elasticsearch
Data modeling for ElasticsearchFlorian Hopf
 
Inside Parquet Format
Inside Parquet FormatInside Parquet Format
Inside Parquet FormatYue Chen
 
Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021
Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021
Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021StreamNative
 
Apache Spark in Depth: Core Concepts, Architecture & Internals
Apache Spark in Depth: Core Concepts, Architecture & InternalsApache Spark in Depth: Core Concepts, Architecture & Internals
Apache Spark in Depth: Core Concepts, Architecture & InternalsAnton Kirillov
 
Raven: End-to-end Optimization of ML Prediction Queries
Raven: End-to-end Optimization of ML Prediction QueriesRaven: End-to-end Optimization of ML Prediction Queries
Raven: End-to-end Optimization of ML Prediction QueriesDatabricks
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_scriptVijay Kalyan
 
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...Altinity Ltd
 
Local Apache NiFi Processor Debug
Local Apache NiFi Processor DebugLocal Apache NiFi Processor Debug
Local Apache NiFi Processor DebugDeon Huang
 
Solving PostgreSQL wicked problems
Solving PostgreSQL wicked problemsSolving PostgreSQL wicked problems
Solving PostgreSQL wicked problemsAlexander Korotkov
 
(BDT318) How Netflix Handles Up To 8 Million Events Per Second
(BDT318) How Netflix Handles Up To 8 Million Events Per Second(BDT318) How Netflix Handles Up To 8 Million Events Per Second
(BDT318) How Netflix Handles Up To 8 Million Events Per SecondAmazon Web Services
 
Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Cloudera, Inc.
 
ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...
ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...
ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...Databricks
 

What's hot (20)

Apache Arrow: High Performance Columnar Data Framework
Apache Arrow: High Performance Columnar Data FrameworkApache Arrow: High Performance Columnar Data Framework
Apache Arrow: High Performance Columnar Data Framework
 
Building Reliable Lakehouses with Apache Flink and Delta Lake
Building Reliable Lakehouses with Apache Flink and Delta LakeBuilding Reliable Lakehouses with Apache Flink and Delta Lake
Building Reliable Lakehouses with Apache Flink and Delta Lake
 
SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...
SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...
SingleStore & Kafka: Better Together to Power Modern Real-Time Data Architect...
 
C sharp
C sharpC sharp
C sharp
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven Design
 
Data modeling for Elasticsearch
Data modeling for ElasticsearchData modeling for Elasticsearch
Data modeling for Elasticsearch
 
Inside Parquet Format
Inside Parquet FormatInside Parquet Format
Inside Parquet Format
 
Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021
Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021
Trino: A Ludicrously Fast Query Engine - Pulsar Summit NA 2021
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Apache Spark in Depth: Core Concepts, Architecture & Internals
Apache Spark in Depth: Core Concepts, Architecture & InternalsApache Spark in Depth: Core Concepts, Architecture & Internals
Apache Spark in Depth: Core Concepts, Architecture & Internals
 
Trees and Hierarchies in SQL
Trees and Hierarchies in SQLTrees and Hierarchies in SQL
Trees and Hierarchies in SQL
 
Raven: End-to-end Optimization of ML Prediction Queries
Raven: End-to-end Optimization of ML Prediction QueriesRaven: End-to-end Optimization of ML Prediction Queries
Raven: End-to-end Optimization of ML Prediction Queries
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
Apache Spark Overview
Apache Spark OverviewApache Spark Overview
Apache Spark Overview
 
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
 
Local Apache NiFi Processor Debug
Local Apache NiFi Processor DebugLocal Apache NiFi Processor Debug
Local Apache NiFi Processor Debug
 
Solving PostgreSQL wicked problems
Solving PostgreSQL wicked problemsSolving PostgreSQL wicked problems
Solving PostgreSQL wicked problems
 
(BDT318) How Netflix Handles Up To 8 Million Events Per Second
(BDT318) How Netflix Handles Up To 8 Million Events Per Second(BDT318) How Netflix Handles Up To 8 Million Events Per Second
(BDT318) How Netflix Handles Up To 8 Million Events Per Second
 
Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0
 
ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...
ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...
ACID ORC, Iceberg, and Delta Lake—An Overview of Table Formats for Large Scal...
 

Similar to 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
 

Similar to 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
 

Recently uploaded

AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101vincent683379
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessUXDXConf
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...FIDO Alliance
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfFIDO Alliance
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 

Recently uploaded (20)

AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 

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