SlideShare a Scribd company logo
1 of 27
Download to read offline
Scaling Scala
to the Database
Stefan Zeiger
1
Overview / Key Concepts
WE WRITE SQL SO
YOU DON'T HAVE TO
h"p://toto.lib.unca.edu/findingaids/photo/na5onal_clima5c_data_center/NCDC_interior.htm	
  
NOAA's	
  Na5onal	
  Clima5c	
  Data	
  Center	
  is	
  the	
  source	
  of	
  this	
  image	
  and	
  it	
  is	
  used	
  by	
  permission	
  
Write database code in Scala
•  Instead of SQL, JPQL, Criteria API, etc.
for { p <- persons } yield p.name

select p.NAME from PERSON p
4	
  
(for {

p <- persons.filter(_.age < 20) ++
persons.filter(_.age >= 50)
if p.name.startsWith("A")
} yield p).groupBy(_.age).map { case (age, ps) =>
(age, ps.length)
}

select x2.x3, count(1) from (
select * from (
select x4."NAME" as x5, x4."AGE" as x3
from "PERSON" x4 where x4."AGE" < 20
union all select x6."NAME" as x5, x6."AGE" as x3
from "PERSON" x6 where x6."AGE" >= 50
) x7 where x7.x5 like 'A%' escape '^'
) x2 group by x2.x3
5	
  
Scala Language
Integrated Connection Kit
• 
• 
• 
• 

Database query and access library for Scala
Successor of ScalaQuery
Developed at Typesafe and EPFL
Open Source
6	
  
Supported Databases
• 
• 
• 
• 
• 
• 
• 

PostgreSQL
MySQL
H2
Hsqldb
Derby / JavaDB
SQLite
Access

Closed-­‐Source	
  Slick	
  Extensions	
  
(with	
  commercial	
  support	
  by	
  
Typesafe):	
  

	
  
•  Oracle	
  
•  DB/2	
  
•  SQL	
  Server	
  

7	
  
Components
• 
• 
• 
• 
• 

Lifted Embedding
Direct Embedding
Plain SQL
Session Management
Schema Model
8	
  
2
Compared to ORMs
Impedance Mismatch: Retrieval
Colombian	
  
French_Roast	
  
Espresso	
  
Colombian_Decaf	
  
French_Roast_Decaf	
  
select COF_NAME
from COFFEES

Espresso	
  
Price: 	
  
Supplier: 	
  

	
  9.99	
  
	
  The	
  High	
  Ground	
  

select c.*, s.SUP_NAME
from COFFEES c, SUPPLIERS s
where c.COF_NAME = ?
and c.SUP_ID = s.SUP_ID
10	
  
Impedance Mismatch: Retrieval

def getAllCoffees(): Seq[Coffee] = …
    
def 
printLinks(s: Seq[Coffee]) {
                                                              +  "  "  +  c.price
 )
for(c <- s) println(c.name
}
def printDetails(c: Coffee) {
println(c.name)
println("Price: " + c.price)
println("Supplier: " + c.supplier.name)
	
  
	
  
	
  	
  
}

Colombian	
  
French_Roast	
  
Espresso	
  
Colombian_Decaf	
  
French_Roast_Decaf	
  

Espresso	
  
Price:	
  
Supplier:

	
  9.99	
  
	
  The	
  High	
  Ground	
  

11	
  
O/R Mapper
•  Mapping low-level programming (OOP) to
high-level concepts (relational algebra)
•  Not transparent (but pretends to be)
12	
  
Better Match: Functional Programming
• Relation
• Attribute
• Tuple
• Relation Value
• Relation Variable

case class Coffee(name: String,
supplierId: Int, price: Double)
val coffees = Set(
Coffee("Colombian",
101, 7.99),
Coffee("French_Roast", 49, 8.99),
Coffee("Espresso",
150, 9.99)
)

- mutable state in the DB
13	
  
Functional-Relational Mapping
• 
• 
• 
• 
• 

Embraces the relational model
No impedance mismatch
Composable Queries
Explicit control over statement execution
Stateless
14	
  
