FUNCTIONAL RELATIONAL MAPPING WITH SLICK

Similar documents
Using Relational Databases With ScalaQuery. Stefan Zeiger

An Introduction to DBIx::Class. Tom Hukins

Noun-Verb Decomposition

Data Types for Data Science

Database Systems CSE 414. Lecture 7: SQL Wrap-up

Environmental Monitoring for Optimized Production in Wineries

An Introduction of Interator Pattern with Ruby

Software engineering process. Literature on UML. Modeling as a Design Technique. Use-case modelling. UML - Unified Modeling Language

Yelp Chanllenge. Tianshu Fan Xinhang Shao University of Washington. June 7, 2013

Semantic Web. Ontology Engineering. Gerd Gröner, Matthias Thimm. Institute for Web Science and Technologies (WeST) University of Koblenz-Landau

NVIVO 10 WORKSHOP. Hui Bian Office for Faculty Excellence BY HUI BIAN

Barista at a Glance BASIS International Ltd.

Annis on MonetDB. Viktor Rosenfeld 14. January Advisors: Prof. Dr. Ulf Leser and Dr.

The Dun & Bradstreet Asia Match Environment. AME FAQ. Warwick R Matthews

The Future of the Still & Sparkling Wine Market in Poland to 2019

THE STEEL DETAILER SolidWorks 2016 INSTALLATION PROCEDURE

Why PAM Works. An In-Depth Look at Scoring Matrices and Algorithms. Michael Darling Nazareth College. The Origin: Sequence Alignment

STUDY REGARDING THE RATIONALE OF COFFEE CONSUMPTION ACCORDING TO GENDER AND AGE GROUPS

THE STEEL DETAILER SolidWorks 2015 INSTALLATION PROCEDURE

TEST PROJECT. Server Side B. Submitted by: WorldSkills International Manuel Schaffner CH. Competition Time: 3 hours. Assessment Browser: Google Chrome

Cafeteria Ordering System, Release 1.0

Heinz Soup Quality and Safety

The Future of the Ice Cream Market in Finland to 2018

VIII. Claim Drafting Methodologies. Becky White

Tamanend Wine Consulting

TEAM BUILDING ACTIVITIES IN THE ARDENNES

Why Nescafé Dolce Gusto?

The aim of the thesis is to determine the economic efficiency of production factors utilization in S.C. AGROINDUSTRIALA BUCIUM S.A.

Restaurant reservation system thesis documentation. Restaurant reservation system thesis documentation.zip

CORN O.Y. COUNT AND HARVEST INSTRUCTIONS

Jura ENA Brew Group Replacement. Parts Guru

SCI-5 MES- Lamb Variables, measurement and scientific method Exam not valid for Paper Pencil Test Sessions

A Framework for Processes Submission and Monitoring from Mobile Devices to Grid Configurations Utilizing Resource Matching

Esri Demographic Data Release Notes: Israel

CALIFORNIA MASTER FRANCHISOR DIGITAL PRESS KIT

Virginia Western Community College HRI 225 Menu Planning & Dining Room Service

Pizza Ontology. a review of core concepts for building a pizza ontology

Difference Cordial Labeling of Graphs Obtained from Triangular Snakes

Wine in Moderation. ImplementatIon GuIde for WInerIes

Azoth. Azoth Uses RIZE AM to Transform Supply Chain From Order On Demand to Make On Demand. Fastest Time to Fabricated Part CHALLENGES

FOR PERSONAL USE. Capacity BROWARD COUNTY ELEMENTARY SCIENCE BENCHMARK PLAN ACTIVITY ASSESSMENT OPPORTUNITIES. Grade 3 Quarter 1 Activity 2

Barista Document Output Object

LM-80 Data. Results from Curve Desk Lamp Lumen Maintenance Testing And Use Of IES LM Data

Predicting Wine Quality

Dum Ka Biryani, Make for each other

Cut Rite V9 MDF Door Library

Effects of Drying and Tempering Rice Using a Continuous Drying Procedure 1

Table of Contents. Toast Inc. 2

INSTALLATION AND WARRANTY CERTIFICATE. Machine model Serial Number # Rating and optional. Installation Company: Technician ID: Date: / /

Menus of Change General Session 3 Changing Consumer Behaviors and Attitudes

