SlideShare une entreprise Scribd logo
1  sur  31
Scala Language Integrated Connection
Kit(1.0.1)
Satendra Kumar
Software Consultant
Knoldus Software LLP
Topics Covered
What is Slick
Slick Key Features
Quick Overview
Live Demo
What is Slick
for{e ← Employees} yield e

“select * from employee”

●

Slick is a library written in scala for taking to database from scala programs.

●

It is currently based on Jdbc.

●

It is Successor of ScalaQuery.

●

Developed By Typesafe and EPFL(École Polytechnique Fédérale de Lausanne)
Slick's API
●

Lifted embedding
- The lifted embedding is Slick's stable query API which is based on ScalaQuery.

●

Direct embedding
- The direct embedding is a new experimental API for Slick that uses macros to
allow expressions operating on standard Scala types to be used for database
queries

●

Plain SQL
- Slick also allows you to write your own SQL queries and execute them with an
API which is optimized for Scala, much easier to use and more concise than
JDBC.
Supported Databases
●

PostgreSQL

●

MySQL

●

H2

●

Hsqldb

●

Derby/JavaDB

●

SQL Server

●

SQLite

●

Access

●

Oracle

●

DB2
* All green color database driver are open source
* All yellow color database driver are not open source.( commercially supported by Typesafe)
Slick Key Features
●

Easy

●

Concise

●

Safe

●

Composable

●

Explicit
Easy
●

Access stored data just like Scala collections.
- for{ e ← Emp if( p.age === 25 )} yield e

●

