[Takusen] working out how to use bind variables

oleg at okmij.org oleg at okmij.org
Thu Aug 12 21:56:04 EDT 2010

Michael Litchard wrote:

> main :: IO ()
> main = do
> let connection = connect [CAdbname "tutorialDB"]
> ...
> withSession connection (execDML (cmdbind "insert into activities (Activity, Cost) values (?, ?)" [bindP foo, bindP bar]))

> I know this means I need to fix the type, but I don't know how. I've

The short answer: add "return ()" at the end.

The long answer: the statement 
	withSession connection (execDML ...)
is the last statement of the `main' do-block. Therefore, the type of
the statement is the type of the block. From the signature of "main"
we know that the type of the do-block, and hence the type of the last
statement must be "IO ()". That is, the action must yield the unit
value. The expression "withSession connection body" returns the value
yielded by the body. In the error message, the compiler says that the
expression (execDML ... ) has the type ``DBM mark Session Int'' --
that is, it yields an Int, rather than () as we expected.

In my experience, it is quite common for data manipulation statements
(DML) to report the number of affected data base rows (that is, the
number of rows that have been inserted, deleted, modified). Takusen
follows that tradition. So, the DML statement in your code will return
the number of inserted rows. 

Chances are you don't care about that number (since it is clear that
the number must be one). In that case, you can ignore the result of
the DML statement, by making it not the last statement and adding
"return ()", so that the overall type of main will be "IO ()" as

Incidentally, it would be more idiomatic and efficient to write the
code thusly:

  main = do
   let connection = connect [CAdbname "tutorialDB"]
   let foo = "test"
   let bar = 42
   withSession connection $ do
      execDDL (sql ...)
      execDDL (sql ...)
      execDML ...
   return ()

That is, establish connection to the database only once, and use the
connection for doing all the needed operations. Establishing a
connection is typically quite slow on most databases.

More information about the Takusen mailing list