3
Demo
4
Under The Hood
APIs
Direct Embedding

Lifted Embedding

Scala
Compiler

Scala AST
Slick AST

Slick Macros

Query
Compiler

Slick AST

Executor

DB
Result
17	
  
Lifted Embedding
Query[ (Column[String], Column[String]), (String, String) ]
TableQuery[Coffees]
Coffees
Suppliers

ColumnExtensionMethods.<

val q = for {
c <- coffees if c.price < 9.0
s <- c.supplier
ConstColumn(9.0)
} yield (c.name, s.name)

(Column[String], Column[String])

Seq[ (String, String) ]

Column[Double]

val result = q.run
18	
  
Direct Embedding (experimental)
Queryable[ (String, String) ]
Queryable[Coffee]
Coffee
Supplier

Double.<

val q = for {
c <- coffees if c.price < 9.0
s <- c.supplier
} yield (c.name, s.name)

(String, String)

Seq[ (String, String) ]

9.0: Double

Double

val result = q.run
19	
  
Query Compiler
•  Immutable ASTs
–  Types can be mutated until they are observed

•  Immutable compiler state
–  containing AST + phase output state

•  Phases transform compiler state
–  using mutable state locally

•  Drivers provide their own compilers
20	
  
Compiler Phases: SQL
Clean Up
• 
• 
• 
• 
• 
• 

inline
assignUniqueSymbols
expandTables
inferTypes
createResultSetMapping
forceOuterBinds

Flatten Columns
• 
• 
• 
• 
• 
• 

expandRefs
replaceFieldSymbols
rewritePaths
relabelUnions
pruneFields
assignTypes

SQL Shape
• 
• 
• 
• 
• 

resolveZipJoins
convertToComprehensions
fuseComprehensions
fixRowNumberOrdering
hoistClientOps

Generate Code
• 

codeGen
(driver-specific)

21	
  
Compiler Phases: MemoryDriver
Clean Up
• 
• 
• 
• 
• 
• 

inline
assignUniqueSymbols
expandTables
inferTypes
createResultSetMapping
forceOuterBinds

Flatten Columns
• 
• 
• 
• 
• 
• 

expandRefs
replaceFieldSymbols
rewritePaths
relabelUnions
pruneFields
assignTypes

Prepare for
Interpreter
• 

codeGen

22	
  
Compiler Phases: Scheduling
Clean Up
• 
• 

inline
assignUniqueSymbols

Clean Up II

Distribute
• 