Unified session management based on JDBC Connections
-forURL(url: String, user: String = null, password: String = null, prop:
Properties = null, driver: String = null): Database
- database.withSession{ // put code here }

●

Supports SQL if you need it

●

Simple setup
Concise
●

Slick uses scala syntax.

●

Fetch results without pain
- [jdbc] val sql = "select * from employee where name = ?“
val st = conn.prepareStatement( sql )
try {
st.setString(1, name)
val rs = st.executeQuery()
val b = new ListBuffer[(Int, String)]
while(rs.next)
b.append((rs.getInt(1), rs.getString(2)))
b.toList
} finally st.close()
- [slick]( for( e <- Epmloyees if e.name === name ) yield e).list
Safe
●

No SQL-injections

●

Compile-time safety (types, names, no typos, etc.)
-[jdbc] "select

* from employee wehres nami = ' " + name + " ' "

-[slick]for( e <- Employees if e.name === name ) yield e
●

Type-safe use of stored procedures
val getfeedbackByQuestionId =
SimpleFunction.unary[ Int,String] ("getfeedbackbyquestionid")
Composable
Projects

Employees

*
*
EmpProjects
●

def employeeByJoiningDate( from:Date, to:Date ) = Employees.filter(
emp => emp.joiningDate >= from && emp.joiningDate <= to )
// projects with employee name (joining between 1-1-2013 and 1-10-2013)
for{ emp <- employeeByJoiningDate(1-1-2013, 1-10-2013)
empproject <- EmpProjects if (emp.id === empproject.empId)
project <- Projects if (empproject.projectId === project.id)
} yield (emp.name, project.name, project.location)
Explicit
●

No lazy loading means predictable performance.

●

Only read the data you need.

●

State less
- no caches
Overview
Accessing databases using Slick’s lifted embedding requires the following
steps: 1. Add the dependencies
2. Pick a driver for a particular database
3. Database Connection
- Database object
- Session
5. Describe Database schema
6. Write queries
* In this presentation we are using postgres database.
Dependencies
Add dependencies in your build.sbt
libraryDependencies ++= List(
"com.typesafe.slick" %% "slick" % "1.0.1",
"org.slf4j" % "slf4j-nop" % "1.6.4",
"postgresql" % "postgresql" % "9.1-901.jdbc4"
)

- Slick uses SLF4J for its own debug logging so you also need to add an SLF4J
implementation. Here we are using slf4j-nop to disable logging.

- You have to replace this with a real logging framework like Logback if you want to see
log output
Database drive
Import database drive :
// for postgres database
●

import scala.slick.driver.PostgresDriver.simple._
- Since we are using postgres as our database system, we need to import features from
Slick’s PostgresDriver. A driver’s simple object contains all commonly needed imports
from the driver and other parts of Slick such as session handling.
Database object
Factory methods for creating Database objects:
●

def forDataSource(ds: DataSource): Database
- Create a Database based on a DataSource.

●

def forName(name: String): Database
- Create a Database based on the JNDI name of a DataSource.

●

def forDriver(driver: Driver, url: String, user: String = null, password: String = null,
prop: Properties = null): Database
- Create a Database that directly uses a Driver to open new connections. This is needed to open a

JDBC URL with a driver that was not loaded by the system ClassLoader.
●

def forURL(url: String, user: String = null, password: String = null, prop: Properties
= null, driver: String = null): Database
- Create a Database that uses the DriverManager to open new connections.
Session
A database instance to which connections can be created. Encapsulates either a DataSource
or parameters for DriverManager.getConnection().
Methods for session creation:
def createSession(): Session
- Create a new session. The session needs to be closed explicitly by calling its close()
method.
def withSession[T](f: (Session) ⇒ T): T
- Run the supplied function with a new session and automatically close the session at
the end.
def withTransaction[T](f: (Session) ⇒ T): T
- Run the supplied function with a new session in a transaction and automatically close the
session at the end.
Example
Get database object:
val dbObject = Database.forURL("jdbc:postgresql://localhost:5432/slickdemo", "sky",
"satendra", null, "org.postgresql.Driver")
Get Session:
dbObject.withSession{ implicit session: Session =>
// write query here
}
* End of block session closed automatically.
Database schema structure
Employees

Projects

id integer (primary key)
name varchar(100)
email varchar(100)
designation varchar(100)
doj date

id integer (primary key)
name varchar(100)
location varchar(100)

EmpProjects
empid integer(FKey)
projectid integer(FKey)
primarykey(empid,projectid)
Database schema in slick
For employee table:
case class Emp(id: Int, name: String, email: String, designation: String, doj: Date)
object Employees extends Table[Emp]("emp") {
def id = column[Int]("id", O.PrimaryKey)
def name = column[String]("name", O.NotNull, O.DBType("VARCHAR(100)"))
def email = column[String]("email", O.NotNull, O.DBType("VARCHAR(100)"))
def designation = column[String]("designation", O.NotNull, O DBType ("VARCHAR(100)"))
def doj = column[Date]("doj", O.NotNull)
def * = id ~ name ~ email ~ designation ~ doj <> (Emp.apply _, Emp unapply _)
}
Database schema in slick
For project table:

case class Project(id: Int, name: String, location: String)
object Projects extends Table[Project]("project") {
def id = column[Int]("id", O.PrimaryKey, O.DBType("INT"))
def name = column[String]("name", O.DBType("VARCHAR(100)"))
def location = column[String]("location", O.DBType("VARCHAR(100)"))
def * = id ~ name ~ location <> (Project, Project unapply _)
}
Database schema in slick
●

For empprojects table:
case class EmpProject(empId: Int, projectId: Int)
object EmpProjects extends Table[EmpProject]("emp_project") {
def empId = column[Int]("empid", O.DBType("INT"))
def projectId = column[Int]("projectid", O.DBType("INT"))
def * = empId ~ projectId <> (EmpProject , EmpProject unapply _)
def empFKey = foreignKey("emp_id_fkey", empId, Employees) { employees => employees.id }
def projectFKey = foreignKey("project_id_fkey", projectId, Projects) { projects => projects.id }
def empProjectPKey = primaryKey("emp_project_pkey", (empId, projectId))
}
Supported datatype
●

Numeric types: Byte, Short, Int, Long, BigDecimal, Float, Double

●

LOB types: java.sql.Blob, java.sql.Clob, Array[Byte]

●

Date types: java.sql.Date, java.sql.Time, java.sql.Timestamp

●

Boolean

●

String

●

Unit

●

java.util.UUID

If you need a custom column type you can implement TypeMapper and TypeMapperDelegate. The most
common scenario is mapping an application-specific type to an already supported type in the database.
This can be done much simpler by using a MappedTypeMapper which takes care of all the boilerplate:
def arrayTypeMapped = MappedTypeMapper.base[Array[Int], String](
array => array mkString ",",
str => { if (str != "") { (str split "," map Integer.parseInt) } else { Array() } })
Queries
●

Data Definition Language
-create/drop

●

Data manipulation language
- insert/update/delete
- Sorting and Filtering
- Joins
- Unions
Data Definition Language
Create tables:
dbObject withSession { implicit session: Session =>
val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl
ddl.create
}

Drop tables:
dbObject withSession { implicit session: Session =>
val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl
ddl.drop
}
Insert
●

Insert a row in Employees table:
Employees.insert( Emp(8, "satendra kumar", "satendra@knoldus.com", "consultant", java.sql.Date.valueOf("201306-3")) ) )

●