Compiler. --- Lexical Analysis: Principle&Implementation. Zhang Zhizheng.

Geographic Information Systemystem

Integration of RFID Technology for Tracking our Fleet of Kegs. Presented By: Jordan Kivelstadt, Managing Partner

GLOSSARY Last Updated: 10/17/ KL. Terms and Definitions

CAFFE. CAPPUCCINO. AUTOCAPPUCCINO!

The Austin Coffee Shop: Schema for a Functional Space. Schema Creation Project: Organizing Information Sandra Sweat.

Creating an Interactive Network for Wine-cultivation

CREATING. School. ood RESTAURANTS. Major City Directors Session Successful Marketing Strategies. D. Berkowitz

Statewide Monthly Participation for Asian Non-Hispanic by Cultural Identities, Months of Prenatal Participation & Breastfeeding Amount

Texas Tech University

Somchai Rice 1, Jacek A. Koziel 1, Anne Fennell 2 1

The British Pub What Does the Future Hold?

Inventory of the Bern C. Ramey Papers, No online items

Online Appendix to. Are Two heads Better Than One: Team versus Individual Play in Signaling Games. David C. Cooper and John H.

Internet Appendix. For. Birds of a feather: Value implications of political alignment between top management and directors

SAP Fiori UX Design and Build Assignment SOMMELIER

Special Events Catering Menu

Introduction to Management Science Midterm Exam October 29, 2002

Given a realistic scenario depicting a new site install, the learner will be able to install and setup the brewer for retail turnover without error.

CONSEQUENCES OF THE BPR

Title: Farmers Growing Connections (anytime in the year)

Shaping the Future: Production and Market Challenges

We will assign duties depending on your comfort level and background. In exchange for a shift, Volunteers will receive:

Added ID100 Beer Tub Mist Twst 5 22 Main Cabin Food for Sale 5/1/ Main Cabin Empty 5/1/ Main Cabin Refuse 5/1/16

Coffee and Tea Dispensing

CARL S JR RESTAURANT NNN INVESTMENT

TRTP and TRTA in BDS Application per CDISC ADaM Standards Maggie Ci Jiang, Teva Pharmaceuticals, West Chester, PA

4/10/17. Announcements. Database Systems CSE 414. Examples of Complex Queries. Recap from last lecture. Example 1. Example 1

EN Electric Coffee Grinder

SPATIAL ANALYSIS OF WINERY CONTAMINATION

THE MEAT PRODUCTS REGULATIONS 2003 SUMMARY GUIDANCE NOTES

PRODUCTION SOFTWARE FOR WINEMAKERS. Wine Operations and Laboratory Analyses

From Code to Confectionary

Allergen Control for Dietary Supplements

MULTIBRANDING GREAT BRANDS. Dave Deno Chief Financial Officer & Chief Operating Officer

The wine industry. a model for climate change attribution and adaptation studies. Professor Snow Barlow, ATSE,FAIAST

Room: Mainau / Reichenau (1. floor, over ALLWEILER entrance)

COMSTRAT 310 Semester-Long Project Part Three

10. THE ROLE OF PLANT GROWTH REGULATORS IN THE DEVELOPMENT, GROWTH AND MATURATION OF THE FRUIT

Big Data and the Productivity Challenge for Wine Grapes. Nick Dokoozlian Agricultural Outlook Forum February

Case Study. Café Coffee Day. Cafe Coffee Day a unique proposition for Experiential Marketing for the. Automobile Industry

The Function of English on the Spread of Chinese Tea Culture under the Background of Cross-Border E-Commerce

Prehistory Overview & Study Guide

REMARKS BY PAUL BULCKE, GROUP CHIEF EXECUTIVE OFFICER, NESTLÉ S.A. MEDIA CONFERENCE, NAIROBI, FRIDAY, JULY 2, 2010

[Billing Code: U] [Docket No. TTB ; T.D. TTB 112; Ref: Notice No. 127] Amendment to the Standards of Identity for Distilled Spirits

TEST SUMMARY HIGH SPEED DOCKING CONNECTOR. Table of Contents

INDEPENDENT, TRADITIONAL, AND INNOVATIVE Flottweg Separators for Craft Breweries

Partnership Opportunities for Private Liquor Retail Stores in BC

Missing value imputation in SAS: an intro to Proc MI and MIANALYZE

