Reputation: 699
I have table in haskell database. My 'link_des' table has two columns. I want to view both columns (data only) at the same time. My code is:
printURLs :: IO ()
printURLs = do urls <- getURLs
mapM_ print urls
getURLs :: IO [String]
getURLs = do conn <- connectSqlite3 "database.db"
res <- quickQuery' conn "SELECT * FROM link_des" []
return $ map fromSql (map head res)
With this I am getting first column data like
["col_1_data_1","col_1_data_2", ...]
using 'last' in lieu of 'head' I can get
["col_2_data_1","col_2_data_2", ...]
But I want to get data like
[("col_1_data_1","col_2_data_1"),("col_1_data_2","col_2_data_2"), ...]
which is actually like the pattern [(row_1),(row_2), ...]
Can anyone please help me. Thanks.
Upvotes: 1
Views: 463
Reputation: 12070
If you look at the type signature of quickQuery', you will see that it returns type IO [[SqlValue]]. That means that you already have the data in a form very similar to what you want.... Instead of
[("col_1_data_1","col_2_data_1"),("col_1_data_2","col_2_data_2"), ...]
you have
[["col_1_data_1","col_2_data_1"],["col_1_data_2","col_2_data_2"], ...]
The function you wrote is just pulling out the first column of this using "map head".
You could always write some code to convert a table with a known number of columns and types to the corresponding tuples (using a function like "convert [first, second] = (fromSql first, fromSql second)"), but it is much harder to write something that does this for arbitrary tables with differing number of columns and types. There are two reasons this is so....
a. First, you need to turn a list into a tuple, which isn't possible in Haskell for lists of differing sizes unless you use extensions. The main problem is that each size of tuple is its own type, and a single function can't choose its output type based on the input. You can do some trickery using GHC extensions, but the result is probably more complicated that you probably want to get into.
b. Second, You have to convert each value in the result from SqlValue to the appropriate Haskell type. This is also hard for similar reasons.
You might want to consider another approach altogether.... Take a look at the Yesod persistent database library, which is described at http://www.yesodweb.com/book/persistent. With that you define your schema in a quasiquote, and it creates Haskell records that are completely type safe.
Upvotes: 1