{-# LANGUAGE
FlexibleContexts
, MagicHash
, OverloadedStrings
, PolyKinds
, RankNTypes
, ScopedTypeVariables
#-}
module Squeal.PostgreSQL.Render
(
parenthesized
, (<+>)
, commaSeparated
, doubleQuoted
, renderCommaSeparated
, renderCommaSeparatedMaybe
, renderNat
, RenderSQL (..)
, printSQL
) where
import Control.Monad.Base
import Data.ByteString (ByteString)
import Data.Maybe
import Data.Monoid ((<>))
import Generics.SOP
import GHC.Exts
import GHC.TypeLits
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Char8 as Char8
parenthesized :: ByteString -> ByteString
parenthesized str = "(" <> str <> ")"
(<+>) :: ByteString -> ByteString -> ByteString
str1 <+> str2 = str1 <> " " <> str2
commaSeparated :: [ByteString] -> ByteString
commaSeparated = ByteString.intercalate ", "
doubleQuoted :: ByteString -> ByteString
doubleQuoted str = "\"" <> str <> "\""
renderCommaSeparated
:: SListI xs
=> (forall x. expression x -> ByteString)
-> NP expression xs -> ByteString
renderCommaSeparated render
= commaSeparated
. hcollapse
. hmap (K . render)
renderCommaSeparatedMaybe
:: SListI xs
=> (forall x. expression x -> Maybe ByteString)
-> NP expression xs -> ByteString
renderCommaSeparatedMaybe render
= commaSeparated
. catMaybes
. hcollapse
. hmap (K . render)
renderNat :: KnownNat n => proxy n -> ByteString
renderNat (_ :: proxy n) = fromString (show (natVal' (proxy# :: Proxy# n)))
class RenderSQL sql where
renderSQL :: sql -> ByteString
printSQL :: (RenderSQL sql, MonadBase IO io) => sql -> io ()
printSQL = liftBase . Char8.putStrLn . renderSQL