如何使用mnesia:select / 4和mnesia:select / 1进行分页查询

时间:2013-08-13 09:42:38

标签: mnesia

一个名为“md”的表,结构为{id,name},我想从md中读取记录使用分页查询,我尝试了mnesia:select / 4和mnesia:select / 1如下:

%% first use select/2: "ID < 10",returned [1,2,4,3,8,5,9,7,6]
(ejabberd@localhost)5> mnesia:activity(transaction,fun mnesia:select/2,md,                 [{{md,'$1','_'},[{'<','$1',10}],['$1']}]).
{atomic,[1,2,4,3,8,5,9,7,6]}

%%but when query with select/4,returned [6], why?
(ejabberd@localhost)7> {atomic,{R1,C1}}=mnesia:activity(transaction,fun mnesia:select/4,md,[{{md,'$1','_'},[{'<','$1',10}],['$1']}],5,read).
{atomic,{[6],
     {mnesia_select,md,
                    {tid,10535470,<0.460.0>},
                    ejabberd@localhost,disc_only_copies,
                    {dets_cont,select,5,
                               <<0,0,0,29,18,52,86,120,0,0,0,21,131,104,3,...>>,
                               {141720,148792,<<>>},
                               md,<0.130.0>,<<>>},
                    [],undefined,undefined,
                    [{{md,'$1','_'},[{'<','$1',10}],['$1']}]}}}
%% and then use mnesia:select/1 with continuation "C1",got wrong_transaction
(ejabberd@localhost)8> mnesia:activity(transaction,fun mnesia:select/1,C1).
{aborted,wrong_transaction}

如何使用mnesia:select / 4和mnesia:select / 1进行分页查询?

2 个答案:

答案 0 :(得分:0)

您必须在同一交易中调用select / 1。

否则表可以在调用之间进行更改以选择/ 4并选择/。

如果您想使用如上所述,则必须使用脏上下文。

答案 1 :(得分:0)

这是我的解决方案: 使用 async_dirty 代替交易

{Record,Cont}=mnesia:activity(async_dirty, fun mnesia:select/4,[md,[{Match_head,[Guard],[Result]}],Limit,read])

然后阅读下一个限制记录数量:

mnesia:activity(async_dirty, fun mnesia:select/1,[Cont])

完整代码:

-record(md,{id,name}).
batch_delete(Id,Limit) ->
    Match_head = #md{id='$1',name='$2'},
    Guard = {'<','$1',Id},
    Result = '$_',
    {Record,Cont} = mnesia:activity(async_dirty, fun mnesia:select/4,[md,[{Match_head,[Guard],[Result]}],Limit,read]),
    delete_next({Record,Cont}).

delete_next('$end_of_table') ->
    over;
delete_next({Record,Cont}) ->
    delete(Record),
    delete_next(mnesia:activity(async_dirty, fun mnesia:select/1,[Cont])).

delete(Records) ->
    io:format("delete(~p)~n",[Records]),
    F = fun() ->
        [ mnesia:delete_object(O) || O <- Records]
    end,
    mnesia:transaction(F).