我有这个记录
-record(transaction, {id, transaction_code, operation_code, ip_access).
使用此代码,我创建了一个名为transaction_backup
的表的副本mnesia:create_table(transaction_backup,[{disc_copies, [node()]},{attributes, record_info(fields, transaction)},
{record_name, transaction}]).
使用此代码我将数据从交易传输到 transaction_backup
mnesia:transaction(fun() ->
Records = mnesia:select(transaction, [{'_', [], ['$_']}]),
[ok = mnesia:write(transaction_backup, Record, write) || Record <- Records]
end).
表示表事务是否包含以下值:
1 E001 F200 127.0.01
2 E102 F300 127.0.01
3 E105 F402 127.0.01
表transaction_backup将包含相同的内容
1 E001 F200 127.0.01
2 E102 F300 127.0.01
3 E105 F402 127.0.01
现在我想创建一个表transaction_backup,但这次表transaction_backup还有其他名为 idback 的字段,它们将是transaction_backup的唯一ID
所以我们应该用另一种方式创建transaction_backup而不是像这样
mnesia:create_table(transaction_backup,[{disc_copies, [node()]},{attributes, record_info(fields, transaction)},
{record_name, transaction}]).
并且 idback 的值将使用此代码自动递增
idback= next_id(tranasction_backup),
next_id(T) ->
mnesia:dirty_update_counter(counter, T, 1).
所以当我们将数据从事务传输到transaction_backup时,我想是这样的事情
mnesia:transaction(fun() ->
Records = mnesia:select(transaction, [{'_', [], ['$_']}]),
F = fun() ->
Idback= next_id(tranasction_backup),
Trans = #tranasaction_backup{idback= Idback},
mnesia:write(Trans),
{ok};
end,
{atomic, Val} = mnesia:transaction(F),
Val.
[ok = mnesia:write(transaction_backup, Record, write) || Record <- Records]
end).
所以表transaction_backup将包含此值
1 1 E001 F200 127.0.01
2 2 E102 F300 127.0.01
3 3 E105 F402 127.0.01
我想知道如何创建表transaction_backup
正如我所说的那样:
mnesia:create_table(transaction_backup,[{disc_copies, [node()]},{attributes, record_info(fields, transaction)},
{record_name, transaction}]).
但在我的情况下,表 transaction_backup 的表格字段比表交易更多字段, idback
所以为了创建表transaction_backup
,我们应该尝试另一种方式
答案 0 :(得分:0)
是的,您可以拥有相同的交易记录。您需要使用idback创建新记录。 在写入备份表之前,您需要将所有元素从事务复制到transaction_backup记录。或者你可以做到
Records = mnesia:select(transaction, [{'_', [], ['$_']}]),
[ok = mnesia:write(erlang:setelement(1, erlang:insert_element(2, Record, next_id(tranasction_backup)), transaction_backup) || Record <- Records]
以上仅适用于R16A以上。否则你可以做
[ok = mnesia:write(to_backup(Record, next_id(tranasction_backup)))
|| Record <- Records].
和to_backup看起来像
to_backup(Record, Id) ->
[_H| List] = tuple_to_list(Record),
list_to_tuple([transaction_backup, x| List]).