2

I'm having trouble with defining FromField instance for my custom enum data type:

data Role = Staff | Student deriving (Eq, Ord, Show)

To represent Role in my database, I will use ints 0 and 1 (more roles could be added later) most likely smallint.

Review is used in my other data type that represents a row in my db table:

data ReviewAssignment = ReviewAssignment
  { aID :: ID
  , reviewID :: ID
  , reviewerID :: ID
  , revieweeID :: ID
  , reviewerRole :: Role -- <-- right there
  , reviewFinished :: Bool
  , reviewPoints :: Float
  } deriving (Show, Eq)

This is my FromRow instance for ReviewAssignment:

instance FromRow ReviewAssignment where
  fromRow = ReviewAssignment <$> field <*> field <*> field <*> field <*> field <*> field <*> field

Now I'm just missing the following which I don't understand how to implement :

instance FromField Role where
  fromField = undefined
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
Reygoch
  • 1,204
  • 1
  • 11
  • 24

2 Answers2

2

Probably to late but something like this should work (hopefully):

instance FromField Role where
  fromField f mdata =
    return role
    where role = case mdata of
      Just 0 -> Staff   
      _      -> Student
itsu
  • 222
  • 1
  • 10
1

fromField should take an integer (the smallint from your database) and return a Role value. I sugegst you implement it using pattern matching. You can read more about fromField in the documentation. You can also take inspiration from predefined fromField implementations.

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • 1
    I have read the documentation, but I still don't understand it quite clearly so I'm asking here. I do understand the concept, but I don't know how to do it with FromField – Reygoch Jan 21 '16 at 09:45