{-# LANGUAGE DuplicateRecordFields #-}
module PostgREST.Request.Types
  ( Alias
  , Depth
  , EmbedParam(..)
  , EmbedPath
  , Field
  , Filter(..)
  , Hint
  , CallQuery(..)
  , CallParams(..)
  , CallRequest
  , JoinCondition(..)
  , JoinType(..)
  , JsonOperand(..)
  , JsonOperation(..)
  , JsonPath
  , ListVal
  , LogicOperator(..)
  , LogicTree(..)
  , MutateQuery(..)
  , MutateRequest
  , NodeName
  , OpExpr(..)
  , Operation (..)
  , OrderDirection(..)
  , OrderNulls(..)
  , OrderTerm(..)
  , ReadNode
  , ReadQuery(..)
  , ReadRequest
  , SelectItem
  , SingleVal
  , TrileanVal(..)
  , fstFieldNames
  ) where

import qualified Data.ByteString.Lazy as LBS
import qualified Data.Set             as S

import Data.Tree (Tree (..))

import PostgREST.DbStructure.Identifiers  (FieldName,
                                           QualifiedIdentifier)
import PostgREST.DbStructure.Proc         (ProcParam (..))
import PostgREST.DbStructure.Relationship (Relationship)
import PostgREST.RangeQuery               (NonnegRange)
import PostgREST.Request.Preferences      (PreferResolution)

import Protolude


type ReadRequest = Tree ReadNode
type MutateRequest = MutateQuery
type CallRequest = CallQuery

type ReadNode =
  (ReadQuery, (NodeName, Maybe Relationship, Maybe Alias, Maybe Hint, Maybe JoinType, Depth))

type NodeName = Text
type Depth = Integer

data ReadQuery = Select
  { ReadQuery -> [SelectItem]
select         :: [SelectItem]
  , ReadQuery -> QualifiedIdentifier
from           :: QualifiedIdentifier
  -- ^ A table alias is used in case of self joins
  , ReadQuery -> Maybe Alias
fromAlias      :: Maybe Alias
  -- ^ Only used for Many to Many joins. Parent and Child joins use explicit joins.
  , ReadQuery -> [QualifiedIdentifier]
implicitJoins  :: [QualifiedIdentifier]
  , ReadQuery -> [LogicTree]
where_         :: [LogicTree]
  , ReadQuery -> [JoinCondition]
joinConditions :: [JoinCondition]
  , ReadQuery -> [OrderTerm]
order          :: [OrderTerm]
  , ReadQuery -> NonnegRange
range_         :: NonnegRange
  }
  deriving (ReadQuery -> ReadQuery -> Bool
(ReadQuery -> ReadQuery -> Bool)
-> (ReadQuery -> ReadQuery -> Bool) -> Eq ReadQuery
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: ReadQuery -> ReadQuery -> Bool
$c/= :: ReadQuery -> ReadQuery -> Bool
== :: ReadQuery -> ReadQuery -> Bool
$c== :: ReadQuery -> ReadQuery -> Bool
Eq)

data JoinCondition =
  JoinCondition
    (QualifiedIdentifier, FieldName)
    (QualifiedIdentifier, FieldName)
  deriving (JoinCondition -> JoinCondition -> Bool
(JoinCondition -> JoinCondition -> Bool)
-> (JoinCondition -> JoinCondition -> Bool) -> Eq JoinCondition
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: JoinCondition -> JoinCondition -> Bool
$c/= :: JoinCondition -> JoinCondition -> Bool
== :: JoinCondition -> JoinCondition -> Bool
$c== :: JoinCondition -> JoinCondition -> Bool
Eq)

data OrderTerm = OrderTerm
  { OrderTerm -> Field
otTerm      :: Field
  , OrderTerm -> Maybe OrderDirection
otDirection :: Maybe OrderDirection
  , OrderTerm -> Maybe OrderNulls
otNullOrder :: Maybe OrderNulls
  }
  deriving (OrderTerm -> OrderTerm -> Bool
(OrderTerm -> OrderTerm -> Bool)
-> (OrderTerm -> OrderTerm -> Bool) -> Eq OrderTerm
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: OrderTerm -> OrderTerm -> Bool
$c/= :: OrderTerm -> OrderTerm -> Bool
== :: OrderTerm -> OrderTerm -> Bool
$c== :: OrderTerm -> OrderTerm -> Bool
Eq)

data OrderDirection
  = OrderAsc
  | OrderDesc
  deriving (OrderDirection -> OrderDirection -> Bool
(OrderDirection -> OrderDirection -> Bool)
-> (OrderDirection -> OrderDirection -> Bool) -> Eq OrderDirection
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: OrderDirection -> OrderDirection -> Bool
$c/= :: OrderDirection -> OrderDirection -> Bool
== :: OrderDirection -> OrderDirection -> Bool
$c== :: OrderDirection -> OrderDirection -> Bool
Eq)

data OrderNulls
  = OrderNullsFirst
  | OrderNullsLast
  deriving (OrderNulls -> OrderNulls -> Bool
(OrderNulls -> OrderNulls -> Bool)
-> (OrderNulls -> OrderNulls -> Bool) -> Eq OrderNulls
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: OrderNulls -> OrderNulls -> Bool
$c/= :: OrderNulls -> OrderNulls -> Bool
== :: OrderNulls -> OrderNulls -> Bool
$c== :: OrderNulls -> OrderNulls -> Bool
Eq)

data MutateQuery
  = Insert
      { MutateQuery -> QualifiedIdentifier
in_        :: QualifiedIdentifier
      , MutateQuery -> Set Alias
insCols    :: S.Set FieldName
      , MutateQuery -> Maybe ByteString
insBody    :: Maybe LBS.ByteString
      , MutateQuery -> Maybe (PreferResolution, [Alias])
onConflict :: Maybe (PreferResolution, [FieldName])
      , MutateQuery -> [LogicTree]
where_     :: [LogicTree]
      , MutateQuery -> [Alias]
returning  :: [FieldName]
      }
  | Update
      { in_       :: QualifiedIdentifier
      , MutateQuery -> Set Alias
updCols   :: S.Set FieldName
      , MutateQuery -> Maybe ByteString
updBody   :: Maybe LBS.ByteString
      , where_    :: [LogicTree]
      , returning :: [FieldName]
      }
  | Delete
      { in_       :: QualifiedIdentifier
      , where_    :: [LogicTree]
      , returning :: [FieldName]
      }

data CallQuery = FunctionCall
  { CallQuery -> QualifiedIdentifier
funCQi           :: QualifiedIdentifier
  , CallQuery -> CallParams
funCParams       :: CallParams
  , CallQuery -> Maybe ByteString
funCArgs         :: Maybe LBS.ByteString
  , CallQuery -> Bool
funCScalar       :: Bool
  , CallQuery -> Bool
funCMultipleCall :: Bool
  , CallQuery -> [Alias]
funCReturning    :: [FieldName]
  }

data CallParams
  = KeyParams [ProcParam] -- ^ Call with key params: func(a := val1, b:= val2)
  | OnePosParam ProcParam -- ^ Call with positional params(only one supported): func(val)

-- | The select value in `/tbl?select=alias:field::cast`
type SelectItem = (Field, Maybe Cast, Maybe Alias, Maybe Hint, Maybe JoinType)

type Field = (FieldName, JsonPath)
type Cast = Text
type Alias = Text
type Hint = Text

data EmbedParam
  -- | Disambiguates an embedding operation when there's multiple relationships
  -- between two tables. Can be the name of a foreign key constraint, column
  -- name or the junction in an m2m relationship.
  = EPHint Hint
  | EPJoinType JoinType

data JoinType
  = JTInner
  | JTLeft
  deriving JoinType -> JoinType -> Bool
(JoinType -> JoinType -> Bool)
-> (JoinType -> JoinType -> Bool) -> Eq JoinType
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: JoinType -> JoinType -> Bool
$c/= :: JoinType -> JoinType -> Bool
== :: JoinType -> JoinType -> Bool
$c== :: JoinType -> JoinType -> Bool
Eq

-- | Path of the embedded levels, e.g "clients.projects.name=eq.." gives Path
-- ["clients", "projects"]
type EmbedPath = [Text]

-- | Json path operations as specified in
-- https://www.postgresql.org/docs/current/static/functions-json.html
type JsonPath = [JsonOperation]

-- | Represents the single arrow `->` or double arrow `->>` operators
data JsonOperation
  = JArrow { JsonOperation -> JsonOperand
jOp :: JsonOperand }
  | J2Arrow { jOp :: JsonOperand }
  deriving (JsonOperation -> JsonOperation -> Bool
(JsonOperation -> JsonOperation -> Bool)
-> (JsonOperation -> JsonOperation -> Bool) -> Eq JsonOperation
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: JsonOperation -> JsonOperation -> Bool
$c/= :: JsonOperation -> JsonOperation -> Bool
== :: JsonOperation -> JsonOperation -> Bool
$c== :: JsonOperation -> JsonOperation -> Bool
Eq)

-- | Represents the key(`->'key'`) or index(`->'1`::int`), the index is Text
-- because we reuse our escaping functons and let pg do the casting with
-- '1'::int
data JsonOperand
  = JKey { JsonOperand -> Alias
jVal :: Text }
  | JIdx { jVal :: Text }
  deriving (JsonOperand -> JsonOperand -> Bool
(JsonOperand -> JsonOperand -> Bool)
-> (JsonOperand -> JsonOperand -> Bool) -> Eq JsonOperand
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: JsonOperand -> JsonOperand -> Bool
$c/= :: JsonOperand -> JsonOperand -> Bool
== :: JsonOperand -> JsonOperand -> Bool
$c== :: JsonOperand -> JsonOperand -> Bool
Eq)

-- First level FieldNames(e.g get a,b from /table?select=a,b,other(c,d))
fstFieldNames :: ReadRequest -> [FieldName]
fstFieldNames :: ReadRequest -> [Alias]
fstFieldNames (Node (ReadQuery
sel, (Alias, Maybe Relationship, Maybe Alias, Maybe Alias,
 Maybe JoinType, Depth)
_) [ReadRequest]
_) =
  Field -> Alias
forall a b. (a, b) -> a
fst (Field -> Alias) -> (SelectItem -> Field) -> SelectItem -> Alias
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (\(Field
f, Maybe Alias
_, Maybe Alias
_, Maybe Alias
_, Maybe JoinType
_) -> Field
f) (SelectItem -> Alias) -> [SelectItem] -> [Alias]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ReadQuery -> [SelectItem]
select ReadQuery
sel


-- | Boolean logic expression tree e.g. "and(name.eq.N,or(id.eq.1,id.eq.2))" is:
--
--            And
--           /   \
--  name.eq.N     Or
--               /  \
--         id.eq.1   id.eq.2
data LogicTree
  = Expr Bool LogicOperator [LogicTree]
  | Stmnt Filter
  deriving (LogicTree -> LogicTree -> Bool
(LogicTree -> LogicTree -> Bool)
-> (LogicTree -> LogicTree -> Bool) -> Eq LogicTree
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: LogicTree -> LogicTree -> Bool
$c/= :: LogicTree -> LogicTree -> Bool
== :: LogicTree -> LogicTree -> Bool
$c== :: LogicTree -> LogicTree -> Bool
Eq)

data LogicOperator
  = And
  | Or
  deriving LogicOperator -> LogicOperator -> Bool
(LogicOperator -> LogicOperator -> Bool)
-> (LogicOperator -> LogicOperator -> Bool) -> Eq LogicOperator
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: LogicOperator -> LogicOperator -> Bool
$c/= :: LogicOperator -> LogicOperator -> Bool
== :: LogicOperator -> LogicOperator -> Bool
$c== :: LogicOperator -> LogicOperator -> Bool
Eq

data Filter = Filter
  { Filter -> Field
field  :: Field
  , Filter -> OpExpr
opExpr :: OpExpr
  }
  deriving (Filter -> Filter -> Bool
(Filter -> Filter -> Bool)
-> (Filter -> Filter -> Bool) -> Eq Filter
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Filter -> Filter -> Bool
$c/= :: Filter -> Filter -> Bool
== :: Filter -> Filter -> Bool
$c== :: Filter -> Filter -> Bool
Eq)

data OpExpr =
  OpExpr Bool Operation
  deriving (OpExpr -> OpExpr -> Bool
(OpExpr -> OpExpr -> Bool)
-> (OpExpr -> OpExpr -> Bool) -> Eq OpExpr
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: OpExpr -> OpExpr -> Bool
$c/= :: OpExpr -> OpExpr -> Bool
== :: OpExpr -> OpExpr -> Bool
$c== :: OpExpr -> OpExpr -> Bool
Eq)

data Operation
  = Op Operator SingleVal
  | In ListVal
  | Is TrileanVal
  | Fts Operator (Maybe Language) SingleVal
  deriving (Operation -> Operation -> Bool
(Operation -> Operation -> Bool)
-> (Operation -> Operation -> Bool) -> Eq Operation
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Operation -> Operation -> Bool
$c/= :: Operation -> Operation -> Bool
== :: Operation -> Operation -> Bool
$c== :: Operation -> Operation -> Bool
Eq)

type Operator = Text
type Language = Text

-- | Represents a single value in a filter, e.g. id=eq.singleval
type SingleVal = Text

-- | Represents a list value in a filter, e.g. id=in.(val1,val2,val3)
type ListVal = [Text]

-- | Three-valued logic values
data TrileanVal
  = TriTrue
  | TriFalse
  | TriNull
  | TriUnknown
  deriving TrileanVal -> TrileanVal -> Bool
(TrileanVal -> TrileanVal -> Bool)
-> (TrileanVal -> TrileanVal -> Bool) -> Eq TrileanVal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: TrileanVal -> TrileanVal -> Bool
$c/= :: TrileanVal -> TrileanVal -> Bool
== :: TrileanVal -> TrileanVal -> Bool
$c== :: TrileanVal -> TrileanVal -> Bool
Eq