Store existing data-type with Yesod's Persistent

吃可爱长大的小学妹 提交于 2019-12-03 12:27:39

From: http://www.yesodweb.com/book/persistent

{-# LANGUAGE TemplateHaskell #-}
module Employment where

import Database.Persist.TH

data Employment = Employed | Unemployed | Retired
    deriving (Show, Read, Eq)
derivePersistField "Employment"

The derivePersistField function is the template Haskell magic that makes it work.

Note, you need to do the derivePersistField thing in a separate file to where you do the mkPersist to avoid a TH phase error.

My solution to this problem was to add a new type through Yesod's mkPersist, and manually marshal between those.

config/models:

PlayerEntry
    name Text
    points Int
    created UTCTime default=CURRENT_TIMESTAMP

Marshalling.hs:

fromPlayerEntry :: PlayerEntry -> Player
fromPlayerEntry PlayerEntry {..} = Player { name = playerName
                                          , points = playerPoints
                                          }

createPlayerEntry :: Text -> YesodDB App (Entity PlayerEntry)
createPlayerEntry name = do
    currentTime <- liftIO getCurrentTime
    let player = PlayerEntry { playerName = name
                             , playerPoints = 0
                             , playerCreated = currentTime
                             }
    playerId <- insert player
    return $ Entity playerId player

updatePlayerEntry :: PlayerEntryId -> Player -> YesodDB App ()
updatePlayerEntry playerId Player {..} =
    update playerId [ PlayerName =. name
                    , PlayerPoints =. points
                    ]

One possible advantage is that you can have fields in your table, that are not required in the internal record. In my example, it was useful to attach a creation date to the player. However, this was only used in the web-interface layer, it was never used in the internal game logic, which defined the Player type. However, due to the manual marshalling I could add that field to the same database table nonetheless.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!