-- | This module defines the top-level translation functions pertaining to
-- queries that use aggregation (i.e., /not/ so-called "simple" selects) into
-- Postgres AST.
module Hasura.Backends.Postgres.Translate.Select.Aggregate
  ( mkAggregateSelect,
    selectAggregateQuerySQL,
  )
where

import Control.Monad.Writer.Strict (runWriter)
import Database.PG.Query (Query)
import Hasura.Backends.Postgres.SQL.DML (BoolExp (BELit), Select)
import Hasura.Backends.Postgres.SQL.Types (IsIdentifier (toIdentifier))
import Hasura.Backends.Postgres.Translate.Select.AnnotatedFieldJSON
import Hasura.Backends.Postgres.Translate.Select.Internal.GenerateSelect (generateSQLSelectFromArrayNode)
import Hasura.Backends.Postgres.Translate.Select.Internal.Helpers (selectToSelectWith, toQuery)
import Hasura.Backends.Postgres.Translate.Select.Internal.Process (processAnnAggregateSelect)
import Hasura.Backends.Postgres.Translate.Types (CustomSQLCTEs, MultiRowSelectNode (MultiRowSelectNode), SelectNode (SelectNode), SelectWriter (..), SourcePrefixes (SourcePrefixes), initialNativeQueryFreshIdStore)
import Hasura.Prelude
import Hasura.RQL.IR.Select (AnnAggregateSelect, AnnSelectG (_asnStrfyNum))
import Hasura.RQL.Types.Backend (Backend)
import Hasura.RQL.Types.BackendType (BackendType (Postgres))
import Hasura.RQL.Types.Common (FieldName (FieldName))

