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

Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopSvetlin Nakov
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Scott Leberknight
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBXESUG
 
ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersKazuhiro Sera
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentationnrjoshiee
 
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 ThingsJustin Edelson
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORPESUG
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtimeDneprCiklumEvents
 
NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)Masaki Oshikawa
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
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 developersJSFestUA
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
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 SQLAlchemyRoger Barnes
 
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 SQLAlchemyInada Naoki
 
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 seriesHolden Karau
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQLjeykottalam
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
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...Inhacking
 
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...Аліна Шепшелей
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
 
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 StreamingDatabricks
 
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 ComputingGerger
 
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-MallaSpark Summit
 
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ādeRaimonds 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 OracleRaimonds Simanovskis
 
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...Michael Rys
 
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 applicationsLudmila Nesvitiy
 
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 MeetupDatabricks
 
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 2018Codemotion
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
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
 

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
 
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...
 
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...
 
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.

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
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 PresentationKnoldus Inc.
 
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 APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

Plus de Knoldus Inc. (20)

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
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Dernier

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Dernier (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

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