{-# LANGUAGE OverloadedStrings #-}
module Database.Peregrin.Metadata
    ( Identifier(..)
    , QIdentifier(..)
    , Schema(..)
    ) where

import           Data.Text (Text)
import           Database.PostgreSQL.Simple.ToField (ToField(..))
import qualified Database.PostgreSQL.Simple.Types as PST

-- | An /unqalified/ identifier of an object in the database, i.e.
-- an identifier without an attached schema.
data Identifier = Identifier Text

instance ToField Identifier where
  toField :: Identifier -> Action
toField (Identifier Text
i) = forall a. ToField a => a -> Action
toField forall a b. (a -> b) -> a -> b
$ Text -> Identifier
PST.Identifier Text
i

-- | A /qualified/ identifier of an object in the database, i.e.
-- an identifier with an attached schema.
data QIdentifier = QIdentifier Schema Text

instance ToField QIdentifier where
  toField :: QIdentifier -> Action
toField (QIdentifier Schema
schema Text
i) = forall a. ToField a => a -> Action
toField forall a b. (a -> b) -> a -> b
$ Maybe Text -> Text -> QualifiedIdentifier
PST.QualifiedIdentifier (forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ Schema -> Text
schemaToText Schema
schema) Text
i

-- | A schema designation.
data Schema = DefaultSchema
            | NamedSchema Text

instance ToField Schema where
  toField :: Schema -> Action
toField Schema
schema = forall a. ToField a => a -> Action
toField forall a b. (a -> b) -> a -> b
$ Text -> Identifier
Identifier forall a b. (a -> b) -> a -> b
$ Schema -> Text
schemaToText Schema
schema

-- | Convert schema to 'Text'.
schemaToText :: Schema -> Text
schemaToText :: Schema -> Text
schemaToText Schema
DefaultSchema = Text
"public"
schemaToText (NamedSchema Text
schemaId) = Text
schemaId