SlideShare una empresa de Scribd logo
1 de 20
Descargar para leer sin conexión
Statement Fragments
- How to write dynamic SQL queries in doobie -
2017-01-28
第十八回 #渋谷java
0.4.0 release!
● Cats Support
● Simple statement logging Support
● Changes to Add-On Modules
● Dynamic SQL
0.4.0 release!
● Cats Support
● Simple statement logging Support
● Changes to Add-On Modules
● Dynamic SQL
The dynamic SQL story
The dynamic SQL story is now slightly better with
the introduction of composable statement
fragments.
"Changes to Core". changelog.
https://github.com/tpolecat/doobie/blob/series/0.4.x/CHANGELOG.md#changes-to-core, (参照 2017-01-25)
The dynamic SQL story
The dynamic SQL story is now slightly better with
the introduction of composable statement
fragments.
"Changes to Core". changelog.
https://github.com/tpolecat/doobie/blob/series/0.4.x/CHANGELOG.md#changes-to-core, (参照 2017-01-25)
若干改善された
Setting Up
import doobie.imports._
import scalaz._, Scalaz._, concurrent.Task
val xa = DriverManagerTransactor[Task](
"org.h2.Driver", "url", "user", "password"
)
// YOLO mode
import xa.yolo._
SQL literals
val select = fr"select * from user"
val where = fr"where uid = $id"
val sql = select ++ where
sql.query[User].quick.unsafePerformSync
SQL literals
val select: Fragment = fr"select * from user"
val where: Fragment = fr"where uid = $id"
val sql: Fragment = select ++ where
sql.query[User].quick.unsafePerformSync
sqlの代わりにfrで定義
SQL literals
val select: Fragment = fr"select * from user"
val where: Fragment = fr"where uid = $id"
val sql: Fragment = select ++ where
sql.query[User].quick.unsafePerformSync
++で連結
An arbitrary string value
val table = "user"
val select = fr"select * from"
val sql = select ++ Fragment.const(table)
sql.query[Unit].sql
// "select * from user"
An arbitrary string value
val table = "user"
val select = fr"select * from"
val sql = select ++ Fragment.const(table)
sql.query[Unit].sql
// "select * from user"
SQLパラメータではないもの
The Fragments Module
● some convenience combinators
○ andOpt
○ orOpt
○ whereAndOpt
○ whereOrOpt
○ in
and so on
The Fragments Module - whereAndOpt
import Fragments._
val uid: Option[Int] = ...
val json: Option[String] = ...
val sql = fr"select * from user" ++
whereAndOpt(
uid.map(p => fr"uid = $p"), // Option[Fragment]
json.map(p => fr"json like $p") // Option[Fragment]
)
The Fragments Module - whereAndOpt
import Fragments._
val uid: Option[Int] = None
val json: Option[String] = None
val sql = fr"select * from user" ++
whereAndOpt(
uid.map(p => fr"uid = $p"), // Option[Fragment]
json.map(p => fr"json like $p") // Option[Fragment]
)
// "select * from user "
The Fragments Module - whereAndOpt
import Fragments._
val uid: Option[Int] = Some(1)
val json: Option[String] = None
val sql = fr"select * from user" ++
whereAndOpt(
uid.map(p => fr"uid = $p"), // Option[Fragment]
json.map(p => fr"json like $p") // Option[Fragment]
)
// "select * from user WHERE uid = ? "
The Fragments Module - whereAndOpt
import Fragments._
val uid: Option[Int] = Some(1)
val json: Option[String] = Some("%foo%")
val sql = fr"select * from user" ++
whereAndOpt(
uid.map(p => fr"uid = $p"), // Option[Fragment]
json.map(p => fr"json like $p") // Option[Fragment]
)
// "select * from user WHERE uid = ? AND json like ? "
The Fragments Module - in
import Fragments._
val uids: List[Int] = ...
val sql = fr"select * from user" ++
whereAndOpt(
uids.toNel.map(p => in(fr"uid", p))// Option[Fragment]
)
Option[NonEmptyList[Int]]
The Fragments Module - in
import Fragments._
val uids: List[Int] = Nil
val sql = fr"select * from user" ++
whereAndOpt(
uids.toNel.map(p => in(fr"uid", p))// Option[Fragment]
)
// "select * from user "
The Fragments Module - in
import Fragments._
val uids: List[Int] = List(1,10)
val sql = fr"select * from user" ++
whereAndOpt(
uids.toNel.map(p => in(fr"uid", p))// Option[Fragment]
)
// "select * from user WHERE uid IN (?, ?) "
Conclusion
● 嬉しいこと
○ dynamic SQL が書けるようになった
○ 特にwhere句の組み立ては高確率で必要になる
● 悲しいこと
○ 「若干」感
○ 使い方がよくわからないもの(andOpt)
まだ0.4.xなのでこれからの進化に期待!

