SlideShare a Scribd company logo
The Slick Library 
Rebecca Grenier 
rebeccagrenier@gmail.com
Intro to Slick 
 Static Typing + Compilation = Type Safety 
 For-Comprehensions 
 Compositionality: build complex queries out of simple 
parts 
@beckythebest
Introduction to Slick 
@beckythebest
Slick Connection Drivers 
 Oracle ($$$) 
 DB2 ($$$) 
 SQL Server ($$$) 
@beckythebest 
Note: Connection Pooling is your 
responsibility 
 PostgreSQL 
 MySQL 
 Access 
 Derby 
 H2 
 Hsqldb 
 SQLite
The Files Table 
@beckythebest 
Field Type Null 
id int (10) unsigned NO 
uid int (10) unsigned NO 
path varchar (255) NO 
filetype varchar (255) NO
Table Definitions: 
Mapping to tuples 
@beckythebest
Table Definitions: 
Mapping to case classes 
@beckythebest
How the 22-item 
tuple Limit Affects Slick 
What if your table has more than 22 columns? 
Define multiple Table Classes that refer to the same table – 
similar to “views” 
* There is a workaround for Scala >= 2.10.3 where you can 
use HList instead 
@beckythebest
Queries in Slick 
Every query starts out as a TableQuery first: 
val files = TableQuery[Files] 
is the equivalent of 
select * from files; 
(You can use .selectStatement on any query to see 
the SQL for a select statment that is generated 
behind the scenes) 
@beckythebest
A Quick Full Example 
val allFiles = db withSession { 
implicit session => 
files.run 
} 
allFiles is a Vector of File case class objects 
files is just the query and remains so until it is invoked 
(with .run) 
@beckythebest
Building Your Query: 
Adding a Where Clause 
With .filter 
files.filter(_.filetype === ‘pdf’) 
In SQL: select * from files where 
filetype= ’pdf’ 
• In Slick, equals is === 
• Not-Equals is =!= 
@beckythebest
Use Method Chaining to Add 
More Clauses to Your Query 
Slick: files.filter(_.filetype === 
“pdf”).filter(_.id < 20000) 
SQL: select * from files where filetype= 
“pdf” and id < 20000 
Reminder: You are not really filtering 
yet; 
@beckythebest 
you are building a Query.
Query Building 
with Modifiers from Slick’s DSL 
 take 
files.take(5) SQL: select * from files limit 5 
 Drop 
files.drop(5) SQL: select * from files offset 5 
 length 
files.length SQL: select count(*) from files 
 map 
 flatMap 
 sortBy SQL: sort by 
@beckythebest
Connecting to Your Database 
in Slick 
Connect with Database.forURL 
There is also forDriver, forName, and forDataSource 
@beckythebest
Queries Need Sessions 
Use that Database Connection to get a 
Session 
@beckythebest 
This is a static 
session
Just Say No to 
Dynamic Sessions 
AKA A non-explicit session you hope was opened earlier this 
thread 
Dynamic 
Sessions 
You can’t count on your thread having a session in an 
@beckythebest 
asyncronous world
Query Invokers 
Invoker Returns 
Vector of results 
List of results 
First result or Exception 
Some(first) or None 
Nothing 
files.run 
files.list 
files.first 
files.firstOption 
files.execute 
@beckythebest
Invoke a Delete Query 
scala> files.deleteStatement 
res5: String = delete from `files` 
invoke with .delete 
files.delete 
@beckythebest
Just Delete One Record 
Reduce your query with filter: 
> files.filter(_.id === 56).deleteStatement 
res6: String = delete from `files` where 
`files`.`id` = 56 
Invoked: 
files.filter(_.id === 56).delete 
@beckythebest
Insert Query Invoker 
scala> files.insertStatement 
res1: String = insert into `files` 
(`id`,`path`,`filetype`,`uid`) values 
(?,?,?,?) 
invoke with += 
files += File(0, “path to file”, “type”, 333) 
@beckythebest
Update Query Invoker 
scala> files.map(_.path).updateStatement 
res4: String = update `files` set `path` = ? 
invoke with .update() 
files.map(_.path).update(“new path to file”) 
@beckythebest
Best Practice: Build your Query 
Completely BEFORE Invoking 
The commands below look similar but have very 
different performance: 
files.take(5).run 
SQL: (select * from files limit 5) 
files.run.take(5) 
SQL: (select * from files) take 5 
@beckythebest
What good is all this 
Typing? 
Use SQL to query the files table by fid (which is an integer) 
What happens when a non-integer value gets passed in? 
@beckythebest 
No error? 
No big deal!
VS. Static Typing 
If you do the same thing in Slick: 
We get the following error at compile time: 
@beckythebest
Joining: Introducing The Users 
Table 
@beckythebest
Files has a new column: uid 
@beckythebest
Joining with For- 
Comprehensions 
SQL: select * from 
users,files where 
files.uid = users.id 
When invoked (with innerJoinFileUser.run) this 
returns a Collection of tuples with the first item being of 
type User and the second being of type File 
@beckythebest
Where Clauses in For- 
Comprehensions 
 Use filter expressions instead of filters 
 Example: limit to only files owned by Sarah: 