Word Embeddings for NLP in Python. Marco Bonzanini PyCon Italia 2017

Transcription:

Platinum Sponsor FUNCTIONAL RELATIONAL MAPPING WITH SLICK Stefan Zeiger, Typesafe

Object Relational Mapping

Object Relational

Object Impedance Mismatch Relational

Concepts Object-Oriented Identity State Behavior Encapsulation Relational No Identity Transactional State No Behavior No Encapsulation Func%onal Rela%onal Mapping with Slick 5

Execution Colombian French_Roast Espresso Colombian_Decaf French_Roast_Decaf Espresso Price: 9.99 Supplier: The High Ground select NAME from COFFEES select c.name, c.price, s.name from COFFEES c join SUPPLIERS s on c.sup_id = s.sup_id where c.name =? Func%onal Rela%onal Mapping with Slick 6

Execution Colombian French_Roast Espresso 7.99 8.99 9.99 Colombian_Decaf French_Roast_Decaf 8.99 9.99 def getallcoffees(): Seq[Coffee] = def printlinks(s: Seq[Coffee]) { for(c <- s) println(c.name) + c.price) } Func%onal Rela%onal Mapping with Slick 7

Execution Colombian French_Roast Espresso Colombian_Decaf French_Roast_Decaf Espresso Price: 9.99 Supplier: The High Ground def printdetails(c: Coffee) { println(c.name) println("price: " + c.price) println("supplier: " + c.supplier.name) } Func%onal Rela%onal Mapping with Slick 8

Level of Abstraction Object Oriented Relational Data Organization High Low Data Flow Low High Func%onal Rela%onal Mapping with Slick 9

Functional Relational Mapping

Relational Model Relation Attribute Tuple NAME : String COFFEES PRICE : Double SUP_ID : Int Relation Value Colombian 7.99 101 Relation Variable French_ Roast 8.99 49 Espresso 9.99 150 Func%onal Rela%onal Mapping with Slick 11

Relational Model Relation Attribute Tuple NAME : String COFFEES PRICE : Double SUP_ID : Int Relation Value Colombian 7.99 101 Relation Variable French_ Roast 8.99 49 Espresso 9.99 150 Func%onal Rela%onal Mapping with Slick 12

Relational Model Relation Attribute Tuple NAME : String COFFEES PRICE : Double SUP_ID : Int Relation Value Colombian 7.99 101 Relation Variable French_ Roast 8.99 49 Espresso 9.99 150 Func%onal Rela%onal Mapping with Slick 13

Relational Model Relation Attribute Tuple NAME : String COFFEES PRICE : Double SUP_ID : Int Relation Value Colombian 7.99 101 Relation Variable French_ Roast 8.99 49 Espresso 9.99 150 Func%onal Rela%onal Mapping with Slick 14

Relational Model Relation Attribute Tuple NAME : String COFFEES PRICE : Double SUP_ID : Int Relation Value Colombian 7.99 101 Relation Variable French_ Roast 8.99 49 Espresso 9.99 150 Func%onal Rela%onal Mapping with Slick 15

Relational Model Relation Attribute Tuple NAME : String COFFEES PRICE : Double SUP_ID : Int Relation Value Colombian 7.99 101 Relation Variable French_ Roast 8.99 49 Espresso 9.99 150 Func%onal Rela%onal Mapping with Slick 16

Mapped to Scala Relation Attribute Tuple Relation Value Relation Variable case class Coffee( name: String, supplierid: Int, price: Double ) val coffees = Set( Coffee("Colombian", 101, 7.99), Coffee("French_Roast", 49, 8.99), Coffee("Espresso", 150, 9.99) ) Func%onal Rela%onal Mapping with Slick 17

Mapped to Scala Relation Attribute Tuple Relation Value Relation Variable case class Coffee( name: String, supplierid: Int, price: Double ) val coffees = Set( Coffee("Colombian", 101, 7.99), Coffee("French_Roast", 49, 8.99), Coffee("Espresso", 150, 9.99) ) Func%onal Rela%onal Mapping with Slick 18

Mapped to Scala Relation Attribute Tuple Relation Value Relation Variable case class Coffee( name: String, supplierid: Int, price: Double ) val coffees = Set( Coffee("Colombian", 101, 7.99), Coffee("French_Roast", 49, 8.99), Coffee("Espresso", 150, 9.99) ) Func%onal Rela%onal Mapping with Slick 19

