[Haskell-cafe] Re: functional database queries

apfelmus at quantentunnel.de apfelmus at quantentunnel.de
Wed Feb 21 13:58:23 EST 2007

Henning Thielemann wrote:
> At
>  http://www.haskell.org/hawiki/HaskellDbTutorial
>   it is described, how database queries can be modelled with a monad.
> However, I wonder if this is also possible without monads. Say, writing
> "DB.map col1 $ DB.filter (\row -> col2 row == 10+2) myTable"
> for
> "SELECT col1 FROM MyTable where col2 = 10+2"

Judging from the papers mentioned in the Haddocks, the monad is used
like a list comprehension. This way, joins can be expressed as

   query = do
       x <- table languages
       y <- table programmers
       restrict (language ! paradigm .==. constant PurelyFunctional)

Seems to be the main reason for a monadic interface.

Of course, the query is compiled to SQL, so filter or its monadic
equivalent cannot use arbitrary functions. This is prevented by giving x
and y opaque types so that the programmer cannot really access them. I
think this is why the monad feels a bit ill, i.e. despite the monad,
subsequent actions cannot depend on the contents of x and y (because
this contents is just a dummy).

Albert Y. C. Lai wrote:
> If and only if the database is a purely functional immutable data
> structure, this can be done. [...]
> Many interesting databases are not purely functional immutable; most
> reside in the external world and can spontaneously change behind your
> program's back.

I don't think this is the problem because SQL requests are emitted
atomically anyway. The (Query a) monad here has nothing to do with
mutability of the data base.


More information about the Haskell-Cafe mailing list