Adding two numbers with Hasql

I am attempting to add two numbers with the Hasql library. I’m unsure of why the types aren’t matching up, and I am wondering if someone is able to assist me.

The sum.hs script:

#!/usr/bin/env cabal
{- cabal:
build-depends:
    base
  , hasql
-}

{-# LANGUAGE OverloadedStrings #-}

import Prelude
import Data.Functor.Contravariant
import Data.Int
import Hasql.Session (Session)
import Hasql.Statement (Statement(..))
import qualified Hasql.Session as Session
import qualified Hasql.Connection as Connection
import qualified Hasql.Encoders as E
import qualified Hasql.Decoders as D

main :: IO ()
main = do
  Right connection <- Connection.acquire connectionSettings
  result <- Session.run (selectSumSession 3 4) connection
  print result where connectionSettings = Connection.settings "localhost" 5432 "postgres" "" "postgres"

selectSumSession :: Int64 -> Int64 -> Session Int64
selectSumSession x y = do
  Session.statement (selectSum x y) selectSum

selectSum :: Statement (Int64, Int64) Int64
selectSum = Statement sql encoder decoder True where
  sql = "select ($1 + $2)"
  encoder =
    (fst >$< E.param (E.nonNullable E.int8)) <>
    (snd >$< E.param (E.nonNullable E.int8))
  decoder = D.singleRow (D.column (D.nonNullable D.int8))

The error received:

# cabal new-run sum.hs
...
Main.hs:27:22: error:
    • Couldn't match expected type ‘Int64 -> Int64 -> (Int64, Int64)’
                  with actual type ‘Statement (Int64, Int64) Int64’
    • The function ‘selectSum’ is applied to two arguments,
      but its type ‘Statement (Int64, Int64) Int64’ has none
      In the first argument of ‘Session.statement’, namely
        ‘(selectSum x y)’
      In a stmt of a 'do' block:
        Session.statement (selectSum x y) selectSum
   |
27 |   Session.statement (selectSum x y) selectSum
   |                      ^^^^^^^^^^^^^```

selectSum is not a function so you can’t pass it arguments. It’s a description of an sql statement that can get arguments. You can supply the arguments using the statement function like this: Session.statement (x, y) selectSum.

Or at least that’s what I gathered from the docs.

2 Likes

Oh right! That seems glaringly obvious when you point it out :smile:

Thanks @gilmi!

2 Likes