haskellpostgresql-simple

Simple SQL query results in - "No instance for (FromRow Int) arising from a use of ‘query’"


Trying to do a very simple sql query using the postgresql-simple library.

{-# LANGUAGE OverloadedStrings #-}
module Main where

import           Database.PostgreSQL.Simple

main :: IO ()
main = do
  putStrLn "Hello, Haskell!"

f :: Connection -> IO ()
f conn = do
  xs <- query conn "selct 123" ()
  print (xs :: [Int])

The error:

src/Main.hs:12:9-33: error:
    • No instance for (FromRow Int) arising from a use of ‘query’
    • In a stmt of a 'do' block: xs <- query conn "selct 123" ()
      In the expression:
        do xs <- query conn "selct 123" ()
           print (xs :: [Int])
      In an equation for ‘f’:
          f conn
            = do xs <- query conn "selct 123" ()
                 print (xs :: [Int])

Solution

  • When dealing with single values that would be returned from the query, it is necessary to wrap using the Only datatype. So xs :: [Int] should instead be xs :: [Only Int].

    This is workaround due to this library using tuples to represent the values, which Haskell does not support a tuple with a single element. https://hackage.haskell.org/package/postgresql-simple-0.6.4/docs/Database-PostgreSQL-Simple.html#g:5