Más contenido relacionado

La actualidad más candente

Christo kutrovsky oracle, memory & linux
Christo kutrovsky   oracle, memory & linuxChristo kutrovsky   oracle, memory & linux
Christo kutrovsky oracle, memory & linux
Kyle Hailey
 

La actualidad más candente (20)

File Format Benchmark - Avro, JSON, ORC & Parquet
File Format Benchmark - Avro, JSON, ORC & ParquetFile Format Benchmark - Avro, JSON, ORC & Parquet
File Format Benchmark - Avro, JSON, ORC & Parquet
 
Solving PostgreSQL wicked problems
Solving PostgreSQL wicked problemsSolving PostgreSQL wicked problems
Solving PostgreSQL wicked problems
 
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
 
Architectural katas
Architectural katasArchitectural katas
Architectural katas
 
Operating and Supporting Delta Lake in Production
Operating and Supporting Delta Lake in ProductionOperating and Supporting Delta Lake in Production
Operating and Supporting Delta Lake in Production
 
Demystifying the Distributed Database Landscape (DevOps) (1).pdf
Demystifying the Distributed Database Landscape (DevOps) (1).pdfDemystifying the Distributed Database Landscape (DevOps) (1).pdf
Demystifying the Distributed Database Landscape (DevOps) (1).pdf
 
openCypher: Introducing subqueries
openCypher: Introducing subqueriesopenCypher: Introducing subqueries
openCypher: Introducing subqueries
 
PostgreSQL HA
PostgreSQL   HAPostgreSQL   HA
PostgreSQL HA
 
The Volcano/Cascades Optimizer
The Volcano/Cascades OptimizerThe Volcano/Cascades Optimizer
The Volcano/Cascades Optimizer
 
ふつうの受託開発チームのつくりかた
ふつうの受託開発チームのつくりかたふつうの受託開発チームのつくりかた
ふつうの受託開発チームのつくりかた
 
Apache Iceberg: An Architectural Look Under the Covers
Apache Iceberg: An Architectural Look Under the CoversApache Iceberg: An Architectural Look Under the Covers
Apache Iceberg: An Architectural Look Under the Covers
 
Rdra2.0 redmine
Rdra2.0 redmineRdra2.0 redmine
Rdra2.0 redmine
 
DRP (Stretch Cluster) for HDP - Future of Data : Paris
DRP (Stretch Cluster) for HDP - Future of Data : Paris DRP (Stretch Cluster) for HDP - Future of Data : Paris
DRP (Stretch Cluster) for HDP - Future of Data : Paris
 
Christo kutrovsky oracle, memory & linux
Christo kutrovsky   oracle, memory & linuxChristo kutrovsky   oracle, memory & linux
Christo kutrovsky oracle, memory & linux
 
Apache Spark Streaming in K8s with ArgoCD & Spark Operator
Apache Spark Streaming in K8s with ArgoCD & Spark OperatorApache Spark Streaming in K8s with ArgoCD & Spark Operator
Apache Spark Streaming in K8s with ArgoCD & Spark Operator
 
mysql 8.0 architecture and enhancement
mysql 8.0 architecture and enhancementmysql 8.0 architecture and enhancement
mysql 8.0 architecture and enhancement
 
MoP(MQTT on Pulsar) - a Powerful Tool for Apache Pulsar in IoT - Pulsar Summi...
MoP(MQTT on Pulsar) - a Powerful Tool for Apache Pulsar in IoT - Pulsar Summi...MoP(MQTT on Pulsar) - a Powerful Tool for Apache Pulsar in IoT - Pulsar Summi...
MoP(MQTT on Pulsar) - a Powerful Tool for Apache Pulsar in IoT - Pulsar Summi...
 