-- | Translates IR to Postgres queries for aggregated SELECTs.
--
-- See 'mkAggregateSelect' for the Postgres AST.
selectAggregateQuerySQL ::
  forall pgKind.
  (Backend ('Postgres pgKind), PostgresAnnotatedFieldJSON pgKind) =>
  AnnAggregateSelect ('Postgres pgKind) ->
  Query
selectAggregateQuerySQL :: forall (pgKind :: PostgresKind).
(Backend ('Postgres pgKind), PostgresAnnotatedFieldJSON pgKind) =>
AnnAggregateSelect ('Postgres pgKind) -> Query
selectAggregateQuerySQL =
  SelectWithG TopLevelCTE -> Query
toQuery
    (SelectWithG TopLevelCTE -> Query)
-> (AnnAggregateSelectG ('Postgres pgKind) Void SQLExp
    -> SelectWithG TopLevelCTE)
-> AnnAggregateSelectG ('Postgres pgKind) Void SQLExp
-> Query
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Writer CustomSQLCTEs Select -> SelectWithG TopLevelCTE
selectToSelectWith
    (Writer CustomSQLCTEs Select -> SelectWithG TopLevelCTE)
-> (AnnAggregateSelectG ('Postgres pgKind) Void SQLExp
    -> Writer CustomSQLCTEs Select)
-> AnnAggregateSelectG ('Postgres pgKind) Void SQLExp
-> SelectWithG TopLevelCTE
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AnnSelectG
  ('Postgres pgKind)
  (TableAggregateFieldG ('Postgres pgKind) Void)
  (SQLExpression ('Postgres pgKind))
-> Writer CustomSQLCTEs Select
AnnAggregateSelectG ('Postgres pgKind) Void SQLExp
-> Writer CustomSQLCTEs Select
forall (pgKind :: PostgresKind) (m :: * -> *).
(Backend ('Postgres pgKind), PostgresAnnotatedFieldJSON pgKind,
 MonadWriter CustomSQLCTEs m) =>
AnnAggregateSelect ('Postgres pgKind) -> m Select
mkAggregateSelect

-- | We process aggregate queries differently because the types of aggregate queries are different.
--   In the '_asnFields' field of an 'AnnSelectG', we will have a 'TableAggregateFieldG' instead
--   of an 'AnnFieldG'.
mkAggregateSelect ::
  forall pgKind m.
  ( Backend ('Postgres pgKind),
    PostgresAnnotatedFieldJSON pgKind,
    MonadWriter CustomSQLCTEs m
  ) =>
  AnnAggregateSelect ('Postgres pgKind) ->
  m Select
mkAggregateSelect :: forall (pgKind :: PostgresKind) (m :: * -> *).
(Backend ('Postgres pgKind), PostgresAnnotatedFieldJSON pgKind,
 MonadWriter CustomSQLCTEs m) =>
AnnAggregateSelect ('Postgres pgKind) -> m Select
mkAggregateSelect AnnAggregateSelect ('Postgres pgKind)
annAggSel = do
  let ( (SelectSource
selectSource, InsOrdHashMap ColumnAlias SQLExp
nodeExtractors, Extractor
topExtractor),
        SelectWriter {_swJoinTree :: SelectWriter -> JoinTree
_swJoinTree = JoinTree
joinTree, _swCustomSQLCTEs :: SelectWriter -> CustomSQLCTEs
_swCustomSQLCTEs = CustomSQLCTEs
customSQLCTEs}
        ) =
          Writer
  SelectWriter
  (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> ((SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor),
    SelectWriter)
forall w a. Writer w a -> (a, w)
runWriter
            (Writer
   SelectWriter
   (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
 -> ((SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor),
     SelectWriter))
-> Writer
     SelectWriter
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> ((SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor),
    SelectWriter)
forall a b. (a -> b) -> a -> b
$ (ReaderT
   StringifyNumbers
   (WriterT SelectWriter Identity)
   (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
 -> StringifyNumbers
 -> Writer
      SelectWriter
      (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor))
-> StringifyNumbers
-> ReaderT
     StringifyNumbers
     (WriterT SelectWriter Identity)
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> Writer
     SelectWriter
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
forall a b c. (a -> b -> c) -> b -> a -> c
flip ReaderT
  StringifyNumbers
  (WriterT SelectWriter Identity)
  (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> StringifyNumbers
-> Writer
     SelectWriter
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
runReaderT StringifyNumbers
strfyNum
            (ReaderT
   StringifyNumbers
   (WriterT SelectWriter Identity)
   (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
 -> Writer
      SelectWriter
      (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor))
-> ReaderT
     StringifyNumbers
     (WriterT SelectWriter Identity)
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> Writer
     SelectWriter
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
forall a b. (a -> b) -> a -> b
$ (StateT
   NativeQueryFreshIdStore
   (ReaderT StringifyNumbers (WriterT SelectWriter Identity))
   (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
 -> NativeQueryFreshIdStore
 -> ReaderT
      StringifyNumbers
      (WriterT SelectWriter Identity)
      (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor))
-> NativeQueryFreshIdStore
-> StateT
     NativeQueryFreshIdStore
     (ReaderT StringifyNumbers (WriterT SelectWriter Identity))
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> ReaderT
     StringifyNumbers
     (WriterT SelectWriter Identity)
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
forall a b c. (a -> b -> c) -> b -> a -> c
flip StateT
  NativeQueryFreshIdStore
  (ReaderT StringifyNumbers (WriterT SelectWriter Identity))
  (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> NativeQueryFreshIdStore
-> ReaderT
     StringifyNumbers
     (WriterT SelectWriter Identity)
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT NativeQueryFreshIdStore
initialNativeQueryFreshIdStore
            (StateT
   NativeQueryFreshIdStore
   (ReaderT StringifyNumbers (WriterT SelectWriter Identity))
   (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
 -> ReaderT
      StringifyNumbers
      (WriterT SelectWriter Identity)
      (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor))
-> StateT
     NativeQueryFreshIdStore
     (ReaderT StringifyNumbers (WriterT SelectWriter Identity))
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
-> ReaderT
     StringifyNumbers
     (WriterT SelectWriter Identity)
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
forall a b. (a -> b) -> a -> b
$ SourcePrefixes
-> FieldName
-> AnnAggregateSelect ('Postgres pgKind)
-> StateT
     NativeQueryFreshIdStore
     (ReaderT StringifyNumbers (WriterT SelectWriter Identity))
     (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
forall (pgKind :: PostgresKind) (m :: * -> *).
(MonadReader StringifyNumbers m, MonadWriter SelectWriter m,
 MonadState NativeQueryFreshIdStore m, Backend ('Postgres pgKind),
 PostgresAnnotatedFieldJSON pgKind) =>
SourcePrefixes
-> FieldName
-> AnnAggregateSelect ('Postgres pgKind)
-> m (SelectSource, InsOrdHashMap ColumnAlias SQLExp, Extractor)
processAnnAggregateSelect SourcePrefixes
sourcePrefixes FieldName
rootFieldName AnnAggregateSelect ('Postgres pgKind)
annAggSel
      -- select the relevant columns and subquery we want to aggregate
      selectNode :: SelectNode
selectNode = InsOrdHashMap ColumnAlias SQLExp -> JoinTree -> SelectNode
SelectNode InsOrdHashMap ColumnAlias SQLExp
nodeExtractors JoinTree
joinTree
      -- aggregate the results into a top-level return value
      arrayNode :: MultiRowSelectNode
arrayNode = [Extractor] -> SelectNode -> MultiRowSelectNode
MultiRowSelectNode [Extractor
topExtractor] SelectNode
selectNode
  CustomSQLCTEs -> m ()
forall w (m :: * -> *). MonadWriter w m => w -> m ()
tell CustomSQLCTEs
customSQLCTEs

  Select -> m Select
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Select -> m Select) -> Select -> m Select
forall a b. (a -> b) -> a -> b
$ SelectSource -> MultiRowSelectNode -> BoolExp -> Select
generateSQLSelectFromArrayNode SelectSource
selectSource MultiRowSelectNode
arrayNode (BoolExp -> Select) -> BoolExp -> Select
forall a b. (a -> b) -> a -> b
$ Bool -> BoolExp
BELit Bool
True
  where
    strfyNum :: StringifyNumbers
strfyNum = AnnSelectG
  ('Postgres pgKind)
  (TableAggregateFieldG ('Postgres pgKind) Void)
  SQLExp
-> StringifyNumbers
forall (b :: BackendType) (f :: * -> *) v.
AnnSelectG b f v -> StringifyNumbers
_asnStrfyNum AnnAggregateSelect ('Postgres pgKind)
AnnSelectG
  ('Postgres pgKind)
  (TableAggregateFieldG ('Postgres pgKind) Void)
  SQLExp
annAggSel
    rootFieldName :: FieldName
rootFieldName = Text -> FieldName
FieldName Text
"root"
    rootIdentifier :: Identifier
rootIdentifier = FieldName -> Identifier
forall a. IsIdentifier a => a -> Identifier
toIdentifier FieldName
rootFieldName
    sourcePrefixes :: SourcePrefixes
sourcePrefixes = Identifier -> Identifier -> SourcePrefixes
SourcePrefixes Identifier
rootIdentifier Identifier
rootIdentifier