Search code examples
erlangmnesia

How to implement dynamic queries for MNesia?


I'm trying to implement a function that generates dynamic queries for MNesia.

For example, when function is called with these arguments;

dyn_query(list, person, [name, age], ["jack", 21])

I want to query MNesia to list items whose name is "jack" and age is 21 in person table.

I've tried to implement this by using qlc:q(ListComprehension) and qlc:string_to_handle("ListComprehension"). First failed because of compile errors, compiler didn't let me to use functions instead of ListComprehentions and variables instead of record names like "Item#Table.Field". Second failed, because erl_eval couldn't handle records and throwed exceptions like {undefined_record, person}.

Which method should I use? How could i solve these problems? Or should I use a different method?

Thanks.


Solution

  • Check out match specs that mnesia:select/1 uses for queries against a table. There is mnesia:table_info/2 for finding out the column names (and column indexes) of a table.

    Matchspecs are documented in ERTS user guide on match specifications. I usually resort to using ets:fun2ms/1 which is a handy parse-transform that can create a matchspec from erlang-looking fun syntax at compile time. You can play around with it from the shell directly.