Dynamic Function Dispatch - pick&cache backend at runtime

Let’s imagine I’d like to have a DB API that can switch DB drivers based on a runtime option. So calls to DB.query get dispatched with minimal overhead to DB.Adapters.sqlite.query. Which DB gets picked is set in sys.config via conform.

My DB module should not know the names of the available adapters, those are drop-in.

If you know Ecto, you could say: I want a runtime-configurable-Ecto.

This recipe using Dynamic Function Dispatch does most of what I want https://edmz.org/personal/2016/02/25/dynamic_function_dispatch_with_elixir.html but the hot path is slow; it walks the list of module names every time.

Is there a better way? I would gladly take a static variable in this case to stash the module reference :slight_smile:

The backend does not change during the execution of the application.

1 Like

What about an init callback for the module (called on app startup)? That’s how ecto does it now, I think.

1 Like

Looked a bit around Ecto, it does use an init callback… and perhaps there’s partial support for what I’m thinking of… see https://github.com/elixir-ecto/ecto/issues/1964 and mentions the Process dictionary.

1 Like