@beckythebest
Slick also has its own Join 
Methods 
We just looked at this query joined with a for-comprehension: 
Same query joined with innerJoin method: 
@beckythebest
The SQL Behind the 
Scenes 
Joined with a for-comprehension 
select x2.`uid`, x2.`name`, x2.`mail`, x2.`status`, 
x3.`id`, x3.`path`, x3.`filetype`, x3.`uid` from 
`users` x2, `files` x3 where x3.`id` = x2.`uid` 
Joined with the innerJoin method 
select x2.x3, x2.x4, x2.x5, x2.x6, x7.x8, x7.x9, 
x7.x10, x7.x11 from (select x12.`id` as x3, x12.`name` 
as x4, x12.`mail` as x5, x12.`status` as x6 from 
`users` x12) x2 inner join (select x13.`id` as x8, 
x13.`path` as x9, x13.`filetype` as x10, x13.`uid` as 
x11 from `files` x13) x7 on x2.x3 = x7.x11 
@beckythebest
Return Anything You Want 
With these for-comprehension use yield to reduce the data 
you want returned 
Instead of yield(u, f) you could have 
 yield(f) 
 yield (u.name, f.path) 
 yield (f.path) 
@beckythebest
Slick Outer Joins 
 You can’t do these with for-comprehensions 
 f.path.? turns values into Options (there might not be 
files for every user) 
 f.? doesn’t work 
