.TH qlc 3erl "stdlib 1.18.1" "Ericsson AB" "Erlang Module Definition" .SH NAME qlc \- Query Interface to Mnesia, ETS, Dets, etc .SH DESCRIPTION .LP The \fIqlc\fR\& module provides a query interface to Mnesia, ETS, Dets and other data structures that implement an iterator style traversal of objects\&. .SH "OVERVIEW" .LP The \fIqlc\fR\& module implements a query interface to \fIQLC tables\fR\&\&. Typical QLC tables are ETS, Dets, and Mnesia tables\&. There is also support for user defined tables, see the \fBImplementing a QLC table\fR\& section\&. A \fIquery\fR\& is stated using \fIQuery List Comprehensions\fR\& (QLCs)\&. The answers to a query are determined by data in QLC tables that fulfill the constraints expressed by the QLCs of the query\&. QLCs are similar to ordinary list comprehensions as described in the Erlang Reference Manual and Programming Examples except that variables introduced in patterns cannot be used in list expressions\&. In fact, in the absence of optimizations and options such as \fIcache\fR\& and \fIunique\fR\& (see below), every QLC free of QLC tables evaluates to the same list of answers as the identical ordinary list comprehension\&. .LP While ordinary list comprehensions evaluate to lists, calling \fBqlc:q/1,2\fR\& returns a \fI Query Handle\fR\&\&. To obtain all the answers to a query, \fBqlc:eval/1,2\fR\& should be called with the query handle as first argument\&. Query handles are essentially functional objects ("funs") created in the module calling \fIq/1,2\fR\&\&. As the funs refer to the module\&'s code, one should be careful not to keep query handles too long if the module\&'s code is to be replaced\&. Code replacement is described in the \fBErlang Reference Manual\fR\&\&. The list of answers can also be traversed in chunks by use of a \fIQuery Cursor\fR\&\&. Query cursors are created by calling \fBqlc:cursor/1,2\fR\& with a query handle as first argument\&. Query cursors are essentially Erlang processes\&. One answer at a time is sent from the query cursor process to the process that created the cursor\&. .SH "SYNTAX" .LP Syntactically QLCs have the same parts as ordinary list comprehensions: .LP .nf [Expression || Qualifier1, Qualifier2, ...] .fi .LP \fIExpression\fR\& (the \fItemplate\fR\&) is an arbitrary Erlang expression\&. Qualifiers are either \fIfilters\fR\& or \fIgenerators\fR\&\&. Filters are Erlang expressions returning \fIbool()\fR\&\&. Generators have the form \fIPattern <- ListExpression\fR\&, where \fIListExpression\fR\& is an expression evaluating to a query handle or a list\&. Query handles are returned from \fIqlc:table/2\fR\&, \fIqlc:append/1,2\fR\&, \fIqlc:sort/1,2\fR\&, \fIqlc:keysort/2,3\fR\&, \fIqlc:q/1,2\fR\&, and \fIqlc:string_to_handle/1,2,3\fR\&\&. .SH "EVALUATION" .LP The evaluation of a query handle begins by the inspection of options and the collection of information about tables\&. As a result qualifiers are modified during the optimization phase\&. Next all list expressions are evaluated\&. If a cursor has been created evaluation takes place in the cursor process\&. For those list expressions that are QLCs, the list expressions of the QLCs\&' generators are evaluated as well\&. One has to be careful if list expressions have side effects since the order in which list expressions are evaluated is unspecified\&. Finally the answers are found by evaluating the qualifiers from left to right, backtracking when some filter returns \fIfalse\fR\&, or collecting the template when all filters return \fItrue\fR\&\&. .LP Filters that do not return \fIbool()\fR\& but fail are handled differently depending on their syntax: if the filter is a guard it returns \fIfalse\fR\&, otherwise the query evaluation fails\&. This behavior makes it possible for the \fIqlc\fR\& module to do some optimizations without affecting the meaning of a query\&. For example, when testing some position of a table and one or more constants for equality, only the objects with equal values are candidates for further evaluation\&. The other objects are guaranteed to make the filter return \fIfalse\fR\&, but never fail\&. The (small) set of candidate objects can often be found by looking up some key values of the table or by traversing the table using a match specification\&. It is necessary to place the guard filters immediately after the table\&'s generator, otherwise the candidate objects will not be restricted to a small set\&. The reason is that objects that could make the query evaluation fail must not be excluded by looking up a key or running a match specification\&. .SH "JOIN" .LP The \fIqlc\fR\& module supports fast join of two query handles\&. Fast join is possible if some position \fIP1\fR\& of one query handler and some position \fIP2\fR\& of another query handler are tested for equality\&. Two fast join methods have been implemented: .RS 2 .TP 2 * Lookup join traverses all objects of one query handle and finds objects of the other handle (a QLC table) such that the values at \fIP1\fR\& and \fIP2\fR\& match or compare equal\&. The \fIqlc\fR\& module does not create any indices but looks up values using the key position and the indexed positions of the QLC table\&. .LP .TP 2 * Merge join sorts the objects of each query handle if necessary and filters out objects where the values at \fIP1\fR\& and \fIP2\fR\& do not compare equal\&. If there are many objects with the same value of \fIP2\fR\& a temporary file will be used for the equivalence classes\&. .LP .RE .LP The \fIqlc\fR\& module warns at compile time if a QLC combines query handles in such a way that more than one join is possible\&. In other words, there is no query planner that can choose a good order between possible join operations\&. It is up to the user to order the joins by introducing query handles\&. .LP The join is to be expressed as a guard filter\&. The filter must be placed immediately after the two joined generators, possibly after guard filters that use variables from no other generators but the two joined generators\&. The \fIqlc\fR\& module inspects the operands of \fI=:=/2\fR\&, \fI==/2\fR\&, \fIis_record/2\fR\&, \fIelement/2\fR\&, and logical operators (\fIand/2\fR\&, \fIor/2\fR\&, \fIandalso/2\fR\&, \fIorelse/2\fR\&, \fIxor/2\fR\&) when determining which joins to consider\&. .SH "COMMON OPTIONS" .LP The following options are accepted by \fIcursor/2\fR\&, \fIeval/2\fR\&, \fIfold/4\fR\&, and \fIinfo/2\fR\&: .RS 2 .TP 2 * \fI{cache_all, Cache}\fR\& where \fICache\fR\& is equal to \fIets\fR\& or \fIlist\fR\& adds a \fI{cache, Cache}\fR\& option to every list expression of the query except tables and lists\&. Default is \fI{cache_all, no}\fR\&\&. The option \fIcache_all\fR\& is equivalent to \fI{cache_all, ets}\fR\&\&. .LP .TP 2 * \fI{max_list_size, MaxListSize}\fR\& where \fIMaxListSize\fR\& is the size in bytes of terms on the external format\&. If the accumulated size of collected objects exceeds \fIMaxListSize\fR\& the objects are written onto a temporary file\&. This option is used by the \fI{cache, list}\fR\& option as well as by the merge join method\&. Default is 512*1024 bytes\&. .LP .TP 2 * \fI{tmpdir_usage, TmpFileUsage}\fR\& determines the action taken when \fIqlc\fR\& is about to create temporary files on the directory set by the \fItmpdir\fR\& option\&. If the value is \fInot_allowed\fR\& an error tuple is returned, otherwise temporary files are created as needed\&. Default is \fIallowed\fR\& which means that no further action is taken\&. The values \fIinfo_msg\fR\&, \fIwarning_msg\fR\&, and \fIerror_msg\fR\& mean that the function with the corresponding name in the module \fIerror_logger\fR\& is called for printing some information (currently the stacktrace)\&. .LP .TP 2 * \fI{tmpdir, TempDirectory}\fR\& sets the directory used by merge join for temporary files and by the \fI{cache, list}\fR\& option\&. The option also overrides the \fItmpdir\fR\& option of \fIkeysort/3\fR\& and \fIsort/2\fR\&\&. The default value is \fI""\fR\& which means that the directory returned by \fIfile:get_cwd()\fR\& is used\&. .LP .TP 2 * \fI{unique_all, true}\fR\& adds a \fI{unique, true}\fR\& option to every list expression of the query\&. Default is \fI{unique_all, false}\fR\&\&. The option \fIunique_all\fR\& is equivalent to \fI{unique_all, true}\fR\&\&. .LP .RE .SH "GETTING STARTED" .LP As already mentioned queries are stated in the list comprehension syntax as described in the \fBErlang Reference Manual\fR\&\&. In the following some familiarity with list comprehensions is assumed\&. There are examples in \fBProgramming Examples\fR\& that can get you started\&. It should be stressed that list comprehensions do not add any computational power to the language; anything that can be done with list comprehensions can also be done without them\&. But they add a syntax for expressing simple search problems which is compact and clear once you get used to it\&. .LP Many list comprehension expressions can be evaluated by the \fIqlc\fR\& module\&. Exceptions are expressions such that variables introduced in patterns (or filters) are used in some generator later in the list comprehension\&. As an example consider an implementation of lists:append(L): \fI[X ||Y <- L, X <- Y]\fR\&\&. Y is introduced in the first generator and used in the second\&. The ordinary list comprehension is normally to be preferred when there is a choice as to which to use\&. One difference is that \fIqlc:eval/1,2\fR\& collects answers in a list which is finally reversed, while list comprehensions collect answers on the stack which is finally unwound\&. .LP What the \fIqlc\fR\& module primarily adds to list comprehensions is that data can be read from QLC tables in small chunks\&. A QLC table is created by calling \fIqlc:table/2\fR\&\&. Usually \fIqlc:table/2\fR\& is not called directly from the query but via an interface function of some data structure\&. There are a few examples of such functions in Erlang/OTP: \fImnesia:table/1,2\fR\&, \fIets:table/1,2\fR\&, and \fIdets:table/1,2\fR\&\&. For a given data structure there can be several functions that create QLC tables, but common for all these functions is that they return a query handle created by \fIqlc:table/2\fR\&\&. Using the QLC tables provided by OTP is probably sufficient in most cases, but for the more advanced user the section \fBImplementing a QLC table\fR\& describes the implementation of a function calling \fIqlc:table/2\fR\&\&. .LP Besides \fIqlc:table/2\fR\& there are other functions that return query handles\&. They might not be used as often as tables, but are useful from time to time\&. \fIqlc:append\fR\& traverses objects from several tables or lists after each other\&. If, for instance, you want to traverse all answers to a query QH and then finish off by a term \fI{finished}\fR\&, you can do that by calling \fIqlc:append(QH, [{finished}])\fR\&\&. \fIappend\fR\& first returns all objects of QH, then \fI{finished}\fR\&\&. If there is one tuple \fI{finished}\fR\& among the answers to QH it will be returned twice from \fIappend\fR\&\&. .LP As another example, consider concatenating the answers to two queries QH1 and QH2 while removing all duplicates\&. The means to accomplish this is to use the \fIunique\fR\& option: .LP .nf qlc:q([X || X <- qlc:append(QH1, QH2)], {unique, true}) .fi .LP The cost is substantial: every returned answer will be stored in an ETS table\&. Before returning an answer it is looked up in the ETS table to check if it has already been returned\&. Without the \fIunique\fR\& options all answers to QH1 would be returned followed by all answers to QH2\&. The \fIunique\fR\& options keeps the order between the remaining answers\&. .LP If the order of the answers is not important there is the alternative to sort the answers uniquely: .LP .nf qlc:sort(qlc:q([X || X <- qlc:append(QH1, QH2)], {unique, true})). .fi .LP This query also removes duplicates but the answers will be sorted\&. If there are many answers temporary files will be used\&. Note that in order to get the first unique answer all answers have to be found and sorted\&. Both alternatives find duplicates by comparing answers, that is, if A1 and A2 are answers found in that order, then A2 is a removed if A1 == A2\&. .LP To return just a few answers cursors can be used\&. The following code returns no more than five answers using an ETS table for storing the unique answers: .LP .nf C = qlc:cursor(qlc:q([X || X <- qlc:append(QH1, QH2)],{unique,true})), R = qlc:next_answers(C, 5), ok = qlc:delete_cursor(C), R. .fi .LP Query list comprehensions are convenient for stating constraints on data from two or more tables\&. An example that does a natural join on two query handles on position 2: .LP .nf qlc:q([{X1,X2,X3,Y1} || {X1,X2,X3} <- QH1, {Y1,Y2} <- QH2, X2 =:= Y2]) .fi .LP The \fIqlc\fR\& module will evaluate this differently depending on the query handles \fIQH1\fR\& and \fIQH2\fR\&\&. If, for example, \fIX2\fR\& is matched against the key of a QLC table the lookup join method will traverse the objects of \fIQH2\fR\& while looking up key values in the table\&. On the other hand, if neither \fIX2\fR\& nor \fIY2\fR\& is matched against the key or an indexed position of a QLC table, the merge join method will make sure that \fIQH1\fR\& and \fIQH2\fR\& are both sorted on position 2 and next do the join by traversing the objects one by one\&. .LP The \fIjoin\fR\& option can be used to force the \fIqlc\fR\& module to use a certain join method\&. For the rest of this section it is assumed that the excessively slow join method called "nested loop" has been chosen: .LP .nf qlc:q([{X1,X2,X3,Y1} || {X1,X2,X3} <- QH1, {Y1,Y2} <- QH2, X2 =:= Y2], {join, nested_loop}) .fi .LP In this case the filter will be applied to every possible pair of answers to QH1 and QH2, one at a time\&. If there are M answers to QH1 and N answers to QH2 the filter will be run M*N times\&. .LP If QH2 is a call to the function for \fIgb_trees\fR\& as defined in the \fBImplementing a QLC table\fR\& section, \fIgb_table:table/1\fR\&, the iterator for the gb-tree will be initiated for each answer to QH1 after which the objects of the gb-tree will be returned one by one\&. This is probably the most efficient way of traversing the table in that case since it takes minimal computational power to get the following object\&. But if QH2 is not a table but a more complicated QLC, it can be more efficient use some RAM memory for collecting the answers in a cache, particularly if there are only a few answers\&. It must then be assumed that evaluating QH2 has no side effects so that the meaning of the query does not change if QH2 is evaluated only once\&. One way of caching the answers is to evaluate QH2 first of all and substitute the list of answers for QH2 in the query\&. Another way is to use the \fIcache\fR\& option\&. It is stated like this: .LP .nf QH2' = qlc:q([X || X <- QH2], {cache, ets}) .fi .LP or just .LP .nf QH2' = qlc:q([X || X <- QH2], cache) .fi .LP The effect of the \fIcache\fR\& option is that when the generator QH2\&' is run the first time every answer is stored in an ETS table\&. When next answer of QH1 is tried, answers to QH2\&' are copied from the ETS table which is very fast\&. As for the \fIunique\fR\& option the cost is a possibly substantial amount of RAM memory\&. The \fI{cache, list}\fR\& option offers the possibility to store the answers in a list on the process heap\&. While this has the potential of being faster than ETS tables since there is no need to copy answers from the table it can often result in slower evaluation due to more garbage collections of the process\&' heap as well as increased RAM memory consumption due to larger heaps\&. Another drawback with cache lists is that if the size of the list exceeds a limit a temporary file will be used\&. Reading the answers from a file is very much slower than copying them from an ETS table\&. But if the available RAM memory is scarce setting the \fBlimit\fR\& to some low value is an alternative\&. .LP There is an option \fIcache_all\fR\& that can be set to \fIets\fR\& or \fIlist\fR\& when evaluating a query\&. It adds a \fIcache\fR\& or \fI{cache, list}\fR\& option to every list expression except QLC tables and lists on all levels of the query\&. This can be used for testing if caching would improve efficiency at all\&. If the answer is yes further testing is needed to pinpoint the generators that should be cached\&. .SH "IMPLEMENTING A QLC TABLE" .LP As an example of how to use the \fBqlc:table/2\fR\& function the implementation of a QLC table for the \fBgb_trees\fR\& module is given: .LP .nf -module(gb_table). -export([table/1]). table(T) -> TF = fun() -> qlc_next(gb_trees:next(gb_trees:iterator(T))) end, InfoFun = fun(num_of_objects) -> gb_trees:size(T); (keypos) -> 1; (is_sorted_key) -> true; (is_unique_objects) -> true; (_) -> undefined end, LookupFun = fun(1, Ks) -> lists:flatmap(fun(K) -> case gb_trees:lookup(K, T) of {value, V} -> [{K,V}]; none -> [] end end, Ks) end, FormatFun = fun({all, NElements, ElementFun}) -> ValsS = io_lib:format("gb_trees:from_orddict(~w)", [gb_nodes(T, NElements, ElementFun)]), io_lib:format("gb_table:table(~s)", [ValsS]); ({lookup, 1, KeyValues, _NElements, ElementFun}) -> ValsS = io_lib:format("gb_trees:from_orddict(~w)", [gb_nodes(T, infinity, ElementFun)]), io_lib:format("lists:flatmap(fun(K) -> " "case gb_trees:lookup(K, ~s) of " "{value, V} -> [{K,V}];none -> [] end " "end, ~w)", [ValsS, [ElementFun(KV) || KV <- KeyValues]]) end, qlc:table(TF, [{info_fun, InfoFun}, {format_fun, FormatFun}, {lookup_fun, LookupFun},{key_equality,'=='}]). qlc_next({X, V, S}) -> [{X,V} | fun() -> qlc_next(gb_trees:next(S)) end]; qlc_next(none) -> []. gb_nodes(T, infinity, ElementFun) -> gb_nodes(T, -1, ElementFun); gb_nodes(T, NElements, ElementFun) -> gb_iter(gb_trees:iterator(T), NElements, ElementFun). gb_iter(_I, 0, _EFun) -> '...'; gb_iter(I0, N, EFun) -> case gb_trees:next(I0) of {X, V, I} -> [EFun({X,V}) | gb_iter(I, N-1, EFun)]; none -> [] end. .fi .LP \fITF\fR\& is the traversal function\&. The \fIqlc\fR\& module requires that there is a way of traversing all objects of the data structure; in \fIgb_trees\fR\& there is an iterator function suitable for that purpose\&. Note that for each object returned a new fun is created\&. As long as the list is not terminated by \fI[]\fR\& it is assumed that the tail of the list is a nullary function and that calling the function returns further objects (and functions)\&. .LP The lookup function is optional\&. It is assumed that the lookup function always finds values much faster than it would take to traverse the table\&. The first argument is the position of the key\&. Since \fIqlc_next\fR\& returns the objects as {Key, Value} pairs the position is 1\&. Note that the lookup function should return {Key, Value} pairs, just as the traversal function does\&. .LP The format function is also optional\&. It is called by \fIqlc:info\fR\& to give feedback at runtime of how the query will be evaluated\&. One should try to give as good feedback as possible without showing too much details\&. In the example at most 7 objects of the table are shown\&. The format function handles two cases: \fIall\fR\& means that all objects of the table will be traversed; \fI{lookup, 1, KeyValues}\fR\& means that the lookup function will be used for looking up key values\&. .LP Whether the whole table will be traversed or just some keys looked up depends on how the query is stated\&. If the query has the form .LP .nf qlc:q([T || P <- LE, F]) .fi .LP and P is a tuple, the \fIqlc\fR\& module analyzes P and F in compile time to find positions of the tuple P that are tested for equality to constants\&. If such a position at runtime turns out to be the key position, the lookup function can be used, otherwise all objects of the table have to be traversed\&. It is the info function \fIInfoFun\fR\& that returns the key position\&. There can be indexed positions as well, also returned by the info function\&. An index is an extra table that makes lookup on some position fast\&. Mnesia maintains indices upon request, thereby introducing so called secondary keys\&. The \fIqlc\fR\& module prefers to look up objects using the key before secondary keys regardless of the number of constants to look up\&. .SH "KEY EQUALITY" .LP In Erlang there are two operators for testing term equality, namely \fI==/2\fR\& and \fI=:=/2\fR\&\&. The difference between them is all about the integers that can be represented by floats\&. For instance, \fI2 == 2\&.0\fR\& evaluates to \fItrue\fR\& while \fI2 =:= 2\&.0\fR\& evaluates to \fIfalse\fR\&\&. Normally this is a minor issue, but the \fIqlc\fR\& module cannot ignore the difference, which affects the user\&'s choice of operators in QLCs\&. .LP If the \fIqlc\fR\& module can find out at compile time that some constant is free of integers, it does not matter which one of \fI==/2\fR\& or \fI=:=/2\fR\& is used: .LP .nf 1> E1 = ets:new(t, [set]), % uses =:=/2 for key equality Q1 = qlc:q([K || {K} <- ets:table(E1), K == 2\&.71 orelse K == a]), io:format("~s~n", [qlc:info(Q1)])\&. ets:match_spec_run(lists:flatmap(fun(V) -> ets:lookup(20493, V) end, [a,2.71]), ets:match_spec_compile([{{'$1'},[],['$1']}])) .fi .LP In the example the \fI==/2\fR\& operator has been handled exactly as \fI=:=/2\fR\& would have been handled\&. On the other hand, if it cannot be determined at compile time that some constant is free of integers and the table uses \fI=:=/2\fR\& when comparing keys for equality (see the option \fBkey_equality\fR\&), the \fIqlc\fR\& module will not try to look up the constant\&. The reason is that there is in the general case no upper limit on the number of key values that can compare equal to such a constant; every combination of integers and floats has to be looked up: .LP .nf 2> E2 = ets:new(t, [set]), true = ets:insert(E2, [{{2,2},a},{{2,2\&.0},b},{{2\&.0,2},c}]), F2 = fun(I) -> qlc:q([V || {K,V} <- ets:table(E2), K == I]) end, Q2 = F2({2,2}), io:format("~s~n", [qlc:info(Q2)])\&. ets:table(53264, [{traverse, {select,[{{'$1','$2'},[{'==','$1',{const,{2,2}}}],['$2']}]}}]) 3> lists:sort(qlc:e(Q2))\&. [a,b,c] .fi .LP Looking up just \fI{2,2}\fR\& would not return \fIb\fR\& and \fIc\fR\&\&. .LP If the table uses \fI==/2\fR\& when comparing keys for equality, the \fIqlc\fR\& module will look up the constant regardless of which operator is used in the QLC\&. However, \fI==/2\fR\& is to be preferred: .LP .nf 4> E3 = ets:new(t, [ordered_set]), % uses ==/2 for key equality true = ets:insert(E3, [{{2,2\&.0},b}]), F3 = fun(I) -> qlc:q([V || {K,V} <- ets:table(E3), K == I]) end, Q3 = F3({2,2}), io:format("~s~n", [qlc:info(Q3)])\&. ets:match_spec_run(ets:lookup(86033, {2,2}), ets:match_spec_compile([{{'$1','$2'},[],['$2']}])) 5> qlc:e(Q3)\&. [b] .fi .LP Lookup join is handled analogously to lookup of constants in a table: if the join operator is \fI==/2\fR\& and the table where constants are to be looked up uses \fI=:=/2\fR\& when testing keys for equality, the \fIqlc\fR\& module will not consider lookup join for that table\&. .SH DATA TYPES .nf \fBabstract_expr()\fR\& = \fBerl_parse:abstract_expr()\fR\& .br .fi .RS .LP Parse trees for Erlang expression, see the \fBabstract format\fR\& documentation in the ERTS User\&'s Guide\&. .RE .nf \fBanswer()\fR\& = term() .br .fi .nf \fBanswers()\fR\& = [\fBanswer()\fR\&] .br .fi .nf \fBcache()\fR\& = ets | list | no .br .fi .nf \fBmatch_expression()\fR\& = \fBets:match_spec()\fR\& .br .fi .RS .LP Match specification, see the \fBmatch specification\fR\& documentation in the ERTS User\&'s Guide and \fBms_transform(3erl)\&.\fR\& .RE .nf \fBno_files()\fR\& = integer() >= 1 .br .fi .RS .LP Actually an integer > 1\&. .RE .nf \fBkey_pos()\fR\& = integer() >= 1 | [integer() >= 1] .br .fi .nf \fBmax_list_size()\fR\& = integer() >= 0 .br .fi .nf \fBorder()\fR\& = ascending | descending | \fBorder_fun()\fR\& .br .fi .nf \fBorder_fun()\fR\& = fun((term(), term()) -> boolean()) .br .fi .nf \fBquery_cursor()\fR\& .br .fi .RS .LP A \fBquery cursor\fR\&\&. .RE .nf \fBquery_handle()\fR\& .br .fi .RS .LP A \fBquery handle\fR\&\&. .RE .nf \fBquery_handle_or_list()\fR\& = \fBquery_handle()\fR\& | list() .br .fi .nf \fBquery_list_comprehension()\fR\& = term() .br .fi .RS .LP A literal \fBquery list comprehension\fR\&\&. .RE .nf \fBspawn_options()\fR\& = default | [\fBproc_lib:spawn_option()\fR\&] .br .fi .nf \fBsort_options()\fR\& = [\fBsort_option()\fR\&] | \fBsort_option()\fR\& .br .fi .nf \fBsort_option()\fR\& = {compressed, boolean()} .br | {no_files, \fBno_files()\fR\&} .br | {order, \fBorder()\fR\&} .br | {size, integer() >= 1} .br | {tmpdir, \fBtmp_directory()\fR\&} .br | {unique, boolean()} .br .fi .RS .LP See \fBfile_sorter(3erl)\fR\&\&. .RE .nf \fBtmp_directory()\fR\& = [] | \fBfile:name()\fR\& .br .fi .nf \fBtmp_file_usage()\fR\& = allowed .br | not_allowed .br | info_msg .br | warning_msg .br | error_msg .br .fi .SH EXPORTS .LP .nf .B append(QHL) -> QH .br .fi .br .RS .LP Types: .RS 3 QHL = [\fBquery_handle_or_list()\fR\&] .br QH = \fBquery_handle()\fR\& .br .RE .RE .RS .LP Returns a query handle\&. When evaluating the query handle \fIQH\fR\& all answers to the first query handle in \fIQHL\fR\& are returned followed by all answers to the rest of the query handles in \fIQHL\fR\&\&. .RE .LP .nf .B append(QH1, QH2) -> QH3 .br .fi .br .RS .LP Types: .RS 3 QH1 = QH2 = \fBquery_handle_or_list()\fR\& .br QH3 = \fBquery_handle()\fR\& .br .RE .RE .RS .LP Returns a query handle\&. When evaluating the query handle \fIQH3\fR\& all answers to \fIQH1\fR\& are returned followed by all answers to \fIQH2\fR\&\&. .LP \fIappend(QH1, QH2)\fR\& is equivalent to \fIappend([QH1, QH2])\fR\&\&. .RE .LP .nf .B cursor(QH) -> Cursor .br .fi .br .nf .B cursor(QH, Options) -> Cursor .br .fi .br .RS .LP Types: .RS 3 QH = \fBquery_handle_or_list()\fR\& .br Options = [Option] | Option .br Option = {cache_all, \fBcache()\fR\&} .br | cache_all .br | {max_list_size, \fBmax_list_size()\fR\&} .br | {spawn_options, \fBspawn_options()\fR\&} .br | {tmpdir_usage, \fBtmp_file_usage()\fR\&} .br | {tmpdir, \fBtmp_directory()\fR\&} .br | {unique_all, boolean()} .br | unique_all .br Cursor = \fBquery_cursor()\fR\& .br .RE .RE .RS .LP Creates a query cursor and makes the calling process the owner of the cursor\&. The cursor is to be used as argument to \fInext_answers/1,2\fR\& and (eventually) \fIdelete_cursor/1\fR\&\&. Calls \fIerlang:spawn_opt\fR\& to spawn and link a process which will evaluate the query handle\&. The value of the option \fIspawn_options\fR\& is used as last argument when calling \fIspawn_opt\fR\&\&. The default value is \fI[link]\fR\&\&. .LP .nf 1> QH = qlc:q([{X,Y} || X <- [a,b], Y <- [1,2]]), QC = qlc:cursor(QH), qlc:next_answers(QC, 1)\&. [{a,1}] 2> qlc:next_answers(QC, 1)\&. [{a,2}] 3> qlc:next_answers(QC, all_remaining)\&. [{b,1},{b,2}] 4> qlc:delete_cursor(QC)\&. ok .fi .LP \fIcursor(QH)\fR\& is equivalent to \fIcursor(QH, [])\fR\&\&. .RE .LP .nf .B delete_cursor(QueryCursor) -> ok .br .fi .br .RS .LP Types: .RS 3 QueryCursor = \fBquery_cursor()\fR\& .br .RE .RE .RS .LP Deletes a query cursor\&. Only the owner of the cursor can delete the cursor\&. .RE .LP .nf .B eval(QH) -> Answers | Error .br .fi .br .nf .B eval(QH, Options) -> Answers | Error .br .fi .br .nf .B e(QH) -> Answers | Error .br .fi .br .nf .B e(QH, Options) -> Answers | Error .br .fi .br .RS .LP Types: .RS 3 QH = \fBquery_handle_or_list()\fR\& .br Options = [Option] | Option .br Option = {cache_all, \fBcache()\fR\&} .br | cache_all .br | {max_list_size, \fBmax_list_size()\fR\&} .br | {tmpdir_usage, \fBtmp_file_usage()\fR\&} .br | {tmpdir, \fBtmp_directory()\fR\&} .br | {unique_all, boolean()} .br | unique_all .br Answers = \fBanswers()\fR\& .br Error = {error, module(), Reason} .br Reason = \fBfile_sorter:reason()\fR\& .br .RE .RE .RS .LP Evaluates a query handle in the calling process and collects all answers in a list\&. .LP .nf 1> QH = qlc:q([{X,Y} || X <- [a,b], Y <- [1,2]]), qlc:eval(QH)\&. [{a,1},{a,2},{b,1},{b,2}] .fi .LP \fIeval(QH)\fR\& is equivalent to \fIeval(QH, [])\fR\&\&. .RE .LP .nf .B fold(Function, Acc0, QH) -> Acc1 | Error .br .fi .br .nf .B fold(Function, Acc0, QH, Options) -> Acc1 | Error .br .fi .br .RS .LP Types: .RS 3 QH = \fBquery_handle_or_list()\fR\& .br Function = fun((\fBanswer()\fR\&, AccIn) -> AccOut) .br Acc0 = Acc1 = AccIn = AccOut = term() .br Options = [Option] | Option .br Option = {cache_all, \fBcache()\fR\&} .br | cache_all .br | {max_list_size, \fBmax_list_size()\fR\&} .br | {tmpdir_usage, \fBtmp_file_usage()\fR\&} .br | {tmpdir, \fBtmp_directory()\fR\&} .br | {unique_all, boolean()} .br | unique_all .br Error = {error, module(), Reason} .br Reason = \fBfile_sorter:reason()\fR\& .br .RE .RE .RS .LP Calls \fIFunction\fR\& on successive answers to the query handle together with an extra argument \fIAccIn\fR\&\&. The query handle and the function are evaluated in the calling process\&. \fIFunction\fR\& must return a new accumulator which is passed to the next call\&. \fIAcc0\fR\& is returned if there are no answers to the query handle\&. .LP .nf 1> QH = [1,2,3,4,5,6], qlc:fold(fun(X, Sum) -> X + Sum end, 0, QH)\&. 21 .fi .LP \fIfold(Function, Acc0, QH)\fR\& is equivalent to \fIfold(Function, Acc0, QH, [])\fR\&\&. .RE .LP .nf .B format_error(Error) -> Chars .br .fi .br .RS .LP Types: .RS 3 Error = {error, module(), term()} .br Chars = \fBio_lib:chars()\fR\& .br .RE .RE .RS .LP Returns a descriptive string in English of an error tuple returned by some of the functions of the \fIqlc\fR\& module or the parse transform\&. This function is mainly used by the compiler invoking the parse transform\&. .RE .LP .nf .B info(QH) -> Info .br .fi .br .nf .B info(QH, Options) -> Info .br .fi .br .RS .LP Types: .RS 3 QH = \fBquery_handle_or_list()\fR\& .br Options = [Option] | Option .br Option = EvalOption | ReturnOption .br EvalOption = {cache_all, \fBcache()\fR\&} .br | cache_all .br | {max_list_size, \fBmax_list_size()\fR\&} .br | {tmpdir_usage, \fBtmp_file_usage()\fR\&} .br | {tmpdir, \fBtmp_directory()\fR\&} .br | {unique_all, boolean()} .br | unique_all .br ReturnOption = {depth, Depth} .br | {flat, boolean()} .br | {format, Format} .br | {n_elements, NElements} .br Depth = infinity | integer() >= 0 .br Format = abstract_code | string .br NElements = infinity | integer() >= 1 .br Info = \fBabstract_expr()\fR\& | string() .br .RE .RE .RS .LP Returns information about a query handle\&. The information describes the simplifications and optimizations that are the results of preparing the query for evaluation\&. This function is probably useful mostly during debugging\&. .LP The information has the form of an Erlang expression where QLCs most likely occur\&. Depending on the format functions of mentioned QLC tables it may not be absolutely accurate\&. .LP The default is to return a sequence of QLCs in a block, but if the option \fI{flat, false}\fR\& is given, one single QLC is returned\&. The default is to return a string, but if the option \fI{format, abstract_code}\fR\& is given, abstract code is returned instead\&. In the abstract code port identifiers, references, and pids are represented by strings\&. The default is to return all elements in lists, but if the \fI{n_elements, NElements}\fR\& option is given, only a limited number of elements are returned\&. The default is to show all of objects and match specifications, but if the \fI{depth, Depth}\fR\& option is given, parts of terms below a certain depth are replaced by \fI\&'\&.\&.\&.\&'\fR\&\&. .LP .nf 1> QH = qlc:q([{X,Y} || X <- [x,y], Y <- [a,b]]), io:format("~s~n", [qlc:info(QH, unique_all)])\&. begin V1 = qlc:q([ SQV || SQV <- [x,y] ], [{unique,true}]), V2 = qlc:q([ SQV || SQV <- [a,b] ], [{unique,true}]), qlc:q([ {X,Y} || X <- V1, Y <- V2 ], [{unique,true}]) end .fi .LP In this example two simple QLCs have been inserted just to hold the \fI{unique, true}\fR\& option\&. .LP .nf 1> E1 = ets:new(e1, []), E2 = ets:new(e2, []), true = ets:insert(E1, [{1,a},{2,b}]), true = ets:insert(E2, [{a,1},{b,2}]), Q = qlc:q([{X,Z,W} || {X, Z} <- ets:table(E1), {W, Y} <- ets:table(E2), X =:= Y]), io:format("~s~n", [qlc:info(Q)])\&. begin V1 = qlc:q([ P0 || P0 = {W,Y} <- ets:table(17) ]), V2 = qlc:q([ [G1|G2] || G2 <- V1, G1 <- ets:table(16), element(2, G1) =:= element(1, G2) ], [{join,lookup}]), qlc:q([ {X,Z,W} || [{X,Z}|{W,Y}] <- V2 ]) end .fi .LP In this example the query list comprehension \fIV2\fR\& has been inserted to show the joined generators and the join method chosen\&. A convention is used for lookup join: the first generator (\fIG2\fR\&) is the one traversed, the second one (\fIG1\fR\&) is the table where constants are looked up\&. .LP \fIinfo(QH)\fR\& is equivalent to \fIinfo(QH, [])\fR\&\&. .RE .LP .nf .B keysort(KeyPos, QH1) -> QH2 .br .fi .br .nf .B keysort(KeyPos, QH1, SortOptions) -> QH2 .br .fi .br .RS .LP Types: .RS 3 KeyPos = \fBkey_pos()\fR\& .br SortOptions = \fBsort_options()\fR\& .br QH1 = \fBquery_handle_or_list()\fR\& .br QH2 = \fBquery_handle()\fR\& .br .RE .RE .RS .LP Returns a query handle\&. When evaluating the query handle \fIQH2\fR\& the answers to the query handle \fIQH1\fR\& are sorted by \fBfile_sorter:keysort/4\fR\& according to the options\&. .LP The sorter will use temporary files only if \fIQH1\fR\& does not evaluate to a list and the size of the binary representation of the answers exceeds \fISize\fR\& bytes, where \fISize\fR\& is the value of the \fIsize\fR\& option\&. .LP \fIkeysort(KeyPos, QH1)\fR\& is equivalent to \fIkeysort(KeyPos, QH1, [])\fR\&\&. .RE .LP .nf .B next_answers(QueryCursor) -> Answers | Error .br .fi .br .nf .B next_answers(QueryCursor, NumberOfAnswers) -> Answers | Error .br .fi .br .RS .LP Types: .RS 3 QueryCursor = \fBquery_cursor()\fR\& .br Answers = \fBanswers()\fR\& .br NumberOfAnswers = all_remaining | integer() >= 1 .br Error = {error, module(), Reason} .br Reason = \fBfile_sorter:reason()\fR\& .br .RE .RE .RS .LP Returns some or all of the remaining answers to a query cursor\&. Only the owner of \fIQueryCursor\fR\& can retrieve answers\&. .LP The optional argument \fINumberOfAnswers\fR\&determines the maximum number of answers returned\&. The default value is \fI10\fR\&\&. If less than the requested number of answers is returned, subsequent calls to \fInext_answers\fR\& will return \fI[]\fR\&\&. .RE .LP .nf .B q(QLC) -> QH .br .fi .br .nf .B q(QLC, Options) -> QH .br .fi .br .RS .LP Types: .RS 3 QH = \fBquery_handle()\fR\& .br Options = [Option] | Option .br Option = {max_lookup, MaxLookup} .br | {cache, \fBcache()\fR\&} .br | cache .br | {join, Join} .br | {lookup, Lookup} .br | {unique, boolean()} .br | unique .br MaxLookup = integer() >= 0 | infinity .br Join = any | lookup | merge | nested_loop .br Lookup = boolean() | any .br QLC = \fBquery_list_comprehension()\fR\& .br .RE .RE .RS .LP Returns a query handle for a query list comprehension\&. The query list comprehension must be the first argument to \fIqlc:q/1,2\fR\& or it will be evaluated as an ordinary list comprehension\&. It is also necessary to add the line .LP .nf -include_lib("stdlib/include/qlc.hrl"). .fi .LP to the source file\&. This causes a parse transform to substitute a fun for the query list comprehension\&. The (compiled) fun will be called when the query handle is evaluated\&. .LP When calling \fIqlc:q/1,2\fR\& from the Erlang shell the parse transform is automatically called\&. When this happens the fun substituted for the query list comprehension is not compiled but will be evaluated by \fIerl_eval(3erl)\fR\&\&. This is also true when expressions are evaluated by means of \fIfile:eval/1,2\fR\& or in the debugger\&. .LP To be very explicit, this will not work: .LP .nf \&... A = [X || {X} <- [{1},{2}]], QH = qlc:q(A), \&... .fi .LP The variable \fIA\fR\& will be bound to the evaluated value of the list comprehension (\fI[1,2]\fR\&)\&. The compiler complains with an error message ("argument is not a query list comprehension"); the shell process stops with a \fIbadarg\fR\& reason\&. .LP \fIq(QLC)\fR\& is equivalent to \fIq(QLC, [])\fR\&\&. .LP The \fI{cache, ets}\fR\& option can be used to cache the answers to a query list comprehension\&. The answers are stored in one ETS table for each cached query list comprehension\&. When a cached query list comprehension is evaluated again, answers are fetched from the table without any further computations\&. As a consequence, when all answers to a cached query list comprehension have been found, the ETS tables used for caching answers to the query list comprehension\&'s qualifiers can be emptied\&. The option \fIcache\fR\& is equivalent to \fI{cache, ets}\fR\&\&. .LP The \fI{cache, list}\fR\& option can be used to cache the answers to a query list comprehension just like \fI{cache, ets}\fR\&\&. The difference is that the answers are kept in a list (on the process heap)\&. If the answers would occupy more than a certain amount of RAM memory a temporary file is used for storing the answers\&. The option \fImax_list_size\fR\& sets the limit in bytes and the temporary file is put on the directory set by the \fItmpdir\fR\& option\&. .LP The \fIcache\fR\& option has no effect if it is known that the query list comprehension will be evaluated at most once\&. This is always true for the top-most query list comprehension and also for the list expression of the first generator in a list of qualifiers\&. Note that in the presence of side effects in filters or callback functions the answers to query list comprehensions can be affected by the \fIcache\fR\& option\&. .LP The \fI{unique, true}\fR\& option can be used to remove duplicate answers to a query list comprehension\&. The unique answers are stored in one ETS table for each query list comprehension\&. The table is emptied every time it is known that there are no more answers to the query list comprehension\&. The option \fIunique\fR\& is equivalent to \fI{unique, true}\fR\&\&. If the \fIunique\fR\& option is combined with the \fI{cache, ets}\fR\& option, two ETS tables are used, but the full answers are stored in one table only\&. If the \fIunique\fR\& option is combined with the \fI{cache, list}\fR\& option the answers are sorted twice using \fIkeysort/3\fR\&; once to remove duplicates, and once to restore the order\&. .LP The \fIcache\fR\& and \fIunique\fR\& options apply not only to the query list comprehension itself but also to the results of looking up constants, running match specifications, and joining handles\&. .LP .nf 1> Q = qlc:q([{A,X,Z,W} || A <- [a,b,c], {X,Z} <- [{a,1},{b,4},{c,6}], {W,Y} <- [{2,a},{3,b},{4,c}], X =:= Y], {cache, list}), io:format("~s~n", [qlc:info(Q)])\&. begin V1 = qlc:q([ P0 || P0 = {X,Z} <- qlc:keysort(1, [{a,1},{b,4},{c,6}], []) ]), V2 = qlc:q([ P0 || P0 = {W,Y} <- qlc:keysort(2, [{2,a},{3,b},{4,c}], []) ]), V3 = qlc:q([ [G1|G2] || G1 <- V1, G2 <- V2, element(1, G1) == element(2, G2) ], [{join,merge},{cache,list}]), qlc:q([ {A,X,Z,W} || A <- [a,b,c], [{X,Z}|{W,Y}] <- V3, X =:= Y ]) end .fi .LP In this example the cached results of the merge join are traversed for each value of \fIA\fR\&\&. Note that without the \fIcache\fR\& option the join would have been carried out three times, once for each value of \fIA\fR\& .LP \fIsort/1,2\fR\& and \fIkeysort/2,3\fR\& can also be used for caching answers and for removing duplicates\&. When sorting answers are cached in a list, possibly stored on a temporary file, and no ETS tables are used\&. .LP Sometimes (see \fBqlc:table/2\fR\& below) traversal of tables can be done by looking up key values, which is assumed to be fast\&. Under certain (rare) circumstances it could happen that there are too many key values to look up\&. The \fI{max_lookup, MaxLookup}\fR\& option can then be used to limit the number of lookups: if more than \fIMaxLookup\fR\& lookups would be required no lookups are done but the table traversed instead\&. The default value is \fIinfinity\fR\& which means that there is no limit on the number of keys to look up\&. .LP .nf 1> T = gb_trees:empty(), QH = qlc:q([X || {{X,Y},_} <- gb_table:table(T), ((X == 1) or (X == 2)) andalso ((Y == a) or (Y == b) or (Y == c))]), io:format("~s~n", [qlc:info(QH)])\&. ets:match_spec_run( lists:flatmap(fun(K) -> case gb_trees:lookup(K, gb_trees:from_orddict([])) of {value,V} -> [{K,V}]; none -> [] end end, [{1,a},{1,b},{1,c},{2,a},{2,b},{2,c}]), ets:match_spec_compile([{{{'$1','$2'},'_'},[],['$1']}])) .fi .LP In this example using the \fIgb_table\fR\& module from the \fBImplementing a QLC table\fR\& section there are six keys to look up: \fI{1,a}\fR\&, \fI{1,b}\fR\&, \fI{1,c}\fR\&, \fI{2,a}\fR\&, \fI{2,b}\fR\&, and \fI{2,c}\fR\&\&. The reason is that the two elements of the key {X, Y} are compared separately\&. .LP The \fI{lookup, true}\fR\& option can be used to ensure that the \fIqlc\fR\& module will look up constants in some QLC table\&. If there are more than one QLC table among the generators\&' list expressions, constants have to be looked up in at least one of the tables\&. The evaluation of the query fails if there are no constants to look up\&. This option is useful in situations when it would be unacceptable to traverse all objects in some table\&. Setting the \fIlookup\fR\& option to \fIfalse\fR\& ensures that no constants will be looked up (\fI{max_lookup, 0}\fR\& has the same effect)\&. The default value is \fIany\fR\& which means that constants will be looked up whenever possible\&. .LP The \fI{join, Join}\fR\& option can be used to ensure that a certain join method will be used: \fI{join, lookup}\fR\& invokes the lookup join method; \fI{join, merge}\fR\& invokes the merge join method; and \fI{join, nested_loop}\fR\& invokes the method of matching every pair of objects from two handles\&. The last method is mostly very slow\&. The evaluation of the query fails if the \fIqlc\fR\& module cannot carry out the chosen join method\&. The default value is \fIany\fR\& which means that some fast join method will be used if possible\&. .RE .LP .nf .B sort(QH1) -> QH2 .br .fi .br .nf .B sort(QH1, SortOptions) -> QH2 .br .fi .br .RS .LP Types: .RS 3 SortOptions = \fBsort_options()\fR\& .br QH1 = \fBquery_handle_or_list()\fR\& .br QH2 = \fBquery_handle()\fR\& .br .RE .RE .RS .LP Returns a query handle\&. When evaluating the query handle \fIQH2\fR\& the answers to the query handle \fIQH1\fR\& are sorted by \fBfile_sorter:sort/3\fR\& according to the options\&. .LP The sorter will use temporary files only if \fIQH1\fR\& does not evaluate to a list and the size of the binary representation of the answers exceeds \fISize\fR\& bytes, where \fISize\fR\& is the value of the \fIsize\fR\& option\&. .LP \fIsort(QH1)\fR\& is equivalent to \fIsort(QH1, [])\fR\&\&. .RE .LP .nf .B string_to_handle(QueryString) -> QH | Error .br .fi .br .nf .B string_to_handle(QueryString, Options) -> QH | Error .br .fi .br .nf .B string_to_handle(QueryString, Options, Bindings) -> QH | Error .br .fi .br .RS .LP Types: .RS 3 QueryString = string() .br Options = [Option] | Option .br Option = {max_lookup, MaxLookup} .br | {cache, \fBcache()\fR\&} .br | cache .br | {join, Join} .br | {lookup, Lookup} .br | {unique, boolean()} .br | unique .br MaxLookup = integer() >= 0 | infinity .br Join = any | lookup | merge | nested_loop .br Lookup = boolean() | any .br Bindings = \fBerl_eval:binding_struct()\fR\& .br QH = \fBquery_handle()\fR\& .br Error = {error, module(), Reason} .br Reason = \fBerl_parse:error_info()\fR\& | \fBerl_scan:error_info()\fR\& .br .RE .RE .RS .LP A string version of \fIqlc:q/1,2\fR\&\&. When the query handle is evaluated the fun created by the parse transform is interpreted by \fIerl_eval(3erl)\fR\&\&. The query string is to be one single query list comprehension terminated by a period\&. .LP .nf 1> L = [1,2,3], Bs = erl_eval:add_binding(\&'L\&', L, erl_eval:new_bindings()), QH = qlc:string_to_handle("[X+1 || X <- L]\&.", [], Bs), qlc:eval(QH)\&. [2,3,4] .fi .LP \fIstring_to_handle(QueryString)\fR\& is equivalent to \fIstring_to_handle(QueryString, [])\fR\&\&. .LP \fIstring_to_handle(QueryString, Options)\fR\& is equivalent to \fIstring_to_handle(QueryString, Options, erl_eval:new_bindings())\fR\&\&. .LP This function is probably useful mostly when called from outside of Erlang, for instance from a driver written in C\&. .RE .LP .nf .B table(TraverseFun, Options) -> QH .br .fi .br .RS .LP Types: .RS 3 TraverseFun = TraverseFun0 | TraverseFun1 .br TraverseFun0 = fun(() -> TraverseResult) .br TraverseFun1 = fun((\fBmatch_expression()\fR\&) -> TraverseResult) .br TraverseResult = Objects | term() .br Objects = [] | [term() | ObjectList] .br ObjectList = TraverseFun0 | Objects .br Options = [Option] | Option .br Option = {format_fun, FormatFun} .br | {info_fun, InfoFun} .br | {lookup_fun, LookupFun} .br | {parent_fun, ParentFun} .br | {post_fun, PostFun} .br | {pre_fun, PreFun} .br | {key_equality, KeyComparison} .br FormatFun = undefined | fun((SelectedObjects) -> FormatedTable) .br SelectedObjects = all .br | {all, NElements, DepthFun} .br | {match_spec, \fBmatch_expression()\fR\&} .br | {lookup, Position, Keys} .br | {lookup, Position, Keys, NElements, DepthFun} .br NElements = infinity | integer() >= 1 .br DepthFun = fun((term()) -> term()) .br FormatedTable = {Mod, Fun, Args} | \fBabstract_expr()\fR\& | string() .br InfoFun = undefined | fun((InfoTag) -> InfoValue) .br InfoTag = indices | is_unique_objects | keypos | num_of_objects .br InfoValue = undefined | term() .br LookupFun = undefined | fun((Position, Keys) -> LookupResult) .br LookupResult = [term()] | term() .br ParentFun = undefined | fun(() -> ParentFunValue) .br PostFun = undefined | fun(() -> term()) .br PreFun = undefined | fun((PreArgs) -> term()) .br PreArgs = [PreArg] .br PreArg = {parent_value, ParentFunValue} | {stop_fun, StopFun} .br ParentFunValue = undefined | term() .br StopFun = undefined | fun(() -> term()) .br KeyComparison = \&'=:=\&' | \&'==\&' .br Position = integer() >= 1 .br Keys = [term()] .br Mod = Fun = atom() .br Args = [term()] .br QH = \fBquery_handle()\fR\& .br .RE .RE .RS .LP Returns a query handle for a QLC table\&. In Erlang/OTP there is support for ETS, Dets and Mnesia tables, but it is also possible to turn many other data structures into QLC tables\&. The way to accomplish this is to let function(s) in the module implementing the data structure create a query handle by calling \fIqlc:table/2\fR\&\&. The different ways to traverse the table as well as properties of the table are handled by callback functions provided as options to \fIqlc:table/2\fR\&\&. .LP The callback function \fITraverseFun\fR\& is used for traversing the table\&. It is to return a list of objects terminated by either \fI[]\fR\& or a nullary fun to be used for traversing the not yet traversed objects of the table\&. Any other return value is immediately returned as value of the query evaluation\&. Unary \fITraverseFun\fR\&s are to accept a match specification as argument\&. The match specification is created by the parse transform by analyzing the pattern of the generator calling \fIqlc:table/2\fR\& and filters using variables introduced in the pattern\&. If the parse transform cannot find a match specification equivalent to the pattern and filters, \fITraverseFun\fR\& will be called with a match specification returning every object\&. Modules that can utilize match specifications for optimized traversal of tables should call \fIqlc:table/2\fR\& with a unary \fITraverseFun\fR\& while other modules can provide a nullary \fITraverseFun\fR\&\&. \fIets:table/2\fR\& is an example of the former; \fIgb_table:table/1\fR\& in the \fBImplementing a QLC table\fR\& section is an example of the latter\&. .LP \fIPreFun\fR\& is a unary callback function that is called once before the table is read for the first time\&. If the call fails, the query evaluation fails\&. Similarly, the nullary callback function \fIPostFun\fR\& is called once after the table was last read\&. The return value, which is caught, is ignored\&. If \fIPreFun\fR\& has been called for a table, \fIPostFun\fR\& is guaranteed to be called for that table, even if the evaluation of the query fails for some reason\&. The order in which pre (post) functions for different tables are evaluated is not specified\&. Other table access than reading, such as calling \fIInfoFun\fR\&, is assumed to be OK at any time\&. The argument \fIPreArgs\fR\& is a list of tagged values\&. Currently there are two tags, \fIparent_value\fR\& and \fIstop_fun\fR\&, used by Mnesia for managing transactions\&. The value of \fIparent_value\fR\& is the value returned by \fIParentFun\fR\&, or \fIundefined\fR\& if there is no \fIParentFun\fR\&\&. \fIParentFun\fR\& is called once just before the call of \fIPreFun\fR\& in the context of the process calling \fIeval\fR\&, \fIfold\fR\&, or \fIcursor\fR\&\&. The value of \fIstop_fun\fR\& is a nullary fun that deletes the cursor if called from the parent, or \fIundefined\fR\& if there is no cursor\&. .LP The binary callback function \fILookupFun\fR\& is used for looking up objects in the table\&. The first argument \fIPosition\fR\& is the key position or an indexed position and the second argument \fIKeys\fR\& is a sorted list of unique values\&. The return value is to be a list of all objects (tuples) such that the element at \fIPosition\fR\& is a member of \fIKeys\fR\&\&. Any other return value is immediately returned as value of the query evaluation\&. \fILookupFun\fR\& is called instead of traversing the table if the parse transform at compile time can find out that the filters match and compare the element at \fIPosition\fR\& in such a way that only \fIKeys\fR\& need to be looked up in order to find all potential answers\&. The key position is obtained by calling \fIInfoFun(keypos)\fR\& and the indexed positions by calling \fIInfoFun(indices)\fR\&\&. If the key position can be used for lookup it is always chosen, otherwise the indexed position requiring the least number of lookups is chosen\&. If there is a tie between two indexed positions the one occurring first in the list returned by \fIInfoFun\fR\& is chosen\&. Positions requiring more than \fBmax_lookup\fR\& lookups are ignored\&. .LP The unary callback function \fIInfoFun\fR\& is to return information about the table\&. \fIundefined\fR\& should be returned if the value of some tag is unknown: .RS 2 .TP 2 * \fIindices\fR\&\&. Returns a list of indexed positions, a list of positive integers\&. .LP .TP 2 * \fIis_unique_objects\fR\&\&. Returns \fItrue\fR\& if the objects returned by \fITraverseFun\fR\& are unique\&. .LP .TP 2 * \fIkeypos\fR\&\&. Returns the position of the table\&'s key, a positive integer\&. .LP .TP 2 * \fIis_sorted_key\fR\&\&. Returns \fItrue\fR\& if the objects returned by \fITraverseFun\fR\& are sorted on the key\&. .LP .TP 2 * \fInum_of_objects\fR\&\&. Returns the number of objects in the table, a non-negative integer\&. .LP .RE .LP The unary callback function \fIFormatFun\fR\& is used by \fBqlc:info/1,2\fR\& for displaying the call that created the table\&'s query handle\&. The default value, \fIundefined\fR\&, means that \fIinfo/1,2\fR\& displays a call to \fI\&'$MOD\&':\&'$FUN\&'/0\fR\&\&. It is up to \fIFormatFun\fR\& to present the selected objects of the table in a suitable way\&. However, if a character list is chosen for presentation it must be an Erlang expression that can be scanned and parsed (a trailing dot will be added by \fIqlc:info\fR\& though)\&. \fIFormatFun\fR\& is called with an argument that describes the selected objects based on optimizations done as a result of analyzing the filters of the QLC where the call to \fIqlc:table/2\fR\& occurs\&. The possible values of the argument are: .RS 2 .TP 2 * \fI{lookup, Position, Keys, NElements, DepthFun}\fR\&\&. \fILookupFun\fR\& is used for looking up objects in the table\&. .LP .TP 2 * \fI{match_spec, MatchExpression}\fR\&\&. No way of finding all possible answers by looking up keys was found, but the filters could be transformed into a match specification\&. All answers are found by calling \fITraverseFun(MatchExpression)\fR\&\&. .LP .TP 2 * \fI{all, NElements, DepthFun}\fR\&\&. No optimization was found\&. A match specification matching all objects will be used if \fITraverseFun\fR\& is unary\&. .LP .RE .LP \fINElements\fR\& is the value of the \fIinfo/1,2\fR\& option \fIn_elements\fR\&, and \fIDepthFun\fR\& is a function that can be used for limiting the size of terms; calling \fIDepthFun(Term)\fR\& substitutes \fI\&'\&.\&.\&.\&'\fR\& for parts of \fITerm\fR\& below the depth specified by the \fIinfo/1,2\fR\& option \fIdepth\fR\&\&. If calling \fIFormatFun\fR\& with an argument including \fINElements\fR\& and \fIDepthFun\fR\& fails, \fIFormatFun\fR\& is called once again with an argument excluding \fINElements\fR\& and \fIDepthFun\fR\& (\fI{lookup, Position, Keys}\fR\& or \fIall\fR\&)\&. .LP The value of \fIkey_equality\fR\& is to be \fI\&'=:=\&'\fR\& if the table considers two keys equal if they match, and to be \fI\&'==\&'\fR\& if two keys are equal if they compare equal\&. The default is \fI\&'=:=\&'\fR\&\&. .LP See \fBets(3erl)\fR\&, \fBdets(3erl)\fR\& and \fBmnesia(3erl)\fR\& for the various options recognized by \fItable/1,2\fR\& in respective module\&. .RE .SH "SEE ALSO" .LP \fBdets(3erl)\fR\&, \fB Erlang Reference Manual\fR\&, \fBerl_eval(3erl)\fR\&, \fBerlang(3erl)\fR\&, \fBets(3erl)\fR\&, \fBfile(3erl)\fR\&, \fBerror_logger(3erl)\fR\&, \fBfile_sorter(3erl)\fR\&, \fBmnesia(3erl)\fR\&, \fB Programming Examples\fR\&, \fBshell(3erl)\fR\&