{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-} -- Pattern match 'PersistDbSpecific'

-- | A postgresql backend for persistent.
module Database.Persist.Postgresql
    ( withPostgresqlPool
    , withPostgresqlPoolWithVersion
    , withPostgresqlConn
    , withPostgresqlConnWithVersion
    , withPostgresqlPoolWithConf
    , createPostgresqlPool
    , createPostgresqlPoolModified
    , createPostgresqlPoolModifiedWithVersion
    , createPostgresqlPoolWithConf
    , module Database.Persist.Sql
    , ConnectionString
    , PostgresConf (..)
    , PgInterval (..)
    , openSimpleConn
    , openSimpleConnWithVersion
    , tableName
    , fieldName
    , mockMigration
    , migrateEnableExtension
    , PostgresConfHooks(..)
    , defaultPostgresConfHooks
    ) where

import qualified Database.PostgreSQL.LibPQ as LibPQ

import qualified Database.PostgreSQL.Simple as PG
import qualified Database.PostgreSQL.Simple.Internal as PG
import qualified Database.PostgreSQL.Simple.FromField as PGFF
import qualified Database.PostgreSQL.Simple.ToField as PGTF
import qualified Database.PostgreSQL.Simple.Transaction as PG
import qualified Database.PostgreSQL.Simple.Types as PG
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as PS
import Database.PostgreSQL.Simple.Ok (Ok (..))

import Control.Arrow
import Control.Exception (Exception, throw, throwIO)
import Control.Monad
import Control.Monad.Except
import Control.Monad.IO.Unlift (MonadIO (..), MonadUnliftIO)
import Control.Monad.Logger (MonadLoggerIO, runNoLoggingT)
import Control.Monad.Trans.Reader (runReaderT)
import Control.Monad.Trans.Writer (WriterT(..), runWriterT)

import qualified Blaze.ByteString.Builder.Char8 as BBB
import Data.Acquire (Acquire, mkAcquire, with)
import Data.Aeson
import Data.Aeson.Types (modifyFailure)
import qualified Data.Attoparsec.Text as AT
import qualified Data.Attoparsec.ByteString.Char8 as P
import Data.Bits ((.&.))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Char8 as B8
import Data.Char (ord)
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Data
import Data.Either (partitionEithers)
import Data.Fixed (Fixed(..), Pico)
import Data.Function (on)
import Data.Int (Int64)
import qualified Data.IntMap as I
import Data.IORef
import Data.List (find, sort, groupBy, foldl')
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List as List
import qualified Data.List.NonEmpty as NEL
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid ((<>))
import Data.Pool (Pool)
import Data.String.Conversions.Monomorphic (toStrictByteString)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import Data.Text.Read (rational)
import Data.Time (utc, NominalDiffTime, localTimeToUTC)
import System.Environment (getEnvironment)

import Database.Persist.Sql
import qualified Database.Persist.Sql.Util as Util

-- | A @libpq@ connection string.  A simple example of connection
-- string would be @\"host=localhost port=5432 user=test
-- dbname=test password=test\"@.  Please read libpq's
-- documentation at
-- <https://www.postgresql.org/docs/current/static/libpq-connect.html>
-- for more details on how to create such strings.
type ConnectionString = ByteString

-- | PostgresServerVersionError exception. This is thrown when persistent
-- is unable to find the version of the postgreSQL server.
data PostgresServerVersionError = PostgresServerVersionError String

instance Show PostgresServerVersionError where
    show :: PostgresServerVersionError -> String
show (PostgresServerVersionError String
uniqueMsg) =
      String
"Unexpected PostgreSQL server version, got " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
uniqueMsg
instance Exception PostgresServerVersionError

-- | Create a PostgreSQL connection pool and run the given action. The pool is
-- properly released after the action finishes using it.  Note that you should
-- not use the given 'ConnectionPool' outside the action since it may already
-- have been released.
-- The provided action should use 'runSqlConn' and *not* 'runReaderT' because
-- the former brackets the database action with transaction begin/commit.
withPostgresqlPool :: (MonadLoggerIO m, MonadUnliftIO m)
                   => ConnectionString
                   -- ^ Connection string to the database.
                   -> Int
                   -- ^ Number of connections to be kept open in
                   -- the pool.
                   -> (Pool SqlBackend -> m a)
                   -- ^ Action to be executed that uses the
                   -- connection pool.
                   -> m a
withPostgresqlPool :: ConnectionString -> Int -> (Pool SqlBackend -> m a) -> m a
withPostgresqlPool ConnectionString
ci = (Connection -> IO (Maybe Double))
-> ConnectionString -> Int -> (Pool SqlBackend -> m a) -> m a
forall (m :: * -> *) a.
(MonadUnliftIO m, MonadLoggerIO m) =>
(Connection -> IO (Maybe Double))
-> ConnectionString -> Int -> (Pool SqlBackend -> m a) -> m a
withPostgresqlPoolWithVersion Connection -> IO (Maybe Double)
getServerVersion ConnectionString
ci

-- | Same as 'withPostgresPool', but takes a callback for obtaining
-- the server version (to work around an Amazon Redshift bug).
--
-- @since 2.6.2
withPostgresqlPoolWithVersion :: (MonadUnliftIO m, MonadLoggerIO m)
                              => (PG.Connection -> IO (Maybe Double))
                              -- ^ Action to perform to get the server version.
                              -> ConnectionString
                              -- ^ Connection string to the database.
                              -> Int
                              -- ^ Number of connections to be kept open in
                              -- the pool.
                              -> (Pool SqlBackend -> m a)
                              -- ^ Action to be executed that uses the
                              -- connection pool.
                              -> m a
withPostgresqlPoolWithVersion :: (Connection -> IO (Maybe Double))
-> ConnectionString -> Int -> (Pool SqlBackend -> m a) -> m a
withPostgresqlPoolWithVersion Connection -> IO (Maybe Double)
getVerDouble ConnectionString
ci = do
  let getVer :: Connection -> IO (NonEmpty Word)
getVer = (Connection -> IO (Maybe Double))
-> Connection -> IO (NonEmpty Word)
oldGetVersionToNew Connection -> IO (Maybe Double)
getVerDouble
  (LogFunc -> IO SqlBackend)
-> Int -> (Pool SqlBackend -> m a) -> m a
forall backend (m :: * -> *) a.
(MonadLoggerIO m, MonadUnliftIO m,
 BackendCompatible SqlBackend backend) =>
(LogFunc -> IO backend) -> Int -> (Pool backend -> m a) -> m a
withSqlPool ((LogFunc -> IO SqlBackend)
 -> Int -> (Pool SqlBackend -> m a) -> m a)
-> (LogFunc -> IO SqlBackend)
-> Int
-> (Pool SqlBackend -> m a)
-> m a
forall a b. (a -> b) -> a -> b
$ (Connection -> IO ())
-> (Connection -> IO (NonEmpty Word))
-> ConnectionString
-> LogFunc
-> IO SqlBackend
open' (IO () -> Connection -> IO ()
forall a b. a -> b -> a
const (IO () -> Connection -> IO ()) -> IO () -> Connection -> IO ()
forall a b. (a -> b) -> a -> b
$ () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()) Connection -> IO (NonEmpty Word)
getVer ConnectionString
ci

-- | Same as 'withPostgresqlPool', but can be configured with 'PostgresConf' and 'PostgresConfHooks'.
--
-- @since 2.11.0.0
withPostgresqlPoolWithConf :: (MonadUnliftIO m, MonadLoggerIO m)
                           => PostgresConf -- ^ Configuration for connecting to Postgres
                           -> PostgresConfHooks -- ^ Record of callback functions
                           -> (Pool SqlBackend -> m a)
                           -- ^ Action to be executed that uses the
                           -- connection pool.
                           -> m a
withPostgresqlPoolWithConf :: PostgresConf
-> PostgresConfHooks -> (Pool SqlBackend -> m a) -> m a
withPostgresqlPoolWithConf PostgresConf
conf PostgresConfHooks
hooks = do
  let getVer :: Connection -> IO (NonEmpty Word)
getVer = PostgresConfHooks -> Connection -> IO (NonEmpty Word)
pgConfHooksGetServerVersion PostgresConfHooks
hooks
      modConn :: Connection -> IO ()
modConn = PostgresConfHooks -> Connection -> IO ()
pgConfHooksAfterCreate PostgresConfHooks
hooks
  let logFuncToBackend :: LogFunc -> IO SqlBackend
logFuncToBackend = (Connection -> IO ())
-> (Connection -> IO (NonEmpty Word))
-> ConnectionString
-> LogFunc
-> IO SqlBackend
open' Connection -> IO ()
modConn Connection -> IO (NonEmpty Word)
getVer (PostgresConf -> ConnectionString
pgConnStr PostgresConf
conf)
  (LogFunc -> IO SqlBackend)
-> ConnectionPoolConfig -> (Pool SqlBackend -> m a) -> m a
forall backend (m :: * -> *) a.
(MonadLoggerIO m, MonadUnliftIO m,
 BackendCompatible SqlBackend backend) =>
(LogFunc -> IO backend)
-> ConnectionPoolConfig -> (Pool backend -> m a) -> m a
withSqlPoolWithConfig LogFunc -> IO SqlBackend
logFuncToBackend (PostgresConf -> ConnectionPoolConfig
postgresConfToConnectionPoolConfig PostgresConf
conf)

-- | Create a PostgreSQL connection pool.  Note that it's your
-- responsibility to properly close the connection pool when
-- unneeded.  Use 'withPostgresqlPool' for an automatic resource
-- control.
createPostgresqlPool :: (MonadUnliftIO m, MonadLoggerIO m)
                     => ConnectionString
                     -- ^ Connection string to the database.
                     -> Int
                     -- ^ Number of connections to be kept open
                     -- in the pool.
                     -> m (Pool SqlBackend)
createPostgresqlPool :: ConnectionString -> Int -> m (Pool SqlBackend)
createPostgresqlPool = (Connection -> IO ())
-> ConnectionString -> Int -> m (Pool SqlBackend)
forall (m :: * -> *).
(MonadUnliftIO m, MonadLoggerIO m) =>
(Connection -> IO ())
-> ConnectionString -> Int -> m (Pool SqlBackend)
createPostgresqlPoolModified (IO () -> Connection -> IO ()
forall a b. a -> b -> a
const (IO () -> Connection -> IO ()) -> IO () -> Connection -> IO ()
forall a b. (a -> b) -> a -> b
$ () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ())

-- | Same as 'createPostgresqlPool', but additionally takes a callback function
-- for some connection-specific tweaking to be performed after connection
-- creation. This could be used, for example, to change the schema. For more
-- information, see:
--
-- <https://groups.google.com/d/msg/yesodweb/qUXrEN_swEo/O0pFwqwQIdcJ>
--
-- @since 2.1.3
createPostgresqlPoolModified
    :: (MonadUnliftIO m, MonadLoggerIO m)
    => (PG.Connection -> IO ()) -- ^ Action to perform after connection is created.
    -> ConnectionString -- ^ Connection string to the database.
    -> Int -- ^ Number of connections to be kept open in the pool.
    -> m (Pool SqlBackend)
createPostgresqlPoolModified :: (Connection -> IO ())
-> ConnectionString -> Int -> m (Pool SqlBackend)
createPostgresqlPoolModified = (Connection -> IO (Maybe Double))
-> (Connection -> IO ())
-> ConnectionString
-> Int
-> m (Pool SqlBackend)
forall (m :: * -> *).
(MonadUnliftIO m, MonadLoggerIO m) =>
(Connection -> IO (Maybe Double))
-> (Connection -> IO ())
-> ConnectionString
-> Int
-> m (Pool SqlBackend)
createPostgresqlPoolModifiedWithVersion Connection -> IO (Maybe Double)
getServerVersion

-- | Same as other similarly-named functions in this module, but takes callbacks for obtaining
-- the server version (to work around an Amazon Redshift bug) and connection-specific tweaking
-- (to change the schema).
--
-- @since 2.6.2
createPostgresqlPoolModifiedWithVersion
    :: (MonadUnliftIO m, MonadLoggerIO m)
    => (PG.Connection -> IO (Maybe Double)) -- ^ Action to perform to get the server version.
    -> (PG.Connection -> IO ()) -- ^ Action to perform after connection is created.
    -> ConnectionString -- ^ Connection string to the database.
    -> Int -- ^ Number of connections to be kept open in the pool.
    -> m (Pool SqlBackend)
createPostgresqlPoolModifiedWithVersion :: (Connection -> IO (Maybe Double))
-> (Connection -> IO ())
-> ConnectionString
-> Int
-> m (Pool SqlBackend)
createPostgresqlPoolModifiedWithVersion Connection -> IO (Maybe Double)
getVerDouble Connection -> IO ()
modConn ConnectionString
ci = do
  let getVer :: Connection -> IO (NonEmpty Word)
getVer = (Connection -> IO (Maybe Double))
-> Connection -> IO (NonEmpty Word)
oldGetVersionToNew Connection -> IO (Maybe Double)
getVerDouble
  (LogFunc -> IO SqlBackend) -> Int -> m (Pool SqlBackend)
forall backend (m :: * -> *).
(MonadLoggerIO m, MonadUnliftIO m,
 BackendCompatible SqlBackend backend) =>
(LogFunc -> IO backend) -> Int -> m (Pool backend)
createSqlPool ((LogFunc -> IO SqlBackend) -> Int -> m (Pool SqlBackend))
-> (LogFunc -> IO SqlBackend) -> Int -> m (Pool SqlBackend)
forall a b. (a -> b) -> a -> b
$ (Connection -> IO ())
-> (Connection -> IO (NonEmpty Word))
-> ConnectionString
-> LogFunc
-> IO SqlBackend
open' Connection -> IO ()
modConn Connection -> IO (NonEmpty Word)
getVer ConnectionString
ci

-- | Same as 'createPostgresqlPool', but can be configured with 'PostgresConf' and 'PostgresConfHooks'.
--
-- @since 2.11.0.0
createPostgresqlPoolWithConf
    :: (MonadUnliftIO m, MonadLoggerIO m)
    => PostgresConf -- ^ Configuration for connecting to Postgres
    -> PostgresConfHooks -- ^ Record of callback functions
    -> m (Pool SqlBackend)
createPostgresqlPoolWithConf :: PostgresConf -> PostgresConfHooks -> m (Pool SqlBackend)
createPostgresqlPoolWithConf PostgresConf
conf PostgresConfHooks
hooks = do
  let getVer :: Connection -> IO (NonEmpty Word)
getVer = PostgresConfHooks -> Connection -> IO (NonEmpty Word)
pgConfHooksGetServerVersion PostgresConfHooks
hooks
      modConn :: Connection -> IO ()
modConn = PostgresConfHooks -> Connection -> IO ()
pgConfHooksAfterCreate PostgresConfHooks
hooks
  (LogFunc -> IO SqlBackend)
-> ConnectionPoolConfig -> m (Pool SqlBackend)
forall (m :: * -> *) backend.
(MonadLoggerIO m, MonadUnliftIO m,
 BackendCompatible SqlBackend backend) =>
(LogFunc -> IO backend) -> ConnectionPoolConfig -> m (Pool backend)
createSqlPoolWithConfig ((Connection -> IO ())
-> (Connection -> IO (NonEmpty Word))
-> ConnectionString
-> LogFunc
-> IO SqlBackend
open' Connection -> IO ()
modConn Connection -> IO (NonEmpty Word)
getVer (PostgresConf -> ConnectionString
pgConnStr PostgresConf
conf)) (PostgresConf -> ConnectionPoolConfig
postgresConfToConnectionPoolConfig PostgresConf
conf)

postgresConfToConnectionPoolConfig :: PostgresConf -> ConnectionPoolConfig
postgresConfToConnectionPoolConfig :: PostgresConf -> ConnectionPoolConfig
postgresConfToConnectionPoolConfig PostgresConf
conf =
  ConnectionPoolConfig :: Int -> NominalDiffTime -> Int -> ConnectionPoolConfig
ConnectionPoolConfig
    { connectionPoolConfigStripes :: Int
connectionPoolConfigStripes = PostgresConf -> Int
pgPoolStripes PostgresConf
conf
    , connectionPoolConfigIdleTimeout :: NominalDiffTime
connectionPoolConfigIdleTimeout = Integer -> NominalDiffTime
forall a. Num a => Integer -> a
fromInteger (Integer -> NominalDiffTime) -> Integer -> NominalDiffTime
forall a b. (a -> b) -> a -> b
$ PostgresConf -> Integer
pgPoolIdleTimeout PostgresConf
conf
    , connectionPoolConfigSize :: Int
connectionPoolConfigSize = PostgresConf -> Int
pgPoolSize PostgresConf
conf
    }

-- | Same as 'withPostgresqlPool', but instead of opening a pool
-- of connections, only one connection is opened.
-- The provided action should use 'runSqlConn' and *not* 'runReaderT' because
-- the former brackets the database action with transaction begin/commit.
withPostgresqlConn :: (MonadUnliftIO m, MonadLoggerIO m)
                   => ConnectionString -> (SqlBackend -> m a) -> m a
withPostgresqlConn :: ConnectionString -> (SqlBackend -> m a) -> m a
withPostgresqlConn = (Connection -> IO (Maybe Double))
-> ConnectionString -> (SqlBackend -> m a) -> m a
forall (m :: * -> *) a.
(MonadUnliftIO m, MonadLoggerIO m) =>
(Connection -> IO (Maybe Double))
-> ConnectionString -> (SqlBackend -> m a) -> m a
withPostgresqlConnWithVersion Connection -> IO (Maybe Double)
getServerVersion

-- | Same as 'withPostgresqlConn', but takes a callback for obtaining
-- the server version (to work around an Amazon Redshift bug).
--
-- @since 2.6.2
withPostgresqlConnWithVersion :: (MonadUnliftIO m, MonadLoggerIO m)
                              => (PG.Connection -> IO (Maybe Double))
                              -> ConnectionString
                              -> (SqlBackend -> m a)
                              -> m a
withPostgresqlConnWithVersion :: (Connection -> IO (Maybe Double))
-> ConnectionString -> (SqlBackend -> m a) -> m a
withPostgresqlConnWithVersion Connection -> IO (Maybe Double)
getVerDouble = do
  let getVer :: Connection -> IO (NonEmpty Word)
getVer = (Connection -> IO (Maybe Double))
-> Connection -> IO (NonEmpty Word)
oldGetVersionToNew Connection -> IO (Maybe Double)
getVerDouble
  (LogFunc -> IO SqlBackend) -> (SqlBackend -> m a) -> m a
forall backend (m :: * -> *) a.
(MonadUnliftIO m, MonadLoggerIO m,
 BackendCompatible SqlBackend backend) =>
(LogFunc -> IO backend) -> (backend -> m a) -> m a
withSqlConn ((LogFunc -> IO SqlBackend) -> (SqlBackend -> m a) -> m a)
-> (ConnectionString -> LogFunc -> IO SqlBackend)
-> ConnectionString
-> (SqlBackend -> m a)
-> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Connection -> IO ())
-> (Connection -> IO (NonEmpty Word))
-> ConnectionString
-> LogFunc
-> IO SqlBackend
open' (IO () -> Connection -> IO ()
forall a b. a -> b -> a
const (IO () -> Connection -> IO ()) -> IO () -> Connection -> IO ()
forall a b. (a -> b) -> a -> b
$ () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()) Connection -> IO (NonEmpty Word)
getVer

open'
    :: (PG.Connection -> IO ())
    -> (PG.Connection -> IO (NonEmpty Word))
    -> ConnectionString -> LogFunc -> IO SqlBackend
open' :: (Connection -> IO ())
-> (Connection -> IO (NonEmpty Word))
-> ConnectionString
-> LogFunc
-> IO SqlBackend
open' Connection -> IO ()
modConn Connection -> IO (NonEmpty Word)
getVer ConnectionString
cstr LogFunc
logFunc = do
    Connection
conn <- ConnectionString -> IO Connection
PG.connectPostgreSQL ConnectionString
cstr
    Connection -> IO ()
modConn Connection
conn
    NonEmpty Word
ver <- Connection -> IO (NonEmpty Word)
getVer Connection
conn
    IORef (Map Text Statement)
smap <- Map Text Statement -> IO (IORef (Map Text Statement))
forall a. a -> IO (IORef a)
newIORef (Map Text Statement -> IO (IORef (Map Text Statement)))
-> Map Text Statement -> IO (IORef (Map Text Statement))
forall a b. (a -> b) -> a -> b
$ Map Text Statement
forall k a. Map k a
Map.empty
    SqlBackend -> IO SqlBackend
forall (m :: * -> *) a. Monad m => a -> m a
return (SqlBackend -> IO SqlBackend) -> SqlBackend -> IO SqlBackend
forall a b. (a -> b) -> a -> b
$ LogFunc
-> NonEmpty Word
-> IORef (Map Text Statement)
-> Connection
-> SqlBackend
createBackend LogFunc
logFunc NonEmpty Word
ver IORef (Map Text Statement)
smap Connection
conn

-- | Gets the PostgreSQL server version
getServerVersion :: PG.Connection -> IO (Maybe Double)
getServerVersion :: Connection -> IO (Maybe Double)
getServerVersion Connection
conn = do
  [PG.Only Text
version] <- Connection -> Query -> IO [Only Text]
forall r. FromRow r => Connection -> Query -> IO [r]
PG.query_ Connection
conn Query
"show server_version";
  let version' :: Either String (Double, Text)
version' = Reader Double
forall a. Fractional a => Reader a
rational Text
version
  --- λ> rational "9.8.3"
  --- Right (9.8,".3")
  --- λ> rational "9.8.3.5"
  --- Right (9.8,".3.5")
  case Either String (Double, Text)
version' of
    Right (Double
a,Text
_) -> Maybe Double -> IO (Maybe Double)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Double -> IO (Maybe Double))
-> Maybe Double -> IO (Maybe Double)
forall a b. (a -> b) -> a -> b
$ Double -> Maybe Double
forall a. a -> Maybe a
Just Double
a
    Left String
err -> PostgresServerVersionError -> IO (Maybe Double)
forall e a. Exception e => e -> IO a
throwIO (PostgresServerVersionError -> IO (Maybe Double))
-> PostgresServerVersionError -> IO (Maybe Double)
forall a b. (a -> b) -> a -> b
$ String -> PostgresServerVersionError
PostgresServerVersionError String
err

getServerVersionNonEmpty :: PG.Connection -> IO (NonEmpty Word)
getServerVersionNonEmpty :: Connection -> IO (NonEmpty Word)
getServerVersionNonEmpty Connection
conn = do
  [PG.Only String
version] <- Connection -> Query -> IO [Only String]
forall r. FromRow r => Connection -> Query -> IO [r]
PG.query_ Connection
conn Query
"show server_version";
  case Parser [Word] -> Text -> Either String [Word]
forall a. Parser a -> Text -> Either String a
AT.parseOnly Parser [Word]
parseVersion (String -> Text
T.pack String
version) of
    Left String
err -> PostgresServerVersionError -> IO (NonEmpty Word)
forall e a. Exception e => e -> IO a
throwIO (PostgresServerVersionError -> IO (NonEmpty Word))
-> PostgresServerVersionError -> IO (NonEmpty Word)
forall a b. (a -> b) -> a -> b
$ String -> PostgresServerVersionError
PostgresServerVersionError (String -> PostgresServerVersionError)
-> String -> PostgresServerVersionError
forall a b. (a -> b) -> a -> b
$ String
"Parse failure on: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
version String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
". Error: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
err
    Right [Word]
versionComponents -> case [Word] -> Maybe (NonEmpty Word)
forall a. [a] -> Maybe (NonEmpty a)
NEL.nonEmpty [Word]
versionComponents of
      Maybe (NonEmpty Word)
Nothing -> PostgresServerVersionError -> IO (NonEmpty Word)
forall e a. Exception e => e -> IO a
throwIO (PostgresServerVersionError -> IO (NonEmpty Word))
-> PostgresServerVersionError -> IO (NonEmpty Word)
forall a b. (a -> b) -> a -> b
$ String -> PostgresServerVersionError
PostgresServerVersionError (String -> PostgresServerVersionError)
-> String -> PostgresServerVersionError
forall a b. (a -> b) -> a -> b
$ String
"Empty Postgres version string: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
version
      Just NonEmpty Word
neVersion -> NonEmpty Word -> IO (NonEmpty Word)
forall (f :: * -> *) a. Applicative f => a -> f a
pure NonEmpty Word
neVersion

  where
    -- Partially copied from the `versions` package
    -- Typically server_version gives e.g. 12.3
    -- In Persistent's CI, we get "12.4 (Debian 12.4-1.pgdg100+1)", so we ignore the trailing data.
    parseVersion :: Parser [Word]
parseVersion = Parser Word
forall a. Integral a => Parser a
AT.decimal Parser Word -> Parser Text Char -> Parser [Word]
forall (f :: * -> *) a s. Alternative f => f a -> f s -> f [a]
`AT.sepBy` Char -> Parser Text Char
AT.char Char
'.'

-- | Choose upsert sql generation function based on postgresql version.
-- PostgreSQL version >= 9.5 supports native upsert feature,
-- so depending upon that we have to choose how the sql query is generated.
-- upsertFunction :: Double -> Maybe (EntityDef -> Text -> Text)
upsertFunction :: a -> NonEmpty Word -> Maybe a
upsertFunction :: a -> NonEmpty Word -> Maybe a
upsertFunction a
f NonEmpty Word
version = if (NonEmpty Word
version NonEmpty Word -> NonEmpty Word -> Bool
forall a. Ord a => a -> a -> Bool
>= NonEmpty Word
postgres9dot5)
                         then a -> Maybe a
forall a. a -> Maybe a
Just a
f
                         else Maybe a
forall a. Maybe a
Nothing
  where

postgres9dot5 :: NonEmpty Word
postgres9dot5 :: NonEmpty Word
postgres9dot5 = Word
9 Word -> [Word] -> NonEmpty Word
forall a. a -> [a] -> NonEmpty a
NEL.:| [Word
5]

-- | If the user doesn't supply a Postgres version, we assume this version.
--
-- This is currently below any version-specific features Persistent uses.
minimumPostgresVersion :: NonEmpty Word
minimumPostgresVersion :: NonEmpty Word
minimumPostgresVersion = Word
9 Word -> [Word] -> NonEmpty Word
forall a. a -> [a] -> NonEmpty a
NEL.:| [Word
4]

oldGetVersionToNew :: (PG.Connection -> IO (Maybe Double)) -> (PG.Connection -> IO (NonEmpty Word))
oldGetVersionToNew :: (Connection -> IO (Maybe Double))
-> Connection -> IO (NonEmpty Word)
oldGetVersionToNew Connection -> IO (Maybe Double)
oldFn = \Connection
conn -> do
  Maybe Double
mDouble <- Connection -> IO (Maybe Double)
oldFn Connection
conn
  case Maybe Double
mDouble of
    Maybe Double
Nothing -> NonEmpty Word -> IO (NonEmpty Word)
forall (f :: * -> *) a. Applicative f => a -> f a
pure NonEmpty Word
minimumPostgresVersion
    Just Double
double -> do
      let (Word
major, Double
minor) = Double -> (Word, Double)
forall a b. (RealFrac a, Integral b) => a -> (b, a)
properFraction Double
double
      NonEmpty Word -> IO (NonEmpty Word)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NonEmpty Word -> IO (NonEmpty Word))
-> NonEmpty Word -> IO (NonEmpty Word)
forall a b. (a -> b) -> a -> b
$ Word
major Word -> [Word] -> NonEmpty Word
forall a. a -> [a] -> NonEmpty a
NEL.:| [Double -> Word
forall a b. (RealFrac a, Integral b) => a -> b
floor Double
minor]

-- | Generate a 'SqlBackend' from a 'PG.Connection'.
openSimpleConn :: LogFunc -> PG.Connection -> IO SqlBackend
openSimpleConn :: LogFunc -> Connection -> IO SqlBackend
openSimpleConn = (Connection -> IO (Maybe Double))
-> LogFunc -> Connection -> IO SqlBackend
openSimpleConnWithVersion Connection -> IO (Maybe Double)
getServerVersion

-- | Generate a 'SqlBackend' from a 'PG.Connection', but takes a callback for
-- obtaining the server version.
--
-- @since 2.9.1
openSimpleConnWithVersion :: (PG.Connection -> IO (Maybe Double)) -> LogFunc -> PG.Connection -> IO SqlBackend
openSimpleConnWithVersion :: (Connection -> IO (Maybe Double))
-> LogFunc -> Connection -> IO SqlBackend
openSimpleConnWithVersion Connection -> IO (Maybe Double)
getVerDouble LogFunc
logFunc Connection
conn = do
    IORef (Map Text Statement)
smap <- Map Text Statement -> IO (IORef (Map Text Statement))
forall a. a -> IO (IORef a)
newIORef (Map Text Statement -> IO (IORef (Map Text Statement)))
-> Map Text Statement -> IO (IORef (Map Text Statement))
forall a b. (a -> b) -> a -> b
$ Map Text Statement
forall k a. Map k a
Map.empty
    NonEmpty Word
