rmonjo
rmonjo

Reputation: 2745

Handling Test and Dev Mnesia databases in Elixir

I'm learning Elixir and need some help. I have a simple app that uses mnesia (not Amnesia for now). When I start mnesia I do:

:mnesia.create_schema([node()])
:mnesia.create_table(Table, [attributes: [:id, :name]])
:mnesia.start

This creates a Mnesia.nonode@nohost directory. What I want is to have at least 2 different databases, one for tests and one for development. I'm currently checking this using Mix.env. I plan to erase the test database every time my application stops and create it every time it starts (using the start and stop methods).

The data directory created by mnesia takes the name of the Erlang VM, that is why I guess I need to name my VMs according to the environment (:dev, :test or :prod).

Is this possible? Is this the right way ?


Update

I know I can choose where the data of my mnesia database is stored (thank you Maryna). But when I specify a "custom" directory, I have this strange behaviour:

iex(1)> :mnesia.system_info()
===> System info in version {mnesia_not_loaded,nonode@nohost,
                                {1486,66262,472243}}, debug level =  trace <===
opt_disc. Directory     <<"/my/custom/dir">> is NOT used.
use fallback at restart = false
running db nodes   = []
stopped db nodes   = [nonode@nohost] 
:no

So I can see that it knows where I want to store my data, however it's telling me "is NOT used". I don't know why ... Then

iex(2)> :mnesia.create_schema([node()])
{:error, {:EXIT, :function_clause}}

It fails creating the schema (works fine when I dont specify a "custom" directory). Any ideas?


Update 2

MUST use single quotes around the directory path (no idea why)

Upvotes: 2

Views: 863

Answers (1)

Sheharyar
Sheharyar

Reputation: 75840

The easiest way to have separate mnesia databases for different environments is to specify the Mix.env in your application configuration. You can put something like this in your config.exs:

config :mnesia, dir: 'mnesia/#{Mix.env}/#{node()}'

But there are a few important things you need to take care of:

  • Use have to use single quotes instead of double quotes
  • The parent directory for the database must exist, otherwise it'll fail. (The reason it doesn't fail when you don't specify a custom path is because your app directory already exists)

Upvotes: 6

Related Questions