Insert List of rows in Employees table:
val listOfEmp = List(
Emp(1, "Janmejani", "Janmejani@knoldus.com", "consultant", java.sql.Date.valueOf("2012-11-26")),
Emp(2, "Anand", "anand@knoldus.com", "consultant", java.sql.Date.valueOf("2013-07-01")),
Emp(3, "Rishi Khandelwal ", "rishi@knoldus.com", "consultant", java.sql.Date.valueOf("2012-08-29"))
)
Employees.insertAll( listOfEmp: _*)
Retrieve row
●

Retrieve all rows:
Query(Employees).list
or
(for(emp <-Employees)yield(emp)).list

●

Retrieve all rows with only two columns(name and joning date):
( for(emp <-Employees) yield (emp.name, emp.doj) ).list
or
(Employees map {emp =>( emp.name,emp.doj)}).list
Update/Delete
●

Update name of employee (where employee id is 8):
val query = for (emp <- Employees if emp.id === 8) yield (emp.name)
query.update("satendra")

●

Delete employee (where employee id is 8 ):
val query = for (emp <- Employees if emp.id === 8) yield (emp)
query.delete

●

Delete all employee:
val query = for (emp <- Employees) yield (emp)
query.delete
Sorting and Filtering
●

Sort employee list by id:
(for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list

reverse sorting
(for (emp <- Employees) yield (emp)).sortBy(emp => emp.id.desc).list

●

Sort employee list by joining date:
(for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list

●

Filter employees which have joining date between 2013-07-10 and 2012-11-2:
Employees.filter{emp => (emp.doj <= Date.valueOf("2013-07-10") &&
Date.valueOf("2012-11-26")) }.list

emp.doj >=
Joins
●

Employee with project name and project location:
(for {
emp <- Employees
empproject <- EmpProjects if emp.id === empproject.empId
project <- Projects if (empproject.projectId === project.id)
} yield (emp.name, project.name,project.location)).list
Union
val query1 = Employees.filter { emp => emp.id === 8 }
val query2 = Employees.filter { emp => emp.id ===2}
(query1 union query2).list
Thanks

Contenu connexe

Tendances

Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
Kat Roque
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
DneprCiklumEvents
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 

Tendances (20)

Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache Hadoop
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Linq
LinqLinq
Linq
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBX
 
ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for Beginners
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the Things
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORP
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
Lobos Introduction
Lobos IntroductionLobos Introduction
Lobos Introduction
 
NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
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
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 

Similaire à Slickdemo

PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
Inada Naoki
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrāde
Raimonds Simanovskis
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 

Similaire à Slickdemo (20)

PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesIntroducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Real-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to StreamingReal-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to Streaming
 
Apache Spark Workshop
Apache Spark WorkshopApache Spark Workshop
Apache Spark Workshop
 
Apache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster ComputingApache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster Computing
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrāde
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
 
Jdbc
JdbcJdbc
Jdbc
 
Spark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark MeetupSpark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark Meetup
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
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
 

Plus de Knoldus Inc.

Plus de Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Slickdemo

  • 1. Scala Language Integrated Connection Kit(1.0.1) Satendra Kumar Software Consultant Knoldus Software LLP
  • 2. Topics Covered What is Slick Slick Key Features Quick Overview Live Demo
  • 3. What is Slick for{e ← Employees} yield e “select * from employee” ● Slick is a library written in scala for taking to database from scala programs. ● It is currently based on Jdbc. ● It is Successor of ScalaQuery. ● Developed By Typesafe and EPFL(École Polytechnique Fédérale de Lausanne)
  • 4. Slick's API ● Lifted embedding - The lifted embedding is Slick's stable query API which is based on ScalaQuery. ● Direct embedding - The direct embedding is a new experimental API for Slick that uses macros to allow expressions operating on standard Scala types to be used for database queries ● Plain SQL - Slick also allows you to write your own SQL queries and execute them with an API which is optimized for Scala, much easier to use and more concise than JDBC.
  • 5. Supported Databases ● PostgreSQL ● MySQL ● H2 ● Hsqldb ● Derby/JavaDB ● SQL Server ● SQLite ● Access ● Oracle ● DB2 * All green color database driver are open source * All yellow color database driver are not open source.( commercially supported by Typesafe)
  • 7. Easy ● Access stored data just like Scala collections. - for{ e ← Emp if( p.age === 25 )} yield e ● Unified session management based on JDBC Connections -forURL(url: String, user: String = null, password: String = null, prop: Properties = null, driver: String = null): Database - database.withSession{ // put code here } ● Supports SQL if you need it ● Simple setup
  • 8. Concise ● Slick uses scala syntax. ● Fetch results without pain - [jdbc] val sql = "select * from employee where name = ?“ val st = conn.prepareStatement( sql ) try { st.setString(1, name) val rs = st.executeQuery() val b = new ListBuffer[(Int, String)] while(rs.next) b.append((rs.getInt(1), rs.getString(2))) b.toList } finally st.close() - [slick]( for( e <- Epmloyees if e.name === name ) yield e).list
  • 9. Safe ● No SQL-injections ● Compile-time safety (types, names, no typos, etc.) -[jdbc] "select * from employee wehres nami = ' " + name + " ' " -[slick]for( e <- Employees if e.name === name ) yield e ● Type-safe use of stored procedures val getfeedbackByQuestionId = SimpleFunction.unary[ Int,String] ("getfeedbackbyquestionid")
  • 10. Composable Projects Employees * * EmpProjects ● def employeeByJoiningDate( from:Date, to:Date ) = Employees.filter( emp => emp.joiningDate >= from && emp.joiningDate <= to ) // projects with employee name (joining between 1-1-2013 and 1-10-2013) for{ emp <- employeeByJoiningDate(1-1-2013, 1-10-2013) empproject <- EmpProjects if (emp.id === empproject.empId) project <- Projects if (empproject.projectId === project.id) } yield (emp.name, project.name, project.location)
  • 11. Explicit ● No lazy loading means predictable performance. ● Only read the data you need. ● State less - no caches
  • 12. Overview Accessing databases using Slick’s lifted embedding requires the following steps: 1. Add the dependencies 2. Pick a driver for a particular database 3. Database Connection - Database object - Session 5. Describe Database schema 6. Write queries * In this presentation we are using postgres database.
  • 13. Dependencies Add dependencies in your build.sbt libraryDependencies ++= List( "com.typesafe.slick" %% "slick" % "1.0.1", "org.slf4j" % "slf4j-nop" % "1.6.4", "postgresql" % "postgresql" % "9.1-901.jdbc4" ) - Slick uses SLF4J for its own debug logging so you also need to add an SLF4J implementation. Here we are using slf4j-nop to disable logging. - You have to replace this with a real logging framework like Logback if you want to see log output
  • 14. Database drive Import database drive : // for postgres database ● import scala.slick.driver.PostgresDriver.simple._ - Since we are using postgres as our database system, we need to import features from Slick’s PostgresDriver. A driver’s simple object contains all commonly needed imports from the driver and other parts of Slick such as session handling.
  • 15. Database object Factory methods for creating Database objects: ● def forDataSource(ds: DataSource): Database - Create a Database based on a DataSource. ● def forName(name: String): Database - Create a Database based on the JNDI name of a DataSource. ● def forDriver(driver: Driver, url: String, user: String = null, password: String = null, prop: Properties = null): Database - Create a Database that directly uses a Driver to open new connections. This is needed to open a JDBC URL with a driver that was not loaded by the system ClassLoader. ● def forURL(url: String, user: String = null, password: String = null, prop: Properties = null, driver: String = null): Database - Create a Database that uses the DriverManager to open new connections.
  • 16. Session A database instance to which connections can be created. Encapsulates either a DataSource or parameters for DriverManager.getConnection(). Methods for session creation: def createSession(): Session - Create a new session. The session needs to be closed explicitly by calling its close() method. def withSession[T](f: (Session) ⇒ T): T - Run the supplied function with a new session and automatically close the session at the end. def withTransaction[T](f: (Session) ⇒ T): T - Run the supplied function with a new session in a transaction and automatically close the session at the end.
  • 17. Example Get database object: val dbObject = Database.forURL("jdbc:postgresql://localhost:5432/slickdemo", "sky", "satendra", null, "org.postgresql.Driver") Get Session: dbObject.withSession{ implicit session: Session => // write query here } * End of block session closed automatically.
  • 18. Database schema structure Employees Projects id integer (primary key) name varchar(100) email varchar(100) designation varchar(100) doj date id integer (primary key) name varchar(100) location varchar(100) EmpProjects empid integer(FKey) projectid integer(FKey) primarykey(empid,projectid)
  • 19. Database schema in slick For employee table: case class Emp(id: Int, name: String, email: String, designation: String, doj: Date) object Employees extends Table[Emp]("emp") { def id = column[Int]("id", O.PrimaryKey) def name = column[String]("name", O.NotNull, O.DBType("VARCHAR(100)")) def email = column[String]("email", O.NotNull, O.DBType("VARCHAR(100)")) def designation = column[String]("designation", O.NotNull, O DBType ("VARCHAR(100)")) def doj = column[Date]("doj", O.NotNull) def * = id ~ name ~ email ~ designation ~ doj <> (Emp.apply _, Emp unapply _) }
  • 20. Database schema in slick For project table: case class Project(id: Int, name: String, location: String) object Projects extends Table[Project]("project") { def id = column[Int]("id", O.PrimaryKey, O.DBType("INT")) def name = column[String]("name", O.DBType("VARCHAR(100)")) def location = column[String]("location", O.DBType("VARCHAR(100)")) def * = id ~ name ~ location <> (Project, Project unapply _) }
  • 21. Database schema in slick ● For empprojects table: case class EmpProject(empId: Int, projectId: Int) object EmpProjects extends Table[EmpProject]("emp_project") { def empId = column[Int]("empid", O.DBType("INT")) def projectId = column[Int]("projectid", O.DBType("INT")) def * = empId ~ projectId <> (EmpProject , EmpProject unapply _) def empFKey = foreignKey("emp_id_fkey", empId, Employees) { employees => employees.id } def projectFKey = foreignKey("project_id_fkey", projectId, Projects) { projects => projects.id } def empProjectPKey = primaryKey("emp_project_pkey", (empId, projectId)) }
  • 22. Supported datatype ● Numeric types: Byte, Short, Int, Long, BigDecimal, Float, Double ● LOB types: java.sql.Blob, java.sql.Clob, Array[Byte] ● Date types: java.sql.Date, java.sql.Time, java.sql.Timestamp ● Boolean ● String ● Unit ● java.util.UUID If you need a custom column type you can implement TypeMapper and TypeMapperDelegate. The most common scenario is mapping an application-specific type to an already supported type in the database. This can be done much simpler by using a MappedTypeMapper which takes care of all the boilerplate: def arrayTypeMapped = MappedTypeMapper.base[Array[Int], String]( array => array mkString ",", str => { if (str != "") { (str split "," map Integer.parseInt) } else { Array() } })
  • 23. Queries ● Data Definition Language -create/drop ● Data manipulation language - insert/update/delete - Sorting and Filtering - Joins - Unions
  • 24. Data Definition Language Create tables: dbObject withSession { implicit session: Session => val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl ddl.create } Drop tables: dbObject withSession { implicit session: Session => val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl ddl.drop }
  • 25. Insert ● Insert a row in Employees table: Employees.insert( Emp(8, "satendra kumar", "satendra@knoldus.com", "consultant", java.sql.Date.valueOf("201306-3")) ) ) ● Insert List of rows in Employees table: val listOfEmp = List( Emp(1, "Janmejani", "Janmejani@knoldus.com", "consultant", java.sql.Date.valueOf("2012-11-26")), Emp(2, "Anand", "anand@knoldus.com", "consultant", java.sql.Date.valueOf("2013-07-01")), Emp(3, "Rishi Khandelwal ", "rishi@knoldus.com", "consultant", java.sql.Date.valueOf("2012-08-29")) ) Employees.insertAll( listOfEmp: _*)
  • 26. Retrieve row ● Retrieve all rows: Query(Employees).list or (for(emp <-Employees)yield(emp)).list ● Retrieve all rows with only two columns(name and joning date): ( for(emp <-Employees) yield (emp.name, emp.doj) ).list or (Employees map {emp =>( emp.name,emp.doj)}).list
  • 27. Update/Delete ● Update name of employee (where employee id is 8): val query = for (emp <- Employees if emp.id === 8) yield (emp.name) query.update("satendra") ● Delete employee (where employee id is 8 ): val query = for (emp <- Employees if emp.id === 8) yield (emp) query.delete ● Delete all employee: val query = for (emp <- Employees) yield (emp) query.delete
  • 28. Sorting and Filtering ● Sort employee list by id: (for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list reverse sorting (for (emp <- Employees) yield (emp)).sortBy(emp => emp.id.desc).list ● Sort employee list by joining date: (for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list ● Filter employees which have joining date between 2013-07-10 and 2012-11-2: Employees.filter{emp => (emp.doj <= Date.valueOf("2013-07-10") && Date.valueOf("2012-11-26")) }.list emp.doj >=
  • 29. Joins ● Employee with project name and project location: (for { emp <- Employees empproject <- EmpProjects if emp.id === empproject.empId project <- Projects if (empproject.projectId === project.id) } yield (emp.name, project.name,project.location)).list
  • 30. Union val query1 = Employees.filter { emp => emp.id === 8 } val query2 = Employees.filter { emp => emp.id ===2} (query1 union query2).list