Yesod: Getting a database entity by ID from an Int

非 Y 不嫁゛ 提交于 2019-11-28 20:07:37

Even if the answer can already be found in the comments, I would like to give a complete example.

Assuming we have a Person Model, the following function returns a record for the persion with the given ID (if it exists):

import Database.Persist.Types (PersistValue(PersistInt64))

getByIntId :: Integral i => i -> Handler (Maybe Person)
getByIntId i = runDB $ get $ Key $ PersistInt64 (fromIntegral i)

The import is needed to let us construct the persist-version of an integer. fromIntegral converts any integer to the expected type Int64.

Update: Since Yesod 1.2 PersistValue lives in the module Database.Persist.Types, before 1.2 it was Database.Persist.Store (API Documentation).

Update 2: Since Persistent 2.0.2 there are two build-in functions to convert from/to database keys: toSqlKey and fromSqlKey (API Documentation, see answer by hhefesto for an example).

PersistInt64 is here: Database.Persist.Types.

Previously PersistInt64 was here: Database.Persist.Store.

Just an example of how to use toSqlKey (Persistent 2.0.2)

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Users
    email String
    password String
    alias String
    deriving Show
|]

connStr = "host=localhost dbname=communis_db user=communis password=develpass port=5432"

inBackend :: ReaderT SqlBackend (NoLoggingT (ResourceT IO)) a-> IO a
inBackend action = runStderrLoggingT $ withPostgresqlPool connStr 10 $ \pool -> liftIO $ do
  flip runSqlPersistMPool pool $ do
    runMigration migrateAll
    action

toUserId :: Int64 -> UsersId
toUserId = toSqlKey

get_user :: Int64 -> IO (Maybe Users)
get_user = inBackend . get . toUserId

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