* Remember, you can always use plain SQL with Slick 
@beckythebest
Query Compositionality 
Every query does Double 
Duty: 
1. Invoke to get data 
2. Use as a building block for 
another query 
@beckythebest
Create Query Methods 
object Files { 
def byType(filetype: String) = 
files.filter(_.filetype === filetype) 
} 
implicit session => 
Files.byType(“text/html”).list 
Returns a list of HTML File case classes 
@beckythebest
Let’s Look at the SQL Behind 
That 
The method itself is not a Query, but it returns a Query 
scala> filesByType.selectStatement 
ERROR 
scala> filesByType(“pdf").selectStatement 
res3: String = select * from `files` x2 where 
x2.`filetype` = ‘pdf' 
@beckythebest
Composing Queries out of 
Queries 
object Users { 
def userPDFS(email: String) = for { 
u <- users if u.email === email 
f <- Files.byType(“pdf”) if f.uid === 
u.id 
} yield (f) 
} 
@beckythebest
Quick Look at the SQL 
scala> 
userPDFS("sarah@eatingwell.com").selectStatement 
res0: String = select files`id`, files.`path`, 
files.`filetype`, files.`id` from `users`, 
`files` where ((users.`mail` = 
'sarah@eatingwell.com') and (files.`filetype` = 
'application/pdf')) and (files.`uid` = 
users.`id`) 
* There are many more advanced ways 
@beckythebest
Use the Combos in Code 
Now to get all Sarah’s PDFS is a short, clear statement: 
val sarahsPdfs = db withSession { 
implicit session => 
Users.userPDFS(“sarah@eatingwell.com”).list 
} 
sarahsPDFS is now a List of File case classes OR 
continue to build on it further 
@beckythebest
Slick Drawbacks 
Not a lot of documentation for advanced use 
Re-using Slicks collection methods for query building can 
be confusing 
Learning curve (compared to already knowing SQL) (If 
you do) 
Not the most efficient SQL 
@beckythebest
Save Yourselves! 
There is now code generation in Slick! 
You don’t have to write out 65 Table class definitions like I did 
@beckythebest
Summary 
Slick uses Scala’s best features to bring type safety and 
composability to your Relational Database access 
• Static Typing 
• Collection Methods 
• For-Comprehensions 
• Compositionality 
@beckythebest
Resources 
Slick Documentation: http://slick.typesafe.com/doc/2.1.0/ 
Activator’s Hello Slick! http://typesafe.com/activator/template/hello-slick 
Adam Mackler’s Learning Slick V2 
https://mackler.org/LearningSlick2/ 
IRC chat room #scala on Freenode 
Advanced Query Composing: 
http://slick.typesafe.com/talks/2013-12-03_Scala-eXchange/ 
2013-12-03_Patterns-for-Slick-database-applications- 
Scala-eXchange.pdf 
Working around the 22 tuple limit: 
http://stackoverflow.com/questions/20555304/how-can-i-use-the- 
new-slick-2-0-hlist-to-overcome-22-column-limit 
@beckythebest
Thank You 
Questions? 
Rebecca Grenier 
rebeccagrenier@gmail.com 
@beckythebest 
Special Thanks to: Underscore Consulting 
@beckythebest

More Related Content

What's hot

Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
Scott Leberknight
 
Python database access
Python database accessPython database access
Green dao
Green daoGreen dao
Green dao
Droidcon Berlin
 
Discover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQLDiscover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQL
Dave Stokes
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
Colin Su
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
fRui Apps
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
Karwin Software Solutions LLC
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
Jainul Musani
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
Saeid Zebardast
 
greenDAO
greenDAOgreenDAO
greenDAO
Mu Chun Wang
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemy
Roger Barnes
 
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant   SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
Sencha
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
DataStax
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
Knoldus Inc.
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android
哲偉 楊
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET Developers
Ben van Mol
 
Php summary
Php summaryPhp summary
Php summary
Michelle Darling
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
MongoDB
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
MongoDB
 

What's hot (20)

Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Python database access
Python database accessPython database access
Python database access
 
Green dao
Green daoGreen dao
Green dao
 
Discover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQLDiscover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQL
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
greenDAO
greenDAOgreenDAO
greenDAO
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemy
 
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant   SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET Developers
 
Php summary
Php summaryPhp summary
Php summary
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
 

Viewers also liked

Modular programming Using Object in Scala
Modular programming Using Object in ScalaModular programming Using Object in Scala
Modular programming Using Object in Scala
Knoldus Inc.
 
Slick – the modern way to access your Data
Slick – the modern way to access your DataSlick – the modern way to access your Data
Slick – the modern way to access your Data
Jochen Huelss
 
Reactive Database Access With Slick 3
Reactive Database Access With Slick 3Reactive Database Access With Slick 3
Reactive Database Access With Slick 3
Igor Mielientiev
 
Slick - The Structured Way
Slick - The Structured WaySlick - The Structured Way
Slick - The Structured Way
Yennick Trevels
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
Hermann Hueck
 
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
Legacy Typesafe (now Lightbend)
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
takezoe
 
Slick 3.0 functional programming and db side effects
Slick 3.0   functional programming and db side effectsSlick 3.0   functional programming and db side effects
Slick 3.0 functional programming and db side effects
Joost de Vries
 
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
Kazuki Negoro
 

Viewers also liked (9)

Modular programming Using Object in Scala
Modular programming Using Object in ScalaModular programming Using Object in Scala
Modular programming Using Object in Scala
 
Slick – the modern way to access your Data
Slick – the modern way to access your DataSlick – the modern way to access your Data
Slick – the modern way to access your Data
 
Reactive Database Access With Slick 3
Reactive Database Access With Slick 3Reactive Database Access With Slick 3
Reactive Database Access With Slick 3
 
Slick - The Structured Way
Slick - The Structured WaySlick - The Structured Way
Slick - The Structured Way
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
Slick 3.0 functional programming and db side effects
Slick 3.0   functional programming and db side effectsSlick 3.0   functional programming and db side effects
Slick 3.0 functional programming and db side effects
 
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
 

Similar to Slick: Bringing Scala’s Powerful Features to Your Database Access

Scala Slick-2
Scala Slick-2Scala Slick-2
Scala Slick-2
Artem Vlasenko
 
Sql
SqlSql
Data handling in r
Data handling in rData handling in r
Data handling in r
Abhik Seal
 
R data interfaces
R data interfacesR data interfaces
R data interfaces
Bhavesh Sarvaiya
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
natesanp1234
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
Eric Bottard
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
John David Duncan
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
Rsquared Academy
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Cathrine Wilhelmsen
 
SF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDBSF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDB
Peter Hamilton
 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastore
Haris Khan
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
hendrikvb
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
Dr. Ranbijay Kumar
 
Mdst 3559-03-01-sql-php
Mdst 3559-03-01-sql-phpMdst 3559-03-01-sql-php
Mdst 3559-03-01-sql-php
Rafael Alvarado
 
DBIx::Class walkthrough @ bangalore pm
DBIx::Class walkthrough @ bangalore pmDBIx::Class walkthrough @ bangalore pm
DBIx::Class walkthrough @ bangalore pm
Sheeju Alex
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptx
mebratu9
 

Similar to Slick: Bringing Scala’s Powerful Features to Your Database Access (20)

Scala Slick-2
Scala Slick-2Scala Slick-2
Scala Slick-2
 
Sql
SqlSql
Sql
 
Data handling in r
Data handling in rData handling in r
Data handling in r
 
R data interfaces
R data interfacesR data interfaces
R data interfaces
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)
 
