Is it possible to create a postgresql hook module with crystal?

Hi all !

I’m trying to gather some information about shared library with crystal but I have a hard time finding out if my use case is even possible as I’m not familiar with LLVM.

Here’s the shortest example I can find of a postgresql hook module.

This C file can be compiled to a .so file and loaded by postgresql workers, this is particularly handy when you want to hook and change some postgresql behaviours. I would like to know if crystal can be used to create shared libraries, linking to the postgresql code base ?

The tricky parts are:

  1. we should be able to assign a function address to a pointer (in this example original_client_auth_hook)
  2. the module should include a magic block PG_MODULE_MAGIC; but I don’t even know if it is possible to emit some C code to be compiled along with a crystal program ?
  3. a _PG_init function should exist as it is the entry point of the module when run by postgresql.

I would totally understand that this kind of shared libraries cannot be programmed in crystal but I just need a confirmation (or some hope :)

Thanks in avance.

Related: Add the ability to create a dynamic library · Issue #921 · crystal-lang/crystal · GitHub

Building shared libraries in Crystal is tricky, but technically possible.
Whether it’s feasible depends on how it’s going to be used.
One major issue is that the Crystal runtime expects to be alone in the process namespace and loading multiple shared libraries with Crystal code could lead to conflicts.
I’m not sure how postgresql plugins work, whether objects are loaded globally or per session.

This should be easy. A Proc is essentially a function pointer and you can take pointers of functions as ->my_func.

You can compile the C code into an object file and link that into the Crystal binary.
Alternatively, you could try to recreate the effect of PG_MODULE_MAGIC in native Crystal. It’s defined here: postgres/src/include/fmgr.h at 1ab67c9dfaadda86059f405e5746efb6ddb9fe21 · postgres/postgres · GitHub

fun _PG_init : Void
end

Thanks @Blacksmoke16 and @straight-shoota for your answers.

I’ve read the github issue link and browsed other similar issues + past answers fro @straight-shoota on the subject. I understand now that it’s not a good use-case for crystal, even if theoretically possible.