Mapped to Scala Relation Attribute Tuple Relation Value Relation Variable case class Coffee( name: String, supplierid: Int, price: Double ) val coffees = Set( Coffee("Colombian", 101, 7.99), Coffee("French_Roast", 49, 8.99), Coffee("Espresso", 150, 9.99) ) Func%onal Rela%onal Mapping with Slick 20

Mapped to Scala Relation Attribute Tuple Relation Value Relation Variable case class Coffee( name: String, supplierid: Int, price: Double ) val coffees = Set( Coffee("Colombian", 101, 7.99), Coffee("French_Roast", 49, 8.99), Coffee("Espresso", 150, 9.99) ) Func%onal Rela%onal Mapping with Slick 21

Mapped to Scala Relation Attribute Tuple Relation Value Relation Variable case class Coffee( name: String, supplierid: Int, price: Double ) val coffees = Set( Coffee("Colombian", 101, 7.99), Coffee("French_Roast", 49, 8.99), Coffee("Espresso", 150, 9.99) ) Func%onal Rela%onal Mapping with Slick 22

Write Database Code in Scala for { p <- persons } yield p.name select p.name from PERSON p Func%onal Rela%onal Mapping with Slick 23

(for { p <- persons.filter(_.age < 20) ++ persons.filter(_.age >= 50) if p.name.startswith("a") } yield p).groupby(_.age).map { case (age, ps) => (age, ps.length) } select x2.x3, count(1) from ( select * from ( select x4."name" as x5, x4."age" as x3 from "PERSON" x4 where x4."age" < 20 union all select x6."name" as x5, x6."age" as x3 from "PERSON" x6 where x6."age" >= 50 ) x7 where x7.x5 like 'A%' escape '^' ) x2 group by x2.x3 Func%onal Rela%onal Mapping with Slick 24

Functional Relational Mapping Embraces the relational model Prevents impedance mismatch class Suppliers... extends Table[(Int, String, String)](... "SUPPLIERS") sup.filter(_.id < 2) ++ sup.filter(_.id > 5) Func%onal Rela%onal Mapping with Slick 25

Functional Relational Mapping Embraces the relational model Prevents impedance mismatch Composable Queries def f(id1: Int, id2: Int) = sup.filter(_.id < id1) ++ sup.filter(_.id > id2) val q = f(2, 5).map(_.name) Func%onal Rela%onal Mapping with Slick 26

Functional Relational Mapping Embraces the relational model Prevents impedance mismatch Composable Queries Explicit control over statement execution val result = q.run Func%onal Rela%onal Mapping with Slick 27

Functional Relational

Functional Relational

Slick

Slick Scala Language Integrated Connection Kit Database query and access library for Scala Successor of ScalaQuery Developed at Typesafe and EPFL Open Source Func%onal Rela%onal Mapping with Slick 31

Supported Databases Slick PostgreSQL MySQL H2 Hsqldb Derby / JavaDB SQLite Access Slick Extensions Oracle DB2 SQL Server Closed source, with commercial support by Typesafe Func%onal Rela%onal Mapping with Slick 32

Getting Started with Activator http://typesafe.com/activator Func%onal Rela%onal Mapping with Slick 33

Schema Definition

Table Definition class Suppliers(tag: Tag) extends Table[(Int, String, String)](tag, "SUPPLIERS") { def id = column[int]("sup_id", O.PrimaryKey, O.AutoInc) def name = column[string]("name") def city = column[string]("city") def * = (id, name, city) } val suppliers = TableQuery[Suppliers] Func%onal Rela%onal Mapping with Slick 35

Custom Row Types case class Supplier(id: Int, name: String, city: String) class Suppliers(tag: Tag) extends Table[ Supplier ](tag, "SUPPLIERS") { def id = column[int]("sup_id", O.PrimaryKey, O.AutoInc) def name = column[string]("name") def city = column[string]("city") def * = (id, name, city) <> (Supplier.tupled, Supplier.unapply) } val suppliers = TableQuery[Suppliers] Func%onal Rela%onal Mapping with Slick 36

