How to create mnesia table based on a variable record?

Hello everyone, I have the problem how to create mnesia table based on a variable record, for example:

case Record of

'record1'-> mnesia:create_table('record1', [{attributes, record_info(fields, 'record1')}] ;

'record2' ->.... %% same thing as record1

'record3' ->.... 

so I should enumerate all possible case clauses, when I tried to resume that by

case Record of
X when is_atom(X) -> mnesia:create_table(X, [{attributes, record_info(fields, X)}]). 

I get an error and that’s logic because records are preprocessor structures and should be defined before compilation so is there any way to do that ?

1 Like

It is not possible using record_info as that is purely a compile time construct.

Perhaps you can use a parse transform to extract the fields and use them dynamically.

-module(hello).

-compile({parse_transform, exprecs}). % Run parse transform
-record(person, {name, age}).
-record(animal, {name, type}).

-export([dynamic/1, main/0]).
-export_records([person, animal]). % export the records so that you get access to created functions

main() ->
  io:fwrite("~p~n", [dynamic(person)]),
  io:fwrite("~p~n", [dynamic(animal)]).

dynamic(R) ->
  '#info-'(R, fields).
1 Like

Thank you @cmkarlsson, but I want to do it without other apps, you give me an idea, I will look what’s inside record_info and I will try to reimplement it manually