Search code examples
haskellpostgresql-simple

Nested data types in postgresql-simple


Consider following code which can find some set of coordinates:

data Coord = Coord { lat :: Float
                   , lon :: Float
                   }

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

findSomePoints :: Connection -> Int -> IO [Coord]
findSomePoints = undefined

Then I would like to define data type for named set of coordinates:

data Path = Path { name :: String
                 , points :: [Coord]
                 }

instance FromRow Path where
  fromRow = Path
    <$> field
    <*> -- PROBLEM: would like to call something like `findSomePoints conn field` here...

findPath :: Connection -> Int -> IO Path
findPath = undefined

Unfortunatelly, I don't know how to compose data types with queries (in my case Path with Coord). Is something like this even possible (and how?).


Solution

  • I would write a data type and a FromRow instance for each table in the database, and separate the database code from the changing-schema code. PathRow and [Coord] are things you can get directly from the DB. makePath :: PathRow -> [Coord] -> Path, to build the nested structure you want, doesn't need to interact with the database at all. Then findPath can be implemented in terms of these pieces.