Qwertie
Qwertie

Reputation: 6513

Get id from Entity record

I have an Entity record, specifically Entity User and I need to extract the Id which the User has in the database as an Int.

From reading the docs it seems entityKey would be useful here but I'm not quite sure how I would go about getting an Int out.

Upvotes: 1

Views: 541

Answers (1)

Sibi
Sibi

Reputation: 48664

You have to use a combination of fromSqlKey and entityKey. A sample program demonstrating it:

#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package persistent
     --package persistent-sqlite
     --package persistent-template
     --package mtl
-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE EmptyDataDecls             #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE QuasiQuotes                #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeFamilies               #-}
import           Control.Monad.IO.Class  (liftIO, MonadIO)
import Control.Monad.Reader
import           Database.Persist
import           Database.Persist.Sqlite
import           Database.Persist.TH
import Data.Int

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Person
    name String
    age Int Maybe
    deriving Show
|]

insertPerson :: MonadIO m => ReaderT SqlBackend m (Key Person)
insertPerson =  insert $ Person "Michael" $ Just 26

main :: IO ()
main = runSqlite ":memory:" $ do
    runMigration migrateAll
    michaelId <- insertPerson
    (michael :: Entity Person) <- getJustEntity michaelId
    liftIO $ print $ (fromSqlKey . entityKey $ michael :: Int64)

And it's output:

~/g/scripts $ stack persist.hs
Migrating: CREATE TABLE "person"("id" INTEGER PRIMARY KEY,"name" VARCHAR NOT NULL,"age" INTEGER NULL)
1

Upvotes: 1

Related Questions