View Source QLC Usage

This cheat sheet covers some example queries using Query-List Comprehensions in Erlang, as well as some debugging tips.

QLC modules must include this library include as part of their prelude:

-include_lib("stdlib/include/qlc.hrl").

As per the Erlang docs for QLC:

This causes a parse transform to substitute a fun for the QLC. The (compiled) fun is called when the query handle is evaluated.

Examples

Fetch role members

find_role_users(RequestedGuildId, RoleId, MemberCache) ->
    qlc:q([Member || {{GuildId, MemberId}, Member} <- MemberCache:query_handle(),
                   % Filter to member objects of the selected guild
                   GuildId =:= RequestedGuildId,
                   % Filter to members of the provided role
                   lists:member(RoleId, map_get(roles, Member))]).

Fetch guilds over a certain size

find_large_communities(Threshold, GuildCache) ->
    qlc:q([Guild || {_, Guild} <- GuildCache:query_handle(),
                    % Filter for guilds that are over the provided size
                    map_get(member_count, Guild) > Threshold]).

Find all online users in a guild

find_online_users(RequestedGuildId, PresenceCache, UserCache) ->
    qlc:q([User || {{GuildId, PresenceUserId}, Presence} <- PresenceCache:query_handle(),
                   % Filter to members in the requested guild ID
                   GuildId =:= RequestedGuildId,
                   % Fetch any members where the status is not offline
                   map_get(status, Presence) /= offline,
                   % Join the found users on the UserCache
                   {UserId, User} <- UserCache:query_handle(),
                   % Return the users that match the found presences
                   UserId =:= PresenceUserId]).

This depends on the guild presences intent being enabled and the bot storing received presences in the presence cache.

Getting the largest N guilds

top_guilds(N, GuildCache) ->
  Q = qlc:q([{MemberCount, Guild} || {_Id, #{member_count := MemberCount} = Guild} <- GuildCache:query_handle()]),
  Q2 = qlc:keysort(1, Q, [{order, descending}]),
  GuildCache:wrap_qlc(fun () ->
    C = qlc:cursor(Q2),
    R = qlc:next_answers(C, N),
    ok = qlc:delete_cursor(C),
    R
  end).

Debugging QLC

View query info

You can use :qlc.info/1 to evaluate how Erlang will parse a query. You can read the Erlang docs for an explanation of the value returned by this call

:qlc.info(
    :my_queries.find_users(..., Nostrum.Cache.UserCache)
)

Sampling a query

You can return only X records that match a query using :qlc.next_answers/2, passing in the query as the first argument and the number of answers to return as the second argument.

:qlc.next_answers(
    :my_queries.find_users(..., Nostrum.Cache.UserCache),
    5
)