2015-12-29 17:11:15 +05:30
|
|
|
module Ringo.Generator.Create (tableDefnSQL, factTableDefnSQL) where
|
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
#if MIN_VERSION_base(4,8,0)
|
|
|
|
#else
|
|
|
|
import Control.Applicative ((<$>))
|
|
|
|
#endif
|
|
|
|
|
2015-12-29 17:11:15 +05:30
|
|
|
import Control.Monad.Reader (Reader, asks)
|
|
|
|
import Data.Monoid ((<>))
|
|
|
|
import Data.Text (Text)
|
|
|
|
|
|
|
|
import Ringo.Extractor.Internal
|
|
|
|
import Ringo.Generator.Internal
|
|
|
|
import Ringo.Types
|
|
|
|
import Ringo.Utils
|
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
tableDefnSQL :: Table -> Reader Env [Text]
|
|
|
|
tableDefnSQL Table {..} = do
|
|
|
|
Settings {..} <- asks envSettings
|
|
|
|
let tabName = tableName <> settingTableNameSuffixTemplate
|
|
|
|
|
|
|
|
tableSQL = "CREATE TABLE " <> tabName <> " (\n"
|
|
|
|
<> (joinColumnNames . map columnDefnSQL $ tableColumns)
|
|
|
|
<> "\n)"
|
2015-12-30 12:21:41 +05:30
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
columnDefnSQL Column {..} =
|
|
|
|
columnName <> " " <> columnType <> " " <> nullableDefnSQL columnNullable
|
2015-12-29 17:11:15 +05:30
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
nullableDefnSQL Null = "NULL"
|
|
|
|
nullableDefnSQL NotNull = "NOT NULL"
|
2015-12-29 17:11:15 +05:30
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
constraintDefnSQL constraint =
|
|
|
|
let alterTableSQL = "ALTER TABLE ONLY " <> tabName <> " ADD "
|
|
|
|
in case constraint of
|
|
|
|
PrimaryKey cName -> [ alterTableSQL <> "PRIMARY KEY (" <> cName <> ")" ]
|
|
|
|
ForeignKey oTableName cNamePairs ->
|
|
|
|
[ alterTableSQL <> "FOREIGN KEY (" <> joinColumnNames (map fst cNamePairs) <> ") REFERENCES "
|
|
|
|
<> oTableName <> " (" <> joinColumnNames (map snd cNamePairs) <> ")" ]
|
|
|
|
UniqueKey cNames -> ["CREATE UNIQUE INDEX ON " <> tabName <> " (" <> joinColumnNames cNames <> ")"]
|
2015-12-29 17:11:15 +05:30
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
return $ tableSQL : concatMap constraintDefnSQL tableConstraints
|
2015-12-29 17:11:15 +05:30
|
|
|
|
|
|
|
factTableDefnSQL :: Fact -> Table -> Reader Env [Text]
|
|
|
|
factTableDefnSQL fact table = do
|
|
|
|
Settings {..} <- asks envSettings
|
|
|
|
allDims <- extractAllDimensionTables fact
|
|
|
|
|
|
|
|
let factCols = forMaybe (factColumns fact) $ \col -> case col of
|
|
|
|
DimTime cName -> Just $ timeUnitColumnName settingDimTableIdColumnName cName settingTimeUnit
|
|
|
|
NoDimId cName -> Just cName
|
|
|
|
_ -> Nothing
|
|
|
|
|
|
|
|
dimCols = [ factDimFKIdColumnName settingDimPrefix settingDimTableIdColumnName tableName
|
|
|
|
| (_, Table {..}) <- allDims ]
|
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
indexSQLs = [ "CREATE INDEX ON " <> tableName table <> settingTableNameSuffixTemplate
|
|
|
|
<> " USING btree (" <> col <> ")"
|
2015-12-29 17:11:15 +05:30
|
|
|
| col <- factCols ++ dimCols ]
|
|
|
|
|
2015-12-30 19:57:38 +05:30
|
|
|
(++ indexSQLs) <$> tableDefnSQL table
|