Ocaml record <-> SQL

Let’ say we have:

module Student_Table_Row = struct
  type t = {
    first_name: string;
    last_name: string;
    age: int
  }
end

Now, I’m not looking for ORM. I’m looking for raw SQL. I want two things in particular:

`INSERT INTO main_db.student (first_name, last_name, age) VALUES( ..., ..., ...)

where the … are filled in with obj.first_name, obj.last_name, obj.age

Now, in the situation of:

SELECT * from main_db.student

I want it to return a Student_Table_Row.t List.t

====

What I want to do here is to avoid “hard coding Student_Table_Row”; I want this to work with arbitrary rows.

Because of Records - Real World OCaml , I believe this is possible via First class fields. This is slightly out of my current skill level ; I’m wondering if there is a library that does this.

The key thing here is I want this to be “generic over the fields of the struct”, i.e. not hard code the fields of the struct.

Thanks!

2 Likes

This is an interesting problem that is worth solving. I have a good experience using sqlgg: SQL Guided (code) Generator. While another approach might be using GitHub - roddyyaga/ppx_rapper: Syntax extension for writing SQL in OCaml.

2 Likes

I’ve taken a mental note of looking into Rel (rel.Rel) at some point. It is declared work in progress but looks like a good start.

2 Likes

Indeed rel solves that problem, I hope to release it at some point but it’s not there yet.

If one is interested in seeing what this gives in practice here’s a webapp that makes use of it.

2 Likes