module Database.PostgreSQL.PQTypes.Migrate (
createDomain,
createTable,
createTableConstraints
) where
import Control.Monad
import qualified Data.Foldable as F
import Database.PostgreSQL.PQTypes hiding (def)
import Database.PostgreSQL.PQTypes.Checks.Util
import Database.PostgreSQL.PQTypes.Model
import Database.PostgreSQL.PQTypes.SQL.Builder
createDomain :: MonadDB m => Domain -> m ()
createDomain dom@Domain{..} = do
runQuery_ $ sqlCreateDomain dom
F.forM_ domChecks $ runQuery_ . sqlAlterDomain domName . sqlAddCheck
createTable :: MonadDB m => Bool -> Table -> m ()
createTable withConstraints table@Table{..} = do
runQuery_ $ sqlCreateTable tblName
runQuery_ $ sqlAlterTable tblName $ map sqlAddColumn tblColumns
forM_ tblIndexes $ runQuery_ . sqlCreateIndex tblName
when withConstraints $ createTableConstraints table
runQuery_ . sqlInsert "table_versions" $ do
sqlSet "name" (tblNameText table)
sqlSet "version" tblVersion
createTableConstraints :: MonadDB m => Table -> m ()
createTableConstraints Table{..} = when (not $ null addConstraints) $ do
runQuery_ $ sqlAlterTable tblName addConstraints
where
addConstraints = concat [
[sqlAddPK tblName pk | Just pk <- return tblPrimaryKey]
, map sqlAddCheck tblChecks
, map (sqlAddFK tblName) tblForeignKeys
]