[erlang-questions] Iterating (Page scrolling) over Mnesia database

David King dking@REDACTED
Fri Sep 21 19:10:35 CEST 2007


> I am looking for a way to iterate over the results in the Mnesia  
> that are ordered by some element, in other words equivalent of
> SELECT * FROM TABLE ORDER BY MYFIELD -- that can return results in  
> cursor like fashion

The idea is to combine query handles, like this:

mnesia:transaction(fun() ->
   % give me all of the authors from the author table with an ID over 10
   Q1=qlc:q([ X || X <- mnesia:table(author), X#author.id > 10 ]),

   % sort them by name
   Q2=qlc:sort(Q1,
               {order, % I'm using the OrderFun form here. See  
file_sorter
                fun(Author1,Author2) ->
                  Author1#author.name < Author2#author.name
                end}),

   % and run the query
   qlc:eval(Q2)
end)

Note that these query handles aren't evaluated until you ask them to  
be (with fold, cursor, eval, etc), so it's not as inefficient as  
sorting them all in memory if, for instance, indexes are available..  
To iterate over them, use qlc:fold or qlc:cursor instead of qlc:eval:

qlc:fold(fun(Author,AccIn) ->
            Author#author.id+AccIn
          end, 0, Q2).

That would give me the sum of all of the IDs in the results (which is  
a bit contrived, but you get the idea)

More information at http://www.erlang.org/doc/man/qlc.html


> Or page scrolling like
> SELECT * FROM TABLE ORDER BY MYFIELD where rownum > 100 and rownum  
> < 200;
> I see foldl and foldr methods can iterate, and qlc can query, but  
> can someone point me how to implement Cursor or page scrolling  
> behavior.
>
> Thanks in advance.
> -Shahzad Bhatti
>
> Moody friends. Drama queens. Your life? Nope! - their life, your  
> story.
> Play Sims Stories at Yahoo! Games.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list