SF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDBSF Elixir Meetup - RethinkDB
SF Elixir Meetup - RethinkDB
 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastore
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
 
Mdst 3559-03-01-sql-php
Mdst 3559-03-01-sql-phpMdst 3559-03-01-sql-php
Mdst 3559-03-01-sql-php
 
DBIx::Class walkthrough @ bangalore pm
DBIx::Class walkthrough @ bangalore pmDBIx::Class walkthrough @ bangalore pm
DBIx::Class walkthrough @ bangalore pm
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptx
 

Recently uploaded

Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
christinelarrosa
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
zjhamm304
 
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdfLee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
leebarnesutopia
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's TipsGetting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
ScyllaDB
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
Fwdays
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
UiPathCommunity
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
DianaGray10
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillinQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
LizaNolte
 
AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)
HarpalGohil4
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 

Recently uploaded (20)

Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
 
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdfLee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's TipsGetting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillinQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
 
AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 

Slick: Bringing Scala’s Powerful Features to Your Database Access

  • 1. The Slick Library Rebecca Grenier rebeccagrenier@gmail.com
  • 2. Intro to Slick  Static Typing + Compilation = Type Safety  For-Comprehensions  Compositionality: build complex queries out of simple parts @beckythebest
  • 3. Introduction to Slick @beckythebest
  • 4. Slick Connection Drivers  Oracle ($$$)  DB2 ($$$)  SQL Server ($$$) @beckythebest Note: Connection Pooling is your responsibility  PostgreSQL  MySQL  Access  Derby  H2  Hsqldb  SQLite
  • 5. The Files Table @beckythebest Field Type Null id int (10) unsigned NO uid int (10) unsigned NO path varchar (255) NO filetype varchar (255) NO
  • 6. Table Definitions: Mapping to tuples @beckythebest
  • 7. Table Definitions: Mapping to case classes @beckythebest
  • 8. How the 22-item tuple Limit Affects Slick What if your table has more than 22 columns? Define multiple Table Classes that refer to the same table – similar to “views” * There is a workaround for Scala >= 2.10.3 where you can use HList instead @beckythebest
  • 9. Queries in Slick Every query starts out as a TableQuery first: val files = TableQuery[Files] is the equivalent of select * from files; (You can use .selectStatement on any query to see the SQL for a select statment that is generated behind the scenes) @beckythebest
  • 10. A Quick Full Example val allFiles = db withSession { implicit session => files.run } allFiles is a Vector of File case class objects files is just the query and remains so until it is invoked (with .run) @beckythebest
  • 11. Building Your Query: Adding a Where Clause With .filter files.filter(_.filetype === ‘pdf’) In SQL: select * from files where filetype= ’pdf’ • In Slick, equals is === • Not-Equals is =!= @beckythebest
  • 12. Use Method Chaining to Add More Clauses to Your Query Slick: files.filter(_.filetype === “pdf”).filter(_.id < 20000) SQL: select * from files where filetype= “pdf” and id < 20000 Reminder: You are not really filtering yet; @beckythebest you are building a Query.
  • 13. Query Building with Modifiers from Slick’s DSL  take files.take(5) SQL: select * from files limit 5  Drop files.drop(5) SQL: select * from files offset 5  length files.length SQL: select count(*) from files  map  flatMap  sortBy SQL: sort by @beckythebest
  • 14. Connecting to Your Database in Slick Connect with Database.forURL There is also forDriver, forName, and forDataSource @beckythebest
  • 15. Queries Need Sessions Use that Database Connection to get a Session @beckythebest This is a static session
  • 16. Just Say No to Dynamic Sessions AKA A non-explicit session you hope was opened earlier this thread Dynamic Sessions You can’t count on your thread having a session in an @beckythebest asyncronous world
  • 17. Query Invokers Invoker Returns Vector of results List of results First result or Exception Some(first) or None Nothing files.run files.list files.first files.firstOption files.execute @beckythebest
  • 18. Invoke a Delete Query scala> files.deleteStatement res5: String = delete from `files` invoke with .delete files.delete @beckythebest
  • 19. Just Delete One Record Reduce your query with filter: > files.filter(_.id === 56).deleteStatement res6: String = delete from `files` where `files`.`id` = 56 Invoked: files.filter(_.id === 56).delete @beckythebest
  • 20. Insert Query Invoker scala> files.insertStatement res1: String = insert into `files` (`id`,`path`,`filetype`,`uid`) values (?,?,?,?) invoke with += files += File(0, “path to file”, “type”, 333) @beckythebest
  • 21. Update Query Invoker scala> files.map(_.path).updateStatement res4: String = update `files` set `path` = ? invoke with .update() files.map(_.path).update(“new path to file”) @beckythebest
  • 22. Best Practice: Build your Query Completely BEFORE Invoking The commands below look similar but have very different performance: files.take(5).run SQL: (select * from files limit 5) files.run.take(5) SQL: (select * from files) take 5 @beckythebest
  • 23. What good is all this Typing? Use SQL to query the files table by fid (which is an integer) What happens when a non-integer value gets passed in? @beckythebest No error? No big deal!
  • 24. VS. Static Typing If you do the same thing in Slick: We get the following error at compile time: @beckythebest
  • 25. Joining: Introducing The Users Table @beckythebest
  • 26. Files has a new column: uid @beckythebest
  • 27. Joining with For- Comprehensions SQL: select * from users,files where files.uid = users.id When invoked (with innerJoinFileUser.run) this returns a Collection of tuples with the first item being of type User and the second being of type File @beckythebest
  • 28. Where Clauses in For- Comprehensions  Use filter expressions instead of filters  Example: limit to only files owned by Sarah: @beckythebest
  • 29. Slick also has its own Join Methods We just looked at this query joined with a for-comprehension: Same query joined with innerJoin method: @beckythebest
  • 30. The SQL Behind the Scenes Joined with a for-comprehension select x2.`uid`, x2.`name`, x2.`mail`, x2.`status`, x3.`id`, x3.`path`, x3.`filetype`, x3.`uid` from `users` x2, `files` x3 where x3.`id` = x2.`uid` Joined with the innerJoin method select x2.x3, x2.x4, x2.x5, x2.x6, x7.x8, x7.x9, x7.x10, x7.x11 from (select x12.`id` as x3, x12.`name` as x4, x12.`mail` as x5, x12.`status` as x6 from `users` x12) x2 inner join (select x13.`id` as x8, x13.`path` as x9, x13.`filetype` as x10, x13.`uid` as x11 from `files` x13) x7 on x2.x3 = x7.x11 @beckythebest
  • 31. Return Anything You Want With these for-comprehension use yield to reduce the data you want returned Instead of yield(u, f) you could have  yield(f)  yield (u.name, f.path)  yield (f.path) @beckythebest
  • 32. Slick Outer Joins  You can’t do these with for-comprehensions  f.path.? turns values into Options (there might not be files for every user)  f.? doesn’t work * Remember, you can always use plain SQL with Slick @beckythebest
  • 33. Query Compositionality Every query does Double Duty: 1. Invoke to get data 2. Use as a building block for another query @beckythebest
  • 34. Create Query Methods object Files { def byType(filetype: String) = files.filter(_.filetype === filetype) } implicit session => Files.byType(“text/html”).list Returns a list of HTML File case classes @beckythebest
  • 35. Let’s Look at the SQL Behind That The method itself is not a Query, but it returns a Query scala> filesByType.selectStatement ERROR scala> filesByType(“pdf").selectStatement res3: String = select * from `files` x2 where x2.`filetype` = ‘pdf' @beckythebest
  • 36. Composing Queries out of Queries object Users { def userPDFS(email: String) = for { u <- users if u.email === email f <- Files.byType(“pdf”) if f.uid === u.id } yield (f) } @beckythebest
  • 37. Quick Look at the SQL scala> userPDFS("sarah@eatingwell.com").selectStatement res0: String = select files`id`, files.`path`, files.`filetype`, files.`id` from `users`, `files` where ((users.`mail` = 'sarah@eatingwell.com') and (files.`filetype` = 'application/pdf')) and (files.`uid` = users.`id`) * There are many more advanced ways @beckythebest
  • 38. Use the Combos in Code Now to get all Sarah’s PDFS is a short, clear statement: val sarahsPdfs = db withSession { implicit session => Users.userPDFS(“sarah@eatingwell.com”).list } sarahsPDFS is now a List of File case classes OR continue to build on it further @beckythebest
  • 39. Slick Drawbacks Not a lot of documentation for advanced use Re-using Slicks collection methods for query building can be confusing Learning curve (compared to already knowing SQL) (If you do) Not the most efficient SQL @beckythebest
  • 40. Save Yourselves! There is now code generation in Slick! You don’t have to write out 65 Table class definitions like I did @beckythebest
  • 41. Summary Slick uses Scala’s best features to bring type safety and composability to your Relational Database access • Static Typing • Collection Methods • For-Comprehensions • Compositionality @beckythebest
  • 42. Resources Slick Documentation: http://slick.typesafe.com/doc/2.1.0/ Activator’s Hello Slick! http://typesafe.com/activator/template/hello-slick Adam Mackler’s Learning Slick V2 https://mackler.org/LearningSlick2/ IRC chat room #scala on Freenode Advanced Query Composing: http://slick.typesafe.com/talks/2013-12-03_Scala-eXchange/ 2013-12-03_Patterns-for-Slick-database-applications- Scala-eXchange.pdf Working around the 22 tuple limit: http://stackoverflow.com/questions/20555304/how-can-i-use-the- new-slick-2-0-hlist-to-overcome-22-column-limit @beckythebest
  • 43. Thank You Questions? Rebecca Grenier rebeccagrenier@gmail.com @beckythebest Special Thanks to: Underscore Consulting @beckythebest

Editor's Notes

  1. Should I go over relational databases vs. whatever mongo is
  2. I hope you all know what a tuple is