-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathqlc.cheatmd
77 lines (56 loc) · 2.5 KB
/
qlc.cheatmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 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:
```erl
-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
```erl
find_role_users(RequestedGuildId, RoleId, MemberCache) ->
qlc:q([{User, 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
```erl
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
```erl
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.
## Debugging QLC
{: .col-2 }
### 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
```elixir
: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.
```elixir
:qlc.next_answers(
:my_queries.find_users(..., Nostrum.Cache.UserCache),
5
)
```