[web-devel] [Yesod] how to write PersistFIeld instance?

Max Cantor mxcantor at gmail.com
Thu Feb 3 19:40:44 CET 2011


A more general and far more efficient way is to use the Serialize typeclass in the Cereal (http://hackage.haskell.org/package/cereal) instead of read/show for [un]marshalling.  You can use makeSerialize (i think) TH in the Data.Derive package to automatically derive instances for Serialize.  

Finally, the PersistField instance declaration for any instance of Serialize is pretty straight forward:

instance PersistField SurveyQuestionList where
  toPersistValue (SurveyQuestionList l) = PersistByteString $ Cereal.encode l
  fromPersistValue (PersistByteString b) = fmap SurveyQuestionList $ Cereal.decode b
  fromPersistValue _ = Left "bad type for survey question list"
  sqlType _ = SqlBlob
  isNullable _ = False

mc

On Feb 4, 2011, at 1:14 AM, Michael Snoyman wrote:

> On Thu, Feb 3, 2011 at 6:34 PM, Katsutoshi Itoh <cutsea110 at gmail.com> wrote:
>> I'd like to introduce serializable data type like this:
>> 
>> data Role = Teacher | Student
>>                   deriving (Read, Show, Eq, Ord)
>> 
>> share2 mkPersist (mkMigrate "migrateAll") [$persist|
>> User
>>         ident String
>>         :
>>         :
>>         role Role Maybe Update
>>         :
>> |]
>> 
>> instance PersistField Role where
>>       ???
>>      Would you teach me how to write this instance?
> 
> Check out the Haskellers codebase[1]: Persistent includes a TH
> function called derivePersistField[2] which does this automatically
> for you based on Show/Read instances. I personally find this the best
> approach to the problem. It's more efficient to serialize to integers
> (and you could use an Enum instance for that), but it's less
> future-proof.
> 
> Michael
> 
> [1] https://github.com/snoyberg/haskellers/blob/master/Model.hs
> [2] http://hackage.haskell.org/packages/archive/persistent/0.3.1.3/doc/html/Database-Persist-TH.html#v:derivePersistField
> 
> _______________________________________________
> web-devel mailing list
> web-devel at haskell.org
> http://www.haskell.org/mailman/listinfo/web-devel




More information about the web-devel mailing list