-- |
-- Module: Database.PostgreSQL.Typed.HDBC
-- Copyright: 2016 Dylan Simon
-- 
-- Use postgresql-typed as a backend for HDBC.
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Database.PostgreSQL.Typed.HDBC
  ( Connection
  , connect
  , fromPGConnection
  , withPGConnection
  , reloadTypes
  , connectionFetchSize
  , setFetchSize
  ) where

import Control.Arrow ((&&&))
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Exception (handle, throwIO)
import Control.Monad (void, guard)
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy.Char8 as BSLC
import Data.IORef (newIORef, readIORef, writeIORef, modifyIORef')
import Data.Int (Int16)
import qualified Data.IntMap.Lazy as IntMap
import Data.List (uncons)
import qualified Data.Map.Lazy as Map
import Data.Maybe (fromMaybe, isNothing)
import Data.Time.Clock (DiffTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Time.LocalTime (zonedTimeToUTC)
import Data.Word (Word32)
import qualified Database.HDBC.Types as HDBC
import qualified Database.HDBC.ColTypes as HDBC
import System.Mem.Weak (addFinalizer)
import Text.Read (readMaybe)

import Database.PostgreSQL.Typed.Types
import Database.PostgreSQL.Typed.Protocol
import Database.PostgreSQL.Typed.Dynamic
import Database.PostgreSQL.Typed.TypeCache
import Database.PostgreSQL.Typed.SQLToken
import Paths_postgresql_typed (version)

-- |A wrapped 'PGConnection'.
-- This differs from a bare 'PGConnection' in a few ways:
--
--   1. It always has exactly one active transaction (with 'pgBegin')
--   2. It automatically disconnects on GC
--   3. It provides a mutex around the underlying 'PGConnection' for thread-safety
--
data Connection = Connection
  { Connection -> MVar PGConnection
connectionPG :: MVar PGConnection
  , Connection -> String
connectionServerVer :: String
  , Connection -> IntMap SqlType
connectionTypes :: IntMap.IntMap SqlType
  , Connection -> Word32
connectionFetchSize :: Word32 -- ^Number of rows to fetch (and cache) with 'HDBC.execute' and each time 'HDBC.fetchRow' requires more rows. A higher value will result in fewer round-trips to the database but potentially more wasted data. Defaults to 1. 0 means fetch all rows.
  }

sqlError :: IO a -> IO a
sqlError :: forall a. IO a -> IO a
sqlError = forall e a. Exception e => (e -> IO a) -> IO a -> IO a
handle forall a b. (a -> b) -> a -> b
$ \(PGError MessageFields
m) -> 
  let f :: Char -> String
f Char
c = ByteString -> String
BSC.unpack forall a b. (a -> b) -> a -> b
$ forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault ByteString
BSC.empty Char
c MessageFields
m
      fC :: String
fC = Char -> String
f Char
'C'
      fD :: String
fD = Char -> String
f Char
'D' in
  forall e a. Exception e => e -> IO a
throwIO HDBC.SqlError 
    { seState :: String
HDBC.seState = String
fC
    , seNativeError :: Int
HDBC.seNativeError = if forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
fC then -Int
1 else forall a. a -> Maybe a -> a
fromMaybe Int
0 forall a b. (a -> b) -> a -> b
$ forall a. Read a => String -> Maybe a
readMaybe (Char -> String
f Char
'P')
    , seErrorMsg :: String
HDBC.seErrorMsg = Char -> String
f Char
'S' forall a. [a] -> [a] -> [a]
++ String
": " forall a. [a] -> [a] -> [a]
++ Char -> String
f Char
'M' forall a. [a] -> [a] -> [a]
++ if forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
fD then String
fD else Char
'\n'forall a. a -> [a] -> [a]
:String
fD
    }

-- |Use the underlying 'PGConnection' directly. You must be careful to ensure that the first invariant is preserved: you should not call 'pgBegin', 'pgCommit', or 'pgRollback' on it. All other operations should be safe.
withPGConnection :: Connection -> (PGConnection -> IO a) -> IO a
withPGConnection :: forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c = forall a. IO a -> IO a
sqlError forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (Connection -> MVar PGConnection
connectionPG Connection
c)

takePGConnection :: PGConnection -> IO (MVar PGConnection)
takePGConnection :: PGConnection -> IO (MVar PGConnection)
takePGConnection PGConnection
pg = do
  forall key. key -> IO () -> IO ()
addFinalizer PGConnection
pg (PGConnection -> IO ()
pgDisconnectOnce PGConnection
pg)
  PGConnection -> IO ()
pgBegin PGConnection
pg
  forall a. a -> IO (MVar a)
newMVar PGConnection
pg

-- |Convert an existing 'PGConnection' to an HDBC-compatible 'Connection'.
-- The caveats under 'connectionPG' apply if you plan to continue using the original 'PGConnection'.
fromPGConnection :: PGConnection -> IO Connection
fromPGConnection :: PGConnection -> IO Connection
fromPGConnection PGConnection
pg = do
  MVar PGConnection
pgv <- PGConnection -> IO (MVar PGConnection)
takePGConnection PGConnection
pg
  Connection -> IO Connection
reloadTypes Connection
    { connectionPG :: MVar PGConnection
connectionPG = MVar PGConnection
pgv
    , connectionServerVer :: String
connectionServerVer = forall b a. b -> (a -> b) -> Maybe a -> b
maybe String
"" ByteString -> String
BSC.unpack forall a b. (a -> b) -> a -> b
$ PGTypeEnv -> Maybe ByteString
pgServerVersion forall a b. (a -> b) -> a -> b
$ PGConnection -> PGTypeEnv
pgTypeEnv PGConnection
pg
    , connectionTypes :: IntMap SqlType
connectionTypes = forall a. Monoid a => a
mempty
    , connectionFetchSize :: Word32
connectionFetchSize = Word32
1
    }

-- |Connect to a database for HDBC use (equivalent to 'pgConnect' and 'pgBegin').
connect :: PGDatabase -> IO Connection
connect :: PGDatabase -> IO Connection
connect PGDatabase
d = forall a. IO a -> IO a
sqlError forall a b. (a -> b) -> a -> b
$ do
  PGConnection
pg <- PGDatabase -> IO PGConnection
pgConnect PGDatabase
d
  PGConnection -> IO Connection
fromPGConnection PGConnection
pg

-- |Reload the table of all types from the database.
-- This may be needed if you make structural changes to the database.
reloadTypes :: Connection -> IO Connection
reloadTypes :: Connection -> IO Connection
reloadTypes Connection
c = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
  PGTypes
t <- PGConnection -> IO PGTypes
pgGetTypes PGConnection
pg
  forall (m :: * -> *) a. Monad m => a -> m a
return Connection
c{ connectionTypes :: IntMap SqlType
connectionTypes = forall a b. (a -> b) -> IntMap a -> IntMap b
IntMap.map (PGTypeEnv -> String -> SqlType
sqlType (PGConnection -> PGTypeEnv
pgTypeEnv PGConnection
pg) forall b c a. (b -> c) -> (a -> b) -> a -> c
. PGName -> String
pgNameString) PGTypes
t }

-- |Change the 'connectionFetchSize' for new 'HDBC.Statement's created with 'HDBC.prepare'.
-- Ideally this could be set with each call to 'HDBC.execute' and 'HDBC.fetchRow', but the HDBC interface provides no way to do this.
setFetchSize :: Word32 -> Connection -> Connection
setFetchSize :: Word32 -> Connection -> Connection
setFetchSize Word32
i Connection
c = Connection
c{ connectionFetchSize :: Word32
connectionFetchSize = Word32
i }

sqls :: String -> BSLC.ByteString
sqls :: String -> ByteString
sqls = String -> ByteString
BSLC.pack

placeholders :: Int -> [SQLToken] -> [SQLToken]
placeholders :: Int -> [SQLToken] -> [SQLToken]
placeholders Int
n (SQLQMark Bool
False : [SQLToken]
l) = Int -> SQLToken
SQLParam Int
n forall a. a -> [a] -> [a]
: Int -> [SQLToken] -> [SQLToken]
placeholders (forall a. Enum a => a -> a
succ Int
n) [SQLToken]
l
placeholders Int
n (SQLQMark Bool
True : [SQLToken]
l) = Bool -> SQLToken
SQLQMark Bool
False forall a. a -> [a] -> [a]
: Int -> [SQLToken] -> [SQLToken]
placeholders Int
n [SQLToken]
l
placeholders Int
n (SQLToken
t : [SQLToken]
l) = SQLToken
t forall a. a -> [a] -> [a]
: Int -> [SQLToken] -> [SQLToken]
placeholders Int
n [SQLToken]
l
placeholders Int
_ [] = []

data ColDesc = ColDesc
  { ColDesc -> String
colDescName :: String
  , ColDesc -> SqlColDesc
colDesc :: HDBC.SqlColDesc
  , ColDesc -> PGValue -> SqlValue
colDescDecode :: PGValue -> HDBC.SqlValue
  }

data Cursor = Cursor
  { Cursor -> [ColDesc]
cursorDesc :: [ColDesc]
  , Cursor -> [PGValues]
cursorRow :: [PGValues]
  , Cursor -> Bool
cursorActive :: Bool
  , Cursor -> Statement
_cursorStatement :: HDBC.Statement -- keep a handle to prevent GC
  }

noCursor :: HDBC.Statement -> Cursor
noCursor :: Statement -> Cursor
noCursor = [ColDesc] -> [PGValues] -> Bool -> Statement -> Cursor
Cursor [] [] Bool
False

getType :: Connection -> PGConnection -> Maybe Bool -> PGColDescription -> ColDesc
getType :: Connection
-> PGConnection -> Maybe Bool -> PGColDescription -> ColDesc
getType Connection
c PGConnection
pg Maybe Bool
nul PGColDescription{Bool
Int16
Int32
Word32
ByteString
pgColBinary :: PGColDescription -> Bool
pgColModifier :: PGColDescription -> Int32
pgColSize :: PGColDescription -> Int16
pgColType :: PGColDescription -> Word32
pgColNumber :: PGColDescription -> Int16
pgColTable :: PGColDescription -> Word32
pgColName :: PGColDescription -> ByteString
pgColBinary :: Bool
pgColModifier :: Int32
pgColSize :: Int16
pgColType :: Word32
pgColNumber :: Int16
pgColTable :: Word32
pgColName :: ByteString
..} = ColDesc
  { colDescName :: String
colDescName = ByteString -> String
BSC.unpack ByteString
pgColName
  , colDesc :: SqlColDesc
colDesc = HDBC.SqlColDesc
    { colType :: SqlTypeId
HDBC.colType = SqlType -> SqlTypeId
sqlTypeId SqlType
t
    , colSize :: Maybe Int
HDBC.colSize = forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
pgColModifier forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Int32
pgColModifier forall a. Ord a => a -> a -> Bool
>= Int32
0)
    , colOctetLength :: Maybe Int
HDBC.colOctetLength = forall a b. (Integral a, Num b) => a -> b
fromIntegral Int16
pgColSize forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Int16
pgColSize forall a. Ord a => a -> a -> Bool
>= Int16
0)
    , colDecDigits :: Maybe Int
HDBC.colDecDigits = forall a. Maybe a
Nothing
    , colNullable :: Maybe Bool
HDBC.colNullable = Maybe Bool
nul
    }
  , colDescDecode :: PGValue -> SqlValue
colDescDecode = SqlType -> PGValue -> SqlValue
sqlTypeDecode SqlType
t
  } where t :: SqlType