distribute (to other drivers' compilers)

e.g. H2

• 
• 
• 
• 
• 
• 

expandRefs
replaceFieldSymbols
rewritePaths
relabelUnions
pruneFields
assignTypes

…

Query
Compiler

Flatten Columns

MySQL
Query
Compiler

• 
• 
• 
• 

expandTables
inferTypes
createResultSetMapping
forceOuterBinds

Query
Compiler

Prepare for
Interpreter
• 

codeGen

23	
  
5
Outlook
Slick 2.0
• 
• 
• 
• 
• 

Coming Q4 / 2013
Query scheduling
API Improvements
New driver and back-end architecture
Generate Slick code from database schemas
Outlook
•  Macro-based type providers

–  Prototype based on type macros
(topic/type-providers)
–  Released version will use macro annotations
–  Scala 2.12?

•  Default database library for Play

–  as part of the Typesafe Reactive Platform

•  Focus on usability (API, docs, semantics, etc.)
slick.typesafe.com
@StefanZeiger

More Related Content

What's hot

phoenix-on-calcite-nyc-meetup
phoenix-on-calcite-nyc-meetupphoenix-on-calcite-nyc-meetup
phoenix-on-calcite-nyc-meetup
Maryann Xue
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 

What's hot (20)

Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017
 
Couchbase 5.5: N1QL and Indexing features
Couchbase 5.5: N1QL and Indexing featuresCouchbase 5.5: N1QL and Indexing features
Couchbase 5.5: N1QL and Indexing features
 
Sql query patterns, optimized
Sql query patterns, optimizedSql query patterns, optimized
Sql query patterns, optimized
 
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
 
Mentor Your Indexes
Mentor Your IndexesMentor Your Indexes
Mentor Your Indexes
 
Phoenix h basemeetup
Phoenix h basemeetupPhoenix h basemeetup
Phoenix h basemeetup
 
Oracle views
Oracle viewsOracle views
Oracle views
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
 
Optimizing MySQL Queries
Optimizing MySQL QueriesOptimizing MySQL Queries
Optimizing MySQL Queries
 
phoenix-on-calcite-nyc-meetup
phoenix-on-calcite-nyc-meetupphoenix-on-calcite-nyc-meetup
phoenix-on-calcite-nyc-meetup
 
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
 
MySQL Optimizer Overview
MySQL Optimizer OverviewMySQL Optimizer Overview
MySQL Optimizer Overview
 
No internet? No Problem!
No internet? No Problem!No internet? No Problem!
No internet? No Problem!
 
Apache Calcite overview
Apache Calcite overviewApache Calcite overview
Apache Calcite overview
 
Single-Row Functions in orcale Data base
Single-Row Functions in orcale Data baseSingle-Row Functions in orcale Data base
Single-Row Functions in orcale Data base
 
How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15How to analyze and tune sql queries for better performance percona15
How to analyze and tune sql queries for better performance percona15
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
 
MySQL Optimizer Cost Model
MySQL Optimizer Cost ModelMySQL Optimizer Cost Model
MySQL Optimizer Cost Model
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...
Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...
Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...
 

Viewers also liked

Legal and ethical considerations redone
Legal and ethical considerations   redoneLegal and ethical considerations   redone
Legal and ethical considerations redone
Nicole174
 
Interactive media applications
Interactive media applicationsInteractive media applications
Interactive media applications
Nicole174
 

Viewers also liked (20)

Streams and Things - Darach Ennis (Ubiquiti Networks)
Streams and Things - Darach Ennis (Ubiquiti Networks)Streams and Things - Darach Ennis (Ubiquiti Networks)
Streams and Things - Darach Ennis (Ubiquiti Networks)
 
Legal and ethical considerations redone
Legal and ethical considerations   redoneLegal and ethical considerations   redone
Legal and ethical considerations redone
 
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
 
A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...
A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...
A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...
 
How Java got its Mojo Back - James Governor (Redmonk)
How Java got its Mojo Back - James Governor (Redmonk)					How Java got its Mojo Back - James Governor (Redmonk)
How Java got its Mojo Back - James Governor (Redmonk)
 
Design is a Process, not an Artefact - Trisha Gee (MongoDB)
Design is a Process, not an Artefact - Trisha Gee (MongoDB)Design is a Process, not an Artefact - Trisha Gee (MongoDB)
Design is a Process, not an Artefact - Trisha Gee (MongoDB)
 
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
 
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
What makes Groovy Groovy  - Guillaume Laforge (Pivotal)What makes Groovy Groovy  - Guillaume Laforge (Pivotal)
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
 
Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...
Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...
Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...
 
Introducing Vert.x 2.0 - Taking polyglot application development to the next ...
Introducing Vert.x 2.0 - Taking polyglot application development to the next ...Introducing Vert.x 2.0 - Taking polyglot application development to the next ...
Introducing Vert.x 2.0 - Taking polyglot application development to the next ...
 
Are you better than a coin toss? - Richard Warbuton & John Oliver (jClarity)
Are you better than a coin toss?  - Richard Warbuton & John Oliver (jClarity)Are you better than a coin toss?  - Richard Warbuton & John Oliver (jClarity)
Are you better than a coin toss? - Richard Warbuton & John Oliver (jClarity)
 
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
 
Databases and agile development - Dwight Merriman (MongoDB)
Databases and agile development - Dwight Merriman (MongoDB)Databases and agile development - Dwight Merriman (MongoDB)
Databases and agile development - Dwight Merriman (MongoDB)
 
Big data from the LHC commissioning: practical lessons from big science - Sim...
Big data from the LHC commissioning: practical lessons from big science - Sim...Big data from the LHC commissioning: practical lessons from big science - Sim...
Big data from the LHC commissioning: practical lessons from big science - Sim...
 
The state of the art biorepository at ILRI
The state of the art biorepository at ILRIThe state of the art biorepository at ILRI
The state of the art biorepository at ILRI
 
How Windows 10 will change the way we use devices
How Windows 10 will change the way we use devicesHow Windows 10 will change the way we use devices
How Windows 10 will change the way we use devices
 
Practical Performance: Understand the Performance of Your Application - Chris...
Practical Performance: Understand the Performance of Your Application - Chris...Practical Performance: Understand the Performance of Your Application - Chris...
Practical Performance: Understand the Performance of Your Application - Chris...
 
How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...
How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...
How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...
 
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
 
Interactive media applications
Interactive media applicationsInteractive media applications
Interactive media applications
 

Similar to Scaling Scala to the database - Stefan Zeiger (Typesafe)

Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...
Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...
Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...
Lucas Jellema
 
Mutant Tests Too: The SQL
Mutant Tests Too: The SQLMutant Tests Too: The SQL
Mutant Tests Too: The SQL
DataWorks Summit
 

Similar to Scaling Scala to the database - Stefan Zeiger (Typesafe) (20)

Graph Database Query Languages
Graph Database Query LanguagesGraph Database Query Languages
Graph Database Query Languages
 
Polyalgebra
PolyalgebraPolyalgebra
Polyalgebra
 
Avoiding Bad Database Surprises: Simulation and Scalability - Steven Lott
Avoiding Bad Database Surprises: Simulation and Scalability - Steven LottAvoiding Bad Database Surprises: Simulation and Scalability - Steven Lott
Avoiding Bad Database Surprises: Simulation and Scalability - Steven Lott
 
Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...
Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...
Singpore Oracle Sessions III - What is truly useful in Oracle Database 12c fo...
 
Koalas: Making an Easy Transition from Pandas to Apache Spark
Koalas: Making an Easy Transition from Pandas to Apache SparkKoalas: Making an Easy Transition from Pandas to Apache Spark
Koalas: Making an Easy Transition from Pandas to Apache Spark
 
Spark DataFrames for Data Munging
Spark DataFrames for Data MungingSpark DataFrames for Data Munging
Spark DataFrames for Data Munging
 
Recent Developments In SparkR For Advanced Analytics
Recent Developments In SparkR For Advanced AnalyticsRecent Developments In SparkR For Advanced Analytics
Recent Developments In SparkR For Advanced Analytics
 
Koalas: Making an Easy Transition from Pandas to Apache Spark
Koalas: Making an Easy Transition from Pandas to Apache SparkKoalas: Making an Easy Transition from Pandas to Apache Spark
Koalas: Making an Easy Transition from Pandas to Apache Spark
 
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
 
DataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
DataFrame: Spark's new abstraction for data science by Reynold Xin of DatabricksDataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
DataFrame: Spark's new abstraction for data science by Reynold Xin of Databricks
 
The Pushdown of Everything by Stephan Kessler and Santiago Mola
The Pushdown of Everything by Stephan Kessler and Santiago MolaThe Pushdown of Everything by Stephan Kessler and Santiago Mola
The Pushdown of Everything by Stephan Kessler and Santiago Mola
 
Parallelizing Existing R Packages
Parallelizing Existing R PackagesParallelizing Existing R Packages
Parallelizing Existing R Packages
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
DataMapper
DataMapperDataMapper
DataMapper
 
3rd Athens Big Data Meetup - 2nd Talk - Neo4j: The World's Leading Graph DB
3rd Athens Big Data Meetup - 2nd Talk - Neo4j: The World's Leading Graph DB3rd Athens Big Data Meetup - 2nd Talk - Neo4j: The World's Leading Graph DB
3rd Athens Big Data Meetup - 2nd Talk - Neo4j: The World's Leading Graph DB
 
Mutant Tests Too: The SQL
Mutant Tests Too: The SQLMutant Tests Too: The SQL
Mutant Tests Too: The SQL
 
Webinar: What's New in Solr 6
Webinar: What's New in Solr 6Webinar: What's New in Solr 6
Webinar: What's New in Solr 6
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 

More from jaxLondonConference

More from jaxLondonConference (20)

Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...
Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...
Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...
 
Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...
Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...
Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...
 
JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)
 
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
 
