Haskell HDBC.Sqlite3 fetchAllRows

103 views Asked by At

Since I am an absolute Haskell beginner, but determined to conquer it, I am asking for help again.

using:

fetchData2 = do
  conn <- connectSqlite3 "dBase.db"
  statement <- prepare conn "SELECT * FROM test WHERE id > 0"
  execute statement []
  results <- fetchAllRows statement
  print results

returns:

[[SqlInt64 3,SqlByteString "Newco"],[SqlInt64 4,SqlByteString "Oldco"],[SqlInt64 5,SqlByteString "Mycom"],[SqlInt64 4,SqlByteString "Oldco"],[SqlInt64 5,SqlByteString "Mycom"]]

Is there a clever way to clean this data into Int and [Char], in other words omitting types SqlInt64 and SqlByteString.

1

There are 1 answers

3
fredefox On BEST ANSWER

You could define a helper:

fetchRowFromSql :: Convertible SqlValue a => Statement -> IO (Maybe [a])
fetchRowFromSql = fmap (fmap (fmap fromSql)) . fetchRow

The implementation looks a bit daunting, but this is just because we need to drill down under the layered functors as you already noted (first IO, then Maybe and lastly []). This returns something that is convertible from a SqlValue. There are a bunch of these defined already. See e.g. the docs. An example (using -XTypeApplications):

fetchRowFromSql @String :: Statement -> IO (Maybe [String])

I should perhaps add that the documentation mentions that fromSql is unsafe. Meaning that if you try to convert a sql value to an incompatible Haskell value the program will halt.