postgresqlhaskellpostgresql-simple

haskell postgresql-simple, how to access specific data from a broader query


How can i access the data that`s in my query [VarcharIntDate] ?

data VarcharIntDate = VarcharIntDate {
  vc :: Maybe String,
  i  :: Maybe Int,
  d  :: Maybe Date
} deriving (Show)

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

I understand how to print it, but I cant do much else with it because I don`t understand how to treat 'IO [VarcharIntDate]'

print =<< ( query_ conn "select vc,i,d from varintdate" :: IO [VarcharIntDate] )

but what I want to do is access 'd' from the n'th row of the returned [VarcharIntDate] or 'i' from all rows, so I can start pulling the data out from the query and start working with it.


Solution

  • You actually already process the result of the IO [VarcharIntDate]. You use =<< with print. This is equivalent to:

    main = do  -- or another function
        result <- query_ conn "select vc,i,d from varintdate" :: IO [VarcharIntDate]
        print result
    

    You can process the result of query_ by performing a mapping, or accessing the n-th element of the row like:

    p = 2  -- sample p
    
    main = do
        res <- query_ conn "select vc,i,d from varintdate" :: IO [VarcharIntDate]
        print (map i res)  -- print all i's
        print (d (res!!p)) -- print d of the p-th row
    

    So here we can use res!!p to access the p-th row, and then call the d getter to obtain the d of that row.

    If you want to obtain all i's you can use map i.