MMUG18 - MySQL Failover and Orchestrator
MMUG18 - MySQL Failover and OrchestratorMMUG18 - MySQL Failover and Orchestrator
MMUG18 - MySQL Failover and Orchestrator
 
データベース09 - データベース設計
データベース09 - データベース設計データベース09 - データベース設計
データベース09 - データベース設計
 
RDBにおけるバリデーションをリレーショナルモデルから考える
RDBにおけるバリデーションをリレーショナルモデルから考えるRDBにおけるバリデーションをリレーショナルモデルから考える
RDBにおけるバリデーションをリレーショナルモデルから考える
 

Destacado

Destacado (20)

Deadly Code! (seriously) Blocking & Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking & Hyper Context Switching PatternDeadly Code! (seriously) Blocking & Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking & Hyper Context Switching Pattern
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
What is doobie? - database access for scala -
What is doobie? - database access for scala -What is doobie? - database access for scala -
What is doobie? - database access for scala -
 
ビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streamingビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streaming
 
今から始める Lens/Prism
今から始める Lens/Prism今から始める Lens/Prism
今から始める Lens/Prism
 
マイクロサービスバックエンドAPIのためのRESTとgRPC
マイクロサービスバックエンドAPIのためのRESTとgRPCマイクロサービスバックエンドAPIのためのRESTとgRPC
マイクロサービスバックエンドAPIのためのRESTとgRPC
 
Goでヤフーの分散オブジェクトストレージを作った話 Go Conference 2017 Spring
Goでヤフーの分散オブジェクトストレージを作った話 Go Conference 2017 SpringGoでヤフーの分散オブジェクトストレージを作った話 Go Conference 2017 Spring
Goでヤフーの分散オブジェクトストレージを作った話 Go Conference 2017 Spring
 
Sql
SqlSql
Sql
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Quartzでcronを範囲検索したい
Quartzでcronを範囲検索したいQuartzでcronを範囲検索したい
Quartzでcronを範囲検索したい
 
テストゼロからイチに進むための戦略と戦術
テストゼロからイチに進むための戦略と戦術テストゼロからイチに進むための戦略と戦術
テストゼロからイチに進むための戦略と戦術
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
Why Outsourcing Graphic Design Projects is the Next Big Thing?
Why Outsourcing Graphic Design Projects is the Next Big Thing?Why Outsourcing Graphic Design Projects is the Next Big Thing?
Why Outsourcing Graphic Design Projects is the Next Big Thing?
 
Introduction to Business Statistics
Introduction to Business StatisticsIntroduction to Business Statistics
Introduction to Business Statistics
 
Arquitectura barroca
Arquitectura barrocaArquitectura barroca
Arquitectura barroca
 
sbtマルチプロジェクトビルドの使いどころ
sbtマルチプロジェクトビルドの使いどころsbtマルチプロジェクトビルドの使いどころ
sbtマルチプロジェクトビルドの使いどころ
 
究極のPHP本完成
究極のPHP本完成究極のPHP本完成
究極のPHP本完成
 
20160902 scalaの魅力を話してみる
20160902 scalaの魅力を話してみる20160902 scalaの魅力を話してみる
20160902 scalaの魅力を話してみる
 

Similar a Dynamic SQL in doobie

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
What is your money doing?
What is your money doing?What is your money doing?
What is your money doing?
Alfonso Fernández
 
Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)
njbartlett
 

Similar a Dynamic SQL in doobie (20)

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
The MEAN stack
The MEAN stack The MEAN stack
The MEAN stack
 
Web automation with #d8rules (European Drupal Days 2015)
Web automation with #d8rules (European Drupal Days 2015)Web automation with #d8rules (European Drupal Days 2015)
Web automation with #d8rules (European Drupal Days 2015)
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the Cloud
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Angular js 2.0, ng poznań 20.11
Angular js 2.0, ng poznań 20.11Angular js 2.0, ng poznań 20.11
Angular js 2.0, ng poznań 20.11
 
