[web-devel] [Yesod] how to write PersistFIeld instance?
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?
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
> 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|
>>> ident String
>>> role Role Maybe Update
>>> instance PersistField Role where
>>> Would you teach me how to write this instance?
>> Check out the Haskellers codebase: Persistent includes a TH
>> function called derivePersistField 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
>>  https://github.com/snoyberg/haskellers/blob/master/Model.hs
>>  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
More information about the web-devel