t = forall a. a -> Int -> IntMap a -> a
IntMap.findWithDefault (PGTypeEnv -> String -> SqlType
sqlType (PGConnection -> PGTypeEnv
pgTypeEnv PGConnection
pg) forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show Word32
pgColType) (forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
pgColType) (Connection -> IntMap SqlType
connectionTypes Connection
c)

instance HDBC.IConnection Connection where
  disconnect :: Connection -> IO ()
disconnect Connection
c = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c
    PGConnection -> IO ()
pgDisconnectOnce
  commit :: Connection -> IO ()
commit Connection
c = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
    PGConnection -> IO ()
pgCommitAll PGConnection
pg
    PGConnection -> IO ()
pgBegin PGConnection
pg
  rollback :: Connection -> IO ()
rollback Connection
c = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
    PGConnection -> IO ()
pgRollbackAll PGConnection
pg
    PGConnection -> IO ()
pgBegin PGConnection
pg
  runRaw :: Connection -> String -> IO ()
runRaw Connection
c String
q = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg ->
    PGConnection -> ByteString -> IO ()
pgSimpleQueries_ PGConnection
pg forall a b. (a -> b) -> a -> b
$ String -> ByteString
sqls String
q
  run :: Connection -> String -> [SqlValue] -> IO Integer