Go Web Development
Go Web DevelopmentGo Web Development
Go Web Development
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 App
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
What is your money doing?
What is your money doing?What is your money doing?
What is your money doing?
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
 
Angular 2 at solutions.hamburg
Angular 2 at solutions.hamburgAngular 2 at solutions.hamburg
Angular 2 at solutions.hamburg
 
Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)
 
Getting Reactive with Cycle.js and xstream
Getting Reactive with Cycle.js and xstreamGetting Reactive with Cycle.js and xstream
Getting Reactive with Cycle.js and xstream
 

Más de chibochibo

Spark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with ElasticsearchSpark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with Elasticsearch
chibochibo
 

Más de chibochibo (10)

Tour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 MinutesTour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 Minutes
 
Crawler Commons
Crawler CommonsCrawler Commons
Crawler Commons
 
LocalStack
LocalStackLocalStack
LocalStack
 
Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?
 
nioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になったnioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になった
 
Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-
 
Spark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with ElasticsearchSpark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with Elasticsearch
 
What's a macro?: Learning by Examples
What's a macro?: Learning by ExamplesWhat's a macro?: Learning by Examples
What's a macro?: Learning by Examples
 
Spring Boot Introduction
Spring Boot IntroductionSpring Boot Introduction
Spring Boot Introduction
 
Slick入門
Slick入門Slick入門
Slick入門
 

Último

Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...
Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...
Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...
David Celestin
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
amilabibi1
 
Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...
Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...
Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...
ZurliaSoop
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
Kayode Fayemi
 
Unlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven Curiosity
Unlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven CuriosityUnlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven Curiosity
Unlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven Curiosity
Hung Le
 

Último (17)

Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...
Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...
Proofreading- Basics to Artificial Intelligence Integration - Presentation:Sl...
 
ICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdfICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdf
 
Introduction to Artificial intelligence.
Introduction to Artificial intelligence.Introduction to Artificial intelligence.
Introduction to Artificial intelligence.
 
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfAWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
 
My Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle BaileyMy Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle Bailey
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
 
lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.
 
Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...
Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...
Jual obat aborsi Jakarta 085657271886 Cytote pil telat bulan penggugur kandun...
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
 
Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio III
 
SOLID WASTE MANAGEMENT SYSTEM OF FENI PAURASHAVA, BANGLADESH.pdf
SOLID WASTE MANAGEMENT SYSTEM OF FENI PAURASHAVA, BANGLADESH.pdfSOLID WASTE MANAGEMENT SYSTEM OF FENI PAURASHAVA, BANGLADESH.pdf
SOLID WASTE MANAGEMENT SYSTEM OF FENI PAURASHAVA, BANGLADESH.pdf
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatment
 
Unlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven Curiosity
Unlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven CuriosityUnlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven Curiosity
Unlocking Exploration: Self-Motivated Agents Thrive on Memory-Driven Curiosity
 
Zone Chairperson Role and Responsibilities New updated.pptx
Zone Chairperson Role and Responsibilities New updated.pptxZone Chairperson Role and Responsibilities New updated.pptx
Zone Chairperson Role and Responsibilities New updated.pptx
 
Digital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of DrupalDigital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of Drupal
 
in kuwait௹+918133066128....) @abortion pills for sale in Kuwait City
in kuwait௹+918133066128....) @abortion pills for sale in Kuwait Cityin kuwait௹+918133066128....) @abortion pills for sale in Kuwait City
in kuwait௹+918133066128....) @abortion pills for sale in Kuwait City
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 

