{-# 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) = Identifier -> Action
forall a. ToField a => a -> Action
toField (Identifier -> Action) -> Identifier -> Action
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) = QualifiedIdentifier -> Action
forall a. ToField a => a -> Action
toField (QualifiedIdentifier -> Action) -> QualifiedIdentifier -> Action
forall a b. (a -> b) -> a -> b
$ Maybe Text -> Text -> QualifiedIdentifier
PST.QualifiedIdentifier (Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
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 = Identifier -> Action
forall a. ToField a => a -> Action
toField (Identifier -> Action) -> Identifier -> Action
forall a b. (a -> b) -> a -> b
$ Text -> Identifier
Identifier (Text -> Identifier) -> Text -> 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