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

Michael Snoyman michael at snoyman.com
Thu Feb 3 19:44:46 CET 2011


That's a good idea. I'm not sure if it will really be more efficient
for simple enumeration types, but it would make sense to include some
helper code in Persistent. Anyone feel like writing a patch, or at
least opening a Github issue so I don't forget?

Michael

On Thu, Feb 3, 2011 at 8:40 PM, Max Cantor <mxcantor at gmail.com> wrote:
> 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