run Connection
c String
q [SqlValue]
v = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
    let q' :: ByteString
q' = String -> ByteString
sqls forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show forall a b. (a -> b) -> a -> b
$ Int -> [SQLToken] -> [SQLToken]
placeholders Int
1 forall a b. (a -> b) -> a -> b
$ String -> [SQLToken]
sqlTokens String
q
        v' :: PGValues
v' = forall a b. (a -> b) -> [a] -> [b]
map SqlValue -> PGValue
encode [SqlValue]
v
    forall a. a -> Maybe a -> a
fromMaybe Integer
0 forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PGConnection
-> ByteString -> [Word32] -> PGValues -> IO (Maybe Integer)
pgRun PGConnection
pg ByteString
q' [] PGValues
v'
  prepare :: Connection -> String -> IO Statement
prepare Connection
c String
q = do
    let q' :: ByteString
q' = String -> ByteString
sqls forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show forall a b. (a -> b) -> a -> b
$ Int -> [SQLToken] -> [SQLToken]
placeholders Int
1 forall a b. (a -> b) -> a -> b
$ String -> [SQLToken]
sqlTokens String
q
    PGPreparedStatement
n <- forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> PGConnection -> ByteString -> [Word32] -> IO PGPreparedStatement
pgPrepare PGConnection
pg ByteString
q' []
    IORef Cursor
