module Utils.Persist
  ( fromPersistValueError
  , fromPersistValueErrorSql
  ) where

import ClassyPrelude

import Database.Persist
import Database.Persist.Sql
import Data.Proxy
import Type.Reflection (typeRep)


fromPersistValueError :: Text -- ^ Haskell type
                      -> Text -- ^ Database type
                      -> PersistValue -- ^ Incorrect value
                      -> Text -- ^ Error Message
fromPersistValueError hType dbType received = mconcat
  [ "Failed to parse Haskell type `"
  , hType
  , "`; expected "
  , dbType
  , " from database, but received: "
  , tshow received
  , "."
  ]

fromPersistValueErrorSql :: forall p a.
                            ( PersistFieldSql a
                            , Typeable a
                            )
                         => p a
                         -> PersistValue
                         -> Text
fromPersistValueErrorSql _ = fromPersistValueError (tshow $ typeRep @a) (tshow $ sqlType (Proxy @a))