serverVersion <- (Connection -> IO (Maybe Double))
-> Connection -> IO (NonEmpty Word)
oldGetVersionToNew Connection -> IO (Maybe Double)
getVerDouble Connection
conn
    SqlBackend -> IO SqlBackend
forall (m :: * -> *) a. Monad m => a -> m a
return (SqlBackend -> IO SqlBackend) -> SqlBackend -> IO SqlBackend
forall a b. (a -> b) -> a -> b
$ LogFunc
-> NonEmpty Word
-> IORef (Map Text Statement)
-> Connection
-> SqlBackend
createBackend LogFunc
logFunc NonEmpty Word
serverVersion IORef (Map Text Statement)
smap Connection
conn

-- | Create the backend given a logging function, server version, mutable statement cell,
-- and connection.
createBackend :: LogFunc -> NonEmpty Word
              -> IORef (Map.Map Text Statement) -> PG.Connection -> SqlBackend
createBackend :: LogFunc
-> NonEmpty Word
-> IORef (Map Text Statement)
-> Connection
-> SqlBackend
createBackend LogFunc
logFunc NonEmpty Word
serverVersion IORef (Map Text Statement)
smap Connection
conn = do
    SqlBackend :: (Text -> IO Statement)
-> (EntityDef -> [PersistValue] -> InsertSqlResult)
-> Maybe (EntityDef -> [[PersistValue]] -> InsertSqlResult)
-> Maybe
     (EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text)
-> Maybe (EntityDef -> Int -> Text)
-> IORef (Map Text Statement)
-> IO ()
-> ([EntityDef]
    -> (Text -> IO Statement)
    -> EntityDef
    -> IO (Either [Text] [(Bool, Text)]))