cr <- forall a. a -> IO (IORef a)
newIORef forall a b. (a -> b) -> a -> b
$ forall a. HasCallStack => String -> a
error String
"Cursor"
    let
      execute :: [SqlValue] -> IO Integer
execute [SqlValue]
v = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
        PGRowDescription
d <- PGConnection
-> PGPreparedStatement -> PGValues -> IO PGRowDescription
pgBind PGConnection
pg PGPreparedStatement
n (forall a b. (a -> b) -> [a] -> [b]
map SqlValue -> PGValue
encode [SqlValue]
v)
        ([PGValues]
r, Maybe Integer
e) <- PGConnection
-> PGPreparedStatement -> Word32 -> IO ([PGValues], Maybe Integer)
pgFetch PGConnection
pg PGPreparedStatement
n (Connection -> Word32
connectionFetchSize Connection
c)
        forall a. IORef a -> (a -> a) -> IO ()
modifyIORef' IORef Cursor
cr forall a b. (a -> b) -> a -> b
$ \Cursor
p -> Cursor
p
          { cursorDesc :: [ColDesc]
cursorDesc = forall a b. (a -> b) -> [a] -> [b]
map (Connection
-> PGConnection -> Maybe Bool -> PGColDescription -> ColDesc
getType Connection
c PGConnection
pg forall a. Maybe a
Nothing) PGRowDescription
d
          , cursorRow :: [PGValues]
cursorRow = [PGValues]
r
          , cursorActive :: Bool
cursorActive = forall a. Maybe a -> Bool
isNothing Maybe Integer
e
          }
        forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a -> a
fromMaybe Integer
0 Maybe Integer
e
      stmt :: Statement
stmt = HDBC.Statement
        { execute :: [SqlValue] -> IO Integer
HDBC.execute = [SqlValue] -> IO Integer
execute
        , executeRaw :: IO ()
HDBC.executeRaw = forall (f :: * -> *) a. Functor f => f a -> f ()
void forall a b. (a -> b) -> a -> b
$ [SqlValue] -> IO Integer
execute []
        , executeMany :: [[SqlValue]] -> IO ()
HDBC.executeMany = forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ [SqlValue] -> IO Integer
execute
        , finish :: IO ()
HDBC.finish = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
          forall a. IORef a -> a -> IO ()
writeIORef IORef Cursor
cr forall a b. (a -> b) -> a -> b
$ Statement -> Cursor
noCursor Statement
stmt
          PGConnection -> PGPreparedStatement -> IO ()
pgClose PGConnection
pg PGPreparedStatement
n
        , fetchRow :: IO (Maybe [SqlValue])
HDBC.fetchRow = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
          Cursor
p <- forall a. IORef a -> IO a
readIORef IORef Cursor
cr
          forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith ColDesc -> PGValue -> SqlValue
colDescDecode (Cursor -> [ColDesc]
cursorDesc Cursor
p)) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> case Cursor -> [PGValues]
cursorRow Cursor
p of
            [] | Cursor -> Bool
cursorActive Cursor
p -> do
                ([PGValues]
rl, Maybe Integer
e) <- PGConnection
-> PGPreparedStatement -> Word32 -> IO ([PGValues], Maybe Integer)
pgFetch PGConnection
pg PGPreparedStatement
n (Connection -> Word32
connectionFetchSize Connection
c)
                let rl' :: Maybe (PGValues, [PGValues])
rl' = forall a. [a] -> Maybe (a, [a])
uncons [PGValues]
rl
                forall a. IORef a -> a -> IO ()