Why other ppl_dont_get_it
Why other ppl_dont_get_itWhy other ppl_dont_get_it
Why other ppl_dont_get_it
 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)
 
Big Events, Mob Scale - Darach Ennis (Push Technology)
Big Events, Mob Scale - Darach Ennis (Push Technology)Big Events, Mob Scale - Darach Ennis (Push Technology)
Big Events, Mob Scale - Darach Ennis (Push Technology)
 
The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...
The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...
The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...
 
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
 
Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...
Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...
Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...
 
The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)
 
TDD at scale - Mash Badar (UBS)
TDD at scale - Mash Badar (UBS)TDD at scale - Mash Badar (UBS)
TDD at scale - Mash Badar (UBS)
 
Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)
Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)
Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)
 
Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)
Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)
Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
 
Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...
Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...
Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...
 
Little words of wisdom for the developer - Guillaume Laforge (Pivotal)
Little words of wisdom for the developer - Guillaume Laforge (Pivotal)Little words of wisdom for the developer - Guillaume Laforge (Pivotal)
Little words of wisdom for the developer - Guillaume Laforge (Pivotal)
 
Large scale, interactive ad-hoc queries over different datastores with Apache...
Large scale, interactive ad-hoc queries over different datastores with Apache...Large scale, interactive ad-hoc queries over different datastores with Apache...
Large scale, interactive ad-hoc queries over different datastores with Apache...
 
Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...
Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...
Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Scaling Scala to the database - Stefan Zeiger (Typesafe)

  • 1. Scaling Scala to the Database Stefan Zeiger
  • 2. 1 Overview / Key Concepts
  • 3. WE WRITE SQL SO YOU DON'T HAVE TO h"p://toto.lib.unca.edu/findingaids/photo/na5onal_clima5c_data_center/NCDC_interior.htm   NOAA's  Na5onal  Clima5c  Data  Center  is  the  source  of  this  image  and  it  is  used  by  permission  
  • 4. Write database code in Scala •  Instead of SQL, JPQL, Criteria API, etc. for { p <- persons } yield p.name select p.NAME from PERSON p 4  
  • 5. (for { p <- persons.filter(_.age < 20) ++ persons.filter(_.age >= 50) if p.name.startsWith("A") } yield p).groupBy(_.age).map { case (age, ps) => (age, ps.length) } select x2.x3, count(1) from ( select * from ( select x4."NAME" as x5, x4."AGE" as x3 from "PERSON" x4 where x4."AGE" < 20 union all select x6."NAME" as x5, x6."AGE" as x3 from "PERSON" x6 where x6."AGE" >= 50 ) x7 where x7.x5 like 'A%' escape '^' ) x2 group by x2.x3 5  
  • 6. Scala Language Integrated Connection Kit •  •  •  •  Database query and access library for Scala Successor of ScalaQuery Developed at Typesafe and EPFL Open Source 6  
  • 7. Supported Databases •  •  •  •  •  •  •  PostgreSQL MySQL H2 Hsqldb Derby / JavaDB SQLite Access Closed-­‐Source  Slick  Extensions   (with  commercial  support  by   Typesafe):     •  Oracle   •  DB/2   •  SQL  Server   7  
  • 10. Impedance Mismatch: Retrieval Colombian   French_Roast   Espresso   Colombian_Decaf   French_Roast_Decaf   select COF_NAME from COFFEES Espresso   Price:   Supplier:    9.99    The  High  Ground   select c.*, s.SUP_NAME from COFFEES c, SUPPLIERS s where c.COF_NAME = ? and c.SUP_ID = s.SUP_ID 10  
  • 11. Impedance Mismatch: Retrieval def getAllCoffees(): Seq[Coffee] = …     def printLinks(s: Seq[Coffee]) {                                                              +  "  "  +  c.price ) for(c <- s) println(c.name } def printDetails(c: Coffee) { println(c.name) println("Price: " + c.price) println("Supplier: " + c.supplier.name)         } Colombian   French_Roast   Espresso   Colombian_Decaf   French_Roast_Decaf   Espresso   Price:   Supplier:  9.99    The  High  Ground   11  
  • 12. O/R Mapper •  Mapping low-level programming (OOP) to high-level concepts (relational algebra) •  Not transparent (but pretends to be) 12  
  • 13. Better Match: Functional Programming • Relation • Attribute • Tuple • Relation Value • Relation Variable case class Coffee(name: String, supplierId: Int, price: Double) val coffees = Set( Coffee("Colombian", 101, 7.99), Coffee("French_Roast", 49, 8.99), Coffee("Espresso", 150, 9.99) ) - mutable state in the DB 13  
  • 14. Functional-Relational Mapping •  •  •  •  •  Embraces the relational model No impedance mismatch Composable Queries Explicit control over statement execution Stateless 14  
  • 17. APIs Direct Embedding Lifted Embedding Scala Compiler Scala AST Slick AST Slick Macros Query Compiler Slick AST Executor DB Result 17  
  • 18. Lifted Embedding Query[ (Column[String], Column[String]), (String, String) ] TableQuery[Coffees] Coffees Suppliers ColumnExtensionMethods.< val q = for { c <- coffees if c.price < 9.0 s <- c.supplier ConstColumn(9.0) } yield (c.name, s.name) (Column[String], Column[String]) Seq[ (String, String) ] Column[Double] val result = q.run 18  
  • 19. Direct Embedding (experimental) Queryable[ (String, String) ] Queryable[Coffee] Coffee Supplier Double.< val q = for { c <- coffees if c.price < 9.0 s <- c.supplier } yield (c.name, s.name) (String, String) Seq[ (String, String) ] 9.0: Double Double val result = q.run 19  
  • 20. Query Compiler •  Immutable ASTs –  Types can be mutated until they are observed •  Immutable compiler state –  containing AST + phase output state •  Phases transform compiler state –  using mutable state locally •  Drivers provide their own compilers 20  
  • 21. Compiler Phases: SQL Clean Up •  •  •  •  •  •  inline assignUniqueSymbols expandTables inferTypes createResultSetMapping forceOuterBinds Flatten Columns •  •  •  •  •  •  expandRefs replaceFieldSymbols rewritePaths relabelUnions pruneFields assignTypes SQL Shape •  •  •  •  •  resolveZipJoins convertToComprehensions fuseComprehensions fixRowNumberOrdering hoistClientOps Generate Code •  codeGen (driver-specific) 21  
  • 22. Compiler Phases: MemoryDriver Clean Up •  •  •  •  •  •  inline assignUniqueSymbols expandTables inferTypes createResultSetMapping forceOuterBinds Flatten Columns •  •  •  •  •  •  expandRefs replaceFieldSymbols rewritePaths relabelUnions pruneFields assignTypes Prepare for Interpreter •  codeGen 22  
  • 23. Compiler Phases: Scheduling Clean Up •  •  inline assignUniqueSymbols Clean Up II Distribute •  distribute (to other drivers' compilers) e.g. H2 •  •  •  •  •  •  expandRefs replaceFieldSymbols rewritePaths relabelUnions pruneFields assignTypes … Query Compiler Flatten Columns MySQL Query Compiler •  •  •  •  expandTables inferTypes createResultSetMapping forceOuterBinds Query Compiler Prepare for Interpreter •  codeGen 23  
  • 25. Slick 2.0 •  •  •  •  •  Coming Q4 / 2013 Query scheduling API Improvements New driver and back-end architecture Generate Slick code from database schemas
  • 26. Outlook •  Macro-based type providers –  Prototype based on type macros (topic/type-providers) –  Released version will use macro annotations –  Scala 2.12? •  Default database library for Play –  as part of the Typesafe Reactive Platform •  Focus on usability (API, docs, semantics, etc.)