[Haskell-cafe] toSql and fromSql, for Algebraic Data Type
es at ertes.de
Mon Jun 27 19:32:32 CEST 2011
Tom Murphy <amindfv at gmail.com> wrote:
> The title is self-explanatory. I'd like to store information from
> an algebraic data type in an SQL database, but the type signature of
> toSql (toSql
> :: Data.Convertible.Base.Convertible a SqlValue => a -> SqlValue)
> doesn't make sense to me.
> How is this done (how do I make an instance of a typeclass like that?)
My answer is: This is tiring, redundant work. Honestly, don't do it,
if you can avoid it. Rather find a type with a ready-made Convertible
instance, which can represent the values of your type and convert to and
from that one instead.
By the way, if your type is just an enumeration of nullary constructors,
note that most database systems support efficient 'ENUM' types. For
example in PostgreSQL you can do this:
CREATE TYPE server_status AS ENUM(
According to the documentation columns of type "server_status" will use
a compact, efficient 32 bit integer representation, but on the interface
you can work with regular strings, so you can just convert your
algebraic type to and from strings.
Even better, if you don't mind being tied to the particular database
system, you can abstract away such types by using stored procedures.
nightmare = unsafePerformIO (getWrongWife >>= sex)
More information about the Haskell-Cafe