Scrap your query boilerplate with specql

SCRAP YOUR
QUERY
BOILERPLATE
WITH SPECQL
2.9.2017 ClojuTRE Tatu Tarvainen (@tatut)
WHAT IS SPECQL?
› The combination of clojure.spec, PostgreSQL and the power of
macros
clojure.spec PostgreSQL
λ
SOME BACKGROUND
› Yesql/Jeesql/Hugsql are all fine and specql does not try to ”solve”
SQL so that you don’t have to use it anymore
› When you have multiple slightly different queries, there’s
duplication or fetching too much
› Adding dynamic WHERE clauses leads to ugly NULL checking of
bound parameters
EXAMPLE
› SELECT it.foo, it.bar, it.baz
› FROM interesting_table it
› WHERE it.archived = FALSE
› AND it.organization = :user_org_id
› AND it.category IN (:categories)
EXAMPLE
› SELECT it.foo, it.bar, it.baz
› FROM interesting_table it
› WHERE it.archived = FALSE
› AND it.organization = :user_org_id
› AND it.category IN (:categories)
How to make
variants without
duplication or
selecting too much?
EXAMPLE
› SELECT it.foo, it.bar, it.baz
› FROM interesting_table it
› WHERE it.archived = FALSE
› AND it.organization = :user_org_id
› AND it.category IN (:categories)
How to
add/remove
clauses
dynamically?
EXAMPLE
› SELECT it.foo, it.bar, it.baz,
› o.name AS organization_name
› FROM interesting_table it
› JOIN organization o ON it.organization_id = o.id
› WHERE it.archived = FALSE
› AND it.organization = :user_org_id
› AND it.category IN (:categories)
EXAMPLE
› SELECT it.foo, it.bar, it.baz,
› o.name AS organization_name
› FROM interesting_table it
› JOIN organization o ON it.organization_id = o.id
› WHERE it.archived = FALSE
› AND it.organization = :user_org_id
› AND it.category IN (:categories)
How to cleanly add
these without code
duplication?
THE SPECQL WAY: DEFINE
› (define-tables db
› [”interesting_table” ::it/interesting
› {::it/organization (rel/has-one
› ::it/organization_id
› ::org/organization
› ::org/id)}])
THE SPECQL WAY: DEFINE
› (define-tables db
› [”interesting_table” ::it/interesting
› {::it/organization (rel/has-one
› ::it/organization_id
› ::org/organization
› ::org/id)}])
The main macro
for defining things
THE SPECQL WAY: DEFINE
› (define-tables db
› [”interesting_table” ::it/interesting
› {::it/organization (rel/has-one
› ::it/organization_id
› ::org/organization
› ::org/id)}])
The name of the
table in the
database
THE SPECQL WAY: DEFINE
› (define-tables db
› [”interesting_table” ::it/interesting
› {::it/organization (rel/has-one
› ::it/organization_id
› ::org/organization
› ::org/id)}])
The namespaced
keyword for the
table
THE SPECQL WAY: DEFINE
› (define-tables db
› [”interesting_table” ::it/interesting
› {::it/organization (rel/has-one
› ::it/organization_id
› ::org/organization
› ::org/id)}])
Additional
definitions for
columns
THE SPECQL WAY: FETCH
› (defn fetch-interesting [db org-id categories]
› (fetch db ::it/interesting
› #{::it/foo ::it/bar ::it/baz}
› {::it/archived false
› ::it/organization_id org-id
› ::it/category (op/in categories)}))
THE SPECQL WAY: FETCH
› (defn fetch-interesting [db org-id categories]
› (fetch db ::it/interesting
› #{::it/foo ::it/bar ::it/baz}
› {::it/archived false
› ::it/organization_id org-id
› ::it/category (op/in categories)}))
The table to fetch
from
THE SPECQL WAY: FETCH
› (defn fetch-interesting [db org-id categories]
› (fetch db ::it/interesting
› #{::it/foo ::it/bar ::it/baz}
› {::it/archived false
› ::it/organization_id org-id
› ::it/category (op/in categories)}))
Set of columns to
retrieve
THE SPECQL WAY: FETCH
› (defn fetch-interesting [db org-id categories]
› (fetch db ::it/interesting
› #{::it/foo ::it/bar ::it/baz}
› {::it/archived false
› ::it/organization_id org-id
› ::it/category (op/in categories)}))
The WHERE
clause map
THE SPECQL WAY: RESULT
› (fetch-interesting db 1 #{”stuff” ”things”})
› ;; => ({::it/foo 1
› ::it/bar ”example”
› ::it/baz true} …)
›
THE SPECQL WAY: JOIN
› (fetch db ::it/interesting
› #{::it/foo ::it/bar ::it/baz
› [::it/organization #{::org/id ::org/name}]}
› {::it/archived false
› ::it/organization_id org-id
› ::it/category (op/in categories)}))
THE SPECQL WAY: JOIN
› (fetch db ::it/interesting
› #{::it/foo ::it/bar ::it/baz
› [::it/organization #{::org/id ::org/name}]}
› {::it/archived false
› ::it/organization_id org-id
› ::it/category (op/in categories)}))
Nested column definition
for a JOINed tables
THE SPECQL WAY: JOIN
› ;; => ({::it/foo 1
› ::it/bar ”example”
› ::it/baz true
› ::it/organization {::org/id 1
› ::org/name ”Acme Inc”}
› …)
THE SPECQL WAY: JOIN
› ;; => ({::it/foo 1
› ::it/bar ”example”
› ::it/baz true
› ::it/organization {::org/id 1
› ::org/name ”Acme Inc”}
› …)
Joined entity is
available in a nested
map
SPECQL BENEFITS
› Clojure data!
› The column set is just data and can be easily manipulated
• Even given as parameters from the frontend
› Where clauses can be easily added and are (mostly) just data as well
› Every table and column has a single ns keyword definition
• No more ”order” vs ”order-id” vs ”ord” differences in returned query
results
• Namespaced keys are the way of the future
SPECQL BENEFITS
› Clojure data!
› The column set is just data and can be easily manipulated
• Even given as parameters from the frontend
› Where clauses can be easily added and are (mostly) just data as well
› Every table and column has a single ns keyword definition
• No more ”order” vs ”order-id” vs ”ord” differences in returned query
results
• Namespaced keys are the way of the future HERE TO STAY
SPECQL BENEFITS
› Works with ClojureScript
• The spec generation part, put your specs in .cljc files and enjoy the same
specs and have your db definitions drive your frontend as well
› Works well with ”typed document storage” pattern
• A column can be a user defined type or array
› Provides generic upsert!
• No need to branch code, let the db handle it
› Works with database VIEWs
STATUS
› The github project page (https://github.com/tatut/specql) still says
EXPERIMENTAL
• Current 0.7 alpha stage, should be ready this year
• We are already using it in production in Harja
› No concrete promises before the experimental flag is gone, but the
API should only grow
• The test suite is comprehensive and should not break
STATUS
› 0.7 is coming and adds support for stored procedures
• Macro for defining a stored procedure as a function
• Better JOIN handling
• Currently fetching multiple ”has many” collections at once doesn’t work properly
› How to help
• Please try it out if you are using PostgreSQL
• Report rough edges, I try to provide good error messages
› EXAMPLE
THANK YOU
github.com/tatut/specql twitter.com/tatut
1 of 29

Recommended

Getting Creative with WordPress Queries, Again by
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainDrewAPicture
515 views50 slides
XML Support: Specifications and Development by
XML Support: Specifications and DevelopmentXML Support: Specifications and Development
XML Support: Specifications and DevelopmentPeter Eisentraut
1.2K views19 slides
Information Retrieval - Data Science Bootcamp by
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampKais Hassan, PhD
596 views40 slides
Apache Solr Search Mastery by
Apache Solr Search MasteryApache Solr Search Mastery
Apache Solr Search MasteryAcquia
2.8K views84 slides
Database adapter by
Database adapterDatabase adapter
Database adapterprathap kumar
168 views9 slides
Brief introduction of Slick by
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
2.4K views19 slides

More Related Content

What's hot

Introduction to database by
Introduction to databaseIntroduction to database
Introduction to databaseoly07104
516 views31 slides
Introduction to database by
Introduction to databaseIntroduction to database
Introduction to databaseKazi Uddin Oly
344 views31 slides
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab... by
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...Marco Gralike
692 views47 slides
Enterprise Search Solution: Apache SOLR. What's available and why it's so cool by
Enterprise Search Solution: Apache SOLR. What's available and why it's so coolEnterprise Search Solution: Apache SOLR. What's available and why it's so cool
Enterprise Search Solution: Apache SOLR. What's available and why it's so coolEcommerce Solution Provider SysIQ
2.2K views28 slides
Solr's Search Relevancy (Understand Solr's query debug) by
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Wongnai
273 views17 slides
PostgreSQL (2) by Aswin by
PostgreSQL (2) by AswinPostgreSQL (2) by Aswin
PostgreSQL (2) by AswinAgate Studio
378 views17 slides

What's hot(20)

Introduction to database by oly07104
Introduction to databaseIntroduction to database
Introduction to database
oly07104516 views
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab... by Marco Gralike
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
Oracle Developer Day, 20 October 2009, Oracle De Meern, Holland: Oracle Datab...
Marco Gralike692 views
Solr's Search Relevancy (Understand Solr's query debug) by Wongnai
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)
Wongnai273 views
PostgreSQL (2) by Aswin by Agate Studio
PostgreSQL (2) by AswinPostgreSQL (2) by Aswin
PostgreSQL (2) by Aswin
Agate Studio378 views
supporting t-sql scripts for Heap vs clustered table by Mahabubur Rahaman
supporting t-sql scripts for Heap vs clustered tablesupporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered table
Mahabubur Rahaman245 views
Starting with JSON Path Expressions in Oracle 12.1.0.2 by Marco Gralike
Starting with JSON Path Expressions in Oracle 12.1.0.2Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2
Marco Gralike10.1K views
Slick: Bringing Scala’s Powerful Features to Your Database Access by Rebecca Grenier
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
Rebecca Grenier5.3K views
UKOUG Tech14 - Getting Started With JSON in the Database by Marco Gralike
UKOUG Tech14 - Getting Started With JSON in the DatabaseUKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the Database
Marco Gralike1.3K views
The Query the Whole Query and Nothing but the Query by Chris Olbekson
The Query the Whole Query and Nothing but the QueryThe Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the Query
Chris Olbekson1.2K views
Mysql query optimization by Baohua Cai
Mysql query optimizationMysql query optimization
Mysql query optimization
Baohua Cai1.1K views
Apache Solr + ajax solr by Net7
Apache Solr + ajax solrApache Solr + ajax solr
Apache Solr + ajax solr
Net72.6K views
Advanced Django ORM techniques by Daniel Roseman
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
Daniel Roseman29.9K views

Similar to Scrap your query boilerplate with specql

Introduction to Elasticsearch by
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to ElasticsearchSperasoft
1.2K views47 slides
GreenDao Introduction by
GreenDao IntroductionGreenDao Introduction
GreenDao IntroductionBooch Lin
4K views32 slides
PostgreSQL by
PostgreSQLPostgreSQL
PostgreSQLReuven Lerner
8K views74 slides
An Introduction to Elastic Search. by
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.Jurriaan Persyn
71.1K views86 slides
PostgreSQL - It's kind've a nifty database by
PostgreSQL - It's kind've a nifty databasePostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databaseBarry Jones
5.1K views27 slides
Oracle Database 12c - New Features for Developers and DBAs by
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
192 views111 slides

Similar to Scrap your query boilerplate with specql(20)

Introduction to Elasticsearch by Sperasoft
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
Sperasoft1.2K views
GreenDao Introduction by Booch Lin
GreenDao IntroductionGreenDao Introduction
GreenDao Introduction
Booch Lin4K views
An Introduction to Elastic Search. by Jurriaan Persyn
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.
Jurriaan Persyn71.1K views
PostgreSQL - It's kind've a nifty database by Barry Jones
PostgreSQL - It's kind've a nifty databasePostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty database
Barry Jones5.1K views
Oracle Database 12c - New Features for Developers and DBAs by Alex Zaballa
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
Alex Zaballa192 views
Oracle Database 12c - New Features for Developers and DBAs by Alex Zaballa
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
Alex Zaballa3.9K views
To scale or not to scale: Key/Value, Document, SQL, JPA – What’s right for my... by Uri Cohen
To scale or not to scale: Key/Value, Document, SQL, JPA – What’s right for my...To scale or not to scale: Key/Value, Document, SQL, JPA – What’s right for my...
To scale or not to scale: Key/Value, Document, SQL, JPA – What’s right for my...
Uri Cohen1.9K views
Oracle Database 12c New Features for Developers and DBAs - OTN TOUR LA 2015 by Alex Zaballa
Oracle Database 12c  New Features for Developers and DBAs - OTN TOUR LA 2015Oracle Database 12c  New Features for Developers and DBAs - OTN TOUR LA 2015
Oracle Database 12c New Features for Developers and DBAs - OTN TOUR LA 2015
Alex Zaballa2K views
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx by Pythian
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
Pythian5.7K views
Making Django and NoSQL Play Nice by Alex Gaynor
Making Django and NoSQL Play NiceMaking Django and NoSQL Play Nice
Making Django and NoSQL Play Nice
Alex Gaynor6.1K views
Drupal - dbtng 25th Anniversary Edition by ddiers
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
ddiers2.7K views
10 Reasons to Start Your Analytics Project with PostgreSQL by Satoshi Nagayasu
10 Reasons to Start Your Analytics Project with PostgreSQL10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQL
Satoshi Nagayasu4.5K views
Drupal II: The SQL by ddiers
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
ddiers3.1K views

Recently uploaded

DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J... by
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...Deltares
9 views24 slides
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols by
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDeltares
7 views23 slides
Unleash The Monkeys by
Unleash The MonkeysUnleash The Monkeys
Unleash The MonkeysJacob Duijzer
7 views28 slides
Copilot Prompting Toolkit_All Resources.pdf by
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdfRiccardo Zamana
8 views4 slides
Generic or specific? Making sensible software design decisions by
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
6 views60 slides
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Donato Onofri
795 views34 slides

Recently uploaded(20)

DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J... by Deltares
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
Deltares9 views
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols by Deltares
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
Deltares7 views
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana8 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri795 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin95 views
MariaDB stored procedures and why they should be improved by Federico Razzoli
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut... by Deltares
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
Deltares7 views
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ... by Deltares
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
Deltares10 views
Dapr Unleashed: Accelerating Microservice Development by Miroslav Janeski
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice Development
Miroslav Janeski10 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8711 views
360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info3349237 views
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy13 views
Headless JS UG Presentation.pptx by Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor7 views
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares14 views
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -... by Deltares
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
Deltares6 views
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t... by Deltares
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
Deltares9 views

Scrap your query boilerplate with specql

  • 1. SCRAP YOUR QUERY BOILERPLATE WITH SPECQL 2.9.2017 ClojuTRE Tatu Tarvainen (@tatut)
  • 2. WHAT IS SPECQL? › The combination of clojure.spec, PostgreSQL and the power of macros clojure.spec PostgreSQL λ
  • 3. SOME BACKGROUND › Yesql/Jeesql/Hugsql are all fine and specql does not try to ”solve” SQL so that you don’t have to use it anymore › When you have multiple slightly different queries, there’s duplication or fetching too much › Adding dynamic WHERE clauses leads to ugly NULL checking of bound parameters
  • 4. EXAMPLE › SELECT it.foo, it.bar, it.baz › FROM interesting_table it › WHERE it.archived = FALSE › AND it.organization = :user_org_id › AND it.category IN (:categories)
  • 5. EXAMPLE › SELECT it.foo, it.bar, it.baz › FROM interesting_table it › WHERE it.archived = FALSE › AND it.organization = :user_org_id › AND it.category IN (:categories) How to make variants without duplication or selecting too much?
  • 6. EXAMPLE › SELECT it.foo, it.bar, it.baz › FROM interesting_table it › WHERE it.archived = FALSE › AND it.organization = :user_org_id › AND it.category IN (:categories) How to add/remove clauses dynamically?
  • 7. EXAMPLE › SELECT it.foo, it.bar, it.baz, › o.name AS organization_name › FROM interesting_table it › JOIN organization o ON it.organization_id = o.id › WHERE it.archived = FALSE › AND it.organization = :user_org_id › AND it.category IN (:categories)
  • 8. EXAMPLE › SELECT it.foo, it.bar, it.baz, › o.name AS organization_name › FROM interesting_table it › JOIN organization o ON it.organization_id = o.id › WHERE it.archived = FALSE › AND it.organization = :user_org_id › AND it.category IN (:categories) How to cleanly add these without code duplication?
  • 9. THE SPECQL WAY: DEFINE › (define-tables db › [”interesting_table” ::it/interesting › {::it/organization (rel/has-one › ::it/organization_id › ::org/organization › ::org/id)}])
  • 10. THE SPECQL WAY: DEFINE › (define-tables db › [”interesting_table” ::it/interesting › {::it/organization (rel/has-one › ::it/organization_id › ::org/organization › ::org/id)}]) The main macro for defining things
  • 11. THE SPECQL WAY: DEFINE › (define-tables db › [”interesting_table” ::it/interesting › {::it/organization (rel/has-one › ::it/organization_id › ::org/organization › ::org/id)}]) The name of the table in the database
  • 12. THE SPECQL WAY: DEFINE › (define-tables db › [”interesting_table” ::it/interesting › {::it/organization (rel/has-one › ::it/organization_id › ::org/organization › ::org/id)}]) The namespaced keyword for the table
  • 13. THE SPECQL WAY: DEFINE › (define-tables db › [”interesting_table” ::it/interesting › {::it/organization (rel/has-one › ::it/organization_id › ::org/organization › ::org/id)}]) Additional definitions for columns
  • 14. THE SPECQL WAY: FETCH › (defn fetch-interesting [db org-id categories] › (fetch db ::it/interesting › #{::it/foo ::it/bar ::it/baz} › {::it/archived false › ::it/organization_id org-id › ::it/category (op/in categories)}))
  • 15. THE SPECQL WAY: FETCH › (defn fetch-interesting [db org-id categories] › (fetch db ::it/interesting › #{::it/foo ::it/bar ::it/baz} › {::it/archived false › ::it/organization_id org-id › ::it/category (op/in categories)})) The table to fetch from
  • 16. THE SPECQL WAY: FETCH › (defn fetch-interesting [db org-id categories] › (fetch db ::it/interesting › #{::it/foo ::it/bar ::it/baz} › {::it/archived false › ::it/organization_id org-id › ::it/category (op/in categories)})) Set of columns to retrieve
  • 17. THE SPECQL WAY: FETCH › (defn fetch-interesting [db org-id categories] › (fetch db ::it/interesting › #{::it/foo ::it/bar ::it/baz} › {::it/archived false › ::it/organization_id org-id › ::it/category (op/in categories)})) The WHERE clause map
  • 18. THE SPECQL WAY: RESULT › (fetch-interesting db 1 #{”stuff” ”things”}) › ;; => ({::it/foo 1 › ::it/bar ”example” › ::it/baz true} …) ›
  • 19. THE SPECQL WAY: JOIN › (fetch db ::it/interesting › #{::it/foo ::it/bar ::it/baz › [::it/organization #{::org/id ::org/name}]} › {::it/archived false › ::it/organization_id org-id › ::it/category (op/in categories)}))
  • 20. THE SPECQL WAY: JOIN › (fetch db ::it/interesting › #{::it/foo ::it/bar ::it/baz › [::it/organization #{::org/id ::org/name}]} › {::it/archived false › ::it/organization_id org-id › ::it/category (op/in categories)})) Nested column definition for a JOINed tables
  • 21. THE SPECQL WAY: JOIN › ;; => ({::it/foo 1 › ::it/bar ”example” › ::it/baz true › ::it/organization {::org/id 1 › ::org/name ”Acme Inc”} › …)
  • 22. THE SPECQL WAY: JOIN › ;; => ({::it/foo 1 › ::it/bar ”example” › ::it/baz true › ::it/organization {::org/id 1 › ::org/name ”Acme Inc”} › …) Joined entity is available in a nested map
  • 23. SPECQL BENEFITS › Clojure data! › The column set is just data and can be easily manipulated • Even given as parameters from the frontend › Where clauses can be easily added and are (mostly) just data as well › Every table and column has a single ns keyword definition • No more ”order” vs ”order-id” vs ”ord” differences in returned query results • Namespaced keys are the way of the future
  • 24. SPECQL BENEFITS › Clojure data! › The column set is just data and can be easily manipulated • Even given as parameters from the frontend › Where clauses can be easily added and are (mostly) just data as well › Every table and column has a single ns keyword definition • No more ”order” vs ”order-id” vs ”ord” differences in returned query results • Namespaced keys are the way of the future HERE TO STAY
  • 25. SPECQL BENEFITS › Works with ClojureScript • The spec generation part, put your specs in .cljc files and enjoy the same specs and have your db definitions drive your frontend as well › Works well with ”typed document storage” pattern • A column can be a user defined type or array › Provides generic upsert! • No need to branch code, let the db handle it › Works with database VIEWs
  • 26. STATUS › The github project page (https://github.com/tatut/specql) still says EXPERIMENTAL • Current 0.7 alpha stage, should be ready this year • We are already using it in production in Harja › No concrete promises before the experimental flag is gone, but the API should only grow • The test suite is comprehensive and should not break
  • 27. STATUS › 0.7 is coming and adds support for stored procedures • Macro for defining a stored procedure as a function • Better JOIN handling • Currently fetching multiple ”has many” collections at once doesn’t work properly › How to help • Please try it out if you are using PostgreSQL • Report rough edges, I try to provide good error messages

Editor's Notes

  1. Specql is a new library for using PostgreSQL from a Clojure application. It introspects your database at compile time (with the help of some macro magic) and provides clojure.spec specs for your tables and their columns. In addition to creating specs, Specql also retains runtime information so that it can provide generic query and update operations. More on those later.
  2. We have found that slightly different queries are painful to maintain. Hand written SQL also suffers from the problem of having different keys for different table columns. One query might use :order and another might use :orderid. There is no single truth of what a keyword means.
  3. Let's compare by an example. Consider some table called interesting_table that we want to query from.
  4. How can we easily vary the set of columns we fetch without having multiple almost identical queries or fetching everything and selecting the wanted keys on the caller.
  5. These two problems, in our experience, lead to making similar queries or make the queries you write awkwardly complicated. And we haven’t even talked about JOINs yet. What if I have two similar queries, but the other one needs to join a table?
  6. Adding columns from a JOINed table further changes how our SQL query looks. Making it difficult to even see that they are conceptually the same.
  7. First we define our tables so specql can generate the specs and record information about it.
  8. First we define our tables so specql can generate the specs and record information about it.
  9. First we define our tables so specql can generate the specs and record information about it.
  10. The spec for the table (a keys spec) is generated for the keyword specified here. All column specs will be generated in the same namespace.
  11. The column options can be used to do transformations for the columns (like converting an enum to keywords on the fly). In this example we are defining a JOIN specification. The organization virtual column is a one to one JOIN to the organization table.
  12. Specql provides a function called fetch that can be used to make queries against any previously defined table.
  13. The table is simply the keyword we registered the table under in a previous call to define-tables
  14. The columns is just a Clojure set of the namespaced keywords of the table columns
  15. The where map is interesting. The keys are columns of the table being queried the values can either be values (which are simple equality checks) or operators. The basic SQL operators are provided (equality, less than, greater than, in, like) and there is a protocol for you to define more. Multiple maps of where clauses can be combined with op/and and op/or operators.
  16. Finally the result is a sequence of maps which contain the namespaced keys.
  17. How do we add the JOIN?
  18. We simply add a vector to the column set. The first element is the join definition we defined in define-tables and the second element is a set of columns to retrieve from the join table.
  19. We simply add a vector to the column set. The first element is the join definition we defined in define-tables and the second element is a set of columns to retrieve from the join table.
  20. We simply add a vector to the column set. The first element is the join definition we defined in define-tables and the second element is a set of columns to retrieve from the join table.
  21. ClojureScript: speql understands some of the constraints on fields: NOT NULL and string lengths. PostgreSQL columns can be arbitrarily complex objects. You can have an array of a user defined type as a column and specql will work great with that. Upsert: Upsert, which came in pg 9.5, is fully supported. Upsert takes the db, the table keyword, a record map to insert and a where clause for the update Optionally the unique column set to upsert on can also be specified, and defaults to the primary key Views: you can write your complicated queries as views that and spec those like any table.
  22. Although it is a very young library, we are already using it in production in Harja, which is a large public sector application for road infastructure maintenance. We started adding specql to our new features and it has been helpful.