writeIORef IORef Cursor
cr Cursor
p
                  { cursorRow :: [PGValues]
cursorRow = forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] forall a b. (a, b) -> b
snd Maybe (PGValues, [PGValues])
rl'
                  , cursorActive :: Bool
cursorActive = forall a. Maybe a -> Bool
isNothing Maybe Integer
e
                  }
                forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a b. (a, b) -> a
fst forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (PGValues, [PGValues])
rl'
               | Bool
otherwise ->
                forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
            (PGValues
r:[PGValues]
l) -> do
              forall a. IORef a -> a -> IO ()
writeIORef IORef Cursor
cr Cursor
p{ cursorRow :: [PGValues]
cursorRow = [PGValues]
l }
              forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a
Just PGValues
r
        , getColumnNames :: IO [String]
HDBC.getColumnNames =
          forall a b. (a -> b) -> [a] -> [b]
map ColDesc -> String
colDescName forall b c a. (b -> c) -> (a -> b) -> a -> c
. Cursor -> [ColDesc]
cursorDesc forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. IORef a -> IO a
readIORef IORef Cursor
cr
        , originalQuery :: String
HDBC.originalQuery = String
q
        , describeResult :: IO [(String, SqlColDesc)]
HDBC.describeResult =
          forall a b. (a -> b) -> [a] -> [b]
map (ColDesc -> String
colDescName forall (a :: * -> * -> *) b c c'.
Arrow a =>
a b c -> a b c' -> a b (c, c')
&&& ColDesc -> SqlColDesc
colDesc) forall b c a. (b -> c) -> (a -> b) -> a -> c
. Cursor -> [ColDesc]
cursorDesc forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. IORef a -> IO a
readIORef IORef Cursor
cr
        }
    forall a. IORef a -> a -> IO ()
writeIORef IORef Cursor
cr forall a b. (a -> b) -> a -> b
$ Statement -> Cursor
noCursor Statement
stmt
    forall key. key -> IO () -> IO ()
addFinalizer Statement
stmt forall a b. (a -> b) -> a -> b
$ forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> PGConnection -> PGPreparedStatement -> IO ()
pgClose PGConnection
pg PGPreparedStatement
n
    forall (m :: * -> *) a. Monad m => a -> m a
return Statement
stmt
  clone :: Connection -> IO Connection
clone Connection
c = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg -> do
    PGConnection
pg' <- PGDatabase -> IO PGConnection
pgConnect forall a b. (a -> b) -> a -> b
$ PGConnection -> PGDatabase
pgConnectionDatabase PGConnection
pg
    MVar PGConnection
pgv <- PGConnection -> IO (MVar PGConnection)
takePGConnection PGConnection
pg'
    forall (m :: * -> *) a. Monad m => a -> m a
return Connection
c{ connectionPG :: MVar PGConnection
connectionPG = MVar PGConnection
pgv }
  hdbcDriverName :: Connection -> String
hdbcDriverName Connection
_ = String
"postgresql-typed"
  hdbcClientVer :: Connection -> String
hdbcClientVer Connection
_ = forall a. Show a => a -> String
show Version
version
  proxiedClientName :: Connection -> String
proxiedClientName = forall conn. IConnection conn => conn -> String
HDBC.hdbcDriverName
  proxiedClientVer :: Connection -> String
proxiedClientVer = forall conn. IConnection conn => conn -> String
HDBC.hdbcClientVer
  dbServerVer :: Connection -> String
dbServerVer = Connection -> String
connectionServerVer
  dbTransactionSupport :: Connection -> Bool
dbTransactionSupport Connection
_ = Bool
True
  getTables :: Connection -> IO [String]
getTables Connection
c = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg ->
    forall a b. (a -> b) -> [a] -> [b]
map (forall a. PGRep a => PGValue -> a
pgDecodeRep forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. [a] -> a
head) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a, b) -> b
snd forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PGConnection -> ByteString -> IO (Int, [PGValues])
pgSimpleQuery PGConnection
pg ([ByteString] -> ByteString
BSLC.fromChunks
      [ ByteString
"SELECT relname"
      ,  ByteString
" FROM pg_catalog.pg_class"
      ,  ByteString
" JOIN pg_catalog.pg_namespace ON relnamespace = pg_namespace.oid"
      , ByteString
" WHERE nspname = ANY (current_schemas(false))"
      ,   ByteString
" AND relkind IN ('r','v','m','f')"
      ])
  describeTable :: Connection -> String -> IO [(String, SqlColDesc)]
