-- | This module contains supporting definitions for building temporary tables
-- based off of the schema of other tables. This is used in mutations to capture
-- the data of rows that are affected.
module Hasura.Backends.MSSQL.FromIr.SelectIntoTempTable
  ( toSelectIntoTempTable,
  )
where

import Hasura.Backends.MSSQL.Instances.Types ()
import Hasura.Backends.MSSQL.Types.Internal as TSQL
import Hasura.Prelude
import Hasura.RQL.Types.BackendType
import Hasura.RQL.Types.Column qualified as IR

-- | Create a temporary table with the same schema as the given table.
toSelectIntoTempTable :: TempTableName -> TableName -> [IR.ColumnInfo 'MSSQL] -> SITTConstraints -> SelectIntoTempTable
toSelectIntoTempTable :: TempTableName
-> TableName
-> [ColumnInfo 'MSSQL]
-> SITTConstraints
-> SelectIntoTempTable
toSelectIntoTempTable TempTableName
tempTableName TableName
fromTable [ColumnInfo 'MSSQL]
allColumns SITTConstraints
withConstraints = do
  SelectIntoTempTable
    { $sel:sittTempTableName:SelectIntoTempTable :: TempTableName
sittTempTableName = TempTableName
tempTableName,
      $sel:sittColumns:SelectIntoTempTable :: [UnifiedColumn]
sittColumns = (ColumnInfo 'MSSQL -> UnifiedColumn)
-> [ColumnInfo 'MSSQL] -> [UnifiedColumn]
forall a b. (a -> b) -> [a] -> [b]
map ColumnInfo 'MSSQL -> UnifiedColumn
columnInfoToUnifiedColumn [ColumnInfo 'MSSQL]
allColumns,
      $sel:sittFromTableName:SelectIntoTempTable :: TableName
sittFromTableName = TableName
fromTable,
      $sel:sittConstraints:SelectIntoTempTable :: SITTConstraints
sittConstraints = SITTConstraints
withConstraints
    }

-- | Extracts the type and column name of a ColumnInfo
columnInfoToUnifiedColumn :: IR.ColumnInfo 'MSSQL -> UnifiedColumn
columnInfoToUnifiedColumn :: ColumnInfo 'MSSQL -> UnifiedColumn
columnInfoToUnifiedColumn ColumnInfo 'MSSQL
colInfo =
  case ColumnInfo 'MSSQL -> ColumnType 'MSSQL
forall (b :: BackendType). ColumnInfo b -> ColumnType b
IR.ciType ColumnInfo 'MSSQL
colInfo of
    IR.ColumnScalar ScalarType 'MSSQL
t ->
      UnifiedColumn
        { $sel:name:UnifiedColumn :: ColumnName
name = ColumnInfo 'MSSQL -> Column 'MSSQL
forall (b :: BackendType). ColumnInfo b -> Column b
IR.ciColumn ColumnInfo 'MSSQL
colInfo,
          $sel:type':UnifiedColumn :: ScalarType
type' = ScalarType 'MSSQL
ScalarType
t
        }
    -- Enum values are represented as text value so they will always be of type text
    IR.ColumnEnumReference {} ->
      UnifiedColumn
        { $sel:name:UnifiedColumn :: ColumnName
name = ColumnInfo 'MSSQL -> Column 'MSSQL
forall (b :: BackendType). ColumnInfo b -> Column b
IR.ciColumn ColumnInfo 'MSSQL
colInfo,
          $sel:type':UnifiedColumn :: ScalarType
type' = ScalarType
TextType
        }