Safe interpolated SQL queries in Haskell

License: BSD-3-Clause

Language: Haskell

Keywords: haskell, interpolation, postgresql, postgresql-database, quasiquoter, template-haskell


Write natural SQL statements in Haskell using a QuasiQuotes!

{-# LANGUAGE QuasiQuotes #-}

import Data.Char (toLower)
import qualified Database.PostgreSQL.Simple as Pg
import Database.PostgreSQL.Simple.SqlQQ.Interpolated (isql)
import Control.Exception (bracket)

main :: IO ()
main = do
  bracket (Pg.connectPostgreSQL "host=localhost") Pg.close $ \conn -> do
    let limit = 10
    ages <- uncurry (query conn) [isql|SELECT age FROM table WHERE name = ${map toLower "CLIVE"} LIMIT ${limit}|]
    print (ages :: [Pg.Only Int])


With Nix you can quickly play around with this using a PostgreSQL database:

nix-shell -p '(import ./. {}).haskellPackages.ghcWithPackages (p: [p.gargoyle-postgresql-connect p.postgresql-simple-interpolate])' --run ghci

Then run

:set -XQuasiQuotes
import Gargoyle.PostgreSQL.Connect (withDb)
import Data.Pool (withResource)
import Database.PostgreSQL.Simple (Only (..), query)
import Database.PostgreSQL.Simple.SqlQQ.Interpolated (isql)
[isql|SELECT ${1 + 1}|]
-- ("SELECT ?",[Plain "2"])
withDb "db" $ \pool -> withResource pool $ \c -> (uncurry (query c) [isql|SELECT ${1 + 1}, ${reverse "HELLO"}::text|] :: IO [(Int, String)])
-- [(2,"OLLEH")]


This library is basically just a copy of the here package by Taylor M. Hedberg with slight modifications!

Project Statistics

Sourcerank 3
Repository Size 5.86 KB
Stars 2
Forks 0
Watchers 1
Open issues 0
Dependencies 6
Contributors 1
Tags 0
Last updated
Last pushed

Top Contributors See all

Elliot Cameron

Packages Referencing this Repo

Safe interpolated SQL queries in Haskell
Latest release - Published - 2 stars

Something wrong with this page? Make a suggestion

Last synced: 2019-08-19 05:02:35 UTC

Login to resync this repository