describeTable Connection
c String
t = forall a. Connection -> (PGConnection -> IO a) -> IO a
withPGConnection Connection
c forall a b. (a -> b) -> a -> b
$ \PGConnection
pg ->
    forall a b. (a -> b) -> [a] -> [b]
map (\[PGValue
attname, PGValue
attrelid, PGValue
attnum, PGValue
atttypid, PGValue
attlen, PGValue
atttypmod, PGValue
attnotnull] ->
      ColDesc -> String
colDescName forall (a :: * -> * -> *) b c c'.
Arrow a =>
a b c -> a b c' -> a b (c, c')
&&& ColDesc -> SqlColDesc
colDesc forall a b. (a -> b) -> a -> b
$ Connection
-> PGConnection -> Maybe Bool -> PGColDescription -> ColDesc
getType Connection
c PGConnection
pg (forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not forall a b. (a -> b) -> a -> b
$ forall a. PGRep a => PGValue -> a
pgDecodeRep PGValue
attnotnull) PGColDescription
        { pgColName :: ByteString
pgColName = forall a. PGRep a => PGValue -> a
pgDecodeRep PGValue
attname
        , pgColTable :: Word32
pgColTable = forall a. PGRep a => PGValue -> a
pgDecodeRep PGValue
attrelid
        , pgColNumber :: Int16
pgColNumber = forall a. PGRep a => PGValue -> a
pgDecodeRep PGValue
attnum
        , pgColType :: Word32
pgColType = forall a. PGRep a => PGValue -> a
pgDecodeRep PGValue
atttypid
        , pgColSize :: Int16
pgColSize = forall a. PGRep a => PGValue -> a
pgDecodeRep PGValue
attlen
        , pgColModifier :: Int32
pgColModifier = forall a. PGRep a => PGValue -> a
pgDecodeRep PGValue
atttypmod
        , pgColBinary :: Bool
pgColBinary = Bool
False
        })
      forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a, b) -> b
snd forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PGConnection -> ByteString -> IO (Int, [PGValues])
pgSimpleQuery PGConnection
pg ([ByteString] -> ByteString
BSLC.fromChunks
        [ ByteString
"SELECT attname, attrelid, attnum, atttypid, attlen, atttypmod, attnotnull"
        ,  ByteString
" FROM pg_catalog.pg_attribute"
        , ByteString
" WHERE attrelid = ", forall a. PGRep a => a -> ByteString
pgLiteralRep String
t, ByteString
"::regclass"
        , ByteString
"   AND attnum > 0 AND NOT attisdropped"
        , ByteString
" ORDER BY attrelid, attnum"
        ])

encodeRep :: PGRep a => a -> PGValue
encodeRep :: forall a. PGRep a => a -> PGValue
encodeRep a
x = ByteString -> PGValue
PGTextValue forall a b. (a -> b) -> a -> b
$ forall (t :: Symbol) a.
PGParameter t a =>
PGTypeID t -> a -> ByteString
pgEncode (forall a. a -> PGTypeID (PGRepType a)
pgTypeOf a
x) a
x