-> ((Text -> IO Statement) -> Maybe IsolationLevel -> IO ())
-> ((Text -> IO Statement) -> IO ())
-> ((Text -> IO Statement) -> IO ())
-> (FieldNameDB -> Text)
-> (EntityDef -> Text)
-> (Text -> Text)
-> Text
-> Text
-> ((Int, Int) -> Bool -> Text -> Text)
-> LogFunc
-> Maybe Int
-> Maybe (EntityDef -> Int -> Text)
-> SqlBackend
SqlBackend
        { connPrepare :: Text -> IO Statement
connPrepare    = Connection -> Text -> IO Statement
prepare' Connection
conn
        , connStmtMap :: IORef (Map Text Statement)
connStmtMap    = IORef (Map Text Statement)
smap
        , connInsertSql :: EntityDef -> [PersistValue] -> InsertSqlResult
connInsertSql  = EntityDef -> [PersistValue] -> InsertSqlResult
insertSql'
        , connInsertManySql :: Maybe (EntityDef -> [[PersistValue]] -> InsertSqlResult)
connInsertManySql = (EntityDef -> [[PersistValue]] -> InsertSqlResult)
-> Maybe (EntityDef -> [[PersistValue]] -> InsertSqlResult)
forall a. a -> Maybe a
Just EntityDef -> [[PersistValue]] -> InsertSqlResult
insertManySql'
        , connUpsertSql :: Maybe
  (EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text)
connUpsertSql  = (EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text)
-> NonEmpty Word
-> Maybe
     (EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text)
forall a. a -> NonEmpty Word -> Maybe a
upsertFunction EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text
upsertSql' NonEmpty Word
serverVersion
        , connPutManySql :: Maybe (EntityDef -> Int -> Text)
connPutManySql = (EntityDef -> Int -> Text)
-> NonEmpty Word -> Maybe (EntityDef -> Int -> Text)
forall a. a -> NonEmpty Word -> Maybe a
upsertFunction EntityDef -> Int -> Text
putManySql NonEmpty Word
serverVersion
        , connClose :: IO ()
connClose      = Connection -> IO ()
PG.close Connection
conn
        , connMigrateSql :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
connMigrateSql = [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
migrate'
        , connBegin :: (Text -> IO Statement) -> Maybe IsolationLevel -> IO ()
connBegin      = \Text -> IO Statement
_ Maybe IsolationLevel
mIsolation -> case Maybe IsolationLevel
mIsolation of
              Maybe IsolationLevel
Nothing -> Connection -> IO ()
PG.begin Connection
conn
              Just IsolationLevel
iso -> IsolationLevel -> Connection -> IO ()
PG.beginLevel (case IsolationLevel
iso of
                  IsolationLevel
ReadUncommitted -> IsolationLevel
PG.ReadCommitted -- PG Upgrades uncommitted reads to committed anyways
                  IsolationLevel
ReadCommitted -> IsolationLevel
PG.ReadCommitted
                  IsolationLevel
RepeatableRead -> IsolationLevel
PG.RepeatableRead
                  IsolationLevel
Serializable -> IsolationLevel
PG.Serializable) Connection
conn
        , connCommit :: (Text -> IO Statement) -> IO ()
connCommit     = IO () -> (Text -> IO Statement) -> IO ()
forall a b. a -> b -> a
const (IO () -> (Text -> IO Statement) -> IO ())
-> IO () -> (Text -> IO Statement) -> IO ()
forall a b. (a -> b) -> a -> b
$ Connection -> IO ()
PG.commit   Connection
conn
        , connRollback :: (Text -> IO Statement) -> IO ()
connRollback   = IO () -> (Text -> IO Statement) -> IO ()
forall a b. a -> b -> a
const (IO () -> (Text -> IO Statement) -> IO ())
-> IO () -> (Text -> IO Statement) -> IO ()
forall a b. (a -> b) -> a -> b
$ Connection -> IO ()
PG.rollback Connection
conn
        , connEscapeFieldName :: FieldNameDB -> Text
connEscapeFieldName = FieldNameDB -> Text
escapeF
        , connEscapeTableName :: EntityDef -> Text
connEscapeTableName = EntityNameDB -> Text
escapeE (EntityNameDB -> Text)
-> (EntityDef -> EntityNameDB) -> EntityDef -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> EntityNameDB
entityDB
        , connEscapeRawName :: Text -> Text
connEscapeRawName = Text -> Text
escape
        , connNoLimit :: Text
connNoLimit    = Text
"LIMIT ALL"
        , connRDBMS :: Text
connRDBMS      = Text
"postgresql"
        , connLimitOffset :: (Int, Int) -> Bool -> Text -> Text
connLimitOffset = Text -> (Int, Int) -> Bool -> Text -> Text
decorateSQLWithLimitOffset Text
"LIMIT ALL"
        , connLogFunc :: LogFunc
connLogFunc = LogFunc
logFunc
        , connMaxParams :: Maybe Int
connMaxParams = Maybe Int
forall a. Maybe a
Nothing
        , connRepsertManySql :: Maybe (EntityDef -> Int -> Text)
connRepsertManySql = (EntityDef -> Int -> Text)
-> NonEmpty Word -> Maybe (EntityDef -> Int -> Text)
forall a. a -> NonEmpty Word -> Maybe a
upsertFunction EntityDef -> Int -> Text
repsertManySql NonEmpty Word
serverVersion
        }

prepare' :: PG.Connection -> Text -> IO Statement
prepare' :: Connection -> Text -> IO Statement
prepare' Connection
conn Text
sql = do
    let query :: Query
query = ConnectionString -> Query
PG.Query (Text -> ConnectionString
T.encodeUtf8 Text
sql)
    Statement -> IO Statement
forall (m :: * -> *) a. Monad m => a -> m a
return Statement :: IO ()
-> IO ()
-> ([PersistValue] -> IO Int64)
-> (forall (m :: * -> *).
    MonadIO m =>
    [PersistValue] -> Acquire (ConduitM () [PersistValue] m ()))
-> Statement
Statement
        { stmtFinalize :: IO ()
stmtFinalize = () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        , stmtReset :: IO ()
stmtReset = () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        , stmtExecute :: [PersistValue] -> IO Int64
stmtExecute = Connection -> Query -> [PersistValue] -> IO Int64
execute' Connection
conn Query
query
        , stmtQuery :: forall (m :: * -> *).
MonadIO m =>
[PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
stmtQuery = Connection
-> Query
-> [PersistValue]
-> Acquire (ConduitM () [PersistValue] m ())
forall (m :: * -> *).
MonadIO m =>
Connection
-> Query
-> [PersistValue]
-> Acquire (ConduitM () [PersistValue] m ())
withStmt' Connection
conn Query
query
        }

insertSql' :: EntityDef -> [PersistValue] -> InsertSqlResult
insertSql' :: EntityDef -> [PersistValue] -> InsertSqlResult
insertSql' EntityDef
ent [PersistValue]
vals =
    case EntityDef -> Maybe CompositeDef
entityPrimary EntityDef
ent of
        Just CompositeDef
_pdef -> Text -> [PersistValue] -> InsertSqlResult
ISRManyKeys Text
sql [PersistValue]
vals
        Maybe CompositeDef
Nothing -> Text -> InsertSqlResult
ISRSingle (Text
sql Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" RETURNING " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> FieldNameDB -> Text
escapeF (FieldDef -> FieldNameDB
fieldDB (EntityDef -> FieldDef
entityId EntityDef
ent)))
  where
    ([Text]
fieldNames, [Text]
placeholders) = [(Text, Text)] -> ([Text], [Text])
forall a b. [(a, b)] -> ([a], [b])
unzip (EntityDef -> (FieldNameDB -> Text) -> [(Text, Text)]
Util.mkInsertPlaceholders EntityDef
ent FieldNameDB -> Text
escapeF)
    sql :: Text
sql = [Text] -> Text
T.concat
        [ Text
"INSERT INTO "
        , EntityNameDB -> Text
escapeE (EntityNameDB -> Text) -> EntityNameDB -> Text
forall a b. (a -> b) -> a -> b
$ EntityDef -> EntityNameDB
entityDB EntityDef
ent
        , if [FieldDef] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (EntityDef -> [FieldDef]
entityFields EntityDef
ent)
            then Text
" DEFAULT VALUES"
            else [Text] -> Text
T.concat
                [ Text
"("
                , Text -> [Text] -> Text
T.intercalate Text
"," [Text]
fieldNames
                , Text
") VALUES("
                , Text -> [Text] -> Text
T.intercalate Text
"," [Text]
placeholders
                , Text
")"
                ]
        ]


upsertSql' :: EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text
upsertSql' :: EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text
upsertSql' EntityDef
ent NonEmpty (FieldNameHS, FieldNameDB)
uniqs Text
updateVal =
    [Text] -> Text
T.concat
        [ Text
"INSERT INTO "
        , EntityNameDB -> Text
escapeE (EntityDef -> EntityNameDB
entityDB EntityDef
ent)
        , Text
"("
        , Text -> [Text] -> Text
T.intercalate Text
"," [Text]
fieldNames
        , Text
") VALUES ("
        , Text -> [Text] -> Text
T.intercalate Text
"," [Text]
placeholders
        , Text
") ON CONFLICT ("
        , Text -> [Text] -> Text
T.intercalate Text
"," ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ ((FieldNameHS, FieldNameDB) -> Text)
-> [(FieldNameHS, FieldNameDB)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (FieldNameDB -> Text
escapeF (FieldNameDB -> Text)
-> ((FieldNameHS, FieldNameDB) -> FieldNameDB)
-> (FieldNameHS, FieldNameDB)
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FieldNameHS, FieldNameDB) -> FieldNameDB
forall a b. (a, b) -> b
snd) (NonEmpty (FieldNameHS, FieldNameDB) -> [(FieldNameHS, FieldNameDB)]
forall a. NonEmpty a -> [a]
NEL.toList NonEmpty (FieldNameHS, FieldNameDB)
uniqs)
        , Text
") DO UPDATE SET "
        , Text
updateVal
        , Text
" WHERE "
        , Text
wher
        , Text
" RETURNING ??"
        ]
  where
    ([Text]
fieldNames, [Text]
placeholders) = [(Text, Text)] -> ([Text], [Text])
forall a b. [(a, b)] -> ([a], [b])
unzip (EntityDef -> (FieldNameDB -> Text) -> [(Text, Text)]
Util.mkInsertPlaceholders EntityDef
ent FieldNameDB -> Text
escapeF)

    wher :: Text
wher = Text -> [Text] -> Text
T.intercalate Text
" AND " ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ ((FieldNameHS, FieldNameDB) -> Text)
-> [(FieldNameHS, FieldNameDB)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (FieldNameDB -> Text
singleClause (FieldNameDB -> Text)
-> ((FieldNameHS, FieldNameDB) -> FieldNameDB)
-> (FieldNameHS, FieldNameDB)
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FieldNameHS, FieldNameDB) -> FieldNameDB
forall a b. (a, b) -> b
snd) ([(FieldNameHS, FieldNameDB)] -> [Text])
-> [(FieldNameHS, FieldNameDB)] -> [Text]
forall a b. (a -> b) -> a -> b
$ NonEmpty (FieldNameHS, FieldNameDB) -> [(FieldNameHS, FieldNameDB)]
forall a. NonEmpty a -> [a]
NEL.toList NonEmpty (FieldNameHS, FieldNameDB)
uniqs

    singleClause :: FieldNameDB -> Text
    singleClause :: FieldNameDB -> Text
singleClause FieldNameDB
field = EntityNameDB -> Text
escapeE (EntityDef -> EntityNameDB
entityDB EntityDef
ent) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"." Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (FieldNameDB -> Text
escapeF FieldNameDB
field) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" =?"

-- | SQL for inserting multiple rows at once and returning their primary keys.
insertManySql' :: EntityDef -> [[PersistValue]] -> InsertSqlResult
insertManySql' :: EntityDef -> [[PersistValue]] -> InsertSqlResult
insertManySql' EntityDef
ent [[PersistValue]]
valss =
    Text -> InsertSqlResult
ISRSingle Text
sql
  where
    ([Text]
fieldNames, [Text]
placeholders)= [(Text, Text)] -> ([Text], [Text])
forall a b. [(a, b)] -> ([a], [b])
unzip (EntityDef -> (FieldNameDB -> Text) -> [(Text, Text)]
Util.mkInsertPlaceholders EntityDef
ent FieldNameDB -> Text
escapeF)
    sql :: Text
sql = [Text] -> Text
T.concat
        [ Text
"INSERT INTO "
        , EntityNameDB -> Text
escapeE (EntityDef -> EntityNameDB
entityDB EntityDef
ent)
        , Text
"("
        , Text -> [Text] -> Text
T.intercalate Text
"," [Text]
fieldNames
        , Text
") VALUES ("
        , Text -> [Text] -> Text
T.intercalate Text
"),(" ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ Int -> Text -> [Text]
forall a. Int -> a -> [a]
replicate ([[PersistValue]] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[PersistValue]]
valss) (Text -> [Text]) -> Text -> [Text]
forall a b. (a -> b) -> a -> b
$ Text -> [Text] -> Text
T.intercalate Text
"," [Text]
placeholders
        , Text
") RETURNING "
        , [Text] -> Text
Util.commaSeparated ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (FieldNameDB -> Text) -> EntityDef -> [Text]
Util.dbIdColumnsEsc FieldNameDB -> Text
escapeF EntityDef
ent
        ]


execute' :: PG.Connection -> PG.Query -> [PersistValue] -> IO Int64
execute' :: Connection -> Query -> [PersistValue] -> IO Int64
execute' Connection
conn Query
query [PersistValue]
vals = Connection -> Query -> [P] -> IO Int64
forall q. ToRow q => Connection -> Query -> q -> IO Int64
PG.execute Connection
conn Query
query ((PersistValue -> P) -> [PersistValue] -> [P]
forall a b. (a -> b) -> [a] -> [b]
map PersistValue -> P
P [PersistValue]
vals)

withStmt' :: MonadIO m
          => PG.Connection
          -> PG.Query
          -> [PersistValue]
          -> Acquire (ConduitM () [PersistValue] m ())
withStmt' :: Connection
-> Query
-> [PersistValue]
-> Acquire (ConduitM () [PersistValue] m ())
withStmt' Connection
conn Query
query [PersistValue]
vals =
    (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
-> ConduitM () [PersistValue] m ()
pull ((Result, IORef Row, Row,
  [Maybe ConnectionString -> Conversion PersistValue])
 -> ConduitM () [PersistValue] m ())
-> Acquire
     (Result, IORef Row, Row,
      [Maybe ConnectionString -> Conversion PersistValue])
-> Acquire (ConduitM () [PersistValue] m ())
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` IO
  (Result, IORef Row, Row,
   [Maybe ConnectionString -> Conversion PersistValue])
-> ((Result, IORef Row, Row,
     [Maybe ConnectionString -> Conversion PersistValue])
    -> IO ())
-> Acquire
     (Result, IORef Row, Row,
      [Maybe ConnectionString -> Conversion PersistValue])
forall a. IO a -> (a -> IO ()) -> Acquire a
mkAcquire IO
  (Result, IORef Row, Row,
   [Maybe ConnectionString -> Conversion PersistValue])
openS (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
-> IO ()
forall b c d. (Result, b, c, d) -> IO ()
closeS
  where
    openS :: IO
  (Result, IORef Row, Row,
   [Maybe ConnectionString -> Conversion PersistValue])
openS = do
      -- Construct raw query
      ConnectionString
rawquery <- Connection -> Query -> [P] -> IO ConnectionString
forall q.
ToRow q =>
Connection -> Query -> q -> IO ConnectionString
PG.formatQuery Connection
conn Query
query ((PersistValue -> P) -> [PersistValue] -> [P]
forall a b. (a -> b) -> [a] -> [b]
map PersistValue -> P
P [PersistValue]
vals)

      -- Take raw connection
      (Result
rt, IORef Row
rr, Row
rc, [(Column, Oid)]
ids) <- Connection
-> (Connection -> IO (Result, IORef Row, Row, [(Column, Oid)]))
-> IO (Result, IORef Row, Row, [(Column, Oid)])
forall a. Connection -> (Connection -> IO a) -> IO a
PG.withConnection Connection
conn ((Connection -> IO (Result, IORef Row, Row, [(Column, Oid)]))
 -> IO (Result, IORef Row, Row, [(Column, Oid)]))
-> (Connection -> IO (Result, IORef Row, Row, [(Column, Oid)]))
-> IO (Result, IORef Row, Row, [(Column, Oid)])
forall a b. (a -> b) -> a -> b
$ \Connection
rawconn -> do
            -- Execute query
            Maybe Result
mret <- Connection -> ConnectionString -> IO (Maybe Result)
LibPQ.exec Connection
rawconn ConnectionString
rawquery
            case Maybe Result
mret of
              Maybe Result
Nothing -> do
                Maybe ConnectionString
merr <- Connection -> IO (Maybe ConnectionString)
LibPQ.errorMessage Connection
rawconn
                String -> IO (Result, IORef Row, Row, [(Column, Oid)])
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (Result, IORef Row, Row, [(Column, Oid)]))
-> String -> IO (Result, IORef Row, Row, [(Column, Oid)])
forall a b. (a -> b) -> a -> b
$ case Maybe ConnectionString
merr of
                         Maybe ConnectionString
Nothing -> String
"Postgresql.withStmt': unknown error"
                         Just ConnectionString
e  -> String
"Postgresql.withStmt': " String -> ShowS
forall a. [a] -> [a] -> [a]
++ ConnectionString -> String
B8.unpack ConnectionString
e
              Just Result
ret -> do
                -- Check result status
                ExecStatus
status <- Result -> IO ExecStatus
LibPQ.resultStatus Result
ret
                case ExecStatus
status of
                  ExecStatus
LibPQ.TuplesOk -> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                  ExecStatus
_ -> ConnectionString -> Result -> ExecStatus -> IO ()
forall a. ConnectionString -> Result -> ExecStatus -> IO a
PG.throwResultError ConnectionString
"Postgresql.withStmt': bad result status " Result
ret ExecStatus
status

                -- Get number and type of columns
                Column
cols <- Result -> IO Column
LibPQ.nfields Result
ret
                [(Column, Oid)]
oids <- [Column] -> (Column -> IO (Column, Oid)) -> IO [(Column, Oid)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM [Column
0..Column
colsColumn -> Column -> Column
forall a. Num a => a -> a -> a
-Column
1] ((Column -> IO (Column, Oid)) -> IO [(Column, Oid)])
-> (Column -> IO (Column, Oid)) -> IO [(Column, Oid)]
forall a b. (a -> b) -> a -> b
$ \Column
col -> (Oid -> (Column, Oid)) -> IO Oid -> IO (Column, Oid)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((,) Column
col) (Result -> Column -> IO Oid
LibPQ.ftype Result
ret Column
col)
                -- Ready to go!
                IORef Row
rowRef   <- Row -> IO (IORef Row)
forall a. a -> IO (IORef a)
newIORef (CInt -> Row
LibPQ.Row CInt
0)
                Row
rowCount <- Result -> IO Row
LibPQ.ntuples Result
ret
                (Result, IORef Row, Row, [(Column, Oid)])
-> IO (Result, IORef Row, Row, [(Column, Oid)])
forall (m :: * -> *) a. Monad m => a -> m a
return (Result
ret, IORef Row
rowRef, Row
rowCount, [(Column, Oid)]
oids)
      let getters :: [Maybe ConnectionString -> Conversion PersistValue]
getters
            = ((Column, Oid)
 -> Maybe ConnectionString -> Conversion PersistValue)
-> [(Column, Oid)]
-> [Maybe ConnectionString -> Conversion PersistValue]
forall a b. (a -> b) -> [a] -> [b]
map (\(Column
col, Oid
oid) -> Connection -> Oid -> Getter PersistValue
getGetter Connection
conn Oid
oid Getter PersistValue -> Getter PersistValue
forall a b. (a -> b) -> a -> b
$ Result -> Column -> Oid -> Field
PG.Field Result
rt Column
col Oid
oid) [(Column, Oid)]
ids
      (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
-> IO
     (Result, IORef Row, Row,
      [Maybe ConnectionString -> Conversion PersistValue])
forall (m :: * -> *) a. Monad m => a -> m a
return (Result
rt, IORef Row
rr, Row
rc, [Maybe ConnectionString -> Conversion PersistValue]
getters)

    closeS :: (Result, b, c, d) -> IO ()
closeS (Result
ret, b
_, c
_, d
_) = Result -> IO ()
LibPQ.unsafeFreeResult Result
ret

    pull :: (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
-> ConduitM () [PersistValue] m ()
pull (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
x = do
        Maybe [PersistValue]
y <- IO (Maybe [PersistValue])
-> ConduitT () [PersistValue] m (Maybe [PersistValue])
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Maybe [PersistValue])
 -> ConduitT () [PersistValue] m (Maybe [PersistValue]))
-> IO (Maybe [PersistValue])
-> ConduitT () [PersistValue] m (Maybe [PersistValue])
forall a b. (a -> b) -> a -> b
$ (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
-> IO (Maybe [PersistValue])
pullS (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
x
        case Maybe [PersistValue]
y of
            Maybe [PersistValue]
Nothing -> () -> ConduitM () [PersistValue] m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
            Just [PersistValue]
z -> [PersistValue] -> ConduitM () [PersistValue] m ()
forall (m :: * -> *) o i. Monad m => o -> ConduitT i o m ()
yield [PersistValue]
z ConduitM () [PersistValue] m ()
-> ConduitM () [PersistValue] m ()
-> ConduitM () [PersistValue] m ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
-> ConduitM () [PersistValue] m ()
pull (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
x

    pullS :: (Result, IORef Row, Row,
 [Maybe ConnectionString -> Conversion PersistValue])
-> IO (Maybe [PersistValue])
pullS (Result
ret, IORef Row
rowRef, Row
rowCount, [Maybe ConnectionString -> Conversion PersistValue]
getters) = do
        Row
row <- IORef Row -> (Row -> (Row, Row)) -> IO Row
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef IORef Row
rowRef (\Row
r -> (Row
rRow -> Row -> Row
forall a. Num a => a -> a -> a
+Row
1, Row
r))
        if Row
row Row -> Row -> Bool
forall a. Eq a => a -> a -> Bool
== Row
rowCount
           then Maybe [PersistValue] -> IO (Maybe [PersistValue])
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe [PersistValue]
forall a. Maybe a
Nothing
           else ([PersistValue] -> Maybe [PersistValue])
-> IO [PersistValue] -> IO (Maybe [PersistValue])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [PersistValue] -> Maybe [PersistValue]
forall a. a -> Maybe a
Just (IO [PersistValue] -> IO (Maybe [PersistValue]))
-> IO [PersistValue] -> IO (Maybe [PersistValue])
forall a b. (a -> b) -> a -> b
$ [(Maybe ConnectionString -> Conversion PersistValue, Column)]
-> ((Maybe ConnectionString -> Conversion PersistValue, Column)
    -> IO PersistValue)
-> IO [PersistValue]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM ([Maybe ConnectionString -> Conversion PersistValue]
-> [Column]
-> [(Maybe ConnectionString -> Conversion PersistValue, Column)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Maybe ConnectionString -> Conversion PersistValue]
getters [Column
0..]) (((Maybe ConnectionString -> Conversion PersistValue, Column)
  -> IO PersistValue)
 -> IO [PersistValue])
-> ((Maybe ConnectionString -> Conversion PersistValue, Column)
    -> IO PersistValue)
-> IO [PersistValue]
forall a b. (a -> b) -> a -> b
$ \(Maybe ConnectionString -> Conversion PersistValue
getter, Column
col) -> do
                                Maybe ConnectionString
mbs <- Result -> Row -> Column -> IO (Maybe ConnectionString)
LibPQ.getvalue' Result
ret Row
row Column
col
                                case Maybe ConnectionString
mbs of
                                  Maybe ConnectionString
Nothing ->
                                    -- getvalue' verified that the value is NULL.
                                    -- However, that does not mean that there are
                                    -- no NULL values inside the value (e.g., if
                                    -- we're dealing with an array of optional values).
                                    PersistValue -> IO PersistValue
forall (m :: * -> *) a. Monad m => a -> m a
return PersistValue
PersistNull
                                  Just ConnectionString
bs -> do
                                    Ok PersistValue
ok <- Conversion PersistValue -> Connection -> IO (Ok PersistValue)
forall a. Conversion a -> Connection -> IO (Ok a)
PGFF.runConversion (Maybe ConnectionString -> Conversion PersistValue
getter Maybe ConnectionString
mbs) Connection
conn
                                    ConnectionString
bs ConnectionString -> IO PersistValue -> IO PersistValue
`seq` case Ok PersistValue
ok of
                                                        Errors (SomeException
exc:[SomeException]
_) -> SomeException -> IO PersistValue
forall a e. Exception e => e -> a
throw SomeException
exc
                                                        Errors [] -> String -> IO PersistValue
forall a. HasCallStack => String -> a
error String
"Got an Errors, but no exceptions"
                                                        Ok PersistValue
v  -> PersistValue -> IO PersistValue
forall (m :: * -> *) a. Monad m => a -> m a
return PersistValue
v

-- | Avoid orphan instances.
newtype P = P PersistValue


instance PGTF.ToField P where
    toField :: P -> Action
toField (P (PersistText Text
t))        = Text -> Action
forall a. ToField a => a -> Action
PGTF.toField Text
t
    toField (P (PersistByteString ConnectionString
bs)) = Binary ConnectionString -> Action
forall a. ToField a => a -> Action
PGTF.toField (ConnectionString -> Binary ConnectionString
forall a. a -> Binary a
PG.Binary ConnectionString
bs)
    toField (P (PersistInt64 Int64
i))       = Int64 -> Action
forall a. ToField a => a -> Action
PGTF.toField Int64
i
    toField (P (PersistDouble Double
d))      = Double -> Action
forall a. ToField a => a -> Action
PGTF.toField Double
d
    toField (P (PersistRational Rational
r))    = Builder -> Action
PGTF.Plain (Builder -> Action) -> Builder -> Action
forall a b. (a -> b) -> a -> b
$
                                         String -> Builder
BBB.fromString (String -> Builder) -> String -> Builder
forall a b. (a -> b) -> a -> b
$
                                         Pico -> String
forall a. Show a => a -> String
show (Rational -> Pico
forall a. Fractional a => Rational -> a
fromRational Rational
r :: Pico) --  FIXME: Too Ambigous, can not select precision without information about field
    toField (P (PersistBool Bool
b))        = Bool -> Action
forall a. ToField a => a -> Action
PGTF.toField Bool
b
    toField (P (PersistDay Day
d))         = Day -> Action
forall a. ToField a => a -> Action
PGTF.toField Day
d
    toField (P (PersistTimeOfDay TimeOfDay
t))   = TimeOfDay -> Action
forall a. ToField a => a -> Action
PGTF.toField TimeOfDay
t
    toField (P (PersistUTCTime UTCTime
t))     = UTCTime -> Action
forall a. ToField a => a -> Action
PGTF.toField UTCTime
t
    toField (P PersistValue
PersistNull)            = Null -> Action
forall a. ToField a => a -> Action
PGTF.toField Null
PG.Null
    toField (P (PersistList [PersistValue]
l))        = Text -> Action
forall a. ToField a => a -> Action
PGTF.toField (Text -> Action) -> Text -> Action
forall a b. (a -> b) -> a -> b
$ [PersistValue] -> Text
listToJSON [PersistValue]
l
    toField (P (PersistMap [(Text, PersistValue)]
m))         = Text -> Action
forall a. ToField a => a -> Action
PGTF.toField (Text -> Action) -> Text -> Action
forall a b. (a -> b) -> a -> b
$ [(Text, PersistValue)] -> Text
mapToJSON [(Text, PersistValue)]
m
    toField (P (PersistLiteral_ LiteralType
DbSpecific ConnectionString
s))  = Unknown -> Action
forall a. ToField a => a -> Action
PGTF.toField (ConnectionString -> Unknown
Unknown ConnectionString
s)
    toField (P (PersistLiteral_ LiteralType
Unescaped ConnectionString
l))     = UnknownLiteral -> Action
forall a. ToField a => a -> Action
PGTF.toField (ConnectionString -> UnknownLiteral
UnknownLiteral ConnectionString
l)
    toField (P (PersistLiteral_ LiteralType
Escaped ConnectionString
e)) = Unknown -> Action
forall a. ToField a => a -> Action
PGTF.toField (ConnectionString -> Unknown
Unknown ConnectionString
e)
    toField (P (PersistArray [PersistValue]
a))       = PGArray P -> Action
forall a. ToField a => a -> Action
PGTF.toField (PGArray P -> Action) -> PGArray P -> Action
forall a b. (a -> b) -> a -> b
$ [P] -> PGArray P
forall a. [a] -> PGArray a
PG.PGArray ([P] -> PGArray P) -> [P] -> PGArray P
forall a b. (a -> b) -> a -> b
$ PersistValue -> P
P (PersistValue -> P) -> [PersistValue] -> [P]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [PersistValue]
a
    toField (P (PersistObjectId ConnectionString
_))    =
        String -> Action
forall a. HasCallStack => String -> a
error String
"Refusing to serialize a PersistObjectId to a PostgreSQL value"

-- | Represent Postgres interval using NominalDiffTime
--
-- @since 2.11.0.0
newtype PgInterval = PgInterval { PgInterval -> NominalDiffTime
getPgInterval :: NominalDiffTime }
  deriving (PgInterval -> PgInterval -> Bool
(PgInterval -> PgInterval -> Bool)
-> (PgInterval -> PgInterval -> Bool) -> Eq PgInterval
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: PgInterval -> PgInterval -> Bool
$c/= :: PgInterval -> PgInterval -> Bool
== :: PgInterval -> PgInterval -> Bool
$c== :: PgInterval -> PgInterval -> Bool
Eq, Int -> PgInterval -> ShowS
[PgInterval] -> ShowS
PgInterval -> String
(Int -> PgInterval -> ShowS)
-> (PgInterval -> String)
-> ([PgInterval] -> ShowS)
-> Show PgInterval
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [PgInterval] -> ShowS
$cshowList :: [PgInterval] -> ShowS
show :: PgInterval -> String
$cshow :: PgInterval -> String
showsPrec :: Int -> PgInterval -> ShowS
$cshowsPrec :: Int -> PgInterval -> ShowS
Show)

pgIntervalToBs :: PgInterval -> ByteString
pgIntervalToBs :: PgInterval -> ConnectionString
pgIntervalToBs = String -> ConnectionString
forall a.
ConvertibleStrings a ConnectionString =>
a -> ConnectionString
toStrictByteString (String -> ConnectionString)
-> (PgInterval -> String) -> PgInterval -> ConnectionString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NominalDiffTime -> String
forall a. Show a => a -> String
show (NominalDiffTime -> String)
-> (PgInterval -> NominalDiffTime) -> PgInterval -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PgInterval -> NominalDiffTime
getPgInterval

instance PGTF.ToField PgInterval where
    toField :: PgInterval -> Action
toField (PgInterval NominalDiffTime
t) = NominalDiffTime -> Action
forall a. ToField a => a -> Action
PGTF.toField NominalDiffTime
t

instance PGFF.FromField PgInterval where
    fromField :: FieldParser PgInterval
fromField Field
f Maybe ConnectionString
mdata =
      if Field -> Oid
PGFF.typeOid Field
f Oid -> Oid -> Bool
forall a. Eq a => a -> a -> Bool
/= TypeInfo -> Oid
PS.typoid TypeInfo
PS.interval
        then (String -> Maybe Oid -> String -> String -> String -> ResultError)
-> Field -> String -> Conversion PgInterval
forall a err.
(Typeable a, Exception err) =>
(String -> Maybe Oid -> String -> String -> String -> err)
-> Field -> String -> Conversion a
PGFF.returnError String -> Maybe Oid -> String -> String -> String -> ResultError
PGFF.Incompatible Field
f String
""
        else case Maybe ConnectionString
mdata of
          Maybe ConnectionString
Nothing  -> (String -> Maybe Oid -> String -> String -> String -> ResultError)
-> Field -> String -> Conversion PgInterval
forall a err.
(Typeable a, Exception err) =>
(String -> Maybe Oid -> String -> String -> String -> err)
-> Field -> String -> Conversion a
PGFF.returnError String -> Maybe Oid -> String -> String -> String -> ResultError
PGFF.UnexpectedNull Field
f String
""
          Just ConnectionString
dat -> case Parser NominalDiffTime
-> ConnectionString -> Either String NominalDiffTime
forall a. Parser a -> ConnectionString -> Either String a
P.parseOnly (Parser NominalDiffTime
nominalDiffTime Parser NominalDiffTime
-> Parser ConnectionString () -> Parser NominalDiffTime
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ConnectionString ()
forall t. Chunk t => Parser t ()
P.endOfInput) ConnectionString
dat of
            Left String
msg  ->  (String -> Maybe Oid -> String -> String -> String -> ResultError)
-> Field -> String -> Conversion PgInterval
forall a err.
(Typeable a, Exception err) =>
(String -> Maybe Oid -> String -> String -> String -> err)
-> Field -> String -> Conversion a
PGFF.returnError String -> Maybe Oid -> String -> String -> String -> ResultError
PGFF.ConversionFailed Field
f String
msg
            Right NominalDiffTime
t   -> PgInterval -> Conversion PgInterval
forall (m :: * -> *) a. Monad m => a -> m a
return (PgInterval -> Conversion PgInterval)
-> PgInterval -> Conversion PgInterval
forall a b. (a -> b) -> a -> b
$ NominalDiffTime -> PgInterval
PgInterval NominalDiffTime
t

      where
        toPico :: Integer -> Pico
        toPico :: Integer -> Pico
toPico = Integer -> Pico
forall k (a :: k). Integer -> Fixed a
MkFixed

        -- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser
        twoDigits :: P.Parser Int
        twoDigits :: Parser Int
twoDigits = do
          Char
a <- Parser Char
P.digit
          Char
b <- Parser Char
P.digit
          let c2d :: Char -> Int
c2d Char
c = Char -> Int
ord Char
c Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
15
          Int -> Parser Int
forall (m :: * -> *) a. Monad m => a -> m a
return (Int -> Parser Int) -> Int -> Parser Int
forall a b. (a -> b) -> a -> b
$! Char -> Int
c2d Char
a Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
10 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Char -> Int
c2d Char
b

        -- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser
        seconds :: P.Parser Pico
        seconds :: Parser Pico
seconds = do
          Int
real <- Parser Int
twoDigits
          Maybe Char
mc <- Parser (Maybe Char)
P.peekChar
          case Maybe Char
mc of
            Just Char
'.' -> do
              ConnectionString
t <- Parser Char
P.anyChar Parser Char
-> Parser ConnectionString ConnectionString
-> Parser ConnectionString ConnectionString
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> (Char -> Bool) -> Parser ConnectionString ConnectionString
P.takeWhile1 Char -> Bool
P.isDigit
              Pico -> Parser Pico
forall (m :: * -> *) a. Monad m => a -> m a
return (Pico -> Parser Pico) -> Pico -> Parser Pico
forall a b. (a -> b) -> a -> b
$! Int64 -> ConnectionString -> Pico
parsePicos (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
real) ConnectionString
t
            Maybe Char
_ -> Pico -> Parser Pico
forall (m :: * -> *) a. Monad m => a -> m a
return (Pico -> Parser Pico) -> Pico -> Parser Pico
forall a b. (a -> b) -> a -> b
$! Int -> Pico
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
real
         where
          parsePicos :: Int64 -> B8.ByteString -> Pico
          parsePicos :: Int64 -> ConnectionString -> Pico
parsePicos Int64
a0 ConnectionString
t = Integer -> Pico
toPico (Int64 -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int64
t' Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
* Int64
10Int64 -> Int -> Int64
forall a b. (Num a, Integral b) => a -> b -> a
^Int
n))
            where n :: Int
n  = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (Int
12 Int -> Int -> Int
forall a. Num a => a -> a -> a
- ConnectionString -> Int
B8.length ConnectionString
t)
                  t' :: Int64
t' = (Int64 -> Char -> Int64) -> Int64 -> ConnectionString -> Int64
forall a. (a -> Char -> a) -> a -> ConnectionString -> a
B8.foldl' (\Int64
a Char
c -> Int64
10 Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
* Int64
a Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
+ Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Char -> Int
ord Char
c Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
15)) Int64
a0
                                 (Int -> ConnectionString -> ConnectionString
B8.take Int
12 ConnectionString
t)

        parseSign :: P.Parser Bool
        parseSign :: Parser Bool
parseSign = [Parser Bool] -> Parser Bool
forall (f :: * -> *) a. Alternative f => [f a] -> f a
P.choice [Char -> Parser Char
P.char Char
'-' Parser Char -> Parser Bool -> Parser Bool
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool -> Parser Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True, Bool -> Parser Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False]

        -- Db stores it in [-]HHH:MM:SS.[SSSS]
        -- For example, nominalDay is stored as 24:00:00
        interval :: P.Parser (Bool, Int, Int, Pico)
        interval :: Parser (Bool, Int, Int, Pico)
interval = do
            Bool
s  <- Parser Bool
parseSign
            Int
h  <- Parser Int
forall a. Integral a => Parser a
P.decimal Parser Int -> Parser Char -> Parser Int
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Char -> Parser Char
P.char Char
':'
            Int
m  <- Parser Int
twoDigits Parser Int -> Parser Char -> Parser Int
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Char -> Parser Char
P.char Char
':'
            Pico
ss <- Parser Pico
seconds
            if Int
m Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
60 Bool -> Bool -> Bool
&& Pico
ss Pico -> Pico -> Bool
forall a. Ord a => a -> a -> Bool
<= Pico
60
                then (Bool, Int, Int, Pico) -> Parser (Bool, Int, Int, Pico)
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
s, Int
h, Int
m, Pico
ss)
                else String -> Parser (Bool, Int, Int, Pico)
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Invalid interval"

        nominalDiffTime :: P.Parser NominalDiffTime
        nominalDiffTime :: Parser NominalDiffTime
nominalDiffTime = do
          (Bool
s, Int
h, Int
m, Pico
ss) <- Parser (Bool, Int, Int, Pico)
interval
          let pico :: Pico
pico   = Pico
ss Pico -> Pico -> Pico
forall a. Num a => a -> a -> a
+ Pico
60 Pico -> Pico -> Pico
forall a. Num a => a -> a -> a
* (Int -> Pico
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
m) Pico -> Pico -> Pico
forall a. Num a => a -> a -> a
+ Pico
60 Pico -> Pico -> Pico
forall a. Num a => a -> a -> a
* Pico
60 Pico -> Pico -> Pico
forall a. Num a => a -> a -> a
* (Int -> Pico
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Int
forall a. Num a => a -> a
abs Int
h))
          NominalDiffTime -> Parser NominalDiffTime
forall (m :: * -> *) a. Monad m => a -> m a
return (NominalDiffTime -> Parser NominalDiffTime)
-> (Pico -> NominalDiffTime) -> Pico -> Parser NominalDiffTime
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Rational -> NominalDiffTime
forall a. Fractional a => Rational -> a
fromRational (Rational -> NominalDiffTime)
-> (Pico -> Rational) -> Pico -> NominalDiffTime
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Pico -> Rational
forall a. Real a => a -> Rational
toRational (Pico -> Parser NominalDiffTime) -> Pico -> Parser NominalDiffTime
forall a b. (a -> b) -> a -> b
$ if Bool
s then (-Pico
pico) else Pico
pico

fromPersistValueError :: Text -- ^ Haskell type, should match Haskell name exactly, e.g. "Int64"
                      -> Text -- ^ Database type(s), should appear different from Haskell name, e.g. "integer" or "INT", not "Int".
                      -> PersistValue -- ^ Incorrect value
                      -> Text -- ^ Error message
fromPersistValueError :: Text -> Text -> PersistValue -> Text
fromPersistValueError Text
haskellType Text
databaseType PersistValue
received = [Text] -> Text
T.concat
    [ Text
"Failed to parse Haskell type `"
    , Text
haskellType
    , Text
"`; expected "
    , Text
databaseType
    , Text
" from database, but received: "
    , String -> Text
T.pack (PersistValue -> String
forall a. Show a => a -> String
show PersistValue
received)
    , Text
". Potential solution: Check that your database schema matches your Persistent model definitions."
    ]

instance PersistField PgInterval where
    toPersistValue :: PgInterval -> PersistValue
toPersistValue = ConnectionString -> PersistValue
PersistLiteralEscaped (ConnectionString -> PersistValue)
-> (PgInterval -> ConnectionString) -> PgInterval -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PgInterval -> ConnectionString
pgIntervalToBs
    fromPersistValue :: PersistValue -> Either Text PgInterval
fromPersistValue (PersistLiteral_ LiteralType
DbSpecific ConnectionString
bs) =
        PersistValue -> Either Text PgInterval
forall a. PersistField a => PersistValue -> Either Text a
fromPersistValue (ConnectionString -> PersistValue
PersistLiteralEscaped ConnectionString
bs)
    fromPersistValue x :: PersistValue
x@(PersistLiteral_ LiteralType
Escaped ConnectionString
bs) =
      case Parser NominalDiffTime
-> ConnectionString -> Either String NominalDiffTime
forall a. Parser a -> ConnectionString -> Either String a
P.parseOnly (Parser NominalDiffTime -> Parser NominalDiffTime
forall a. Num a => Parser a -> Parser a
P.signed Parser NominalDiffTime
forall a. Fractional a => Parser a
P.rational Parser NominalDiffTime -> Parser Char -> Parser NominalDiffTime
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Char -> Parser Char
P.char Char
's' Parser NominalDiffTime
-> Parser ConnectionString () -> Parser NominalDiffTime
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ConnectionString ()
forall t. Chunk t => Parser t ()
P.endOfInput) ConnectionString
bs of
        Left String
_  -> Text -> Either Text PgInterval
forall a b. a -> Either a b
Left (Text -> Either Text PgInterval) -> Text -> Either Text PgInterval
forall a b. (a -> b) -> a -> b
$ Text -> Text -> PersistValue -> Text
fromPersistValueError Text
"PgInterval" Text
"Interval" PersistValue
x
        Right NominalDiffTime
i -> PgInterval -> Either Text PgInterval
forall a b. b -> Either a b
Right (PgInterval -> Either Text PgInterval)
-> PgInterval -> Either Text PgInterval
forall a b. (a -> b) -> a -> b
$ NominalDiffTime -> PgInterval
PgInterval NominalDiffTime
i
    fromPersistValue PersistValue
x = Text -> Either Text PgInterval
forall a b. a -> Either a b
Left (Text -> Either Text PgInterval) -> Text -> Either Text PgInterval
forall a b. (a -> b) -> a -> b
$ Text -> Text -> PersistValue -> Text
fromPersistValueError Text
"PgInterval" Text
"Interval" PersistValue
x

instance PersistFieldSql PgInterval where
  sqlType :: Proxy PgInterval -> SqlType
sqlType Proxy PgInterval
_ = Text -> SqlType
SqlOther Text
"interval"

newtype Unknown = Unknown { Unknown -> ConnectionString
unUnknown :: ByteString }
  deriving (Unknown -> Unknown -> Bool
(Unknown -> Unknown -> Bool)
-> (Unknown -> Unknown -> Bool) -> Eq Unknown
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Unknown -> Unknown -> Bool
$c/= :: Unknown -> Unknown -> Bool
== :: Unknown -> Unknown -> Bool
$c== :: Unknown -> Unknown -> Bool
Eq, Int -> Unknown -> ShowS
[Unknown] -> ShowS
Unknown -> String
(Int -> Unknown -> ShowS)
-> (Unknown -> String) -> ([Unknown] -> ShowS) -> Show Unknown
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [Unknown] -> ShowS
$cshowList :: [Unknown] -> ShowS
show :: Unknown -> String
$cshow :: Unknown -> String
showsPrec :: Int -> Unknown -> ShowS
$cshowsPrec :: Int -> Unknown -> ShowS
Show, ReadPrec [Unknown]
ReadPrec Unknown
Int -> ReadS Unknown
ReadS [Unknown]
(Int -> ReadS Unknown)
-> ReadS [Unknown]
-> ReadPrec Unknown
-> ReadPrec [Unknown]
-> Read Unknown
forall a.
(Int -> ReadS a)
-> ReadS [a] -> ReadPrec a -> ReadPrec [a] -> Read a
readListPrec :: ReadPrec [Unknown]
$creadListPrec :: ReadPrec [Unknown]
readPrec :: ReadPrec Unknown
$creadPrec :: ReadPrec Unknown
readList :: ReadS [Unknown]
$creadList :: ReadS [Unknown]
readsPrec :: Int -> ReadS Unknown
$creadsPrec :: Int -> ReadS Unknown
Read, Eq Unknown
Eq Unknown
-> (Unknown -> Unknown -> Ordering)
-> (Unknown -> Unknown -> Bool)
-> (Unknown -> Unknown -> Bool)
-> (Unknown -> Unknown -> Bool)
-> (Unknown -> Unknown -> Bool)
-> (Unknown -> Unknown -> Unknown)
-> (Unknown -> Unknown -> Unknown)
-> Ord Unknown
Unknown -> Unknown -> Bool
Unknown -> Unknown -> Ordering
Unknown -> Unknown -> Unknown
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: Unknown -> Unknown -> Unknown
$cmin :: Unknown -> Unknown -> Unknown
max :: Unknown -> Unknown -> Unknown
$cmax :: Unknown -> Unknown -> Unknown
>= :: Unknown -> Unknown -> Bool
$c>= :: Unknown -> Unknown -> Bool
> :: Unknown -> Unknown -> Bool
$c> :: Unknown -> Unknown -> Bool
<= :: Unknown -> Unknown -> Bool
$c<= :: Unknown -> Unknown -> Bool
< :: Unknown -> Unknown -> Bool
$c< :: Unknown -> Unknown -> Bool
compare :: Unknown -> Unknown -> Ordering
$ccompare :: Unknown -> Unknown -> Ordering
$cp1Ord :: Eq Unknown
Ord)

instance PGFF.FromField Unknown where
    fromField :: FieldParser Unknown
fromField Field
f Maybe ConnectionString
mdata =
      case Maybe ConnectionString
mdata of
        Maybe ConnectionString
Nothing  -> (String -> Maybe Oid -> String -> String -> String -> ResultError)
-> Field -> String -> Conversion Unknown
forall a err.
(Typeable a, Exception err) =>
(String -> Maybe Oid -> String -> String -> String -> err)
-> Field -> String -> Conversion a
PGFF.returnError String -> Maybe Oid -> String -> String -> String -> ResultError
PGFF.UnexpectedNull Field
f String
"Database.Persist.Postgresql/PGFF.FromField Unknown"
        Just ConnectionString
dat -> Unknown -> Conversion Unknown
forall (m :: * -> *) a. Monad m => a -> m a
return (ConnectionString -> Unknown
Unknown ConnectionString
dat)

instance PGTF.ToField Unknown where
    toField :: Unknown -> Action
toField (Unknown ConnectionString
a) = ConnectionString -> Action
PGTF.Escape ConnectionString
a

newtype UnknownLiteral = UnknownLiteral { UnknownLiteral -> ConnectionString
unUnknownLiteral :: ByteString }
  deriving (UnknownLiteral -> UnknownLiteral -> Bool
(UnknownLiteral -> UnknownLiteral -> Bool)
-> (UnknownLiteral -> UnknownLiteral -> Bool) -> Eq UnknownLiteral
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: UnknownLiteral -> UnknownLiteral -> Bool
$c/= :: UnknownLiteral -> UnknownLiteral -> Bool
== :: UnknownLiteral -> UnknownLiteral -> Bool
$c== :: UnknownLiteral -> UnknownLiteral -> Bool
Eq, Int -> UnknownLiteral -> ShowS
[UnknownLiteral] -> ShowS
UnknownLiteral -> String
(Int -> UnknownLiteral -> ShowS)
-> (UnknownLiteral -> String)
-> ([UnknownLiteral] -> ShowS)
-> Show UnknownLiteral
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [UnknownLiteral] -> ShowS
$cshowList :: [UnknownLiteral] -> ShowS
show :: UnknownLiteral -> String
$cshow :: UnknownLiteral -> String
showsPrec :: Int -> UnknownLiteral -> ShowS
$cshowsPrec :: Int -> UnknownLiteral -> ShowS
Show, ReadPrec [UnknownLiteral]
ReadPrec UnknownLiteral
Int -> ReadS UnknownLiteral
ReadS [UnknownLiteral]
(Int -> ReadS UnknownLiteral)
-> ReadS [UnknownLiteral]
-> ReadPrec UnknownLiteral
-> ReadPrec [UnknownLiteral]
-> Read UnknownLiteral
forall a.
(Int -> ReadS a)
-> ReadS [a] -> ReadPrec a -> ReadPrec [a] -> Read a
readListPrec :: ReadPrec [UnknownLiteral]
$creadListPrec :: ReadPrec [UnknownLiteral]
readPrec :: ReadPrec UnknownLiteral
$creadPrec :: ReadPrec UnknownLiteral
readList :: ReadS [UnknownLiteral]
$creadList :: ReadS [UnknownLiteral]
readsPrec :: Int -> ReadS UnknownLiteral
$creadsPrec :: Int -> ReadS UnknownLiteral
Read, Eq UnknownLiteral
Eq UnknownLiteral
-> (UnknownLiteral -> UnknownLiteral -> Ordering)
-> (UnknownLiteral -> UnknownLiteral -> Bool)
-> (UnknownLiteral -> UnknownLiteral -> Bool)
-> (UnknownLiteral -> UnknownLiteral -> Bool)
-> (UnknownLiteral -> UnknownLiteral -> Bool)
-> (UnknownLiteral -> UnknownLiteral -> UnknownLiteral)
-> (UnknownLiteral -> UnknownLiteral -> UnknownLiteral)
-> Ord UnknownLiteral
UnknownLiteral -> UnknownLiteral -> Bool
UnknownLiteral -> UnknownLiteral -> Ordering
UnknownLiteral -> UnknownLiteral -> UnknownLiteral
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: UnknownLiteral -> UnknownLiteral -> UnknownLiteral
$cmin :: UnknownLiteral -> UnknownLiteral -> UnknownLiteral
max :: UnknownLiteral -> UnknownLiteral -> UnknownLiteral
$cmax :: UnknownLiteral -> UnknownLiteral -> UnknownLiteral
>= :: UnknownLiteral -> UnknownLiteral -> Bool
$c>= :: UnknownLiteral -> UnknownLiteral -> Bool
> :: UnknownLiteral -> UnknownLiteral -> Bool
$c> :: UnknownLiteral -> UnknownLiteral -> Bool
<= :: UnknownLiteral -> UnknownLiteral -> Bool
$c<= :: UnknownLiteral -> UnknownLiteral -> Bool
< :: UnknownLiteral -> UnknownLiteral -> Bool
$c< :: UnknownLiteral -> UnknownLiteral -> Bool
compare :: UnknownLiteral -> UnknownLiteral -> Ordering
$ccompare :: UnknownLiteral -> UnknownLiteral -> Ordering
$cp1Ord :: Eq UnknownLiteral
Ord, Typeable)

instance PGFF.FromField UnknownLiteral where
    fromField :: FieldParser UnknownLiteral
fromField Field
f Maybe ConnectionString
mdata =
      case Maybe ConnectionString
mdata of
        Maybe ConnectionString
Nothing  -> (String -> Maybe Oid -> String -> String -> String -> ResultError)
-> Field -> String -> Conversion UnknownLiteral
forall a err.
(Typeable a, Exception err) =>
(String -> Maybe Oid -> String -> String -> String -> err)
-> Field -> String -> Conversion a
PGFF.returnError String -> Maybe Oid -> String -> String -> String -> ResultError
PGFF.UnexpectedNull Field
f String
"Database.Persist.Postgresql/PGFF.FromField UnknownLiteral"
        Just ConnectionString
dat -> UnknownLiteral -> Conversion UnknownLiteral
forall (m :: * -> *) a. Monad m => a -> m a
return (ConnectionString -> UnknownLiteral
UnknownLiteral ConnectionString
dat)

instance PGTF.ToField UnknownLiteral where
    toField :: UnknownLiteral -> Action
toField (UnknownLiteral ConnectionString
a) = Builder -> Action
PGTF.Plain (Builder -> Action) -> Builder -> Action
forall a b. (a -> b) -> a -> b
$ ConnectionString -> Builder
BB.byteString ConnectionString
a


type Getter a = PGFF.FieldParser a

convertPV :: PGFF.FromField a => (a -> b) -> Getter b
convertPV :: (a -> b) -> Getter b
convertPV a -> b
f = ((a -> b) -> Conversion a -> Conversion b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> b
f (Conversion a -> Conversion b)
-> (Maybe ConnectionString -> Conversion a)
-> Maybe ConnectionString
-> Conversion b
forall b c a. (b -> c) -> (a -> b) -> a -> c
.) ((Maybe ConnectionString -> Conversion a)
 -> Maybe ConnectionString -> Conversion b)
-> (Field -> Maybe ConnectionString -> Conversion a) -> Getter b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Field -> Maybe ConnectionString -> Conversion a
forall a. FromField a => FieldParser a
PGFF.fromField

builtinGetters :: I.IntMap (Getter PersistValue)
builtinGetters :: IntMap (Getter PersistValue)
builtinGetters = [(Int, Getter PersistValue)] -> IntMap (Getter PersistValue)
forall a. [(Int, a)] -> IntMap a
I.fromList
    [ (TypeInfo -> Int
k TypeInfo
PS.bool,        (Bool -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Bool -> PersistValue
PersistBool)
    , (TypeInfo -> Int
k TypeInfo
PS.bytea,       (Binary ConnectionString -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Binary ConnectionString -> ConnectionString)
-> Binary ConnectionString
-> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Binary ConnectionString -> ConnectionString
forall a. Binary a -> a
unBinary))
    , (TypeInfo -> Int
k TypeInfo
PS.char,        (Text -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Text -> PersistValue
PersistText)
    , (TypeInfo -> Int
k TypeInfo
PS.name,        (Text -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Text -> PersistValue
PersistText)
    , (TypeInfo -> Int
k TypeInfo
PS.int8,        (Int64 -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Int64 -> PersistValue
PersistInt64)
    , (TypeInfo -> Int
k TypeInfo
PS.int2,        (Int64 -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Int64 -> PersistValue
PersistInt64)
    , (TypeInfo -> Int
k TypeInfo
PS.int4,        (Int64 -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Int64 -> PersistValue
PersistInt64)
    , (TypeInfo -> Int
k TypeInfo
PS.text,        (Text -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Text -> PersistValue
PersistText)
    , (TypeInfo -> Int
k TypeInfo
PS.xml,         (Unknown -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))
    , (TypeInfo -> Int
k TypeInfo
PS.float4,      (Double -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Double -> PersistValue
PersistDouble)
    , (TypeInfo -> Int
k TypeInfo
PS.float8,      (Double -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Double -> PersistValue
PersistDouble)
    , (TypeInfo -> Int
k TypeInfo
PS.money,       (Rational -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Rational -> PersistValue
PersistRational)
    , (TypeInfo -> Int
k TypeInfo
PS.bpchar,      (Text -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Text -> PersistValue
PersistText)
    , (TypeInfo -> Int
k TypeInfo
PS.varchar,     (Text -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Text -> PersistValue
PersistText)
    , (TypeInfo -> Int
k TypeInfo
PS.date,        (Day -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Day -> PersistValue
PersistDay)
    , (TypeInfo -> Int
k TypeInfo
PS.time,        (TimeOfDay -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV TimeOfDay -> PersistValue
PersistTimeOfDay)
    , (TypeInfo -> Int
k TypeInfo
PS.timestamp,   (LocalTime -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (UTCTime -> PersistValue
PersistUTCTime(UTCTime -> PersistValue)
-> (LocalTime -> UTCTime) -> LocalTime -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TimeZone -> LocalTime -> UTCTime
localTimeToUTC TimeZone
utc))
    , (TypeInfo -> Int
k TypeInfo
PS.timestamptz, (UTCTime -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV UTCTime -> PersistValue
PersistUTCTime)
    , (TypeInfo -> Int
k TypeInfo
PS.interval,    (PgInterval -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (ConnectionString -> PersistValue
PersistLiteralEscaped (ConnectionString -> PersistValue)
-> (PgInterval -> ConnectionString) -> PgInterval -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PgInterval -> ConnectionString
pgIntervalToBs))
    , (TypeInfo -> Int
k TypeInfo
PS.bit,         (Int64 -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Int64 -> PersistValue
PersistInt64)
    , (TypeInfo -> Int
k TypeInfo
PS.varbit,      (Int64 -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Int64 -> PersistValue
PersistInt64)
    , (TypeInfo -> Int
k TypeInfo
PS.numeric,     (Rational -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV Rational -> PersistValue
PersistRational)
    , (TypeInfo -> Int
k TypeInfo
PS.void,        \Field
_ Maybe ConnectionString
_ -> PersistValue -> Conversion PersistValue
forall (m :: * -> *) a. Monad m => a -> m a
return PersistValue
PersistNull)
    , (TypeInfo -> Int
k TypeInfo
PS.json,        (Unknown -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))
    , (TypeInfo -> Int
k TypeInfo
PS.jsonb,       (Unknown -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))
    , (TypeInfo -> Int
k TypeInfo
PS.unknown,     (Unknown -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))

    -- Array types: same order as above.
    -- The OIDs were taken from pg_type.
    , (Int
1000,             (Bool -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Bool -> PersistValue
PersistBool)
    , (Int
1001,             (Binary ConnectionString -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Binary ConnectionString -> ConnectionString)
-> Binary ConnectionString
-> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Binary ConnectionString -> ConnectionString
forall a. Binary a -> a
unBinary))
    , (Int
1002,             (Text -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Text -> PersistValue
PersistText)
    , (Int
1003,             (Text -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Text -> PersistValue
PersistText)
    , (Int
1016,             (Int64 -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Int64 -> PersistValue
PersistInt64)
    , (Int
1005,             (Int64 -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Int64 -> PersistValue
PersistInt64)
    , (Int
1007,             (Int64 -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Int64 -> PersistValue
PersistInt64)
    , (Int
1009,             (Text -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Text -> PersistValue
PersistText)
    , (Int
143,              (Unknown -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))
    , (Int
1021,             (Double -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Double -> PersistValue
PersistDouble)
    , (Int
1022,             (Double -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Double -> PersistValue
PersistDouble)
    , (Int
1023,             (UTCTime -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf UTCTime -> PersistValue
PersistUTCTime)
    , (Int
1024,             (UTCTime -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf UTCTime -> PersistValue
PersistUTCTime)
    , (Int
791,              (Rational -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Rational -> PersistValue
PersistRational)
    , (Int
1014,             (Text -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Text -> PersistValue
PersistText)
    , (Int
1015,             (Text -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Text -> PersistValue
PersistText)
    , (Int
1182,             (Day -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Day -> PersistValue
PersistDay)
    , (Int
1183,             (TimeOfDay -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf TimeOfDay -> PersistValue
PersistTimeOfDay)
    , (Int
1115,             (UTCTime -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf UTCTime -> PersistValue
PersistUTCTime)
    , (Int
1185,             (UTCTime -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf UTCTime -> PersistValue
PersistUTCTime)
    , (Int
1187,             (PgInterval -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf (ConnectionString -> PersistValue
PersistLiteralEscaped (ConnectionString -> PersistValue)
-> (PgInterval -> ConnectionString) -> PgInterval -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PgInterval -> ConnectionString
pgIntervalToBs))
    , (Int
1561,             (Int64 -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Int64 -> PersistValue
PersistInt64)
    , (Int
1563,             (Int64 -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Int64 -> PersistValue
PersistInt64)
    , (Int
1231,             (Rational -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf Rational -> PersistValue
PersistRational)
    -- no array(void) type
    , (Int
2951,             (Unknown -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf (ConnectionString -> PersistValue
PersistLiteralEscaped (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))
    , (Int
199,              (Unknown -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))
    , (Int
3807,             (Unknown -> PersistValue) -> Getter PersistValue
forall a.
(FromField a, Typeable a) =>
(a -> PersistValue) -> Getter PersistValue
listOf (ConnectionString -> PersistValue
PersistByteString (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown))
    -- no array(unknown) either
    ]
    where
        k :: TypeInfo -> Int
k (TypeInfo -> Oid
PGFF.typoid -> Oid
i) = Oid -> Int
PG.oid2int Oid
i
        -- A @listOf f@ will use a @PGArray (Maybe T)@ to convert
        -- the values to Haskell-land.  The @Maybe@ is important
        -- because the usual way of checking NULLs
        -- (c.f. withStmt') won't check for NULL inside
        -- arrays---or any other compound structure for that matter.
        listOf :: (a -> PersistValue) -> Getter PersistValue
listOf a -> PersistValue
f = (PGArray (Maybe a) -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV ([PersistValue] -> PersistValue
PersistList ([PersistValue] -> PersistValue)
-> (PGArray (Maybe a) -> [PersistValue])
-> PGArray (Maybe a)
-> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe a -> PersistValue) -> [Maybe a] -> [PersistValue]
forall a b. (a -> b) -> [a] -> [b]
map ((a -> PersistValue) -> Maybe a -> PersistValue
forall a. (a -> PersistValue) -> Maybe a -> PersistValue
nullable a -> PersistValue
f) ([Maybe a] -> [PersistValue])
-> (PGArray (Maybe a) -> [Maybe a])
-> PGArray (Maybe a)
-> [PersistValue]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PGArray (Maybe a) -> [Maybe a]
forall a. PGArray a -> [a]
PG.fromPGArray)
          where nullable :: (a -> PersistValue) -> Maybe a -> PersistValue
nullable = PersistValue -> (a -> PersistValue) -> Maybe a -> PersistValue
forall b a. b -> (a -> b) -> Maybe a -> b
maybe PersistValue
PersistNull

getGetter :: PG.Connection -> PG.Oid -> Getter PersistValue
getGetter :: Connection -> Oid -> Getter PersistValue
getGetter Connection
_conn Oid
oid
  = Getter PersistValue
-> Maybe (Getter PersistValue) -> Getter PersistValue
forall a. a -> Maybe a -> a
fromMaybe Getter PersistValue
defaultGetter (Maybe (Getter PersistValue) -> Getter PersistValue)
-> Maybe (Getter PersistValue) -> Getter PersistValue
forall a b. (a -> b) -> a -> b
$ Int -> IntMap (Getter PersistValue) -> Maybe (Getter PersistValue)
forall a. Int -> IntMap a -> Maybe a
I.lookup (Oid -> Int
PG.oid2int Oid
oid) IntMap (Getter PersistValue)
builtinGetters
  where defaultGetter :: Getter PersistValue
defaultGetter = (Unknown -> PersistValue) -> Getter PersistValue
forall a b. FromField a => (a -> b) -> Getter b
convertPV (ConnectionString -> PersistValue
PersistLiteralEscaped (ConnectionString -> PersistValue)
-> (Unknown -> ConnectionString) -> Unknown -> PersistValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unknown -> ConnectionString
unUnknown)

unBinary :: PG.Binary a -> a
unBinary :: Binary a -> a
unBinary (PG.Binary a
x) = a
x

doesTableExist :: (Text -> IO Statement)
               -> EntityNameDB
               -> IO Bool
doesTableExist :: (Text -> IO Statement) -> EntityNameDB -> IO Bool
doesTableExist Text -> IO Statement
getter (EntityNameDB Text
name) = do
    Statement
stmt <- Text -> IO Statement
getter Text
sql
    Acquire (ConduitM () [PersistValue] IO ())
-> (ConduitM () [PersistValue] IO () -> IO Bool) -> IO Bool
forall (m :: * -> *) a b.
MonadUnliftIO m =>
Acquire a -> (a -> m b) -> m b
with (Statement
-> [PersistValue] -> Acquire (ConduitM () [PersistValue] IO ())
Statement
-> forall (m :: * -> *).
   MonadIO m =>
   [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
stmtQuery Statement
stmt [PersistValue]
vals) (\ConduitM () [PersistValue] IO ()
src -> ConduitT () Void IO Bool -> IO Bool
forall (m :: * -> *) r. Monad m => ConduitT () Void m r -> m r
runConduit (ConduitT () Void IO Bool -> IO Bool)
-> ConduitT () Void IO Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ ConduitM () [PersistValue] IO ()
src ConduitM () [PersistValue] IO ()
-> ConduitM [PersistValue] Void IO Bool -> ConduitT () Void IO Bool
forall (m :: * -> *) a b c r.
Monad m =>
ConduitM a b m () -> ConduitM b c m r -> ConduitM a c m r
.| ConduitM [PersistValue] Void IO Bool
forall o. ConduitT [PersistValue] o IO Bool
start)
  where
    sql :: Text
sql = Text
"SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog'"
          Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" AND schemaname != 'information_schema' AND tablename=?"
    vals :: [PersistValue]
vals = [Text -> PersistValue
PersistText Text
name]

    start :: ConduitT [PersistValue] o IO Bool
start = ConduitT [PersistValue] o IO (Maybe [PersistValue])
forall (m :: * -> *) i. Monad m => Consumer i m (Maybe i)
await ConduitT [PersistValue] o IO (Maybe [PersistValue])
-> (Maybe [PersistValue] -> ConduitT [PersistValue] o IO Bool)
-> ConduitT [PersistValue] o IO Bool
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ConduitT [PersistValue] o IO Bool
-> ([PersistValue] -> ConduitT [PersistValue] o IO Bool)
-> Maybe [PersistValue]
-> ConduitT [PersistValue] o IO Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> ConduitT [PersistValue] o IO Bool
forall a. HasCallStack => String -> a
error String
"No results when checking doesTableExist") [PersistValue] -> ConduitT [PersistValue] o IO Bool
forall (m :: * -> *) a o.
Monad m =>
[PersistValue] -> ConduitT a o m Bool
start'
    start' :: [PersistValue] -> ConduitT a o m Bool
start' [PersistInt64 Int64
0] = Bool -> ConduitT a o m Bool
forall (m :: * -> *) b a o. Monad m => b -> ConduitT a o m b
finish Bool
False
    start' [PersistInt64 Int64
1] = Bool -> ConduitT a o m Bool
forall (m :: * -> *) b a o. Monad m => b -> ConduitT a o m b
finish Bool
True
    start' [PersistValue]
res = String -> ConduitT a o m Bool
forall a. HasCallStack => String -> a
error (String -> ConduitT a o m Bool) -> String -> ConduitT a o m Bool
forall a b. (a -> b) -> a -> b
$ String
"doesTableExist returned unexpected result: " String -> ShowS
forall a. [a] -> [a] -> [a]
++ [PersistValue] -> String
forall a. Show a => a -> String
show [PersistValue]
res
    finish :: b -> ConduitT a o m b
finish b
x = ConduitT a o m (Maybe a)
forall (m :: * -> *) i. Monad m => Consumer i m (Maybe i)
await ConduitT a o m (Maybe a)
-> (Maybe a -> ConduitT a o m b) -> ConduitT a o m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ConduitT a o m b
-> (a -> ConduitT a o m b) -> Maybe a -> ConduitT a o m b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (b -> ConduitT a o m b
forall (m :: * -> *) a. Monad m => a -> m a
return b
x) (String -> a -> ConduitT a o m b
forall a. HasCallStack => String -> a
error String
"Too many rows returned in doesTableExist")

migrate' :: [EntityDef]
         -> (Text -> IO Statement)
         -> EntityDef
         -> IO (Either [Text] [(Bool, Text)])
migrate' :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
migrate' [EntityDef]
allDefs Text -> IO Statement
getter EntityDef
entity = (Either [Text] [AlterDB] -> Either [Text] [(Bool, Text)])
-> IO (Either [Text] [AlterDB])
-> IO (Either [Text] [(Bool, Text)])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (([AlterDB] -> [(Bool, Text)])
-> Either [Text] [AlterDB] -> Either [Text] [(Bool, Text)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (([AlterDB] -> [(Bool, Text)])
 -> Either [Text] [AlterDB] -> Either [Text] [(Bool, Text)])
-> ([AlterDB] -> [(Bool, Text)])
-> Either [Text] [AlterDB]
-> Either [Text] [(Bool, Text)]
forall a b. (a -> b) -> a -> b
$ (AlterDB -> (Bool, Text)) -> [AlterDB] -> [(Bool, Text)]
forall a b. (a -> b) -> [a] -> [b]
map AlterDB -> (Bool, Text)
showAlterDb) (IO (Either [Text] [AlterDB]) -> IO (Either [Text] [(Bool, Text)]))
-> IO (Either [Text] [AlterDB])
-> IO (Either [Text] [(Bool, Text)])
forall a b. (a -> b) -> a -> b
$ do
    [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
old <- (Text -> IO Statement)
-> EntityDef
-> [Column]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
getColumns Text -> IO Statement
getter EntityDef
entity [Column]
newcols'
    case [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> ([Text], [Either Column (ConstraintNameDB, [FieldNameDB])])
forall a b. [Either a b] -> ([a], [b])
partitionEithers [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
old of
        ([], [Either Column (ConstraintNameDB, [FieldNameDB])]
old'') -> do
            Bool
exists' <-
                if [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
old
                    then (Text -> IO Statement) -> EntityNameDB -> IO Bool
doesTableExist Text -> IO Statement
getter EntityNameDB
name
                    else Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
            Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall (m :: * -> *) a. Monad m => a -> m a
return (Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB]))
-> Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall a b. (a -> b) -> a -> b
$ [AlterDB] -> Either [Text] [AlterDB]
forall a b. b -> Either a b
Right ([AlterDB] -> Either [Text] [AlterDB])
-> [AlterDB] -> Either [Text] [AlterDB]
forall a b. (a -> b) -> a -> b
$ Bool
-> [Either Column (ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
migrationText Bool
exists' [Either Column (ConstraintNameDB, [FieldNameDB])]
old''
        ([Text]
errs, [Either Column (ConstraintNameDB, [FieldNameDB])]
_) -> Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall (m :: * -> *) a. Monad m => a -> m a
return (Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB]))
-> Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall a b. (a -> b) -> a -> b
$ [Text] -> Either [Text] [AlterDB]
forall a b. a -> Either a b
Left [Text]
errs
  where
    name :: EntityNameDB
name = EntityDef -> EntityNameDB
entityDB EntityDef
entity
    ([Column]
newcols', [UniqueDef]
udefs, [ForeignDef]
fdefs) = [EntityDef] -> EntityDef -> ([Column], [UniqueDef], [ForeignDef])
postgresMkColumns [EntityDef]
allDefs EntityDef
entity
    migrationText :: Bool
-> [Either Column (ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
migrationText Bool
exists' [Either Column (ConstraintNameDB, [FieldNameDB])]
old''
        | Bool -> Bool
not Bool
exists' =
            [Column]
-> [ForeignDef] -> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
createText [Column]
newcols [ForeignDef]
fdefs [(ConstraintNameDB, [FieldNameDB])]
udspair
        | Bool
otherwise =
            let ([AlterColumn]
acs, [AlterTable]
ats) =
                    [EntityDef]
-> EntityDef
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([AlterColumn], [AlterTable])
getAlters [EntityDef]
allDefs EntityDef
entity ([Column]
newcols, [(ConstraintNameDB, [FieldNameDB])]
udspair) ([Column], [(ConstraintNameDB, [FieldNameDB])])
old'
                acs' :: [AlterDB]
acs' = (AlterColumn -> AlterDB) -> [AlterColumn] -> [AlterDB]
forall a b. (a -> b) -> [a] -> [b]
map (EntityNameDB -> AlterColumn -> AlterDB
AlterColumn EntityNameDB
name) [AlterColumn]
acs
                ats' :: [AlterDB]
ats' = (AlterTable -> AlterDB) -> [AlterTable] -> [AlterDB]
forall a b. (a -> b) -> [a] -> [b]
map (EntityNameDB -> AlterTable -> AlterDB
AlterTable EntityNameDB
name) [AlterTable]
ats
            in
                [AlterDB]
acs' [AlterDB] -> [AlterDB] -> [AlterDB]
forall a. [a] -> [a] -> [a]
++ [AlterDB]
ats'
       where
         old' :: ([Column], [(ConstraintNameDB, [FieldNameDB])])
old' = [Either Column (ConstraintNameDB, [FieldNameDB])]
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
forall a b. [Either a b] -> ([a], [b])
partitionEithers [Either Column (ConstraintNameDB, [FieldNameDB])]
old''
         newcols :: [Column]
newcols = (Column -> Bool) -> [Column] -> [Column]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Column -> Bool) -> Column -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> FieldNameDB -> Bool
safeToRemove EntityDef
entity (FieldNameDB -> Bool) -> (Column -> FieldNameDB) -> Column -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Column -> FieldNameDB
cName) [Column]
newcols'
         udspair :: [(ConstraintNameDB, [FieldNameDB])]
udspair = (UniqueDef -> (ConstraintNameDB, [FieldNameDB]))
-> [UniqueDef] -> [(ConstraintNameDB, [FieldNameDB])]
forall a b. (a -> b) -> [a] -> [b]
map UniqueDef -> (ConstraintNameDB, [FieldNameDB])
udToPair [UniqueDef]
udefs
            -- Check for table existence if there are no columns, workaround
            -- for https://github.com/yesodweb/persistent/issues/152

    createText :: [Column]
-> [ForeignDef] -> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
createText [Column]
newcols [ForeignDef]
fdefs_ [(ConstraintNameDB, [FieldNameDB])]
udspair =
        ([Column] -> EntityDef -> AlterDB
addTable [Column]
newcols EntityDef
entity) AlterDB -> [AlterDB] -> [AlterDB]
forall a. a -> [a] -> [a]
: [AlterDB]
uniques [AlterDB] -> [AlterDB] -> [AlterDB]
forall a. [a] -> [a] -> [a]
++ [AlterDB]
references [AlterDB] -> [AlterDB] -> [AlterDB]
forall a. [a] -> [a] -> [a]
++ [AlterDB]
foreignsAlt
      where
        uniques :: [AlterDB]
uniques = (((ConstraintNameDB, [FieldNameDB]) -> [AlterDB])
 -> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB])
-> [(ConstraintNameDB, [FieldNameDB])]
-> ((ConstraintNameDB, [FieldNameDB]) -> [AlterDB])
-> [AlterDB]
forall a b c. (a -> b -> c) -> b -> a -> c
flip ((ConstraintNameDB, [FieldNameDB]) -> [AlterDB])
-> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap [(ConstraintNameDB, [FieldNameDB])]
udspair (((ConstraintNameDB, [FieldNameDB]) -> [AlterDB]) -> [AlterDB])
-> ((ConstraintNameDB, [FieldNameDB]) -> [AlterDB]) -> [AlterDB]
forall a b. (a -> b) -> a -> b
$ \(ConstraintNameDB
uname, [FieldNameDB]
ucols) ->
                [EntityNameDB -> AlterTable -> AlterDB
AlterTable EntityNameDB
name (AlterTable -> AlterDB) -> AlterTable -> AlterDB
forall a b. (a -> b) -> a -> b
$ ConstraintNameDB -> [FieldNameDB] -> AlterTable
AddUniqueConstraint ConstraintNameDB
uname [FieldNameDB]
ucols]
        references :: [AlterDB]
references =
            (Column -> Maybe AlterDB) -> [Column] -> [AlterDB]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe
                (\Column { FieldNameDB
cName :: FieldNameDB
cName :: Column -> FieldNameDB
cName, Maybe ColumnReference
cReference :: Column -> Maybe ColumnReference
cReference :: Maybe ColumnReference
cReference } ->
                    [EntityDef]
-> EntityDef -> FieldNameDB -> ColumnReference -> Maybe AlterDB
getAddReference [EntityDef]
allDefs EntityDef
entity FieldNameDB
cName (ColumnReference -> Maybe AlterDB)
-> Maybe ColumnReference -> Maybe AlterDB
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe ColumnReference
cReference
                )
                [Column]
newcols
        foreignsAlt :: [AlterDB]
foreignsAlt = (ForeignDef -> Maybe AlterDB) -> [ForeignDef] -> [AlterDB]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (EntityDef -> ForeignDef -> Maybe AlterDB
mkForeignAlt EntityDef
entity) [ForeignDef]
fdefs_

mkForeignAlt
    :: EntityDef
    -> ForeignDef
    -> Maybe AlterDB
mkForeignAlt :: EntityDef -> ForeignDef -> Maybe AlterDB
mkForeignAlt EntityDef
entity ForeignDef
fdef = AlterDB -> Maybe AlterDB
forall (f :: * -> *) a. Applicative f => a -> f a
pure (AlterDB -> Maybe AlterDB) -> AlterDB -> Maybe AlterDB
forall a b. (a -> b) -> a -> b
$ EntityNameDB -> AlterColumn -> AlterDB
AlterColumn EntityNameDB
tableName_ AlterColumn
addReference
  where
    tableName_ :: EntityNameDB
tableName_ = EntityDef -> EntityNameDB
entityDB EntityDef
entity
    addReference :: AlterColumn
addReference =
        EntityNameDB
-> ConstraintNameDB
-> [FieldNameDB]
-> [Text]
-> FieldCascade
-> AlterColumn
AddReference
            (ForeignDef -> EntityNameDB
foreignRefTableDBName ForeignDef
fdef)
            ConstraintNameDB
constraintName
            [FieldNameDB]
childfields
            [Text]
escapedParentFields
            (ForeignDef -> FieldCascade
foreignFieldCascade ForeignDef
fdef)
    constraintName :: ConstraintNameDB
constraintName =
        ForeignDef -> ConstraintNameDB
foreignConstraintNameDBName ForeignDef
fdef
    ([FieldNameDB]
childfields, [FieldNameDB]
parentfields) =
        [(FieldNameDB, FieldNameDB)] -> ([FieldNameDB], [FieldNameDB])
forall a b. [(a, b)] -> ([a], [b])
unzip ((((FieldNameHS, FieldNameDB), (FieldNameHS, FieldNameDB))
 -> (FieldNameDB, FieldNameDB))
-> [((FieldNameHS, FieldNameDB), (FieldNameHS, FieldNameDB))]
-> [(FieldNameDB, FieldNameDB)]
forall a b. (a -> b) -> [a] -> [b]
map (\((FieldNameHS
_,FieldNameDB
b),(FieldNameHS
_,FieldNameDB
d)) -> (FieldNameDB
b,FieldNameDB
d)) (ForeignDef
-> [((FieldNameHS, FieldNameDB), (FieldNameHS, FieldNameDB))]
foreignFields ForeignDef
fdef))
    escapedParentFields :: [Text]
escapedParentFields =
        (FieldNameDB -> Text) -> [FieldNameDB] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map FieldNameDB -> Text
escapeF [FieldNameDB]
parentfields

addTable :: [Column] -> EntityDef -> AlterDB
addTable :: [Column] -> EntityDef -> AlterDB
addTable [Column]
cols EntityDef
entity =
    Text -> AlterDB
AddTable (Text -> AlterDB) -> Text -> AlterDB
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat
        -- Lower case e: see Database.Persist.Sql.Migration
        [ Text
"CREATe TABLE " -- DO NOT FIX THE CAPITALIZATION!
        , EntityNameDB -> Text
escapeE EntityNameDB
name
        , Text
"("
        , Text
idtxt
        , if [Column] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Column]
nonIdCols then Text
"" else Text
","
        , Text -> [Text] -> Text
T.intercalate Text
"," ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Column -> Text) -> [Column] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Column -> Text
showColumn [Column]
nonIdCols
        , Text
")"
        ]
  where
    nonIdCols :: [Column]
nonIdCols =
        case EntityDef -> Maybe CompositeDef
entityPrimary EntityDef
entity of
            Just CompositeDef
_ ->
                [Column]
cols
            Maybe CompositeDef
_ ->
                (Column -> Bool) -> [Column] -> [Column]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Column
c -> Column -> FieldNameDB
cName Column
c FieldNameDB -> FieldNameDB -> Bool
forall a. Eq a => a -> a -> Bool
/= FieldDef -> FieldNameDB
fieldDB (EntityDef -> FieldDef
entityId EntityDef
entity) ) [Column]
cols

    name :: EntityNameDB
name =
        EntityDef -> EntityNameDB
entityDB EntityDef
entity
    idtxt :: Text
idtxt =
        case EntityDef -> Maybe CompositeDef
entityPrimary EntityDef
entity of
            Just CompositeDef
pdef ->
                [Text] -> Text
T.concat
                    [ Text
" PRIMARY KEY ("
                    , Text -> [Text] -> Text
T.intercalate Text
"," ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (FieldDef -> Text) -> [FieldDef] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (FieldNameDB -> Text
escapeF (FieldNameDB -> Text)
-> (FieldDef -> FieldNameDB) -> FieldDef -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> FieldNameDB
fieldDB) ([FieldDef] -> [Text]) -> [FieldDef] -> [Text]
forall a b. (a -> b) -> a -> b
$ CompositeDef -> [FieldDef]
compositeFields CompositeDef
pdef
                    , Text
")"
                    ]
            Maybe CompositeDef
Nothing ->
                let defText :: Maybe Text
defText = [FieldAttr] -> Maybe Text
defaultAttribute ([FieldAttr] -> Maybe Text) -> [FieldAttr] -> Maybe Text
forall a b. (a -> b) -> a -> b
$ FieldDef -> [FieldAttr]
fieldAttrs (FieldDef -> [FieldAttr]) -> FieldDef -> [FieldAttr]
forall a b. (a -> b) -> a -> b
$ EntityDef -> FieldDef
entityId EntityDef
entity
                    sType :: SqlType
sType = FieldDef -> SqlType
fieldSqlType (FieldDef -> SqlType) -> FieldDef -> SqlType
forall a b. (a -> b) -> a -> b
$ EntityDef -> FieldDef
entityId EntityDef
entity
                in  [Text] -> Text
T.concat
                        [ FieldNameDB -> Text
escapeF (FieldNameDB -> Text) -> FieldNameDB -> Text
forall a b. (a -> b) -> a -> b
$ FieldDef -> FieldNameDB
fieldDB (EntityDef -> FieldDef
entityId EntityDef
entity)
                        , SqlType -> Maybe Text -> Text
maySerial SqlType
sType Maybe Text
defText
                        , Text
" PRIMARY KEY UNIQUE"
                        , Maybe Text -> Text
mayDefault Maybe Text
defText
                        ]

maySerial :: SqlType -> Maybe Text -> Text
maySerial :: SqlType -> Maybe Text -> Text
maySerial SqlType
SqlInt64 Maybe Text
Nothing = Text
" SERIAL8 "
maySerial SqlType
sType Maybe Text
_ = Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> SqlType -> Text
showSqlType SqlType
sType

mayDefault :: Maybe Text -> Text
mayDefault :: Maybe Text -> Text
mayDefault Maybe Text
def = case Maybe Text
def of
    Maybe Text
Nothing -> Text
""
    Just Text
d -> Text
" DEFAULT " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
d

type SafeToRemove = Bool

data AlterColumn
    = ChangeType Column SqlType Text
    | IsNull Column
    | NotNull Column
    | Add' Column
    | Drop Column SafeToRemove
    | Default Column Text
    | NoDefault Column
    | Update' Column Text
    | AddReference EntityNameDB ConstraintNameDB [FieldNameDB] [Text] FieldCascade
    | DropReference ConstraintNameDB
    deriving Int -> AlterColumn -> ShowS
[AlterColumn] -> ShowS
AlterColumn -> String
(Int -> AlterColumn -> ShowS)
-> (AlterColumn -> String)
-> ([AlterColumn] -> ShowS)
-> Show AlterColumn
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [AlterColumn] -> ShowS
$cshowList :: [AlterColumn] -> ShowS
show :: AlterColumn -> String
$cshow :: AlterColumn -> String
showsPrec :: Int -> AlterColumn -> ShowS
$cshowsPrec :: Int -> AlterColumn -> ShowS
Show

data AlterTable
    = AddUniqueConstraint ConstraintNameDB [FieldNameDB]
    | DropConstraint ConstraintNameDB
    deriving Int -> AlterTable -> ShowS
[AlterTable] -> ShowS
AlterTable -> String
(Int -> AlterTable -> ShowS)
-> (AlterTable -> String)
-> ([AlterTable] -> ShowS)
-> Show AlterTable
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [AlterTable] -> ShowS
$cshowList :: [AlterTable] -> ShowS
show :: AlterTable -> String
$cshow :: AlterTable -> String
showsPrec :: Int -> AlterTable -> ShowS
$cshowsPrec :: Int -> AlterTable -> ShowS
Show

data AlterDB = AddTable Text
             | AlterColumn EntityNameDB AlterColumn
             | AlterTable EntityNameDB AlterTable
             deriving Int -> AlterDB -> ShowS
[AlterDB] -> ShowS
AlterDB -> String
(Int -> AlterDB -> ShowS)
-> (AlterDB -> String) -> ([AlterDB] -> ShowS) -> Show AlterDB
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [AlterDB] -> ShowS
$cshowList :: [AlterDB] -> ShowS
show :: AlterDB -> String
$cshow :: AlterDB -> String
showsPrec :: Int -> AlterDB -> ShowS
$cshowsPrec :: Int -> AlterDB -> ShowS
Show

-- | Returns all of the columns in the given table currently in the database.
getColumns :: (Text -> IO Statement)
           -> EntityDef -> [Column]
           -> IO [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
getColumns :: (Text -> IO Statement)
-> EntityDef
-> [Column]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
getColumns Text -> IO Statement
getter EntityDef
def [Column]
cols = do
    let sqlv :: Text
sqlv = [Text] -> Text
T.concat
            [ Text
"SELECT "
            , Text
"column_name "
            , Text
",is_nullable "
            , Text
",COALESCE(domain_name, udt_name)" -- See DOMAINS below
            , Text
",column_default "
            , Text
",generation_expression "
            , Text
",numeric_precision "
            , Text
",numeric_scale "
            , Text
",character_maximum_length "
            , Text
"FROM information_schema.columns "
            , Text
"WHERE table_catalog=current_database() "
            , Text
"AND table_schema=current_schema() "
            , Text
"AND table_name=? "
            ]

-- DOMAINS Postgres supports the concept of domains, which are data types
-- with optional constraints.  An app might make an "email" domain over the
-- varchar type, with a CHECK that the emails are valid In this case the
-- generated SQL should use the domain name: ALTER TABLE users ALTER COLUMN
-- foo TYPE email This code exists to use the domain name (email), instead
-- of the underlying type (varchar).  This is tested in
-- EquivalentTypeTest.hs

    Statement
stmt <- Text -> IO Statement
getter Text
sqlv
    let vals :: [PersistValue]
vals =
            [ Text -> PersistValue
PersistText (Text -> PersistValue) -> Text -> PersistValue
forall a b. (a -> b) -> a -> b
$ EntityNameDB -> Text
unEntityNameDB (EntityNameDB -> Text) -> EntityNameDB -> Text
forall a b. (a -> b) -> a -> b
$ EntityDef -> EntityNameDB
entityDB EntityDef
def
            ]
    [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
columns <- Acquire (ConduitM () [PersistValue] IO ())
-> (ConduitM () [PersistValue] IO ()
    -> IO
         [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))])
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a b.
MonadUnliftIO m =>
Acquire a -> (a -> m b) -> m b
with (Statement
-> [PersistValue] -> Acquire (ConduitM () [PersistValue] IO ())
Statement
-> forall (m :: * -> *).
   MonadIO m =>
   [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
stmtQuery Statement
stmt [PersistValue]
vals) (\ConduitM () [PersistValue] IO ()
src -> ConduitT
  ()
  Void
  IO
  [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) r. Monad m => ConduitT () Void m r -> m r
runConduit (ConduitT
   ()
   Void
   IO
   [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
 -> IO
      [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))])
-> ConduitT
     ()
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall a b. (a -> b) -> a -> b
$ ConduitM () [PersistValue] IO ()
src ConduitM () [PersistValue] IO ()
-> ConduitM
     [PersistValue]
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> ConduitT
     ()
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a b c r.
Monad m =>
ConduitM a b m () -> ConduitM b c m r -> ConduitM a c m r
.| ConduitT
  [PersistValue]
  (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
  IO
  ()
processColumns ConduitT
  [PersistValue]
  (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
  IO
  ()
-> ConduitM
     (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> ConduitM
     [PersistValue]
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a b c r.
Monad m =>
ConduitM a b m () -> ConduitM b c m r -> ConduitM a c m r
.| ConduitM
  (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
  Void
  IO
  [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a o. Monad m => ConduitT a o m [a]
CL.consume)
    let sqlc :: Text
sqlc = [Text] -> Text
T.concat
            [ Text
"SELECT "
            , Text
"c.constraint_name, "
            , Text
"c.column_name "
            , Text
"FROM information_schema.key_column_usage AS c, "
            , Text
"information_schema.table_constraints AS k "
            , Text
"WHERE c.table_catalog=current_database() "
            , Text
"AND c.table_catalog=k.table_catalog "
            , Text
"AND c.table_schema=current_schema() "
            , Text
"AND c.table_schema=k.table_schema "
            , Text
"AND c.table_name=? "
            , Text
"AND c.table_name=k.table_name "
            , Text
"AND c.constraint_name=k.constraint_name "
            , Text
"AND NOT k.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY') "
            , Text
"ORDER BY c.constraint_name, c.column_name"
            ]

    Statement
stmt' <- Text -> IO Statement
getter Text
sqlc

    [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
us <- Acquire (ConduitM () [PersistValue] IO ())
-> (ConduitM () [PersistValue] IO ()
    -> IO
         [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))])
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a b.
MonadUnliftIO m =>
Acquire a -> (a -> m b) -> m b
with (Statement
-> [PersistValue] -> Acquire (ConduitM () [PersistValue] IO ())
Statement
-> forall (m :: * -> *).
   MonadIO m =>
   [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
stmtQuery Statement
stmt' [PersistValue]
vals) (\ConduitM () [PersistValue] IO ()
src -> ConduitT
  ()
  Void
  IO
  [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) r. Monad m => ConduitT () Void m r -> m r
runConduit (ConduitT
   ()
   Void
   IO
   [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
 -> IO
      [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))])
-> ConduitT
     ()
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall a b. (a -> b) -> a -> b
$ ConduitM () [PersistValue] IO ()
src ConduitM () [PersistValue] IO ()
-> ConduitM
     [PersistValue]
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> ConduitT
     ()
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a b c r.
Monad m =>
ConduitM a b m () -> ConduitM b c m r -> ConduitM a c m r
.| ConduitM
  [PersistValue]
  Void
  IO
  [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
helperU)
    [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a. Monad m => a -> m a
return ([Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
 -> IO
      [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))])
-> [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall a b. (a -> b) -> a -> b
$ [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
columns [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall a. [a] -> [a] -> [a]
++ [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
us
  where
    refMap :: Map Text (EntityNameDB, ConstraintNameDB)
refMap =
        (ColumnReference -> (EntityNameDB, ConstraintNameDB))
-> Map Text ColumnReference
-> Map Text (EntityNameDB, ConstraintNameDB)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\ColumnReference
cr -> (ColumnReference -> EntityNameDB
crTableName ColumnReference
cr, ColumnReference -> ConstraintNameDB
crConstraintName ColumnReference
cr))
        (Map Text ColumnReference
 -> Map Text (EntityNameDB, ConstraintNameDB))
-> Map Text ColumnReference
-> Map Text (EntityNameDB, ConstraintNameDB)
forall a b. (a -> b) -> a -> b
$ [(Text, ColumnReference)] -> Map Text ColumnReference
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList
        ([(Text, ColumnReference)] -> Map Text ColumnReference)
-> [(Text, ColumnReference)] -> Map Text ColumnReference
forall a b. (a -> b) -> a -> b
$ ([(Text, ColumnReference)] -> Column -> [(Text, ColumnReference)])
-> [(Text, ColumnReference)]
-> [Column]
-> [(Text, ColumnReference)]
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' [(Text, ColumnReference)] -> Column -> [(Text, ColumnReference)]
ref [] [Column]
cols
      where
        ref :: [(Text, ColumnReference)] -> Column -> [(Text, ColumnReference)]
ref [(Text, ColumnReference)]
rs Column
c =
            [(Text, ColumnReference)]
-> (ColumnReference -> [(Text, ColumnReference)])
-> Maybe ColumnReference
-> [(Text, ColumnReference)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [(Text, ColumnReference)]
rs (\ColumnReference
r -> (FieldNameDB -> Text
unFieldNameDB (FieldNameDB -> Text) -> FieldNameDB -> Text
forall a b. (a -> b) -> a -> b
$ Column -> FieldNameDB
cName Column
c, ColumnReference
r) (Text, ColumnReference)
-> [(Text, ColumnReference)] -> [(Text, ColumnReference)]
forall a. a -> [a] -> [a]
: [(Text, ColumnReference)]
rs) (Column -> Maybe ColumnReference
cReference Column
c)
    getAll :: ConduitT [PersistValue] (Text, Text) IO ()
getAll =
        ([PersistValue] -> IO (Text, Text))
-> ConduitT [PersistValue] (Text, Text) IO ()
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> ConduitT a b m ()
CL.mapM (([PersistValue] -> IO (Text, Text))
 -> ConduitT [PersistValue] (Text, Text) IO ())
-> ([PersistValue] -> IO (Text, Text))
-> ConduitT [PersistValue] (Text, Text) IO ()
forall a b. (a -> b) -> a -> b
$ \[PersistValue]
x ->
            (Text, Text) -> IO (Text, Text)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((Text, Text) -> IO (Text, Text))
-> (Text, Text) -> IO (Text, Text)
forall a b. (a -> b) -> a -> b
$ case [PersistValue]
x of
                [PersistText Text
con, PersistText Text
col] ->
                    (Text
con, Text
col)
                [PersistByteString ConnectionString
con, PersistByteString ConnectionString
col] ->
                    (ConnectionString -> Text
T.decodeUtf8 ConnectionString
con, ConnectionString -> Text
T.decodeUtf8 ConnectionString
col)
                [PersistValue]
o ->
                    String -> (Text, Text)
forall a. HasCallStack => String -> a
error (String -> (Text, Text)) -> String -> (Text, Text)
forall a b. (a -> b) -> a -> b
$ String
"unexpected datatype returned for postgres o="String -> ShowS
forall a. [a] -> [a] -> [a]
++[PersistValue] -> String
forall a. Show a => a -> String
show [PersistValue]
o
    helperU :: ConduitM
  [PersistValue]
  Void
  IO
  [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
helperU = do
        [(Text, Text)]
rows <- ConduitT [PersistValue] (Text, Text) IO ()
getAll ConduitT [PersistValue] (Text, Text) IO ()
-> ConduitM (Text, Text) Void IO [(Text, Text)]
-> ConduitM [PersistValue] Void IO [(Text, Text)]
forall (m :: * -> *) a b c r.
Monad m =>
ConduitM a b m () -> ConduitM b c m r -> ConduitM a c m r
.| ConduitM (Text, Text) Void IO [(Text, Text)]
forall (m :: * -> *) a o. Monad m => ConduitT a o m [a]
CL.consume
        [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> ConduitM
     [PersistValue]
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall (m :: * -> *) a. Monad m => a -> m a
return ([Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
 -> ConduitM
      [PersistValue]
      Void
      IO
      [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))])
-> [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> ConduitM
     [PersistValue]
     Void
     IO
     [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall a b. (a -> b) -> a -> b
$ ([(Text, Text)]
 -> Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
-> [[(Text, Text)]]
-> [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall a b. (a -> b) -> [a] -> [b]
map (Either Column (ConstraintNameDB, [FieldNameDB])
-> Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
forall a b. b -> Either a b
Right (Either Column (ConstraintNameDB, [FieldNameDB])
 -> Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
-> ([(Text, Text)]
    -> Either Column (ConstraintNameDB, [FieldNameDB]))
-> [(Text, Text)]
-> Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ConstraintNameDB, [FieldNameDB])
-> Either Column (ConstraintNameDB, [FieldNameDB])
forall a b. b -> Either a b
Right ((ConstraintNameDB, [FieldNameDB])
 -> Either Column (ConstraintNameDB, [FieldNameDB]))
-> ([(Text, Text)] -> (ConstraintNameDB, [FieldNameDB]))
-> [(Text, Text)]
-> Either Column (ConstraintNameDB, [FieldNameDB])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> ConstraintNameDB
ConstraintNameDB (Text -> ConstraintNameDB)
-> ([(Text, Text)] -> Text) -> [(Text, Text)] -> ConstraintNameDB
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text, Text) -> Text
forall a b. (a, b) -> a
fst ((Text, Text) -> Text)
-> ([(Text, Text)] -> (Text, Text)) -> [(Text, Text)] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(Text, Text)] -> (Text, Text)
forall a. [a] -> a
head ([(Text, Text)] -> ConstraintNameDB)
-> ([(Text, Text)] -> [FieldNameDB])
-> [(Text, Text)]
-> (ConstraintNameDB, [FieldNameDB])
forall (a :: * -> * -> *) b c c'.
Arrow a =>
a b c -> a b c' -> a b (c, c')
&&& ((Text, Text) -> FieldNameDB) -> [(Text, Text)] -> [FieldNameDB]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> FieldNameDB
FieldNameDB (Text -> FieldNameDB)
-> ((Text, Text) -> Text) -> (Text, Text) -> FieldNameDB
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text, Text) -> Text
forall a b. (a, b) -> b
snd)))
               ([[(Text, Text)]]
 -> [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))])
-> [[(Text, Text)]]
-> [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
forall a b. (a -> b) -> a -> b
$ ((Text, Text) -> (Text, Text) -> Bool)
-> [(Text, Text)] -> [[(Text, Text)]]
forall a. (a -> a -> Bool) -> [a] -> [[a]]
groupBy (Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
(==) (Text -> Text -> Bool)
-> ((Text, Text) -> Text) -> (Text, Text) -> (Text, Text) -> Bool
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Text, Text) -> Text
forall a b. (a, b) -> a
fst) [(Text, Text)]
rows
    processColumns :: ConduitT
  [PersistValue]
  (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
  IO
  ()
processColumns =
        ([PersistValue]
 -> IO
      (Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))))
-> ConduitT
     [PersistValue]
     (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
     IO
     ()
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> ConduitT a b m ()
CL.mapM (([PersistValue]
  -> IO
       (Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))))
 -> ConduitT
      [PersistValue]
      (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
      IO
      ())
-> ([PersistValue]
    -> IO
         (Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))))
-> ConduitT
     [PersistValue]
     (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
     IO
     ()
forall a b. (a -> b) -> a -> b
$ \x' :: [PersistValue]
x'@((PersistText Text
cname) : [PersistValue]
_) -> do
            Either Text Column
col <- IO (Either Text Column) -> IO (Either Text Column)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either Text Column) -> IO (Either Text Column))
-> IO (Either Text Column) -> IO (Either Text Column)
forall a b. (a -> b) -> a -> b
$ (Text -> IO Statement)
-> EntityNameDB
-> [PersistValue]
-> Maybe (EntityNameDB, ConstraintNameDB)
-> IO (Either Text Column)
getColumn Text -> IO Statement
getter (EntityDef -> EntityNameDB
entityDB EntityDef
def) [PersistValue]
x' (Text
-> Map Text (EntityNameDB, ConstraintNameDB)
-> Maybe (EntityNameDB, ConstraintNameDB)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Text
cname Map Text (EntityNameDB, ConstraintNameDB)
refMap)
            Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
-> IO
     (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
 -> IO
      (Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))))
-> Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
-> IO
     (Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
forall a b. (a -> b) -> a -> b
$ case Either Text Column
col of
                Left Text
e -> Text
-> Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
forall a b. a -> Either a b
Left Text
e
                Right Column
c -> Either Column (ConstraintNameDB, [FieldNameDB])
-> Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
forall a b. b -> Either a b
Right (Either Column (ConstraintNameDB, [FieldNameDB])
 -> Either Text (Either Column (ConstraintNameDB, [FieldNameDB])))
-> Either Column (ConstraintNameDB, [FieldNameDB])
-> Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))
forall a b. (a -> b) -> a -> b
$ Column -> Either Column (ConstraintNameDB, [FieldNameDB])
forall a b. a -> Either a b
Left Column
c

-- | Check if a column name is listed as the "safe to remove" in the entity
-- list.
safeToRemove :: EntityDef -> FieldNameDB -> Bool
safeToRemove :: EntityDef -> FieldNameDB -> Bool
safeToRemove EntityDef
def (FieldNameDB Text
colName)
    = (FieldDef -> Bool) -> [FieldDef] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (FieldAttr -> [FieldAttr] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
elem FieldAttr
FieldAttrSafeToRemove ([FieldAttr] -> Bool)
-> (FieldDef -> [FieldAttr]) -> FieldDef -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> [FieldAttr]
fieldAttrs)
    ([FieldDef] -> Bool) -> [FieldDef] -> Bool
forall a b. (a -> b) -> a -> b
$ (FieldDef -> Bool) -> [FieldDef] -> [FieldDef]
forall a. (a -> Bool) -> [a] -> [a]
filter ((FieldNameDB -> FieldNameDB -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> FieldNameDB
FieldNameDB Text
colName) (FieldNameDB -> Bool)
-> (FieldDef -> FieldNameDB) -> FieldDef -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> FieldNameDB
fieldDB)
    ([FieldDef] -> [FieldDef]) -> [FieldDef] -> [FieldDef]
forall a b. (a -> b) -> a -> b
$ EntityDef -> [FieldDef]
keyAndEntityFields EntityDef
def

getAlters :: [EntityDef]
          -> EntityDef
          -> ([Column], [(ConstraintNameDB, [FieldNameDB])])
          -> ([Column], [(ConstraintNameDB, [FieldNameDB])])
          -> ([AlterColumn], [AlterTable])
getAlters :: [EntityDef]
-> EntityDef
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([AlterColumn], [AlterTable])
getAlters [EntityDef]
defs EntityDef
def ([Column]
c1, [(ConstraintNameDB, [FieldNameDB])]
u1) ([Column]
c2, [(ConstraintNameDB, [FieldNameDB])]
u2) =
    ([Column] -> [Column] -> [AlterColumn]
getAltersC [Column]
c1 [Column]
c2, [(ConstraintNameDB, [FieldNameDB])]
-> [(ConstraintNameDB, [FieldNameDB])] -> [AlterTable]
getAltersU [(ConstraintNameDB, [FieldNameDB])]
u1 [(ConstraintNameDB, [FieldNameDB])]
u2)
  where
    getAltersC :: [Column] -> [Column] -> [AlterColumn]
getAltersC [] [Column]
old =
        (Column -> AlterColumn) -> [Column] -> [AlterColumn]
forall a b. (a -> b) -> [a] -> [b]
map (\Column
x -> Column -> Bool -> AlterColumn
Drop Column
x (Bool -> AlterColumn) -> Bool -> AlterColumn
forall a b. (a -> b) -> a -> b
$ EntityDef -> FieldNameDB -> Bool
safeToRemove EntityDef
def (FieldNameDB -> Bool) -> FieldNameDB -> Bool
forall a b. (a -> b) -> a -> b
$ Column -> FieldNameDB
cName Column
x) [Column]
old
    getAltersC (Column
new:[Column]
news) [Column]
old =
        let ([AlterColumn]
alters, [Column]
old') = [EntityDef]
-> EntityDef -> Column -> [Column] -> ([AlterColumn], [Column])
findAlters [EntityDef]
defs EntityDef
def Column
new [Column]
old
         in [AlterColumn]
alters [AlterColumn] -> [AlterColumn] -> [AlterColumn]
forall a. [a] -> [a] -> [a]
++ [Column] -> [Column] -> [AlterColumn]
getAltersC [Column]
news [Column]
old'

    getAltersU
        :: [(ConstraintNameDB, [FieldNameDB])]
        -> [(ConstraintNameDB, [FieldNameDB])]
        -> [AlterTable]
    getAltersU :: [(ConstraintNameDB, [FieldNameDB])]
-> [(ConstraintNameDB, [FieldNameDB])] -> [AlterTable]
getAltersU [] [(ConstraintNameDB, [FieldNameDB])]
old =
        (ConstraintNameDB -> AlterTable)
-> [ConstraintNameDB] -> [AlterTable]
forall a b. (a -> b) -> [a] -> [b]
map ConstraintNameDB -> AlterTable
DropConstraint ([ConstraintNameDB] -> [AlterTable])
-> [ConstraintNameDB] -> [AlterTable]
forall a b. (a -> b) -> a -> b
$ (ConstraintNameDB -> Bool)
-> [ConstraintNameDB] -> [ConstraintNameDB]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool)
-> (ConstraintNameDB -> Bool) -> ConstraintNameDB -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ConstraintNameDB -> Bool
isManual) ([ConstraintNameDB] -> [ConstraintNameDB])
-> [ConstraintNameDB] -> [ConstraintNameDB]
forall a b. (a -> b) -> a -> b
$ ((ConstraintNameDB, [FieldNameDB]) -> ConstraintNameDB)
-> [(ConstraintNameDB, [FieldNameDB])] -> [ConstraintNameDB]
forall a b. (a -> b) -> [a] -> [b]
map (ConstraintNameDB, [FieldNameDB]) -> ConstraintNameDB
forall a b. (a, b) -> a
fst [(ConstraintNameDB, [FieldNameDB])]
old
    getAltersU ((ConstraintNameDB
name, [FieldNameDB]
cols):[(ConstraintNameDB, [FieldNameDB])]
news) [(ConstraintNameDB, [FieldNameDB])]
old =
        case ConstraintNameDB
-> [(ConstraintNameDB, [FieldNameDB])] -> Maybe [FieldNameDB]
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup ConstraintNameDB
name [(ConstraintNameDB, [FieldNameDB])]
old of
            Maybe [FieldNameDB]
Nothing ->
                ConstraintNameDB -> [FieldNameDB] -> AlterTable
AddUniqueConstraint ConstraintNameDB
name [FieldNameDB]
cols AlterTable -> [AlterTable] -> [AlterTable]
forall a. a -> [a] -> [a]
: [(ConstraintNameDB, [FieldNameDB])]
-> [(ConstraintNameDB, [FieldNameDB])] -> [AlterTable]
getAltersU [(ConstraintNameDB, [FieldNameDB])]
news [(ConstraintNameDB, [FieldNameDB])]
old
            Just [FieldNameDB]
ocols ->
                let old' :: [(ConstraintNameDB, [FieldNameDB])]
old' = ((ConstraintNameDB, [FieldNameDB]) -> Bool)
-> [(ConstraintNameDB, [FieldNameDB])]
-> [(ConstraintNameDB, [FieldNameDB])]
forall a. (a -> Bool) -> [a] -> [a]
filter (\(ConstraintNameDB
x, [FieldNameDB]
_) -> ConstraintNameDB
x ConstraintNameDB -> ConstraintNameDB -> Bool
forall a. Eq a => a -> a -> Bool
/= ConstraintNameDB
name) [(ConstraintNameDB, [FieldNameDB])]
old
                 in if [FieldNameDB] -> [FieldNameDB]
forall a. Ord a => [a] -> [a]
sort [FieldNameDB]
cols [FieldNameDB] -> [FieldNameDB] -> Bool
forall a. Eq a => a -> a -> Bool
== [FieldNameDB] -> [FieldNameDB]
forall a. Ord a => [a] -> [a]
sort [FieldNameDB]
ocols
                        then [(ConstraintNameDB, [FieldNameDB])]
-> [(ConstraintNameDB, [FieldNameDB])] -> [AlterTable]
getAltersU [(ConstraintNameDB, [FieldNameDB])]
news [(ConstraintNameDB, [FieldNameDB])]
old'
                        else  ConstraintNameDB -> AlterTable
DropConstraint ConstraintNameDB
name
                            AlterTable -> [AlterTable] -> [AlterTable]
forall a. a -> [a] -> [a]
: ConstraintNameDB -> [FieldNameDB] -> AlterTable
AddUniqueConstraint ConstraintNameDB
name [FieldNameDB]
cols
                            AlterTable -> [AlterTable] -> [AlterTable]
forall a. a -> [a] -> [a]
: [(ConstraintNameDB, [FieldNameDB])]
-> [(ConstraintNameDB, [FieldNameDB])] -> [AlterTable]
getAltersU [(ConstraintNameDB, [FieldNameDB])]
news [(ConstraintNameDB, [FieldNameDB])]
old'

    -- Don't drop constraints which were manually added.
    isManual :: ConstraintNameDB -> Bool
isManual (ConstraintNameDB Text
x) = Text
"__manual_" Text -> Text -> Bool
`T.isPrefixOf` Text
x

getColumn
    :: (Text -> IO Statement)
    -> EntityNameDB
    -> [PersistValue]
    -> Maybe (EntityNameDB, ConstraintNameDB)
    -> IO (Either Text Column)
getColumn :: (Text -> IO Statement)
-> EntityNameDB
-> [PersistValue]
-> Maybe (EntityNameDB, ConstraintNameDB)
-> IO (Either Text Column)
getColumn Text -> IO Statement
getter EntityNameDB
tableName' [ PersistText Text
columnName
                            , PersistText Text
isNullable
                            , PersistText Text
typeName
                            , PersistValue
defaultValue
                            , PersistValue
generationExpression
                            , PersistValue
numericPrecision
                            , PersistValue
numericScale
                            , PersistValue
maxlen
                            ] Maybe (EntityNameDB, ConstraintNameDB)
refName_ = ExceptT Text IO Column -> IO (Either Text Column)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT Text IO Column -> IO (Either Text Column))
-> ExceptT Text IO Column -> IO (Either Text Column)
forall a b. (a -> b) -> a -> b
$ do
    Maybe Text
defaultValue' <-
        case PersistValue
defaultValue of
            PersistValue
PersistNull ->
                Maybe Text -> ExceptT Text IO (Maybe Text)
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Text
forall a. Maybe a
Nothing
            PersistText Text
t ->
                Maybe Text -> ExceptT Text IO (Maybe Text)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Text -> ExceptT Text IO (Maybe Text))
-> Maybe Text -> ExceptT Text IO (Maybe Text)
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
forall a. a -> Maybe a
Just Text
t
            PersistValue
_ ->
                Text -> ExceptT Text IO (Maybe Text)
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Text -> ExceptT Text IO (Maybe Text))
-> Text -> ExceptT Text IO (Maybe Text)
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ String
"Invalid default column: " String -> ShowS
forall a. [a] -> [a] -> [a]
++ PersistValue -> String
forall a. Show a => a -> String
show PersistValue
defaultValue

    Maybe Text
generationExpression' <-
        case PersistValue
generationExpression of
            PersistValue
PersistNull ->
                Maybe Text -> ExceptT Text IO (Maybe Text)
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Text
forall a. Maybe a
Nothing
            PersistText Text
t ->
                Maybe Text -> ExceptT Text IO (Maybe Text)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Text -> ExceptT Text IO (Maybe Text))
-> Maybe Text -> ExceptT Text IO (Maybe Text)
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
forall a. a -> Maybe a
Just Text
t
            PersistValue
_ ->
                Text -> ExceptT Text IO (Maybe Text)
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Text -> ExceptT Text IO (Maybe Text))
-> Text -> ExceptT Text IO (Maybe Text)
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ String
"Invalid generated column: " String -> ShowS
forall a. [a] -> [a] -> [a]
++ PersistValue -> String
forall a. Show a => a -> String
show PersistValue
generationExpression

    let typeStr :: Text
typeStr =
            case PersistValue
maxlen of
                PersistInt64 Int64
n ->
                    [Text] -> Text
T.concat [Text
typeName, Text
"(", String -> Text
T.pack (Int64 -> String
forall a. Show a => a -> String
show Int64
n), Text
")"]
                PersistValue
_ ->
                    Text
typeName

    SqlType
t <- Text -> ExceptT Text IO SqlType
getType Text
typeStr

    let cname :: FieldNameDB
cname = Text -> FieldNameDB
FieldNameDB Text
columnName

    Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
ref <- IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
-> ExceptT
     Text IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
 -> ExceptT
      Text IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
-> ExceptT
     Text IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall a b. (a -> b) -> a -> b
$ (Maybe (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
 -> Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
-> IO (Maybe (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Maybe (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
-> Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
forall (m :: * -> *) a. Monad m => m (m a) -> m a
join (IO (Maybe (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
 -> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
-> IO (Maybe (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall a b. (a -> b) -> a -> b
$ ((EntityNameDB, ConstraintNameDB)
 -> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
-> Maybe (EntityNameDB, ConstraintNameDB)
-> IO (Maybe (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (FieldNameDB
-> (EntityNameDB, ConstraintNameDB)
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
getRef FieldNameDB
cname) Maybe (EntityNameDB, ConstraintNameDB)
refName_

    Column -> ExceptT Text IO Column
forall (m :: * -> *) a. Monad m => a -> m a
return Column :: FieldNameDB
-> Bool
-> SqlType
-> Maybe Text
-> Maybe Text
-> Maybe ConstraintNameDB
-> Maybe Integer
-> Maybe ColumnReference
-> Column
Column
        { cName :: FieldNameDB
cName = FieldNameDB
cname
        , cNull :: Bool
cNull = Text
isNullable Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"YES"
        , cSqlType :: SqlType
cSqlType = SqlType
t
        , cDefault :: Maybe Text
cDefault = (Text -> Text) -> Maybe Text -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Text -> Text
stripSuffixes Maybe Text
defaultValue'
        , cGenerated :: Maybe Text
cGenerated = (Text -> Text) -> Maybe Text -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Text -> Text
stripSuffixes Maybe Text
generationExpression'
        , cDefaultConstraintName :: Maybe ConstraintNameDB
cDefaultConstraintName = Maybe ConstraintNameDB
forall a. Maybe a
Nothing
        , cMaxLen :: Maybe Integer
cMaxLen = Maybe Integer
forall a. Maybe a
Nothing
        , cReference :: Maybe ColumnReference
cReference = ((EntityNameDB, ConstraintNameDB, Text, Text) -> ColumnReference)
-> Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
-> Maybe ColumnReference
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(EntityNameDB
a,ConstraintNameDB
b,Text
c,Text
d) -> EntityNameDB -> ConstraintNameDB -> FieldCascade -> ColumnReference
ColumnReference EntityNameDB
a ConstraintNameDB
b (Text -> Text -> FieldCascade
forall a a.
(Eq a, Eq a, IsString a, IsString a, Show a, Show a) =>
a -> a -> FieldCascade
mkCascade Text
c Text
d)) Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
ref
        }

  where

    mkCascade :: a -> a -> FieldCascade
mkCascade a
updText a
delText =
        FieldCascade :: Maybe CascadeAction -> Maybe CascadeAction -> FieldCascade
FieldCascade
            { fcOnUpdate :: Maybe CascadeAction
fcOnUpdate = a -> Maybe CascadeAction
forall a. (Eq a, IsString a, Show a) => a -> Maybe CascadeAction
parseCascade a
updText
            , fcOnDelete :: Maybe CascadeAction
fcOnDelete = a -> Maybe CascadeAction
forall a. (Eq a, IsString a, Show a) => a -> Maybe CascadeAction
parseCascade a
delText
            }

    parseCascade :: a -> Maybe CascadeAction
parseCascade a
txt =
        case a
txt of
            a
"NO ACTION" ->
                Maybe CascadeAction
forall a. Maybe a
Nothing
            a
"CASCADE" ->
                CascadeAction -> Maybe CascadeAction
forall a. a -> Maybe a
Just CascadeAction
Cascade
            a
"SET NULL" ->
                CascadeAction -> Maybe CascadeAction
forall a. a -> Maybe a
Just CascadeAction
SetNull
            a
"SET DEFAULT" ->
                CascadeAction -> Maybe CascadeAction
forall a. a -> Maybe a
Just CascadeAction
SetDefault
            a
"RESTRICT" ->
                CascadeAction -> Maybe CascadeAction
forall a. a -> Maybe a
Just CascadeAction
Restrict
            a
_ ->
                String -> Maybe CascadeAction
forall a. HasCallStack => String -> a
error (String -> Maybe CascadeAction) -> String -> Maybe CascadeAction
forall a b. (a -> b) -> a -> b
$ String
"Unexpected value in parseCascade: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> a -> String
forall a. Show a => a -> String
show a
txt

    stripSuffixes :: Text -> Text
stripSuffixes Text
t =
        [Text] -> Text
loop'
            [ Text
"::character varying"
            , Text
"::text"
            ]
      where
        loop' :: [Text] -> Text
loop' [] = Text
t
        loop' (Text
p:[Text]
ps) =
            case Text -> Text -> Maybe Text
T.stripSuffix Text
p Text
t of
                Maybe Text
Nothing -> [Text] -> Text
loop' [Text]
ps
                Just Text
t' -> Text
t'

    getRef :: FieldNameDB
-> (EntityNameDB, ConstraintNameDB)
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
getRef FieldNameDB
cname (EntityNameDB
_, ConstraintNameDB
refName') = do
        let sql :: Text
sql = [Text] -> Text
T.concat
                [ Text
"SELECT DISTINCT "
                , Text
"ccu.table_name, "
                , Text
"tc.constraint_name, "
                , Text
"rc.update_rule, "
                , Text
"rc.delete_rule "
                , Text
"FROM information_schema.constraint_column_usage ccu "
                , Text
"INNER JOIN information_schema.key_column_usage kcu "
                , Text
"  ON ccu.constraint_name = kcu.constraint_name "
                , Text
"INNER JOIN information_schema.table_constraints tc "
                , Text
"  ON tc.constraint_name = kcu.constraint_name "
                , Text
"LEFT JOIN information_schema.referential_constraints AS rc"
                , Text
"  ON rc.constraint_name = ccu.constraint_name "
                , Text
"WHERE tc.constraint_type='FOREIGN KEY' "
                , Text
"AND kcu.ordinal_position=1 "
                , Text
"AND kcu.table_name=? "
                , Text
"AND kcu.column_name=? "
                , Text
"AND tc.constraint_name=?"
                ]
        Statement
stmt <- Text -> IO Statement
getter Text
sql
        [[PersistValue]]
cntrs <-
            Acquire (ConduitM () [PersistValue] IO ())
-> (ConduitM () [PersistValue] IO () -> IO [[PersistValue]])
-> IO [[PersistValue]]
forall (m :: * -> *) a b.
MonadUnliftIO m =>
Acquire a -> (a -> m b) -> m b
with
                (Statement
-> [PersistValue] -> Acquire (ConduitM () [PersistValue] IO ())
Statement
-> forall (m :: * -> *).
   MonadIO m =>
   [PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
stmtQuery Statement
stmt
                    [ Text -> PersistValue
PersistText (Text -> PersistValue) -> Text -> PersistValue
forall a b. (a -> b) -> a -> b
$ EntityNameDB -> Text
unEntityNameDB EntityNameDB
tableName'
                    , Text -> PersistValue
PersistText (Text -> PersistValue) -> Text -> PersistValue
forall a b. (a -> b) -> a -> b
$ FieldNameDB -> Text
unFieldNameDB FieldNameDB
cname
                    , Text -> PersistValue
PersistText (Text -> PersistValue) -> Text -> PersistValue
forall a b. (a -> b) -> a -> b
$ ConstraintNameDB -> Text
unConstraintNameDB ConstraintNameDB
refName'
                    ]
                )
                (\ConduitM () [PersistValue] IO ()
src -> ConduitT () Void IO [[PersistValue]] -> IO [[PersistValue]]
forall (m :: * -> *) r. Monad m => ConduitT () Void m r -> m r
runConduit (ConduitT () Void IO [[PersistValue]] -> IO [[PersistValue]])
-> ConduitT () Void IO [[PersistValue]] -> IO [[PersistValue]]
forall a b. (a -> b) -> a -> b
$ ConduitM () [PersistValue] IO ()
src ConduitM () [PersistValue] IO ()
-> ConduitM [PersistValue] Void IO [[PersistValue]]
-> ConduitT () Void IO [[PersistValue]]
forall (m :: * -> *) a b c r.
Monad m =>
ConduitM a b m () -> ConduitM b c m r -> ConduitM a c m r
.| ConduitM [PersistValue] Void IO [[PersistValue]]
forall (m :: * -> *) a o. Monad m => ConduitT a o m [a]
CL.consume)
        case [[PersistValue]]
cntrs of
          [] ->
              Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
forall a. Maybe a
Nothing
          [[PersistText Text
table, PersistText Text
constraint, PersistText Text
updRule, PersistText Text
delRule]] ->
              Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
 -> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
-> Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall a b. (a -> b) -> a -> b
$ (EntityNameDB, ConstraintNameDB, Text, Text)
-> Maybe (EntityNameDB, ConstraintNameDB, Text, Text)
forall a. a -> Maybe a
Just (Text -> EntityNameDB
EntityNameDB Text
table, Text -> ConstraintNameDB
ConstraintNameDB Text
constraint, Text
updRule, Text
delRule)
          [[PersistValue]]
xs ->
              String -> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall a. HasCallStack => String -> a
error (String -> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text)))
-> String
-> IO (Maybe (EntityNameDB, ConstraintNameDB, Text, Text))
forall a b. (a -> b) -> a -> b
$ [String] -> String
forall a. Monoid a => [a] -> a
mconcat
                  [ String
"Postgresql.getColumn: error fetching constraints. Expected a single result for foreign key query for table: "
                  , Text -> String
T.unpack (EntityNameDB -> Text
unEntityNameDB EntityNameDB
tableName')
                  , String
" and column: "
                  , Text -> String
T.unpack (FieldNameDB -> Text
unFieldNameDB FieldNameDB
cname)
                  , String
" but got: "
                  , [[PersistValue]] -> String
forall a. Show a => a -> String
show [[PersistValue]]
xs
                  ]

    getType :: Text -> ExceptT Text IO SqlType
getType Text
"int4"        = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlInt32
    getType Text
"int8"        = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlInt64
    getType Text
"varchar"     = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlString
    getType Text
"text"        = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlString
    getType Text
"date"        = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlDay
    getType Text
"bool"        = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlBool
    getType Text
"timestamptz" = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlDayTime
    getType Text
"float4"      = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlReal
    getType Text
"float8"      = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlReal
    getType Text
"bytea"       = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlBlob
    getType Text
"time"        = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure SqlType
SqlTime
    getType Text
"numeric"     = PersistValue -> PersistValue -> ExceptT Text IO SqlType
getNumeric PersistValue
numericPrecision PersistValue
numericScale
    getType Text
a             = SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure (SqlType -> ExceptT Text IO SqlType)
-> SqlType -> ExceptT Text IO SqlType
forall a b. (a -> b) -> a -> b
$ Text -> SqlType
SqlOther Text
a

    getNumeric :: PersistValue -> PersistValue -> ExceptT Text IO SqlType
getNumeric (PersistInt64 Int64
a) (PersistInt64 Int64
b) =
        SqlType -> ExceptT Text IO SqlType
forall (f :: * -> *) a. Applicative f => a -> f a
pure (SqlType -> ExceptT Text IO SqlType)
-> SqlType -> ExceptT Text IO SqlType
forall a b. (a -> b) -> a -> b
$ Word32 -> Word32 -> SqlType
SqlNumeric (Int64 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int64
a) (Int64 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int64
b)

    getNumeric PersistValue
PersistNull PersistValue
PersistNull = Text -> ExceptT Text IO SqlType
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Text -> ExceptT Text IO SqlType)
-> Text -> ExceptT Text IO SqlType
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat
        [ Text
"No precision and scale were specified for the column: "
        , Text
columnName
        , Text
" in table: "
        , EntityNameDB -> Text
unEntityNameDB EntityNameDB
tableName'
        , Text
". Postgres defaults to a maximum scale of 147,455 and precision of 16383,"
        , Text
" which is probably not what you intended."
        , Text
" Specify the values as numeric(total_digits, digits_after_decimal_place)."
        ]

    getNumeric PersistValue
a PersistValue
b = Text -> ExceptT Text IO SqlType
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Text -> ExceptT Text IO SqlType)
-> Text -> ExceptT Text IO SqlType
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat
        [ Text
"Can not get numeric field precision for the column: "
        , Text
columnName
        , Text
" in table: "
        , EntityNameDB -> Text
unEntityNameDB EntityNameDB
tableName'
        , Text
". Expected an integer for both precision and scale, "
        , Text
"got: "
        , String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ PersistValue -> String
forall a. Show a => a -> String
show PersistValue
a
        , Text
" and "
        , String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ PersistValue -> String
forall a. Show a => a -> String
show PersistValue
b
        , Text
", respectively."
        , Text
" Specify the values as numeric(total_digits, digits_after_decimal_place)."
        ]

getColumn Text -> IO Statement
_ EntityNameDB
_ [PersistValue]
columnName Maybe (EntityNameDB, ConstraintNameDB)
_ =
    Either Text Column -> IO (Either Text Column)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either Text Column -> IO (Either Text Column))
-> Either Text Column -> IO (Either Text Column)
forall a b. (a -> b) -> a -> b
$ Text -> Either Text Column
forall a b. a -> Either a b
Left (Text -> Either Text Column) -> Text -> Either Text Column
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ String
"Invalid result from information_schema: " String -> ShowS
forall a. [a] -> [a] -> [a]
++ [PersistValue] -> String
forall a. Show a => a -> String
show [PersistValue]
columnName

-- | Intelligent comparison of SQL types, to account for SqlInt32 vs SqlOther integer
sqlTypeEq :: SqlType -> SqlType -> Bool
sqlTypeEq :: SqlType -> SqlType -> Bool
sqlTypeEq SqlType
x SqlType
y =
    Text -> Text
T.toCaseFold (SqlType -> Text
showSqlType SqlType
x) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> Text
T.toCaseFold (SqlType -> Text
showSqlType SqlType
y)

findAlters
    :: [EntityDef]
    -- ^ The list of all entity definitions that persistent is aware of.
    -> EntityDef
    -- ^ The entity definition for the entity that we're working on.
    -> Column
    -- ^ The column that we're searching for potential alterations for.
    -> [Column]
    -> ([AlterColumn], [Column])
findAlters :: [EntityDef]
-> EntityDef -> Column -> [Column] -> ([AlterColumn], [Column])
findAlters [EntityDef]
defs EntityDef
edef col :: Column
col@(Column FieldNameDB
name Bool
isNull SqlType
sqltype Maybe Text
def Maybe Text
_gen Maybe ConstraintNameDB
_defConstraintName Maybe Integer
_maxLen Maybe ColumnReference
ref) [Column]
cols =
    case (Column -> Bool) -> [Column] -> Maybe Column
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
List.find (\Column
c -> Column -> FieldNameDB
cName Column
c FieldNameDB -> FieldNameDB -> Bool
forall a. Eq a => a -> a -> Bool
== FieldNameDB
name) [Column]
cols of
        Maybe Column
Nothing ->
            ([Column -> AlterColumn
Add' Column
col], [Column]
cols)
        Just (Column FieldNameDB
_oldName Bool
isNull' SqlType
sqltype' Maybe Text
def' Maybe Text
_gen' Maybe ConstraintNameDB
_defConstraintName' Maybe Integer
_maxLen' Maybe ColumnReference
ref') ->
            let refDrop :: Maybe ColumnReference -> [AlterColumn]
refDrop Maybe ColumnReference
Nothing = []
                refDrop (Just ColumnReference {crConstraintName :: ColumnReference -> ConstraintNameDB
crConstraintName=ConstraintNameDB
cname}) =
                    [ConstraintNameDB -> AlterColumn
DropReference ConstraintNameDB
cname]

                refAdd :: Maybe ColumnReference -> [AlterColumn]
refAdd Maybe ColumnReference
Nothing = []
                refAdd (Just ColumnReference
colRef) =
                    case (EntityDef -> Bool) -> [EntityDef] -> Maybe EntityDef
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((EntityNameDB -> EntityNameDB -> Bool
forall a. Eq a => a -> a -> Bool
== ColumnReference -> EntityNameDB
crTableName ColumnReference
colRef) (EntityNameDB -> Bool)
-> (EntityDef -> EntityNameDB) -> EntityDef -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> EntityNameDB
entityDB) [EntityDef]
defs of
                        Just EntityDef
refdef
                            | FieldNameDB
_oldName FieldNameDB -> FieldNameDB -> Bool
forall a. Eq a => a -> a -> Bool
/= FieldDef -> FieldNameDB
fieldDB (EntityDef -> FieldDef
entityId EntityDef
edef)
                            ->
                            [EntityNameDB
-> ConstraintNameDB
-> [FieldNameDB]
-> [Text]
-> FieldCascade
-> AlterColumn
AddReference
                                (EntityDef -> EntityNameDB
entityDB EntityDef
edef)
                                (ColumnReference -> ConstraintNameDB
crConstraintName ColumnReference
colRef)
                                [FieldNameDB
name]
                                ((FieldNameDB -> Text) -> EntityDef -> [Text]
Util.dbIdColumnsEsc FieldNameDB -> Text
escapeF EntityDef
refdef)
                                (ColumnReference -> FieldCascade
crFieldCascade ColumnReference
colRef)
                            ]
                        Just EntityDef
_ -> []
                        Maybe EntityDef
Nothing ->
                            String -> [AlterColumn]
forall a. HasCallStack => String -> a
error (String -> [AlterColumn]) -> String -> [AlterColumn]
forall a b. (a -> b) -> a -> b
$ String
"could not find the entityDef for reftable["
                                String -> ShowS
forall a. [a] -> [a] -> [a]
++ EntityNameDB -> String
forall a. Show a => a -> String
show (ColumnReference -> EntityNameDB
crTableName ColumnReference
colRef) String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
"]"
                modRef :: [AlterColumn]
modRef =
                    if Maybe ColumnReference -> Maybe ColumnReference -> Bool
equivalentRef Maybe ColumnReference
ref Maybe ColumnReference
ref'
                        then []
                        else Maybe ColumnReference -> [AlterColumn]
refDrop Maybe ColumnReference
ref' [AlterColumn] -> [AlterColumn] -> [AlterColumn]
forall a. [a] -> [a] -> [a]
++ Maybe ColumnReference -> [AlterColumn]
refAdd Maybe ColumnReference
ref
                modNull :: [AlterColumn]
modNull = case (Bool
isNull, Bool
isNull') of
                            (Bool
True, Bool
False) ->  do
                                Bool -> [()]
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> [()]) -> Bool -> [()]
forall a b. (a -> b) -> a -> b
$ FieldNameDB
name FieldNameDB -> FieldNameDB -> Bool
forall a. Eq a => a -> a -> Bool
/= FieldDef -> FieldNameDB
fieldDB (EntityDef -> FieldDef
entityId EntityDef
edef)
                                AlterColumn -> [AlterColumn]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Column -> AlterColumn
IsNull Column
col)
                            (Bool
False, Bool
True) ->
                                let up :: [AlterColumn] -> [AlterColumn]
up = case Maybe Text
def of
                                            Maybe Text
Nothing -> [AlterColumn] -> [AlterColumn]
forall a. a -> a
id
                                            Just Text
s -> (:) (Column -> Text -> AlterColumn
Update' Column
col Text
s)
                                 in [AlterColumn] -> [AlterColumn]
up [Column -> AlterColumn
NotNull Column
col]
                            (Bool, Bool)
_ -> []
                modType :: [AlterColumn]
modType
                    | SqlType -> SqlType -> Bool
sqlTypeEq SqlType
sqltype SqlType
sqltype' = []
                    -- When converting from Persistent pre-2.0 databases, we
                    -- need to make sure that TIMESTAMP WITHOUT TIME ZONE is
                    -- treated as UTC.
                    | SqlType
sqltype SqlType -> SqlType -> Bool
forall a. Eq a => a -> a -> Bool
== SqlType
SqlDayTime Bool -> Bool -> Bool
&& SqlType
sqltype' SqlType -> SqlType -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> SqlType
SqlOther Text
"timestamp" =
                        [Column -> SqlType -> Text -> AlterColumn
ChangeType Column
col SqlType
sqltype (Text -> AlterColumn) -> Text -> AlterColumn
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat
                            [ Text
" USING "
                            , FieldNameDB -> Text
escapeF FieldNameDB
name
                            , Text
" AT TIME ZONE 'UTC'"
                            ]]
                    | Bool
otherwise = [Column -> SqlType -> Text -> AlterColumn
ChangeType Column
col SqlType
sqltype Text
""]
                modDef :: [AlterColumn]
modDef =
                    if Maybe Text
def Maybe Text -> Maybe Text -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe Text
def'
                        Bool -> Bool -> Bool
|| Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Text -> Text -> Maybe Text
T.stripPrefix Text
"nextval" (Text -> Maybe Text) -> Maybe Text -> Maybe Text
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe Text
def')
                        then []
                        else
                            case Maybe Text
def of
                                Maybe Text
Nothing -> [Column -> AlterColumn
NoDefault Column
col]
                                Just Text
s  -> [Column -> Text -> AlterColumn
Default Column
col Text
s]
             in
                ( [AlterColumn]
modRef [AlterColumn] -> [AlterColumn] -> [AlterColumn]
forall a. [a] -> [a] -> [a]
++ [AlterColumn]
modDef [AlterColumn] -> [AlterColumn] -> [AlterColumn]
forall a. [a] -> [a] -> [a]
++ [AlterColumn]
modNull [AlterColumn] -> [AlterColumn] -> [AlterColumn]
forall a. [a] -> [a] -> [a]
++ [AlterColumn]
modType
                , (Column -> Bool) -> [Column] -> [Column]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Column
c -> Column -> FieldNameDB
cName Column
c FieldNameDB -> FieldNameDB -> Bool
forall a. Eq a => a -> a -> Bool
/= FieldNameDB
name) [Column]
cols
                )

-- We check if we should alter a foreign key. This is almost an equality check,
-- except we consider 'Nothing' and 'Just Restrict' equivalent.
equivalentRef :: Maybe ColumnReference -> Maybe ColumnReference -> Bool
equivalentRef :: Maybe ColumnReference -> Maybe ColumnReference -> Bool
equivalentRef Maybe ColumnReference
Nothing Maybe ColumnReference
Nothing = Bool
True
equivalentRef (Just ColumnReference
cr1) (Just ColumnReference
cr2) =
       ColumnReference -> EntityNameDB
crTableName ColumnReference
cr1 EntityNameDB -> EntityNameDB -> Bool
forall a. Eq a => a -> a -> Bool
== ColumnReference -> EntityNameDB
crTableName ColumnReference
cr2
    Bool -> Bool -> Bool
&& ColumnReference -> ConstraintNameDB
crConstraintName ColumnReference
cr1 ConstraintNameDB -> ConstraintNameDB -> Bool
forall a. Eq a => a -> a -> Bool
== ColumnReference -> ConstraintNameDB
crConstraintName ColumnReference
cr2
    Bool -> Bool -> Bool
&& Maybe CascadeAction -> Maybe CascadeAction -> Bool
eqCascade (FieldCascade -> Maybe CascadeAction
fcOnUpdate (FieldCascade -> Maybe CascadeAction)
-> FieldCascade -> Maybe CascadeAction
forall a b. (a -> b) -> a -> b
$ ColumnReference -> FieldCascade
crFieldCascade ColumnReference
cr1) (FieldCascade -> Maybe CascadeAction
fcOnUpdate (FieldCascade -> Maybe CascadeAction)
-> FieldCascade -> Maybe CascadeAction
forall a b. (a -> b) -> a -> b
$ ColumnReference -> FieldCascade
crFieldCascade ColumnReference
cr2)
    Bool -> Bool -> Bool
&& Maybe CascadeAction -> Maybe CascadeAction -> Bool
eqCascade (FieldCascade -> Maybe CascadeAction
fcOnDelete (FieldCascade -> Maybe CascadeAction)
-> FieldCascade -> Maybe CascadeAction
forall a b. (a -> b) -> a -> b
$ ColumnReference -> FieldCascade
crFieldCascade ColumnReference
cr1) (FieldCascade -> Maybe CascadeAction
fcOnDelete (FieldCascade -> Maybe CascadeAction)
-> FieldCascade -> Maybe CascadeAction
forall a b. (a -> b) -> a -> b
$ ColumnReference -> FieldCascade
crFieldCascade ColumnReference
cr2)
  where
    eqCascade :: Maybe CascadeAction -> Maybe CascadeAction -> Bool
    eqCascade :: Maybe CascadeAction -> Maybe CascadeAction -> Bool
eqCascade Maybe CascadeAction
Nothing Maybe CascadeAction
Nothing         = Bool
True
    eqCascade Maybe CascadeAction
Nothing (Just CascadeAction
Restrict) = Bool
True
    eqCascade (Just CascadeAction
Restrict) Maybe CascadeAction
Nothing = Bool
True
    eqCascade (Just CascadeAction
cs1) (Just CascadeAction
cs2)   = CascadeAction
cs1 CascadeAction -> CascadeAction -> Bool
forall a. Eq a => a -> a -> Bool
== CascadeAction
cs2
    eqCascade Maybe CascadeAction
_ Maybe CascadeAction
_                     = Bool
False
equivalentRef Maybe ColumnReference
_ Maybe ColumnReference
_ = Bool
False

-- | Get the references to be added to a table for the given column.
getAddReference
    :: [EntityDef]
    -> EntityDef
    -> FieldNameDB
    -> ColumnReference
    -> Maybe AlterDB
getAddReference :: [EntityDef]
-> EntityDef -> FieldNameDB -> ColumnReference -> Maybe AlterDB
getAddReference [EntityDef]
allDefs EntityDef
entity FieldNameDB
cname cr :: ColumnReference
cr@ColumnReference {crTableName :: ColumnReference -> EntityNameDB
crTableName = EntityNameDB
s, crConstraintName :: ColumnReference -> ConstraintNameDB
crConstraintName=ConstraintNameDB
constraintName} = do
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ FieldNameDB
cname FieldNameDB -> FieldNameDB -> Bool
forall a. Eq a => a -> a -> Bool
/= FieldDef -> FieldNameDB
fieldDB (EntityDef -> FieldDef
entityId EntityDef
entity)
    AlterDB -> Maybe AlterDB
forall (f :: * -> *) a. Applicative f => a -> f a
pure (AlterDB -> Maybe AlterDB) -> AlterDB -> Maybe AlterDB
forall a b. (a -> b) -> a -> b
$ EntityNameDB -> AlterColumn -> AlterDB
AlterColumn
        EntityNameDB
table
        (EntityNameDB
-> ConstraintNameDB
-> [FieldNameDB]
-> [Text]
-> FieldCascade
-> AlterColumn
AddReference EntityNameDB
s ConstraintNameDB
constraintName [FieldNameDB
cname] [Text]
id_ (ColumnReference -> FieldCascade
crFieldCascade ColumnReference
cr)
        )
  where
    table :: EntityNameDB
table = EntityDef -> EntityNameDB
entityDB EntityDef
entity
    id_ :: [Text]
id_ =
        [Text] -> Maybe [Text] -> [Text]
forall a. a -> Maybe a -> a
fromMaybe
            (String -> [Text]
forall a. HasCallStack => String -> a
error (String -> [Text]) -> String -> [Text]
forall a b. (a -> b) -> a -> b
$ String
"Could not find ID of entity " String -> ShowS
forall a. [a] -> [a] -> [a]
++ EntityNameDB -> String
forall a. Show a => a -> String
show EntityNameDB
s)
            (Maybe [Text] -> [Text]) -> Maybe [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ do
                EntityDef
entDef <- (EntityDef -> Bool) -> [EntityDef] -> Maybe EntityDef
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((EntityNameDB -> EntityNameDB -> Bool
forall a. Eq a => a -> a -> Bool
== EntityNameDB
s) (EntityNameDB -> Bool)
-> (EntityDef -> EntityNameDB) -> EntityDef -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> EntityNameDB
entityDB) [EntityDef]
allDefs
                [Text] -> Maybe [Text]
forall (m :: * -> *) a. Monad m => a -> m a
return ([Text] -> Maybe [Text]) -> [Text] -> Maybe [Text]
forall a b. (a -> b) -> a -> b
$ (FieldNameDB -> Text) -> EntityDef -> [Text]
Util.dbIdColumnsEsc FieldNameDB -> Text
escapeF EntityDef
entDef

showColumn :: Column -> Text
showColumn :: Column -> Text
showColumn (Column FieldNameDB
n Bool
nu SqlType
sqlType' Maybe Text
def Maybe Text
gen Maybe ConstraintNameDB
_defConstraintName Maybe Integer
_maxLen Maybe ColumnReference
_ref) = [Text] -> Text
T.concat
    [ FieldNameDB -> Text
escapeF FieldNameDB
n
    , Text
" "
    , SqlType -> Text
showSqlType SqlType
sqlType'
    , Text
" "
    , if Bool
nu then Text
"NULL" else Text
"NOT NULL"
    , case Maybe Text
def of
        Maybe Text
Nothing -> Text
""
        Just Text
s -> Text
" DEFAULT " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
s
    , case Maybe Text
gen of
        Maybe Text
Nothing -> Text
""
        Just Text
s -> Text
" GENERATED ALWAYS AS (" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
s Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
") STORED"
    ]

showSqlType :: SqlType -> Text
showSqlType :: SqlType -> Text
showSqlType SqlType
SqlString = Text
"VARCHAR"
showSqlType SqlType
SqlInt32 = Text
"INT4"
showSqlType SqlType
SqlInt64 = Text
"INT8"
showSqlType SqlType
SqlReal = Text
"DOUBLE PRECISION"
showSqlType (SqlNumeric Word32
s Word32
prec) = [Text] -> Text
T.concat [ Text
"NUMERIC(", String -> Text
T.pack (Word32 -> String
forall a. Show a => a -> String
show Word32
s), Text
",", String -> Text
T.pack (Word32 -> String
forall a. Show a => a -> String
show Word32
prec), Text
")" ]
showSqlType SqlType
SqlDay = Text
"DATE"
showSqlType SqlType
SqlTime = Text
"TIME"
showSqlType SqlType
SqlDayTime = Text
"TIMESTAMP WITH TIME ZONE"
showSqlType SqlType
SqlBlob = Text
"BYTEA"
showSqlType SqlType
SqlBool = Text
"BOOLEAN"

-- Added for aliasing issues re: https://github.com/yesodweb/yesod/issues/682
showSqlType (SqlOther (Text -> Text
T.toLower -> Text
"integer")) = Text
"INT4"

showSqlType (SqlOther Text
t) = Text
t

showAlterDb :: AlterDB -> (Bool, Text)
showAlterDb :: AlterDB -> (Bool, Text)
showAlterDb (AddTable Text
s) = (Bool
False, Text
s)
showAlterDb (AlterColumn EntityNameDB
t AlterColumn
ac) =
    (AlterColumn -> Bool
isUnsafe AlterColumn
ac, EntityNameDB -> AlterColumn -> Text
showAlter EntityNameDB
t AlterColumn
ac)
  where
    isUnsafe :: AlterColumn -> Bool
isUnsafe (Drop Column
_ Bool
safeRemove) = Bool -> Bool
not Bool
safeRemove
    isUnsafe AlterColumn
_ = Bool
False
showAlterDb (AlterTable EntityNameDB
t AlterTable
at) = (Bool
False, EntityNameDB -> AlterTable -> Text
showAlterTable EntityNameDB
t AlterTable
at)

showAlterTable :: EntityNameDB -> AlterTable -> Text
showAlterTable :: EntityNameDB -> AlterTable -> Text
showAlterTable EntityNameDB
table (AddUniqueConstraint ConstraintNameDB
cname [FieldNameDB]
cols) = [Text] -> Text
T.concat
    [ Text
"ALTER TABLE "
    , EntityNameDB -> Text
escapeE EntityNameDB
table
    , Text
" ADD CONSTRAINT "
    , ConstraintNameDB -> Text
escapeC ConstraintNameDB
cname
    , Text
" UNIQUE("
    , Text -> [Text] -> Text
T.intercalate Text
"," ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (FieldNameDB -> Text) -> [FieldNameDB] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map FieldNameDB -> Text
escapeF [FieldNameDB]
cols
    , Text
")"
    ]
showAlterTable EntityNameDB
table (DropConstraint ConstraintNameDB
cname) = [Text] -> Text
T.concat
    [ Text
"ALTER TABLE "
    , EntityNameDB -> Text
escapeE EntityNameDB
table
    , Text
" DROP CONSTRAINT "
    , ConstraintNameDB -> Text
escapeC ConstraintNameDB
cname
    ]

showAlter :: EntityNameDB -> AlterColumn -> Text
showAlter :: EntityNameDB -> AlterColumn -> Text
showAlter EntityNameDB
table (ChangeType Column
c SqlType
t Text
extra) =
    [Text] -> Text
T.concat
        [ Text
"ALTER TABLE "
        , EntityNameDB -> Text
escapeE EntityNameDB
table
        , Text
" ALTER COLUMN "
        , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
        , Text
" TYPE "
        , SqlType -> Text
showSqlType SqlType
t
        , Text
extra
        ]
showAlter EntityNameDB
table (IsNull Column
c) =
    [Text] -> Text
T.concat
        [ Text
"ALTER TABLE "
        , EntityNameDB -> Text
escapeE EntityNameDB
table
        , Text
" ALTER COLUMN "
        , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
        , Text
" DROP NOT NULL"
        ]
showAlter EntityNameDB
table (NotNull Column
c) =
    [Text] -> Text
T.concat
        [ Text
"ALTER TABLE "
        , EntityNameDB -> Text
escapeE EntityNameDB
table
        , Text
" ALTER COLUMN "
        , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
        , Text
" SET NOT NULL"
        ]
showAlter EntityNameDB
table (Add' Column
col) =
    [Text] -> Text
T.concat
        [ Text
"ALTER TABLE "
        , EntityNameDB -> Text
escapeE EntityNameDB
table
        , Text
" ADD COLUMN "
        , Column -> Text
showColumn Column
col
        ]
showAlter EntityNameDB
table (Drop Column
c Bool
_) =
    [Text] -> Text
T.concat
        [ Text
"ALTER TABLE "
        , EntityNameDB -> Text
escapeE EntityNameDB
table
        , Text
" DROP COLUMN "
        , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
        ]
showAlter EntityNameDB
table (Default Column
c Text
s) =
    [Text] -> Text
T.concat
        [ Text
"ALTER TABLE "
        , EntityNameDB -> Text
escapeE EntityNameDB
table
        , Text
" ALTER COLUMN "
        , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
        , Text
" SET DEFAULT "
        , Text
s
        ]
showAlter EntityNameDB
table (NoDefault Column
c) = [Text] -> Text
T.concat
    [ Text
"ALTER TABLE "
    , EntityNameDB -> Text
escapeE EntityNameDB
table
    , Text
" ALTER COLUMN "
    , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
    , Text
" DROP DEFAULT"
    ]
showAlter EntityNameDB
table (Update' Column
c Text
s) = [Text] -> Text
T.concat
    [ Text
"UPDATE "
    , EntityNameDB -> Text
escapeE EntityNameDB
table
    , Text
" SET "
    , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
    , Text
"="
    , Text
s
    , Text
" WHERE "
    , FieldNameDB -> Text
escapeF (Column -> FieldNameDB
cName Column
c)
    , Text
" IS NULL"
    ]
showAlter EntityNameDB
table (AddReference EntityNameDB
reftable ConstraintNameDB
fkeyname [FieldNameDB]
t2 [Text]
id2 FieldCascade
cascade) = [Text] -> Text
T.concat
    [ Text
"ALTER TABLE "
    , EntityNameDB -> Text
escapeE EntityNameDB
table
    , Text
" ADD CONSTRAINT "
    , ConstraintNameDB -> Text
escapeC ConstraintNameDB
fkeyname
    , Text
" FOREIGN KEY("
    , Text -> [Text] -> Text
T.intercalate Text
"," ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (FieldNameDB -> Text) -> [FieldNameDB] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map FieldNameDB -> Text
escapeF [FieldNameDB]
t2
    , Text
") REFERENCES "
    , EntityNameDB -> Text
escapeE EntityNameDB
reftable
    , Text
"("
    , Text -> [Text] -> Text
T.intercalate Text
"," [Text]
id2
    , Text
")"
    ] Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> FieldCascade -> Text
renderFieldCascade FieldCascade
cascade
showAlter EntityNameDB
table (DropReference ConstraintNameDB
cname) = [Text] -> Text
T.concat
    [ Text
"ALTER TABLE "
    , EntityNameDB -> Text
escapeE EntityNameDB
table
    , Text
" DROP CONSTRAINT "
    , ConstraintNameDB -> Text
escapeC ConstraintNameDB
cname
    ]

-- | Get the SQL string for the table that a PeristEntity represents.
-- Useful for raw SQL queries.
tableName :: (PersistEntity record) => record -> Text
tableName :: record -> Text
tableName = EntityNameDB -> Text
escapeE (EntityNameDB -> Text)
-> (record -> EntityNameDB) -> record -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. record -> EntityNameDB
forall record. PersistEntity record => record -> EntityNameDB
tableDBName

-- | Get the SQL string for the field that an EntityField represents.
-- Useful for raw SQL queries.
fieldName :: (PersistEntity record) => EntityField record typ -> Text
fieldName :: EntityField record typ -> Text
fieldName = FieldNameDB -> Text
escapeF (FieldNameDB -> Text)
-> (EntityField record typ -> FieldNameDB)
-> EntityField record typ
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityField record typ -> FieldNameDB
forall record typ.
PersistEntity record =>
EntityField record typ -> FieldNameDB
fieldDBName

escapeC :: ConstraintNameDB -> Text
escapeC :: ConstraintNameDB -> Text
escapeC = (Text -> Text) -> ConstraintNameDB -> Text
forall a str. DatabaseName a => (Text -> str) -> a -> str
escapeWith Text -> Text
escape

escapeE :: EntityNameDB -> Text
escapeE :: EntityNameDB -> Text
escapeE = (Text -> Text) -> EntityNameDB -> Text
forall a str. DatabaseName a => (Text -> str) -> a -> str
escapeWith Text -> Text
escape

escapeF :: FieldNameDB -> Text
escapeF :: FieldNameDB -> Text
escapeF = (Text -> Text) -> FieldNameDB -> Text
forall a str. DatabaseName a => (Text -> str) -> a -> str
escapeWith Text -> Text
escape

escape :: Text -> Text
escape :: Text -> Text
escape Text
s =
    String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ Char
'"' Char -> ShowS
forall a. a -> [a] -> [a]
: ShowS
go (Text -> String
T.unpack Text
s) String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
"\""
  where
    go :: ShowS
go String
"" = String
""
    go (Char
'"':String
xs) = String
"\"\"" String -> ShowS
forall a. [a] -> [a] -> [a]
++ ShowS
go String
xs
    go (Char
x:String
xs) = Char
x Char -> ShowS
forall a. a -> [a] -> [a]
: ShowS
go String
xs

-- | Information required to connect to a PostgreSQL database
-- using @persistent@'s generic facilities.  These values are the
-- same that are given to 'withPostgresqlPool'.
data PostgresConf = PostgresConf
    { PostgresConf -> ConnectionString
pgConnStr  :: ConnectionString
      -- ^ The connection string.

    -- TODO: Currently stripes, idle timeout, and pool size are all separate fields
    -- When Persistent next does a large breaking release (3.0?), we should consider making these just a single ConnectionPoolConfig value
    --
    -- Currently there the idle timeout is an Integer, rather than resource-pool's NominalDiffTime type.
    -- This is because the time package only recently added the Read instance for NominalDiffTime.
    -- Future TODO: Consider removing the Read instance, and/or making the idle timeout a NominalDiffTime.

    , PostgresConf -> Int
pgPoolStripes :: Int
    -- ^ How many stripes to divide the pool into. See "Data.Pool" for details.
    -- @since 2.11.0.0
    , PostgresConf -> Integer
pgPoolIdleTimeout :: Integer -- Ideally this would be a NominalDiffTime, but that type lacks a Read instance https://github.com/haskell/time/issues/130
    -- ^ How long connections can remain idle before being disposed of, in seconds.
    -- @since 2.11.0.0
    , PostgresConf -> Int
pgPoolSize :: Int
      -- ^ How many connections should be held in the connection pool.
    } deriving (Int -> PostgresConf -> ShowS
[PostgresConf] -> ShowS
PostgresConf -> String
(Int -> PostgresConf -> ShowS)
-> (PostgresConf -> String)
-> ([PostgresConf] -> ShowS)
-> Show PostgresConf
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [PostgresConf] -> ShowS
$cshowList :: [PostgresConf] -> ShowS
show :: PostgresConf -> String
$cshow :: PostgresConf -> String
showsPrec :: Int -> PostgresConf -> ShowS
$cshowsPrec :: Int -> PostgresConf -> ShowS
Show, ReadPrec [PostgresConf]
ReadPrec PostgresConf
Int -> ReadS PostgresConf
ReadS [PostgresConf]
(Int -> ReadS PostgresConf)
-> ReadS [PostgresConf]
-> ReadPrec PostgresConf
-> ReadPrec [PostgresConf]
-> Read PostgresConf
forall a.
(Int -> ReadS a)
-> ReadS [a] -> ReadPrec a -> ReadPrec [a] -> Read a
readListPrec :: ReadPrec [PostgresConf]
$creadListPrec :: ReadPrec [PostgresConf]
readPrec :: ReadPrec PostgresConf
$creadPrec :: ReadPrec PostgresConf
readList :: ReadS [PostgresConf]
$creadList :: ReadS [PostgresConf]
readsPrec :: Int -> ReadS PostgresConf
$creadsPrec :: Int -> ReadS PostgresConf
Read, Typeable PostgresConf
DataType
Constr
Typeable PostgresConf
-> (forall (c :: * -> *).
    (forall d b. Data d => c (d -> b) -> d -> c b)
    -> (forall g. g -> c g) -> PostgresConf -> c PostgresConf)
-> (forall (c :: * -> *).
    (forall b r. Data b => c (b -> r) -> c r)
    -> (forall r. r -> c r) -> Constr -> c PostgresConf)
-> (PostgresConf -> Constr)
-> (PostgresConf -> DataType)
-> (forall (t :: * -> *) (c :: * -> *).
    Typeable t =>
    (forall d. Data d => c (t d)) -> Maybe (c PostgresConf))
-> (forall (t :: * -> * -> *) (c :: * -> *).
    Typeable t =>
    (forall d e. (Data d, Data e) => c (t d e))
    -> Maybe (c PostgresConf))
-> ((forall b. Data b => b -> b) -> PostgresConf -> PostgresConf)
-> (forall r r'.
    (r -> r' -> r)
    -> r -> (forall d. Data d => d -> r') -> PostgresConf -> r)
-> (forall r r'.
    (r' -> r -> r)
    -> r -> (forall d. Data d => d -> r') -> PostgresConf -> r)
-> (forall u. (forall d. Data d => d -> u) -> PostgresConf -> [u])
-> (forall u.
    Int -> (forall d. Data d => d -> u) -> PostgresConf -> u)
-> (forall (m :: * -> *).
    Monad m =>
    (forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf)
-> (forall (m :: * -> *).
    MonadPlus m =>
    (forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf)
-> (forall (m :: * -> *).
    MonadPlus m =>
    (forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf)
-> Data PostgresConf
PostgresConf -> DataType
PostgresConf -> Constr
(forall b. Data b => b -> b) -> PostgresConf -> PostgresConf
(forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g) -> PostgresConf -> c PostgresConf
(forall b r. Data b => c (b -> r) -> c r)
-> (forall r. r -> c r) -> Constr -> c PostgresConf
forall a.
Typeable a
-> (forall (c :: * -> *).
    (forall d b. Data d => c (d -> b) -> d -> c b)
    -> (forall g. g -> c g) -> a -> c a)
-> (forall (c :: * -> *).
    (forall b r. Data b => c (b -> r) -> c r)
    -> (forall r. r -> c r) -> Constr -> c a)
-> (a -> Constr)
-> (a -> DataType)
-> (forall (t :: * -> *) (c :: * -> *).
    Typeable t =>
    (forall d. Data d => c (t d)) -> Maybe (c a))
-> (forall (t :: * -> * -> *) (c :: * -> *).
    Typeable t =>
    (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a))
-> ((forall b. Data b => b -> b) -> a -> a)
-> (forall r r'.
    (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r)
-> (forall r r'.
    (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r)
-> (forall u. (forall d. Data d => d -> u) -> a -> [u])
-> (forall u. Int -> (forall d. Data d => d -> u) -> a -> u)
-> (forall (m :: * -> *).
    Monad m =>
    (forall d. Data d => d -> m d) -> a -> m a)
-> (forall (m :: * -> *).
    MonadPlus m =>
    (forall d. Data d => d -> m d) -> a -> m a)
-> (forall (m :: * -> *).
    MonadPlus m =>
    (forall d. Data d => d -> m d) -> a -> m a)
-> Data a
forall u. Int -> (forall d. Data d => d -> u) -> PostgresConf -> u
forall u. (forall d. Data d => d -> u) -> PostgresConf -> [u]
forall r r'.
(r -> r' -> r)
-> r -> (forall d. Data d => d -> r') -> PostgresConf -> r
forall r r'.
(r' -> r -> r)
-> r -> (forall d. Data d => d -> r') -> PostgresConf -> r
forall (m :: * -> *).
Monad m =>
(forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
forall (m :: * -> *).
MonadPlus m =>
(forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
forall (c :: * -> *).
(forall b r. Data b => c (b -> r) -> c r)
-> (forall r. r -> c r) -> Constr -> c PostgresConf
forall (c :: * -> *).
(forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g) -> PostgresConf -> c PostgresConf
forall (t :: * -> *) (c :: * -> *).
Typeable t =>
(forall d. Data d => c (t d)) -> Maybe (c PostgresConf)
forall (t :: * -> * -> *) (c :: * -> *).
Typeable t =>
(forall d e. (Data d, Data e) => c (t d e))
-> Maybe (c PostgresConf)
$cPostgresConf :: Constr
$tPostgresConf :: DataType
gmapMo :: (forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
$cgmapMo :: forall (m :: * -> *).
MonadPlus m =>
(forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
gmapMp :: (forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
$cgmapMp :: forall (m :: * -> *).
MonadPlus m =>
(forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
gmapM :: (forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
$cgmapM :: forall (m :: * -> *).
Monad m =>
(forall d. Data d => d -> m d) -> PostgresConf -> m PostgresConf
gmapQi :: Int -> (forall d. Data d => d -> u) -> PostgresConf -> u
$cgmapQi :: forall u. Int -> (forall d. Data d => d -> u) -> PostgresConf -> u
gmapQ :: (forall d. Data d => d -> u) -> PostgresConf -> [u]
$cgmapQ :: forall u. (forall d. Data d => d -> u) -> PostgresConf -> [u]
gmapQr :: (r' -> r -> r)
-> r -> (forall d. Data d => d -> r') -> PostgresConf -> r
$cgmapQr :: forall r r'.
(r' -> r -> r)
-> r -> (forall d. Data d => d -> r') -> PostgresConf -> r
gmapQl :: (r -> r' -> r)
-> r -> (forall d. Data d => d -> r') -> PostgresConf -> r
$cgmapQl :: forall r r'.
(r -> r' -> r)
-> r -> (forall d. Data d => d -> r') -> PostgresConf -> r
gmapT :: (forall b. Data b => b -> b) -> PostgresConf -> PostgresConf
$cgmapT :: (forall b. Data b => b -> b) -> PostgresConf -> PostgresConf
dataCast2 :: (forall d e. (Data d, Data e) => c (t d e))
-> Maybe (c PostgresConf)
$cdataCast2 :: forall (t :: * -> * -> *) (c :: * -> *).
Typeable t =>
(forall d e. (Data d, Data e) => c (t d e))
-> Maybe (c PostgresConf)
dataCast1 :: (forall d. Data d => c (t d)) -> Maybe (c PostgresConf)
$cdataCast1 :: forall (t :: * -> *) (c :: * -> *).
Typeable t =>
(forall d. Data d => c (t d)) -> Maybe (c PostgresConf)
dataTypeOf :: PostgresConf -> DataType
$cdataTypeOf :: PostgresConf -> DataType
toConstr :: PostgresConf -> Constr
$ctoConstr :: PostgresConf -> Constr
gunfold :: (forall b r. Data b => c (b -> r) -> c r)
-> (forall r. r -> c r) -> Constr -> c PostgresConf
$cgunfold :: forall (c :: * -> *).
(forall b r. Data b => c (b -> r) -> c r)
-> (forall r. r -> c r) -> Constr -> c PostgresConf
gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g) -> PostgresConf -> c PostgresConf
$cgfoldl :: forall (c :: * -> *).
(forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g) -> PostgresConf -> c PostgresConf
$cp1Data :: Typeable PostgresConf
Data)

instance FromJSON PostgresConf where
    parseJSON :: Value -> Parser PostgresConf
parseJSON Value
v = ShowS -> Parser PostgresConf -> Parser PostgresConf
forall a. ShowS -> Parser a -> Parser a
modifyFailure (String
"Persistent: error loading PostgreSQL conf: " String -> ShowS
forall a. [a] -> [a] -> [a]
++) (Parser PostgresConf -> Parser PostgresConf)
-> Parser PostgresConf -> Parser PostgresConf
forall a b. (a -> b) -> a -> b
$
      ((Object -> Parser PostgresConf) -> Value -> Parser PostgresConf)
-> Value -> (Object -> Parser PostgresConf) -> Parser PostgresConf
forall a b c. (a -> b -> c) -> b -> a -> c
flip (String
-> (Object -> Parser PostgresConf) -> Value -> Parser PostgresConf
forall a. String -> (Object -> Parser a) -> Value -> Parser a
withObject String
"PostgresConf") Value
v ((Object -> Parser PostgresConf) -> Parser PostgresConf)
-> (Object -> Parser PostgresConf) -> Parser PostgresConf
forall a b. (a -> b) -> a -> b
$ \Object
o -> do
        let defaultPoolConfig :: ConnectionPoolConfig
defaultPoolConfig = ConnectionPoolConfig
defaultConnectionPoolConfig
        String
database <- Object
o Object -> Text -> Parser String
forall a. FromJSON a => Object -> Text -> Parser a
.: Text
"database"
        String
host     <- Object
o Object -> Text -> Parser String
forall a. FromJSON a => Object -> Text -> Parser a
.: Text
"host"
        Word16
port     <- Object
o Object -> Text -> Parser (Maybe Word16)
forall a. FromJSON a => Object -> Text -> Parser (Maybe a)
.:? Text
"port" Parser (Maybe Word16) -> Word16 -> Parser Word16
forall a. Parser (Maybe a) -> a -> Parser a
.!= Word16
5432
        String
user     <- Object
o Object -> Text -> Parser String
forall a. FromJSON a => Object -> Text -> Parser a
.: Text
"user"
        String
password <- Object
o Object -> Text -> Parser String
forall a. FromJSON a => Object -> Text -> Parser a
.: Text
"password"
        Int
poolSize <- Object
o Object -> Text -> Parser (Maybe Int)
forall a. FromJSON a => Object -> Text -> Parser (Maybe a)
.:? Text
"poolsize" Parser (Maybe Int) -> Int -> Parser Int
forall a. Parser (Maybe a) -> a -> Parser a
.!= (ConnectionPoolConfig -> Int
connectionPoolConfigSize ConnectionPoolConfig
defaultPoolConfig)
        Int
poolStripes <- Object
o Object -> Text -> Parser (Maybe Int)
forall a. FromJSON a => Object -> Text -> Parser (Maybe a)
.:? Text
"stripes" Parser (Maybe Int) -> Int -> Parser Int
forall a. Parser (Maybe a) -> a -> Parser a
.!= (ConnectionPoolConfig -> Int
connectionPoolConfigStripes ConnectionPoolConfig
defaultPoolConfig)
        Integer
poolIdleTimeout <- Object
o Object -> Text -> Parser (Maybe Integer)
forall a. FromJSON a => Object -> Text -> Parser (Maybe a)
.:? Text
"idleTimeout" Parser (Maybe Integer) -> Integer -> Parser Integer
forall a. Parser (Maybe a) -> a -> Parser a
.!= (NominalDiffTime -> Integer
forall a b. (RealFrac a, Integral b) => a -> b
floor (NominalDiffTime -> Integer) -> NominalDiffTime -> Integer
forall a b. (a -> b) -> a -> b
$ ConnectionPoolConfig -> NominalDiffTime
connectionPoolConfigIdleTimeout ConnectionPoolConfig
defaultPoolConfig)
        let ci :: ConnectInfo
ci = ConnectInfo :: String -> Word16 -> String -> String -> String -> ConnectInfo
PG.ConnectInfo
                   { connectHost :: String
PG.connectHost     = String
host
                   , connectPort :: Word16
PG.connectPort     = Word16
port
                   , connectUser :: String
PG.connectUser     = String
user
                   , connectPassword :: String
PG.connectPassword = String
password
                   , connectDatabase :: String
PG.connectDatabase = String
database
                   }
            cstr :: ConnectionString
cstr = ConnectInfo -> ConnectionString
PG.postgreSQLConnectionString ConnectInfo
ci
        PostgresConf -> Parser PostgresConf
forall (m :: * -> *) a. Monad m => a -> m a
return (PostgresConf -> Parser PostgresConf)
-> PostgresConf -> Parser PostgresConf
forall a b. (a -> b) -> a -> b
$ ConnectionString -> Int -> Integer -> Int -> PostgresConf
PostgresConf ConnectionString
cstr Int
poolStripes Integer
poolIdleTimeout Int
poolSize
instance PersistConfig PostgresConf where
    type PersistConfigBackend PostgresConf = SqlPersistT
    type PersistConfigPool PostgresConf = ConnectionPool
    createPoolConfig :: PostgresConf -> IO (PersistConfigPool PostgresConf)
createPoolConfig PostgresConf
conf = NoLoggingT IO (Pool SqlBackend) -> IO (Pool SqlBackend)
forall (m :: * -> *) a. NoLoggingT m a -> m a
runNoLoggingT (NoLoggingT IO (Pool SqlBackend) -> IO (Pool SqlBackend))
-> NoLoggingT IO (Pool SqlBackend) -> IO (Pool SqlBackend)
forall a b. (a -> b) -> a -> b
$ PostgresConf
-> PostgresConfHooks -> NoLoggingT IO (Pool SqlBackend)
forall (m :: * -> *).
(MonadUnliftIO m, MonadLoggerIO m) =>
PostgresConf -> PostgresConfHooks -> m (Pool SqlBackend)
createPostgresqlPoolWithConf PostgresConf
conf PostgresConfHooks
defaultPostgresConfHooks
    runPool :: PostgresConf
-> PersistConfigBackend PostgresConf m a
-> PersistConfigPool PostgresConf
-> m a
runPool PostgresConf
_ = PersistConfigBackend PostgresConf m a
-> PersistConfigPool PostgresConf -> m a
forall backend (m :: * -> *) a.
(MonadUnliftIO m, BackendCompatible SqlBackend backend) =>
ReaderT backend m a -> Pool backend -> m a
runSqlPool
    loadConfig :: Value -> Parser PostgresConf
loadConfig = Value -> Parser PostgresConf
forall a. FromJSON a => Value -> Parser a
parseJSON

    applyEnv :: PostgresConf -> IO PostgresConf
applyEnv PostgresConf
c0 = do
        [(String, String)]
env <- IO [(String, String)]
getEnvironment
        PostgresConf -> IO PostgresConf
forall (m :: * -> *) a. Monad m => a -> m a
return (PostgresConf -> IO PostgresConf)
-> PostgresConf -> IO PostgresConf
forall a b. (a -> b) -> a -> b
$ [(String, String)] -> PostgresConf -> PostgresConf
addUser [(String, String)]
env
               (PostgresConf -> PostgresConf) -> PostgresConf -> PostgresConf
forall a b. (a -> b) -> a -> b
$ [(String, String)] -> PostgresConf -> PostgresConf
addPass [(String, String)]
env
               (PostgresConf -> PostgresConf) -> PostgresConf -> PostgresConf
forall a b. (a -> b) -> a -> b
$ [(String, String)] -> PostgresConf -> PostgresConf
addDatabase [(String, String)]
env
               (PostgresConf -> PostgresConf) -> PostgresConf -> PostgresConf
forall a b. (a -> b) -> a -> b
$ [(String, String)] -> PostgresConf -> PostgresConf
addPort [(String, String)]
env
               (PostgresConf -> PostgresConf) -> PostgresConf -> PostgresConf
forall a b. (a -> b) -> a -> b
$ [(String, String)] -> PostgresConf -> PostgresConf
addHost [(String, String)]
env PostgresConf
c0
      where
        addParam :: ConnectionString -> String -> PostgresConf -> PostgresConf
addParam ConnectionString
param String
val PostgresConf
c =
            PostgresConf
c { pgConnStr :: ConnectionString
pgConnStr = [ConnectionString] -> ConnectionString
B8.concat [PostgresConf -> ConnectionString
pgConnStr PostgresConf
c, ConnectionString
" ", ConnectionString
param, ConnectionString
"='", String -> ConnectionString
pgescape String
val, ConnectionString
"'"] }

        pgescape :: String -> ConnectionString
pgescape = String -> ConnectionString
B8.pack (String -> ConnectionString) -> ShowS -> String -> ConnectionString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShowS
go
            where
              go :: ShowS
go (Char
'\'':String
rest) = Char
'\\' Char -> ShowS
forall a. a -> [a] -> [a]
: Char
'\'' Char -> ShowS
forall a. a -> [a] -> [a]
: ShowS
go String
rest
              go (Char
'\\':String
rest) = Char
'\\' Char -> ShowS
forall a. a -> [a] -> [a]
: Char
'\\' Char -> ShowS
forall a. a -> [a] -> [a]
: ShowS
go String
rest
              go ( Char
x  :String
rest) =      Char
x      Char -> ShowS
forall a. a -> [a] -> [a]
: ShowS
go String
rest
              go []          = []

        maybeAddParam :: ConnectionString
-> a -> [(a, String)] -> PostgresConf -> PostgresConf
maybeAddParam ConnectionString
param a
envvar [(a, String)]
env =
            (PostgresConf -> PostgresConf)
-> (String -> PostgresConf -> PostgresConf)
-> Maybe String
-> PostgresConf
-> PostgresConf
forall b a. b -> (a -> b) -> Maybe a -> b
maybe PostgresConf -> PostgresConf
forall a. a -> a
id (ConnectionString -> String -> PostgresConf -> PostgresConf
addParam ConnectionString
param) (Maybe String -> PostgresConf -> PostgresConf)
-> Maybe String -> PostgresConf -> PostgresConf
forall a b. (a -> b) -> a -> b
$
            a -> [(a, String)] -> Maybe String
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup a
envvar [(a, String)]
env

        addHost :: [(String, String)] -> PostgresConf -> PostgresConf
addHost     = ConnectionString
-> String -> [(String, String)] -> PostgresConf -> PostgresConf
forall a.
Eq a =>
ConnectionString
-> a -> [(a, String)] -> PostgresConf -> PostgresConf
maybeAddParam ConnectionString
"host"     String
"PGHOST"
        addPort :: [(String, String)] -> PostgresConf -> PostgresConf
addPort     = ConnectionString
-> String -> [(String, String)] -> PostgresConf -> PostgresConf
forall a.
Eq a =>
ConnectionString
-> a -> [(a, String)] -> PostgresConf -> PostgresConf
maybeAddParam ConnectionString
"port"     String
"PGPORT"
        addUser :: [(String, String)] -> PostgresConf -> PostgresConf
addUser     = ConnectionString
-> String -> [(String, String)] -> PostgresConf -> PostgresConf
forall a.
Eq a =>
ConnectionString
-> a -> [(a, String)] -> PostgresConf -> PostgresConf
maybeAddParam ConnectionString
"user"     String
"PGUSER"
        addPass :: [(String, String)] -> PostgresConf -> PostgresConf
addPass     = ConnectionString
-> String -> [(String, String)] -> PostgresConf -> PostgresConf
forall a.
Eq a =>
ConnectionString
-> a -> [(a, String)] -> PostgresConf -> PostgresConf
maybeAddParam ConnectionString
"password" String
"PGPASS"
        addDatabase :: [(String, String)] -> PostgresConf -> PostgresConf
addDatabase = ConnectionString
-> String -> [(String, String)] -> PostgresConf -> PostgresConf
forall a.
Eq a =>
ConnectionString
-> a -> [(a, String)] -> PostgresConf -> PostgresConf
maybeAddParam ConnectionString
"dbname"   String
"PGDATABASE"

-- | Hooks for configuring the Persistent/its connection to Postgres
--
-- @since 2.11.0
data PostgresConfHooks = PostgresConfHooks
  { PostgresConfHooks -> Connection -> IO (NonEmpty Word)
pgConfHooksGetServerVersion :: PG.Connection -> IO (NonEmpty Word)
      -- ^ Function to get the version of Postgres
      --
      -- The default implementation queries the server with "show server_version".
      -- Some variants of Postgres, such as Redshift, don't support showing the version.
      -- It's recommended you return a hardcoded version in those cases.
      --
      -- @since 2.11.0
  , PostgresConfHooks -> Connection -> IO ()
pgConfHooksAfterCreate :: PG.Connection -> IO ()
      -- ^ Action to perform after a connection is created.
      --
      -- Typical uses of this are modifying the connection (e.g. to set the schema) or logging a connection being created.
      --
      -- The default implementation does nothing.
      --
      -- @since 2.11.0
  }

-- | Default settings for 'PostgresConfHooks'. See the individual fields of 'PostgresConfHooks' for the default values.
--
-- @since 2.11.0
defaultPostgresConfHooks :: PostgresConfHooks
defaultPostgresConfHooks :: PostgresConfHooks
defaultPostgresConfHooks = PostgresConfHooks :: (Connection -> IO (NonEmpty Word))
-> (Connection -> IO ()) -> PostgresConfHooks
PostgresConfHooks
  { pgConfHooksGetServerVersion :: Connection -> IO (NonEmpty Word)
pgConfHooksGetServerVersion = Connection -> IO (NonEmpty Word)
getServerVersionNonEmpty
  , pgConfHooksAfterCreate :: Connection -> IO ()
pgConfHooksAfterCreate = IO () -> Connection -> IO ()
forall a b. a -> b -> a
const (IO () -> Connection -> IO ()) -> IO () -> Connection -> IO ()
forall a b. (a -> b) -> a -> b
$ () -> IO ()
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  }


refName :: EntityNameDB -> FieldNameDB -> ConstraintNameDB
refName :: EntityNameDB -> FieldNameDB -> ConstraintNameDB
refName (EntityNameDB Text
table) (FieldNameDB Text
column) =
    let overhead :: Int
overhead = Text -> Int
T.length (Text -> Int) -> Text -> Int
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat [Text
"_", Text
"_fkey"]
        (Int
fromTable, Int
fromColumn) = Int -> (Int, Int) -> (Int, Int)
shortenNames Int
overhead (Text -> Int
T.length Text
table, Text -> Int
T.length Text
column)
    in Text -> ConstraintNameDB
ConstraintNameDB (Text -> ConstraintNameDB) -> Text -> ConstraintNameDB
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat [Int -> Text -> Text
T.take Int
fromTable Text
table, Text
"_", Int -> Text -> Text
T.take Int
fromColumn Text
column, Text
"_fkey"]

    where

      -- Postgres automatically truncates too long foreign keys to a combination of
      -- truncatedTableName + "_" + truncatedColumnName + "_fkey"
      -- This works fine for normal use cases, but it creates an issue for Persistent
      -- Because after running the migrations, Persistent sees the truncated foreign key constraint
      -- doesn't have the expected name, and suggests that you migrate again
      -- To workaround this, we copy the Postgres truncation approach before sending foreign key constraints to it.
      --
      -- I believe this will also be an issue for extremely long table names,
      -- but it's just much more likely to exist with foreign key constraints because they're usually tablename * 2 in length

      -- Approximation of the algorithm Postgres uses to truncate identifiers
      -- See makeObjectName https://github.com/postgres/postgres/blob/5406513e997f5ee9de79d4076ae91c04af0c52f6/src/backend/commands/indexcmds.c#L2074-L2080
      shortenNames :: Int -> (Int, Int) -> (Int, Int)
      shortenNames :: Int -> (Int, Int) -> (Int, Int)
shortenNames Int
overhead (Int
x, Int
y)
           | Int
x Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
y Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
overhead Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
maximumIdentifierLength = (Int
x, Int
y)
           | Int
x Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
y = Int -> (Int, Int) -> (Int, Int)
shortenNames Int
overhead (Int
x Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1, Int
y)
           | Bool
otherwise = Int -> (Int, Int) -> (Int, Int)
shortenNames Int
overhead (Int
x, Int
y Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)

-- | Postgres' default maximum identifier length in bytes
-- (You can re-compile Postgres with a new limit, but I'm assuming that virtually noone does this).
-- See https://www.postgresql.org/docs/11/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
maximumIdentifierLength :: Int
maximumIdentifierLength :: Int
maximumIdentifierLength = Int
63

udToPair :: UniqueDef -> (ConstraintNameDB, [FieldNameDB])
udToPair :: UniqueDef -> (ConstraintNameDB, [FieldNameDB])
udToPair UniqueDef
ud = (UniqueDef -> ConstraintNameDB
uniqueDBName UniqueDef
ud, ((FieldNameHS, FieldNameDB) -> FieldNameDB)
-> [(FieldNameHS, FieldNameDB)] -> [FieldNameDB]
forall a b. (a -> b) -> [a] -> [b]
map (FieldNameHS, FieldNameDB) -> FieldNameDB
forall a b. (a, b) -> b
snd ([(FieldNameHS, FieldNameDB)] -> [FieldNameDB])
-> [(FieldNameHS, FieldNameDB)] -> [FieldNameDB]
forall a b. (a -> b) -> a -> b
$ UniqueDef -> [(FieldNameHS, FieldNameDB)]
uniqueFields UniqueDef
ud)

mockMigrate :: [EntityDef]
         -> (Text -> IO Statement)
         -> EntityDef
         -> IO (Either [Text] [(Bool, Text)])
mockMigrate :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
mockMigrate [EntityDef]
allDefs Text -> IO Statement
_ EntityDef
entity = (Either [Text] [AlterDB] -> Either [Text] [(Bool, Text)])
-> IO (Either [Text] [AlterDB])
-> IO (Either [Text] [(Bool, Text)])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (([AlterDB] -> [(Bool, Text)])
-> Either [Text] [AlterDB] -> Either [Text] [(Bool, Text)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (([AlterDB] -> [(Bool, Text)])
 -> Either [Text] [AlterDB] -> Either [Text] [(Bool, Text)])
-> ([AlterDB] -> [(Bool, Text)])
-> Either [Text] [AlterDB]
-> Either [Text] [(Bool, Text)]
forall a b. (a -> b) -> a -> b
$ (AlterDB -> (Bool, Text)) -> [AlterDB] -> [(Bool, Text)]
forall a b. (a -> b) -> [a] -> [b]
map AlterDB -> (Bool, Text)
showAlterDb) (IO (Either [Text] [AlterDB]) -> IO (Either [Text] [(Bool, Text)]))
-> IO (Either [Text] [AlterDB])
-> IO (Either [Text] [(Bool, Text)])
forall a b. (a -> b) -> a -> b
$ do
    case [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
-> ([Text], [Either Column (ConstraintNameDB, [FieldNameDB])])
forall a b. [Either a b] -> ([a], [b])
partitionEithers [] of
        ([], [Either Column (ConstraintNameDB, [FieldNameDB])]
old'') -> Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall (m :: * -> *) a. Monad m => a -> m a
return (Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB]))
-> Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall a b. (a -> b) -> a -> b
$ [AlterDB] -> Either [Text] [AlterDB]
forall a b. b -> Either a b
Right ([AlterDB] -> Either [Text] [AlterDB])
-> [AlterDB] -> Either [Text] [AlterDB]
forall a b. (a -> b) -> a -> b
$ Bool
-> [Either Column (ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
migrationText Bool
False [Either Column (ConstraintNameDB, [FieldNameDB])]
old''
        ([Text]
errs, [Either Column (ConstraintNameDB, [FieldNameDB])]
_) -> Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall (m :: * -> *) a. Monad m => a -> m a
return (Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB]))
-> Either [Text] [AlterDB] -> IO (Either [Text] [AlterDB])
forall a b. (a -> b) -> a -> b
$ [Text] -> Either [Text] [AlterDB]
forall a b. a -> Either a b
Left [Text]
errs
  where
    name :: EntityNameDB
name = EntityDef -> EntityNameDB
entityDB EntityDef
entity
    migrationText :: Bool
-> [Either Column (ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
migrationText Bool
exists' [Either Column (ConstraintNameDB, [FieldNameDB])]
old'' =
        if Bool -> Bool
not Bool
exists'
            then [Column]
-> [ForeignDef] -> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
createText [Column]
newcols [ForeignDef]
fdefs [(ConstraintNameDB, [FieldNameDB])]
udspair
            else let ([AlterColumn]
acs, [AlterTable]
ats) = [EntityDef]
-> EntityDef
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([AlterColumn], [AlterTable])
getAlters [EntityDef]
allDefs EntityDef
entity ([Column]
newcols, [(ConstraintNameDB, [FieldNameDB])]
udspair) ([Column], [(ConstraintNameDB, [FieldNameDB])])
old'
                     acs' :: [AlterDB]
acs' = (AlterColumn -> AlterDB) -> [AlterColumn] -> [AlterDB]
forall a b. (a -> b) -> [a] -> [b]
map (EntityNameDB -> AlterColumn -> AlterDB
AlterColumn EntityNameDB
name) [AlterColumn]
acs
                     ats' :: [AlterDB]
ats' = (AlterTable -> AlterDB) -> [AlterTable] -> [AlterDB]
forall a b. (a -> b) -> [a] -> [b]
map (EntityNameDB -> AlterTable -> AlterDB
AlterTable EntityNameDB
name) [AlterTable]
ats
                 in  [AlterDB]
acs' [AlterDB] -> [AlterDB] -> [AlterDB]
forall a. [a] -> [a] -> [a]
++ [AlterDB]
ats'
       where
         old' :: ([Column], [(ConstraintNameDB, [FieldNameDB])])
old' = [Either Column (ConstraintNameDB, [FieldNameDB])]
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
forall a b. [Either a b] -> ([a], [b])
partitionEithers [Either Column (ConstraintNameDB, [FieldNameDB])]
old''
         ([Column]
newcols', [UniqueDef]
udefs, [ForeignDef]
fdefs) = [EntityDef] -> EntityDef -> ([Column], [UniqueDef], [ForeignDef])
postgresMkColumns [EntityDef]
allDefs EntityDef
entity
         newcols :: [Column]
newcols = (Column -> Bool) -> [Column] -> [Column]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Column -> Bool) -> Column -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> FieldNameDB -> Bool
safeToRemove EntityDef
entity (FieldNameDB -> Bool) -> (Column -> FieldNameDB) -> Column -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Column -> FieldNameDB
cName) [Column]
newcols'
         udspair :: [(ConstraintNameDB, [FieldNameDB])]
udspair = (UniqueDef -> (ConstraintNameDB, [FieldNameDB]))
-> [UniqueDef] -> [(ConstraintNameDB, [FieldNameDB])]
forall a b. (a -> b) -> [a] -> [b]
map UniqueDef -> (ConstraintNameDB, [FieldNameDB])
udToPair [UniqueDef]
udefs
            -- Check for table existence if there are no columns, workaround
            -- for https://github.com/yesodweb/persistent/issues/152

    createText :: [Column]
-> [ForeignDef] -> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
createText [Column]
newcols [ForeignDef]
fdefs [(ConstraintNameDB, [FieldNameDB])]
udspair =
        ([Column] -> EntityDef -> AlterDB
addTable [Column]
newcols EntityDef
entity) AlterDB -> [AlterDB] -> [AlterDB]
forall a. a -> [a] -> [a]
: [AlterDB]
uniques [AlterDB] -> [AlterDB] -> [AlterDB]
forall a. [a] -> [a] -> [a]
++ [AlterDB]
references [AlterDB] -> [AlterDB] -> [AlterDB]
forall a. [a] -> [a] -> [a]
++ [AlterDB]
foreignsAlt
      where
        uniques :: [AlterDB]
uniques = (((ConstraintNameDB, [FieldNameDB]) -> [AlterDB])
 -> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB])
-> [(ConstraintNameDB, [FieldNameDB])]
-> ((ConstraintNameDB, [FieldNameDB]) -> [AlterDB])
-> [AlterDB]
forall a b c. (a -> b -> c) -> b -> a -> c
flip ((ConstraintNameDB, [FieldNameDB]) -> [AlterDB])
-> [(ConstraintNameDB, [FieldNameDB])] -> [AlterDB]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap [(ConstraintNameDB, [FieldNameDB])]
udspair (((ConstraintNameDB, [FieldNameDB]) -> [AlterDB]) -> [AlterDB])
-> ((ConstraintNameDB, [FieldNameDB]) -> [AlterDB]) -> [AlterDB]
forall a b. (a -> b) -> a -> b
$ \(ConstraintNameDB
uname, [FieldNameDB]
ucols) ->
                [EntityNameDB -> AlterTable -> AlterDB
AlterTable EntityNameDB
name (AlterTable -> AlterDB) -> AlterTable -> AlterDB
forall a b. (a -> b) -> a -> b
$ ConstraintNameDB -> [FieldNameDB] -> AlterTable
AddUniqueConstraint ConstraintNameDB
uname [FieldNameDB]
ucols]
        references :: [AlterDB]
references =
            (Column -> Maybe AlterDB) -> [Column] -> [AlterDB]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe
                (\Column { FieldNameDB
cName :: FieldNameDB
cName :: Column -> FieldNameDB
cName, Maybe ColumnReference
cReference :: Maybe ColumnReference
cReference :: Column -> Maybe ColumnReference
cReference } ->
                    [EntityDef]
-> EntityDef -> FieldNameDB -> ColumnReference -> Maybe AlterDB
getAddReference [EntityDef]
allDefs EntityDef
entity FieldNameDB
cName (ColumnReference -> Maybe AlterDB)
-> Maybe ColumnReference -> Maybe AlterDB
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe ColumnReference
cReference
                )
                [Column]
newcols
        foreignsAlt :: [AlterDB]
foreignsAlt = (ForeignDef -> Maybe AlterDB) -> [ForeignDef] -> [AlterDB]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (EntityDef -> ForeignDef -> Maybe AlterDB
mkForeignAlt EntityDef
entity) [ForeignDef]
fdefs

-- | Mock a migration even when the database is not present.
-- This function performs the same functionality of 'printMigration'
-- with the difference that an actual database is not needed.
mockMigration :: Migration -> IO ()
mockMigration :: Migration -> IO ()
mockMigration Migration
mig = do
  IORef (Map Text Statement)
smap <- Map Text Statement -> IO (IORef (Map Text Statement))
forall a. a -> IO (IORef a)
newIORef (Map Text Statement -> IO (IORef (Map Text Statement)))
-> Map Text Statement -> IO (IORef (Map Text Statement))
forall a b. (a -> b) -> a -> b
$ Map Text Statement
forall k a. Map k a
Map.empty
  let sqlbackend :: SqlBackend
sqlbackend = SqlBackend :: (Text -> IO Statement)
-> (EntityDef -> [PersistValue] -> InsertSqlResult)
-> Maybe (EntityDef -> [[PersistValue]] -> InsertSqlResult)
-> Maybe
     (EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text)
-> Maybe (EntityDef -> Int -> Text)
-> IORef (Map Text Statement)
-> IO ()
-> ([EntityDef]
    -> (Text -> IO Statement)
    -> EntityDef
    -> IO (Either [Text] [(Bool, Text)]))
-> ((Text -> IO Statement) -> Maybe IsolationLevel -> IO ())
-> ((Text -> IO Statement) -> IO ())
-> ((Text -> IO Statement) -> IO ())
-> (FieldNameDB -> Text)
-> (EntityDef -> Text)
-> (Text -> Text)
-> Text
-> Text
-> ((Int, Int) -> Bool -> Text -> Text)
-> LogFunc
-> Maybe Int
-> Maybe (EntityDef -> Int -> Text)
-> SqlBackend
SqlBackend { connPrepare :: Text -> IO Statement
connPrepare = \Text
_ -> do
                                             Statement -> IO Statement
forall (m :: * -> *) a. Monad m => a -> m a
return Statement :: IO ()
-> IO ()
-> ([PersistValue] -> IO Int64)
-> (forall (m :: * -> *).
    MonadIO m =>
    [PersistValue] -> Acquire (ConduitM () [PersistValue] m ()))
-> Statement
Statement
                                                        { stmtFinalize :: IO ()
stmtFinalize = () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                                                        , stmtReset :: IO ()
stmtReset = () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                                                        , stmtExecute :: [PersistValue] -> IO Int64
stmtExecute = [PersistValue] -> IO Int64
forall a. HasCallStack => a
undefined
                                                        , stmtQuery :: forall (m :: * -> *).
MonadIO m =>
[PersistValue] -> Acquire (ConduitM () [PersistValue] m ())
stmtQuery = \[PersistValue]
_ -> ConduitM () [PersistValue] m ()
-> Acquire (ConduitM () [PersistValue] m ())
forall (m :: * -> *) a. Monad m => a -> m a
return (ConduitM () [PersistValue] m ()
 -> Acquire (ConduitM () [PersistValue] m ()))
-> ConduitM () [PersistValue] m ()
-> Acquire (ConduitM () [PersistValue] m ())
forall a b. (a -> b) -> a -> b
$ () -> ConduitM () [PersistValue] m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                                                        },
                             connInsertManySql :: Maybe (EntityDef -> [[PersistValue]] -> InsertSqlResult)
connInsertManySql = Maybe (EntityDef -> [[PersistValue]] -> InsertSqlResult)
forall a. Maybe a
Nothing,
                             connInsertSql :: EntityDef -> [PersistValue] -> InsertSqlResult
connInsertSql = EntityDef -> [PersistValue] -> InsertSqlResult
forall a. HasCallStack => a
undefined,
                             connUpsertSql :: Maybe
  (EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text)
connUpsertSql = Maybe
  (EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text)
forall a. Maybe a
Nothing,
                             connPutManySql :: Maybe (EntityDef -> Int -> Text)
connPutManySql = Maybe (EntityDef -> Int -> Text)
forall a. Maybe a
Nothing,
                             connStmtMap :: IORef (Map Text Statement)
connStmtMap = IORef (Map Text Statement)
smap,
                             connClose :: IO ()
connClose = IO ()
forall a. HasCallStack => a
undefined,
                             connMigrateSql :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
connMigrateSql = [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
mockMigrate,
                             connBegin :: (Text -> IO Statement) -> Maybe IsolationLevel -> IO ()
connBegin = (Text -> IO Statement) -> Maybe IsolationLevel -> IO ()
forall a. HasCallStack => a
undefined,
                             connCommit :: (Text -> IO Statement) -> IO ()
connCommit = (Text -> IO Statement) -> IO ()
forall a. HasCallStack => a
undefined,
                             connRollback :: (Text -> IO Statement) -> IO ()
connRollback = (Text -> IO Statement) -> IO ()
forall a. HasCallStack => a
undefined,
                             connEscapeFieldName :: FieldNameDB -> Text
connEscapeFieldName = FieldNameDB -> Text
escapeF,
                             connEscapeTableName :: EntityDef -> Text
connEscapeTableName = EntityNameDB -> Text
escapeE (EntityNameDB -> Text)
-> (EntityDef -> EntityNameDB) -> EntityDef -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> EntityNameDB
entityDB,
                             connEscapeRawName :: Text -> Text
connEscapeRawName = Text -> Text
escape,
                             connNoLimit :: Text
connNoLimit = Text
forall a. HasCallStack => a
undefined,
                             connRDBMS :: Text
connRDBMS = Text
forall a. HasCallStack => a
undefined,
                             connLimitOffset :: (Int, Int) -> Bool -> Text -> Text
connLimitOffset = (Int, Int) -> Bool -> Text -> Text
forall a. HasCallStack => a
undefined,
                             connLogFunc :: LogFunc
connLogFunc = LogFunc
forall a. HasCallStack => a
undefined,
                             connMaxParams :: Maybe Int
connMaxParams = Maybe Int
forall a. Maybe a
Nothing,
                             connRepsertManySql :: Maybe (EntityDef -> Int -> Text)
connRepsertManySql = Maybe (EntityDef -> Int -> Text)
forall a. Maybe a
Nothing
                             }
      result :: SqlBackend -> IO (((), [Text]), [(Bool, Text)])
result = ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
-> SqlBackend -> IO (((), [Text]), [(Bool, Text)])
forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
runReaderT (ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
 -> SqlBackend -> IO (((), [Text]), [(Bool, Text)]))
-> ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
-> SqlBackend
-> IO (((), [Text]), [(Bool, Text)])
forall a b. (a -> b) -> a -> b
$ WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
-> ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
forall w (m :: * -> *) a. WriterT w m a -> m (a, w)
runWriterT (WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
 -> ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)]))
-> WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
-> ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
forall a b. (a -> b) -> a -> b
$ Migration
-> WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
forall w (m :: * -> *) a. WriterT w m a -> m (a, w)
runWriterT Migration
mig
  (((), [Text]), [(Bool, Text)])
resp <- SqlBackend -> IO (((), [Text]), [(Bool, Text)])
result SqlBackend
sqlbackend
  (Text -> IO ()) -> [Text] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Text -> IO ()
T.putStrLn ([Text] -> IO ()) -> [Text] -> IO ()
forall a b. (a -> b) -> a -> b
$ ((Bool, Text) -> Text) -> [(Bool, Text)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Bool, Text) -> Text
forall a b. (a, b) -> b
snd ([(Bool, Text)] -> [Text]) -> [(Bool, Text)] -> [Text]
forall a b. (a -> b) -> a -> b
$ (((), [Text]), [(Bool, Text)]) -> [(Bool, Text)]
forall a b. (a, b) -> b
snd (((), [Text]), [(Bool, Text)])
resp

putManySql :: EntityDef -> Int -> Text
putManySql :: EntityDef -> Int -> Text
putManySql EntityDef
ent Int
n = [Text] -> [FieldDef] -> EntityDef -> Int -> Text
putManySql' [Text]
conflictColumns [FieldDef]
fields EntityDef
ent Int
n
  where
    fields :: [FieldDef]
fields = EntityDef -> [FieldDef]
entityFields EntityDef
ent
    conflictColumns :: [Text]
conflictColumns = (UniqueDef -> [Text]) -> [UniqueDef] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (((FieldNameHS, FieldNameDB) -> Text)
-> [(FieldNameHS, FieldNameDB)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (FieldNameDB -> Text
escapeF (FieldNameDB -> Text)
-> ((FieldNameHS, FieldNameDB) -> FieldNameDB)
-> (FieldNameHS, FieldNameDB)
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FieldNameHS, FieldNameDB) -> FieldNameDB
forall a b. (a, b) -> b
snd) ([(FieldNameHS, FieldNameDB)] -> [Text])
-> (UniqueDef -> [(FieldNameHS, FieldNameDB)])
-> UniqueDef
-> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UniqueDef -> [(FieldNameHS, FieldNameDB)]
uniqueFields) (EntityDef -> [UniqueDef]
entityUniques EntityDef
ent)

repsertManySql :: EntityDef -> Int -> Text
repsertManySql :: EntityDef -> Int -> Text
repsertManySql EntityDef
ent Int
n = [Text] -> [FieldDef] -> EntityDef -> Int -> Text
putManySql' [Text]
conflictColumns [FieldDef]
fields EntityDef
ent Int
n
  where
    fields :: [FieldDef]
fields = EntityDef -> [FieldDef]
keyAndEntityFields EntityDef
ent
    conflictColumns :: [Text]
conflictColumns = FieldNameDB -> Text
escapeF (FieldNameDB -> Text)
-> (FieldDef -> FieldNameDB) -> FieldDef -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> FieldNameDB
fieldDB (FieldDef -> Text) -> [FieldDef] -> [Text]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> EntityDef -> [FieldDef]
entityKeyFields EntityDef
ent

putManySql' :: [Text] -> [FieldDef] -> EntityDef -> Int -> Text
putManySql' :: [Text] -> [FieldDef] -> EntityDef -> Int -> Text
putManySql' [Text]
conflictColumns ((FieldDef -> Bool) -> [FieldDef] -> [FieldDef]
forall a. (a -> Bool) -> [a] -> [a]
filter FieldDef -> Bool
isFieldNotGenerated -> [FieldDef]
fields) EntityDef
ent Int
n = Text
q
  where
    fieldDbToText :: FieldDef -> Text
fieldDbToText = FieldNameDB -> Text
escapeF (FieldNameDB -> Text)
-> (FieldDef -> FieldNameDB) -> FieldDef -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> FieldNameDB
fieldDB
    mkAssignment :: Text -> Text
mkAssignment Text
f = [Text] -> Text
T.concat [Text
f, Text
"=EXCLUDED.", Text
f]

    table :: Text
table = EntityNameDB -> Text
escapeE (EntityNameDB -> Text)
-> (EntityDef -> EntityNameDB) -> EntityDef -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EntityDef -> EntityNameDB
entityDB (EntityDef -> Text) -> EntityDef -> Text
forall a b. (a -> b) -> a -> b
$ EntityDef
ent
    columns :: Text
columns = [Text] -> Text
Util.commaSeparated ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (FieldDef -> Text) -> [FieldDef] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map FieldDef -> Text
fieldDbToText [FieldDef]
fields
    placeholders :: [Text]
placeholders = (FieldDef -> Text) -> [FieldDef] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> FieldDef -> Text
forall a b. a -> b -> a
const Text
"?") [FieldDef]
fields
    updates :: [Text]
updates = (FieldDef -> Text) -> [FieldDef] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Text
mkAssignment (Text -> Text) -> (FieldDef -> Text) -> FieldDef -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldDef -> Text
fieldDbToText) [FieldDef]
fields

    q :: Text
q = [Text] -> Text
T.concat
        [ Text
"INSERT INTO "
        , Text
table
        , Text -> Text
Util.parenWrapped Text
columns
        , Text
" VALUES "
        , [Text] -> Text
Util.commaSeparated ([Text] -> Text) -> ([Text] -> [Text]) -> [Text] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Text -> [Text]
forall a. Int -> a -> [a]
replicate Int
n
            (Text -> [Text]) -> ([Text] -> Text) -> [Text] -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
Util.parenWrapped (Text -> Text) -> ([Text] -> Text) -> [Text] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Text
Util.commaSeparated ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ [Text]
placeholders
        , Text
" ON CONFLICT "
        , Text -> Text
Util.parenWrapped (Text -> Text) -> ([Text] -> Text) -> [Text] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Text
Util.commaSeparated ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ [Text]
conflictColumns
        , Text
" DO UPDATE SET "
        , [Text] -> Text
Util.commaSeparated [Text]
updates
        ]


-- | Enable a Postgres extension. See https://www.postgresql.org/docs/current/static/contrib.html
-- for a list.
migrateEnableExtension :: Text -> Migration
migrateEnableExtension :: Text -> Migration
migrateEnableExtension Text
extName = WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
-> Migration
forall w (m :: * -> *) a. m (a, w) -> WriterT w m a
WriterT (WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
 -> Migration)
-> WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
-> Migration
forall a b. (a -> b) -> a -> b
$ ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
-> WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
forall w (m :: * -> *) a. m (a, w) -> WriterT w m a
WriterT (ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
 -> WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text]))
-> ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
-> WriterT [(Bool, Text)] (ReaderT SqlBackend IO) ((), [Text])
forall a b. (a -> b) -> a -> b
$ do
  [Single Int]
res :: [Single Int] <-
    Text -> [PersistValue] -> ReaderT SqlBackend IO [Single Int]
forall a (m :: * -> *) backend.
(RawSql a, MonadIO m, BackendCompatible SqlBackend backend) =>
Text -> [PersistValue] -> ReaderT backend m [a]
rawSql Text
"SELECT COUNT(*) FROM pg_catalog.pg_extension WHERE extname = ?" [Text -> PersistValue
PersistText Text
extName]
  if [Single Int]
res [Single Int] -> [Single Int] -> Bool
forall a. Eq a => a -> a -> Bool
== [Int -> Single Int
forall a. a -> Single a
Single Int
0]
    then (((), [Text]), [(Bool, Text)])
-> ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
forall (m :: * -> *) a. Monad m => a -> m a
return (((), []) , [(Bool
False, Text
"CREATe EXTENSION \"" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
extName Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\"")])
    else (((), [Text]), [(Bool, Text)])
-> ReaderT SqlBackend IO (((), [Text]), [(Bool, Text)])
forall (m :: * -> *) a. Monad m => a -> m a
return (((), []), [])

postgresMkColumns :: [EntityDef] -> EntityDef -> ([Column], [UniqueDef], [ForeignDef])
postgresMkColumns :: [EntityDef] -> EntityDef -> ([Column], [UniqueDef], [ForeignDef])
postgresMkColumns [EntityDef]
allDefs EntityDef
t =
    [EntityDef]
-> EntityDef
-> BackendSpecificOverrides
-> ([Column], [UniqueDef], [ForeignDef])
mkColumns [EntityDef]
allDefs EntityDef
t (BackendSpecificOverrides
emptyBackendSpecificOverrides
        { backendSpecificForeignKeyName :: Maybe (EntityNameDB -> FieldNameDB -> ConstraintNameDB)
backendSpecificForeignKeyName = (EntityNameDB -> FieldNameDB -> ConstraintNameDB)
-> Maybe (EntityNameDB -> FieldNameDB -> ConstraintNameDB)
forall a. a -> Maybe a
Just EntityNameDB -> FieldNameDB -> ConstraintNameDB
refName
        }
    )