In Joe Armstrong's book on Erlang, there's an example of inserting a row into an mnesia database:
add_shop_item(Name, Quantity, Cost) ->
Row = #shop{item=Name, quantity=Quantity, cost=Cost},
F = fun() ->
mnesia:write(Row)
end,
mnesia:transaction(F).
The row gets inserted into a table called shop
, but how does that happen if Erlang records like Row
are really just tuples, and mnesia:write/1 doesn't take an argument for the table name?
Records are tuples where the first element is an atom that names the record, in this case shop
. In the mnesia source you can see how it extracts the first element to use as the table name.
https://github.com/erlang/otp/blob/maint/lib/mnesia/src/mnesia.erl#L511-L513
write(Val) when is_tuple(Val), tuple_size(Val) > 2 ->
Tab = element(1, Val),
write(Tab, Val, write);