encode :: HDBC.SqlValue -> PGValue
encode :: SqlValue -> PGValue
encode (HDBC.SqlString String
x)                 = forall a. PGRep a => a -> PGValue
encodeRep String
x
encode (HDBC.SqlByteString ByteString
x)             = forall a. PGRep a => a -> PGValue
encodeRep ByteString
x
encode (HDBC.SqlWord32 Word32
x)                 = forall a. PGRep a => a -> PGValue
encodeRep Word32
x
encode (HDBC.SqlWord64 Word64
x)                 = forall a. PGRep a => a -> PGValue
encodeRep (forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
x :: Rational)
encode (HDBC.SqlInt32 Int32
x)                  = forall a. PGRep a => a -> PGValue
encodeRep Int32
x
encode (HDBC.SqlInt64 Int64
x)                  = forall a. PGRep a => a -> PGValue
encodeRep Int64
x
encode (HDBC.SqlInteger Integer
x)                = forall a. PGRep a => a -> PGValue
encodeRep (forall a. Num a => Integer -> a
fromInteger Integer
x :: Rational)
encode (HDBC.SqlChar Char
x)                   = forall a. PGRep a => a -> PGValue
encodeRep Char
x
encode (HDBC.SqlBool Bool
x)                   = forall a. PGRep a => a -> PGValue
encodeRep Bool
x
encode (HDBC.SqlDouble Double
x)                 = forall a. PGRep a => a -> PGValue
encodeRep Double
x
encode (HDBC.SqlRational Rational
x)               = forall a. PGRep a => a -> PGValue
encodeRep Rational
x
encode (HDBC.SqlLocalDate Day
x)              = forall a. PGRep a => a -> PGValue
encodeRep Day
x
encode (HDBC.SqlLocalTimeOfDay TimeOfDay
x)         = forall a. PGRep a => a -> PGValue
encodeRep TimeOfDay
x
encode (HDBC.SqlZonedLocalTimeOfDay TimeOfDay
t TimeZone
z)  = forall a. PGRep a => a -> PGValue
encodeRep (TimeOfDay
t, TimeZone
z)
encode (HDBC.SqlLocalTime LocalTime
x)              = forall a. PGRep a => a -> PGValue
encodeRep LocalTime
x
encode (HDBC.SqlZonedTime ZonedTime
x)              = forall a. PGRep a => a -> PGValue
encodeRep (ZonedTime -> UTCTime
zonedTimeToUTC ZonedTime
x)
encode (HDBC.SqlUTCTime UTCTime
x)                = forall a. PGRep a => a -> PGValue
encodeRep UTCTime
x
encode (HDBC.SqlDiffTime NominalDiffTime
x)               = forall a. PGRep a => a -> PGValue
encodeRep (forall a b. (Real a, Fractional b) => a -> b
realToFrac NominalDiffTime
x :: DiffTime)
encode (HDBC.SqlPOSIXTime NominalDiffTime
x)              = forall a. PGRep a => a -> PGValue
encodeRep (forall a b. (Real a, Fractional b) => a -> b
realToFrac NominalDiffTime
x :: Rational) -- (posixSecondsToUTCTime x)
encode (HDBC.SqlEpochTime Integer
x)              = forall a. PGRep a => a -> PGValue
encodeRep (NominalDiffTime -> UTCTime
posixSecondsToUTCTime (forall a. Num a => Integer -> a
fromInteger Integer
x))
encode (HDBC.SqlTimeDiff Integer
x)               = forall a. PGRep a => a -> PGValue
encodeRep (forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
x :: DiffTime)
encode SqlValue
HDBC.SqlNull = PGValue
PGNullValue

data SqlType = SqlType
  { SqlType -> SqlTypeId
sqlTypeId :: HDBC.SqlTypeId
  , SqlType -> PGValue -> SqlValue
sqlTypeDecode :: PGValue -> HDBC.SqlValue
  }

sqlType :: PGTypeEnv -> String -> SqlType
sqlType :: PGTypeEnv -> String -> SqlType
sqlType PGTypeEnv
e String
t = SqlType
  { sqlTypeId :: SqlTypeId
sqlTypeId = String -> SqlTypeId
typeId String
t
  , sqlTypeDecode :: PGValue -> SqlValue
sqlTypeDecode = String -> PGTypeEnv -> PGValue -> SqlValue
decode String
t PGTypeEnv
e
  }

typeId :: String -> HDBC.SqlTypeId
typeId :: String -> SqlTypeId
typeId String
"boolean"                      = SqlTypeId
HDBC.SqlBitT
typeId String
"bytea"                        = SqlTypeId
HDBC.SqlVarBinaryT
typeId String
"\"char\""                     = SqlTypeId
HDBC.SqlCharT
typeId String
"name"                         = SqlTypeId
HDBC.SqlVarCharT
typeId String
"bigint"                       = SqlTypeId
HDBC.SqlBigIntT
typeId String
"smallint"                     = SqlTypeId
HDBC.SqlSmallIntT
typeId String
"integer"                      = SqlTypeId
HDBC.SqlIntegerT
typeId String
"text"                         = SqlTypeId
HDBC.SqlLongVarCharT
typeId String
"oid"                          = SqlTypeId
HDBC.SqlIntegerT
typeId String
"real"                         = SqlTypeId
HDBC.SqlFloatT
typeId String
"double precision"             = SqlTypeId
HDBC.SqlDoubleT
typeId String
"abstime"                      = SqlTypeId
HDBC.SqlUTCDateTimeT
typeId String
"reltime"                      = SqlInterval -> SqlTypeId
HDBC.SqlIntervalT SqlInterval
HDBC.SqlIntervalSecondT
typeId String
"tinterval"                    = SqlInterval -> SqlTypeId
HDBC.SqlIntervalT SqlInterval
HDBC.SqlIntervalDayToSecondT
typeId String
"bpchar"                       = SqlTypeId
HDBC.SqlVarCharT
typeId String
"character varying"            = SqlTypeId
HDBC.SqlVarCharT
typeId String
"date"                         = SqlTypeId
HDBC.SqlDateT
typeId String
"time without time zone"       = SqlTypeId
HDBC.SqlTimeT
typeId String
"timestamp without time zone"  = SqlTypeId
HDBC.SqlTimestampT
typeId String
"timestamp with time zone"     = SqlTypeId
HDBC.SqlTimestampWithZoneT -- XXX really SQLUTCDateTimeT
typeId String
"interval"                     = SqlInterval -> SqlTypeId
HDBC.SqlIntervalT SqlInterval
HDBC.SqlIntervalDayToSecondT
typeId String
"time with time zone"          = SqlTypeId
HDBC.SqlTimeWithZoneT
typeId String
"numeric"                      = SqlTypeId
HDBC.SqlDecimalT
typeId String
"uuid"                         = SqlTypeId
HDBC.SqlGUIDT
typeId String
t = String -> SqlTypeId
HDBC.SqlUnknownT String
t