Custom Column Types class SupplierId(val value: Int) extends AnyVal case class Supplier(id: SupplierId, name: String, city: String) implicit val supplieridtype = MappedColumnType.base [SupplierId, Int](_.value, new SupplierId(_)) class Suppliers(tag: Tag) extends Table[Supplier](tag, "SUPPLIERS") { def id = column[supplierid]("sup_id",...)... } Func%onal Rela%onal Mapping with Slick 37

Custom Column Types class SupplierId(val value: Int) extends MappedTo[Int] case class Supplier(id: SupplierId, name: String, city: String) class Suppliers(tag: Tag) extends Table[Supplier](tag, "SUPPLIERS") { def id = column[supplierid]("sup_id",...)... } Func%onal Rela%onal Mapping with Slick 38

Foreign Keys class Coffees(tag: Tag) extends Table[ } (String, SupplierId, Double)](tag, "COFFEES") { def name = column[string]("name", O.PrimaryKey) def supid = column[supplierid]("sup_id") def price = column[double]("price") def * = (name, supid, price) def supplier = foreignkey("sup_fk", supid, suppliers)(_.id) val coffees = TableQuery[Coffees] Func%onal Rela%onal Mapping with Slick 39

Code Generator New in Slick 2.0 Reverse-engineer an existing database schema Create table definitions and case classes Customizable Easy to embed in sbt build Func%onal Rela%onal Mapping with Slick 40

Data Manipulation

Session Management import scala.slick.driver.h2driver.simple._ val db = Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.driver") db.withsession { implicit session => // Use the session: val result = myquery.run } Func%onal Rela%onal Mapping with Slick 42

Creating Tables and Inserting Data val (suppliers.ddl = ++ new coffees.ddl).create ArrayBuffer[Supplier] val coffees = new ArrayBuffer[(String, SupplierId, Double)] suppliers += Supplier(si1, "Acme, Inc.", "Groundsville") suppliers += Supplier(si2, "Superior Coffee", "Mendocino") suppliers += Supplier(si3, "The High Ground", "Meadows") coffees ++= Seq( ) ("Colombian", si1, 7.99), ("French_Roast", si2, 8.99), ("Espresso", si3, 9.99), ("Colombian_Decaf", si1, 8.99), ("French_Roast_Decaf", si2, 9.99) Func%onal Rela%onal Mapping with Slick 43

Auto-Generated Keys val ins = suppliers.map(s => (s.name, s.city)) returning suppliers.map(_.id) val si1 = val si2 = val si3 = ins += ("Acme, Inc.", "Groundsville") ins += ("Superior Coffee", "Mendocino") ins += ("The High Ground", "Meadows") coffees ++= Seq( ) ("Colombian", si1, 7.99), ("French_Roast", si2, 8.99), ("Espresso", si3, 9.99), ("Colombian_Decaf", si1, 8.99), ("French_Roast_Decaf", si2, 9.99) Func%onal Rela%onal Mapping with Slick 44

Querying

Queries Query[ (Column[String], Column[String]), (String, String) ] Coffees Suppliers TableQuery[Coffees] ColumnExtensionMethods.< val q = for { c <- coffees if c.price < 9.0 s <- c.supplier } yield (c.name, s.name) ConstColumn(9.0) (Column[String], Column[String]) val result = q.run (session) Column[Double] Seq[ (String, String) ] Func%onal Rela%onal Mapping with Slick 46

Plain SQL

JDBC def personsmatching(pattern: String)(conn: Connection) = { val st = conn.preparestatement( "select id, name from person where name like?") try { st.setstring(1, pattern) val rs = st.executequery() try { val b = new ListBuffer[(Int, String)] while(rs.next) b.append((rs.getint(1), rs.getstring(2))) b.tolist } finally rs.close() } finally st.close() } Func%onal Rela%onal Mapping with Slick 48 48

Slick: Plain SQL Queries def personsmatching(pattern: String)(implicit s: Session) = sql"select id, name from person where name like $pattern".as[(int, String)].list Func%onal Rela%onal Mapping with Slick 49 49

Compile-Time Checking of SQL def personsmatching(pattern: String)(implicit s: Session) = tsql"select id, name from person where name like $pattern".list Expected in Slick 2.2 Func%onal Rela%onal Mapping with Slick 50 50

slick.typesafe.com @StefanZeiger

Typesafe 2014 All Rights Reserved