SlideShare uma empresa Scribd logo
1 de 43
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
@beckythebest
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)
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
@beckythebest
With .filter
files.filter(_.filetype === ‘pdf’)
In SQL: select * from files where
filetype= ’pdf’
• In Slick, equals is ===
• Not-Equals is =!=
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
@beckythebest
Reminder: You are not really filtering
yet;
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
@beckythebest
Connect with Database.forURL
There is also forDriver, forName, and forDataSource
Queries Need Sessions
Use that Database Connection to get a
Session
@beckythebest
This is a static
session
Just Say No to
@beckythebest
AKA A non-explicit session you hope was opened earlier this
thread
You can’t count on your thread having a session in an
asyncronous world
Dynamic
Sessions
Dynamic Sessions
Query Invokers
Vector of results
List of results
First result or Exception
Some(first) or None
Nothing
@beckythebest
files.run
files.list
files.first
files.firstOption
files.execute
Invoker Returns
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?
@beckythebest
No error?
No big deal!
Use SQL to query the files table by fid (which is an integer)
What happens when a non-integer value gets passed in?
VS. Static Typing
@beckythebest
We get the following error at compile time:
If you do the same thing in Slick:
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
@beckythebest
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
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:
@beckythebest
Same query joined with innerJoin method:
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
@beckythebest
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)
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
@beckythebest
* Remember, you can always use plain SQL with Slick
Query Compositionality
@beckythebest
Every query does Double
Duty:
1. Invoke to get data
2. Use as a building block for
another query
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`)
@beckythebest
* There are many more advanced ways
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

Mais conteúdo relacionado

Mais procurados

ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 
Web scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabsWeb scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabszekeLabs Technologies
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring DataEric Bottard
 
Hacking Lucene for Custom Search Results
Hacking Lucene for Custom Search ResultsHacking Lucene for Custom Search Results
Hacking Lucene for Custom Search ResultsOpenSource Connections
 
Simple.Data intro slides
Simple.Data intro slidesSimple.Data intro slides
Simple.Data intro slidesMark Rendle
 
ملخص تقنية تصميم صفحات الويب - الوحدة السادسة
ملخص تقنية تصميم صفحات الويب - الوحدة السادسةملخص تقنية تصميم صفحات الويب - الوحدة السادسة
ملخص تقنية تصميم صفحات الويب - الوحدة السادسةجامعة القدس المفتوحة
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the ContextRussell Castagnaro
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputuanna
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Hidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard LibraryHidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard Librarydoughellmann
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingChema Alonso
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1ashishspace
 
ObjectBox - The new Mobile Database
ObjectBox - The new Mobile DatabaseObjectBox - The new Mobile Database
ObjectBox - The new Mobile Databasegreenrobot
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wildBrainhub
 

Mais procurados (20)

ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
Web scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabsWeb scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabs
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
 
Hacking Lucene for Custom Search Results
Hacking Lucene for Custom Search ResultsHacking Lucene for Custom Search Results
Hacking Lucene for Custom Search Results
 
Simple.Data intro slides
Simple.Data intro slidesSimple.Data intro slides
Simple.Data intro slides
 
JSON
JSONJSON
JSON
 
ملخص تقنية تصميم صفحات الويب - الوحدة السادسة
ملخص تقنية تصميم صفحات الويب - الوحدة السادسةملخص تقنية تصميم صفحات الويب - الوحدة السادسة
ملخص تقنية تصميم صفحات الويب - الوحدة السادسة
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
Lucene basics
Lucene basicsLucene basics
Lucene basics
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple input
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Hidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard LibraryHidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard Library
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File Downloading
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
ObjectBox - The new Mobile Database
ObjectBox - The new Mobile DatabaseObjectBox - The new Mobile Database
ObjectBox - The new Mobile Database
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
History
HistoryHistory
History
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
 

Destaque (19)

Observaciones foro Universidad del Azuay COA
Observaciones foro Universidad del Azuay COAObservaciones foro Universidad del Azuay COA
Observaciones foro Universidad del Azuay COA
 
Tallerpractico 10 grupo 5-subgrupo 3
Tallerpractico 10  grupo 5-subgrupo 3Tallerpractico 10  grupo 5-subgrupo 3
Tallerpractico 10 grupo 5-subgrupo 3
 
彼得前書第一章
彼得前書第一章彼得前書第一章
彼得前書第一章
 
Breaking the mould of human anatomical understanding
Breaking the mould of human anatomical understandingBreaking the mould of human anatomical understanding
Breaking the mould of human anatomical understanding
 
8051 presentation
8051 presentation8051 presentation
8051 presentation
 
Cati
CatiCati
Cati
 
ADT - TBWAYoungBucs 2013 - Strategic recommendation
ADT - TBWAYoungBucs 2013 - Strategic recommendationADT - TBWAYoungBucs 2013 - Strategic recommendation
ADT - TBWAYoungBucs 2013 - Strategic recommendation
 
Fichas de mat 1º ano
Fichas de mat  1º anoFichas de mat  1º ano
Fichas de mat 1º ano
 
Compras hipermercado2
Compras hipermercado2Compras hipermercado2
Compras hipermercado2
 
P.i.p
P.i.pP.i.p
P.i.p
 
Noite cultural 25 11
Noite cultural 25 11Noite cultural 25 11
Noite cultural 25 11
 
Tirolinas
TirolinasTirolinas
Tirolinas
 
Proposta de intervenção pedagógica - PIP - Cristiano Lage
Proposta de intervenção pedagógica - PIP - Cristiano LageProposta de intervenção pedagógica - PIP - Cristiano Lage
Proposta de intervenção pedagógica - PIP - Cristiano Lage
 
Projeto Minha Família e Eu
Projeto Minha Família e EuProjeto Minha Família e Eu
Projeto Minha Família e Eu
 
Power Point: Islam
Power Point: IslamPower Point: Islam
Power Point: Islam
 
Projeto: Páscoa
Projeto: PáscoaProjeto: Páscoa
Projeto: Páscoa
 
Projeto de Intervenção
Projeto de IntervençãoProjeto de Intervenção
Projeto de Intervenção
 
Exceptional Service, Exceptional Profit
Exceptional Service, Exceptional ProfitExceptional Service, Exceptional Profit
Exceptional Service, Exceptional Profit
 
Cira d zone overview risq-fr
Cira d zone overview risq-frCira d zone overview risq-fr
Cira d zone overview risq-fr
 

Semelhante a Scala Slick-2

Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
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 JonesJohn David Duncan
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRsquared Academy
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptxnatesanp1234
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
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 RetrievalDr. Ranbijay Kumar
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfAbhishekKumarPandit5
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Nuxeo
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptxmebratu9
 

Semelhante a Scala Slick-2 (20)

Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
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
 
Sql
SqlSql
Sql
 
La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
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
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Local Storage
Local StorageLocal Storage
Local Storage
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
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
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptx
 
MongoDB-presentation.pptx
MongoDB-presentation.pptxMongoDB-presentation.pptx
MongoDB-presentation.pptx
 

Último

The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 

Último (20)

The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 

Scala Slick-2

  • 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
  • 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 @beckythebest 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)
  • 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 @beckythebest With .filter files.filter(_.filetype === ‘pdf’) In SQL: select * from files where filetype= ’pdf’ • In Slick, equals is === • Not-Equals is =!=
  • 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 @beckythebest Reminder: You are not really filtering yet; 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 @beckythebest Connect with Database.forURL There is also forDriver, forName, and forDataSource
  • 15. Queries Need Sessions Use that Database Connection to get a Session @beckythebest This is a static session
  • 16. Just Say No to @beckythebest AKA A non-explicit session you hope was opened earlier this thread You can’t count on your thread having a session in an asyncronous world Dynamic Sessions Dynamic Sessions
  • 17. Query Invokers Vector of results List of results First result or Exception Some(first) or None Nothing @beckythebest files.run files.list files.first files.firstOption files.execute Invoker Returns
  • 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? @beckythebest No error? No big deal! Use SQL to query the files table by fid (which is an integer) What happens when a non-integer value gets passed in?
  • 24. VS. Static Typing @beckythebest We get the following error at compile time: If you do the same thing in Slick:
  • 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 @beckythebest 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
  • 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: @beckythebest Same query joined with innerJoin method:
  • 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 @beckythebest 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)
  • 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 @beckythebest * Remember, you can always use plain SQL with Slick
  • 33. Query Compositionality @beckythebest Every query does Double Duty: 1. Invoke to get data 2. Use as a building block for another query
  • 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`) @beckythebest * There are many more advanced ways
  • 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

Notas do Editor

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