decodeRep :: PGColumn t a => PGTypeID t -> PGTypeEnv -> (a -> HDBC.SqlValue) -> PGValue -> HDBC.SqlValue
decodeRep :: forall (t :: Symbol) a.
PGColumn t a =>
PGTypeID t -> PGTypeEnv -> (a -> SqlValue) -> PGValue -> SqlValue
decodeRep PGTypeID t
t PGTypeEnv
e a -> SqlValue
f (PGBinaryValue ByteString
v) = a -> SqlValue
f forall a b. (a -> b) -> a -> b
$ forall (t :: Symbol) a.
PGColumn t a =>
PGTypeEnv -> PGTypeID t -> ByteString -> a
pgDecodeBinary PGTypeEnv
e PGTypeID t
t ByteString
v
decodeRep PGTypeID t
t PGTypeEnv
_ a -> SqlValue
f (PGTextValue ByteString
v) = a -> SqlValue
f forall a b. (a -> b) -> a -> b
$ forall (t :: Symbol) a.
PGColumn t a =>
PGTypeID t -> ByteString -> a
pgDecode PGTypeID t
t ByteString
v
decodeRep PGTypeID t
_ PGTypeEnv
_ a -> SqlValue
_ PGValue
PGNullValue = SqlValue
HDBC.SqlNull

#define DECODE(T) \
  decode T e = decodeRep (PGTypeProxy :: PGTypeID T) e

decode :: String -> PGTypeEnv -> PGValue -> HDBC.SqlValue
decode :: String -> PGTypeEnv -> PGValue -> SqlValue
DECODE(String
"boolean")                     HDBC.SqlBool
DECODE(String
"\"char\"")                    HDBC.SqlChar
DECODE(String
"name")                        HDBC.SqlString
DECODE(String
"bigint")                      HDBC.SqlInt64
DECODE(String
"smallint")                    (HDBC.SqlInt32 . fromIntegral :: Int16 -> HDBC.SqlValue)
DECODE(String
"integer")                     HDBC.SqlInt32
DECODE(String
"text")                        HDBC.SqlString
DECODE(String
"oid")                         HDBC.SqlWord32
DECODE(String
"real")                        HDBC.SqlDouble
DECODE(String
"double precision")            HDBC.SqlDouble
DECODE(String
"bpchar")                      HDBC.SqlString
DECODE(String
"character varying")           HDBC.SqlString
DECODE(String
"date")                        HDBC.SqlLocalDate
DECODE(String
"time without time zone")      HDBC.SqlLocalTimeOfDay
DECODE(String
"time with time zone")         (uncurry HDBC.SqlZonedLocalTimeOfDay)
DECODE(String
"timestamp without time zone") HDBC.SqlLocalTime
DECODE(String
"timestamp with time zone")    HDBC.SqlUTCTime
DECODE(String
"interval")                    (HDBC.SqlDiffTime . realToFrac :: DiffTime -> HDBC.SqlValue)
DECODE(String
"numeric")                     HDBC.SqlRational
decode String
_ PGTypeEnv
_ = PGValue -> SqlValue
decodeRaw where
  decodeRaw :: PGValue -> SqlValue
decodeRaw (PGBinaryValue ByteString
v) = ByteString -> SqlValue
HDBC.SqlByteString ByteString
v
  decodeRaw (PGTextValue ByteString
v)   = ByteString -> SqlValue
HDBC.SqlByteString ByteString
v
  decodeRaw PGValue
PGNullValue       = SqlValue
HDBC.SqlNull