Dynamic SQL in doobie

  • 1. Statement Fragments - How to write dynamic SQL queries in doobie - 2017-01-28 第十八回 #渋谷java
  • 2. 0.4.0 release! ● Cats Support ● Simple statement logging Support ● Changes to Add-On Modules ● Dynamic SQL
  • 3. 0.4.0 release! ● Cats Support ● Simple statement logging Support ● Changes to Add-On Modules ● Dynamic SQL
  • 4. The dynamic SQL story The dynamic SQL story is now slightly better with the introduction of composable statement fragments. "Changes to Core". changelog. https://github.com/tpolecat/doobie/blob/series/0.4.x/CHANGELOG.md#changes-to-core, (参照 2017-01-25)
  • 5. The dynamic SQL story The dynamic SQL story is now slightly better with the introduction of composable statement fragments. "Changes to Core". changelog. https://github.com/tpolecat/doobie/blob/series/0.4.x/CHANGELOG.md#changes-to-core, (参照 2017-01-25) 若干改善された
  • 6. Setting Up import doobie.imports._ import scalaz._, Scalaz._, concurrent.Task val xa = DriverManagerTransactor[Task]( "org.h2.Driver", "url", "user", "password" ) // YOLO mode import xa.yolo._
  • 7. SQL literals val select = fr"select * from user" val where = fr"where uid = $id" val sql = select ++ where sql.query[User].quick.unsafePerformSync
  • 8. SQL literals val select: Fragment = fr"select * from user" val where: Fragment = fr"where uid = $id" val sql: Fragment = select ++ where sql.query[User].quick.unsafePerformSync sqlの代わりにfrで定義
  • 9. SQL literals val select: Fragment = fr"select * from user" val where: Fragment = fr"where uid = $id" val sql: Fragment = select ++ where sql.query[User].quick.unsafePerformSync ++で連結
  • 10. An arbitrary string value val table = "user" val select = fr"select * from" val sql = select ++ Fragment.const(table) sql.query[Unit].sql // "select * from user"
  • 11. An arbitrary string value val table = "user" val select = fr"select * from" val sql = select ++ Fragment.const(table) sql.query[Unit].sql // "select * from user" SQLパラメータではないもの
  • 12. The Fragments Module ● some convenience combinators ○ andOpt ○ orOpt ○ whereAndOpt ○ whereOrOpt ○ in and so on
  • 13. The Fragments Module - whereAndOpt import Fragments._ val uid: Option[Int] = ... val json: Option[String] = ... val sql = fr"select * from user" ++ whereAndOpt( uid.map(p => fr"uid = $p"), // Option[Fragment] json.map(p => fr"json like $p") // Option[Fragment] )
  • 14. The Fragments Module - whereAndOpt import Fragments._ val uid: Option[Int] = None val json: Option[String] = None val sql = fr"select * from user" ++ whereAndOpt( uid.map(p => fr"uid = $p"), // Option[Fragment] json.map(p => fr"json like $p") // Option[Fragment] ) // "select * from user "
  • 15. The Fragments Module - whereAndOpt import Fragments._ val uid: Option[Int] = Some(1) val json: Option[String] = None val sql = fr"select * from user" ++ whereAndOpt( uid.map(p => fr"uid = $p"), // Option[Fragment] json.map(p => fr"json like $p") // Option[Fragment] ) // "select * from user WHERE uid = ? "
  • 16. The Fragments Module - whereAndOpt import Fragments._ val uid: Option[Int] = Some(1) val json: Option[String] = Some("%foo%") val sql = fr"select * from user" ++ whereAndOpt( uid.map(p => fr"uid = $p"), // Option[Fragment] json.map(p => fr"json like $p") // Option[Fragment] ) // "select * from user WHERE uid = ? AND json like ? "
  • 17. The Fragments Module - in import Fragments._ val uids: List[Int] = ... val sql = fr"select * from user" ++ whereAndOpt( uids.toNel.map(p => in(fr"uid", p))// Option[Fragment] ) Option[NonEmptyList[Int]]
  • 18. The Fragments Module - in import Fragments._ val uids: List[Int] = Nil val sql = fr"select * from user" ++ whereAndOpt( uids.toNel.map(p => in(fr"uid", p))// Option[Fragment] ) // "select * from user "
  • 19. The Fragments Module - in import Fragments._ val uids: List[Int] = List(1,10) val sql = fr"select * from user" ++ whereAndOpt( uids.toNel.map(p => in(fr"uid", p))// Option[Fragment] ) // "select * from user WHERE uid IN (?, ?) "
  • 20. Conclusion ● 嬉しいこと ○ dynamic SQL が書けるようになった ○ 特にwhere句の組み立ては高確率で必要になる ● 悲しいこと ○ 「若干」感 ○ 使い方がよくわからないもの(andOpt) まだ0.4.xなのでこれからの進化に期待!