Dennis Dang

June 1, 2025

Proof of Concept: Libsql OCaml client

Code: https://github.com/dangdennis/ocamlc-lesson

Libsql is a fork of sqlite and offers both a C API and an HTTP-based API. You'll want both capabilities in a client library in order to use Turso's embedded replica functionality. This functionality allows a server to sync a copy of a libsql database from Turso's cloud to the server's filesystem. Means reads can be really fast but with the usual benefits of a networked database like hosted Postgres.

In an attempt to build a libsql ocaml client to make ocaml web development easier, I learned how to compile OCaml code via `ocamlopt` and `ocamlc`, OCaml's native and bytecode compilers. I had first started with Dune, OCaml's essentially defacto build system, to build and link the C code. However, I failed to achieve that in Dune so opted to learn `ocamlopt`. A helpful member of the OCaml forums (and maintainer of Dune IIRC) pointed out that Dune does not perform any linking. It's all passed over to the OCaml compiler. This was the impetus for my learning how to compile OCaml code from scratch. 

At the current state, I have a test file that executes and creates a libsql database. 

> Testing libsql bindings...         
> Opening in-memory database...
> Success! Database connection established.
> Opening file database...
> Success! File database connection established.
> All tests passed!

But this is all tied to macOS. I would one day want to release this library such that a typical linux box can run it. In order to build for macOS, I cloned libsql-c. I built a release target. I have a resulting `liblibsql.a` precompiled for macOS. I then copy it to my OCaml client project. In my Dune file, I have to include specific C libraries in order for OCaml to successfully link the C code. 

`/libsql/dune`
> (c_library_flags (-framework CoreFoundation -framework Security))

Now the next step would be to abstract all macOS flags away such that we can build for Linux. 

That's TBD. We're getting into cross compilation territory now where I have to conditionally include flags. Typically we achieve in this an automated CI environment like Github actions. This is enough for today though.

I've depleted my OCaml battery in the meantime. 

Dennis

About Dennis Dang

Ramblings. Stay away.