Hacker News new | ask | show | jobs
by rwmj 3698 days ago
10 years ago I wrote a thing called PG'OCaml which integrates OCaml and SQL in a type safe way. You write code like:

    PGSQL(dbh) "insert into employees (name, salary, email)
                values ($name, $salary, $?email)"
and it (at compile time) creates the correct PREPARE+EXECUTE pair and checks types across the languages. (It's not obvious but it is also free of SQL injections.)

For example if your OCaml 'salary' variable was a string but the column is an int then the above program wouldn't compile. If you change the type of the db column after compiling the program then you get a runtime error instead.

Still around although now maintained by a group of authors: http://pgocaml.forge.ocamlcore.org/ (git source: https://github.com/darioteixeira/pgocaml)

It's only possible because OCaml has real macros. It wouldn't be easy to do this in C/C++ (I guess? - maybe with an LLVM-based pre-processing parser or something)

2 comments

This used to be how a lot of SQL code was written. I think it's about as old as SQL itself. See Oracle's Pro*C for instance. It's a C precompiler that generates API calls and optionally does type checking. There's even an ANSI/ISO standard for embedded SQL.
Yep. I used to use the Sybase SQL precompiler in OS/2 with Watcom C++. Nullable columns were a pain because you had to define a separate boolean variable to hold the null status for each one.
Just last night I was thinking about what it would look like to have a language that would type check your SQL strings. Thanks for sharing PG'OCaml!