summaryrefslogtreecommitdiff
path: root/src/discord/store.hpp
blob: 01401f6179e79861ef79b178311364bb5c64ddf8 (plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#pragma once
#include "objects.hpp"
#include <unordered_map>
#include <unordered_set>
#include <mutex>
#include <filesystem>
#include <sqlite3.h>

#ifdef GetMessage // fuck you windows.h
#undef GetMessage
#endif

class Store {
private:
    class Statement;

public:
    Store(bool mem_store = false);
    ~Store();

    bool IsValid() const;

    void SetUser(Snowflake id, const UserData &user);
    void SetChannel(Snowflake id, const ChannelData &chan);
    void SetGuild(Snowflake id, const GuildData &guild);
    void SetRole(Snowflake guild_id, const RoleData &role);
    void SetMessage(Snowflake id, const Message &message);
    void SetGuildMember(Snowflake guild_id, Snowflake user_id, const GuildMember &data);
    void SetPermissionOverwrite(Snowflake channel_id, Snowflake id, const PermissionOverwrite &perm);
    void SetEmoji(Snowflake id, const EmojiData &emoji);
    void SetBan(Snowflake guild_id, Snowflake user_id, const BanData &ban);
    void SetWebhookMessage(const Message &message);

    std::optional<ChannelData> GetChannel(Snowflake id) const;
    std::optional<EmojiData> GetEmoji(Snowflake id) const;
    std::optional<GuildData> GetGuild(Snowflake id) const;
    std::optional<GuildMember> GetGuildMember(Snowflake guild_id, Snowflake user_id) const;
    std::optional<Message> GetMessage(Snowflake id) const;
    std::optional<PermissionOverwrite> GetPermissionOverwrite(Snowflake channel_id, Snowflake id) const;
    std::optional<RoleData> GetRole(Snowflake id) const;
    std::optional<UserData> GetUser(Snowflake id) const;
    std::optional<BanData> GetBan(Snowflake guild_id, Snowflake user_id) const;
    std::vector<BanData> GetBans(Snowflake guild_id) const;
    std::optional<WebhookMessageData> GetWebhookMessage(Snowflake message_id) const;

    Snowflake GetGuildOwner(Snowflake guild_id) const;
    std::vector<Snowflake> GetMemberRoles(Snowflake guild_id, Snowflake user_id) const;

    std::vector<Message> GetLastMessages(Snowflake id, size_t num) const;
    std::vector<Message> GetMessagesBefore(Snowflake channel_id, Snowflake message_id, size_t limit) const;
    std::vector<Message> GetPinnedMessages(Snowflake channel_id) const;
    std::vector<ChannelData> GetActiveThreads(Snowflake channel_id) const; // public
    std::vector<Snowflake> GetChannelIDsWithParentID(Snowflake channel_id) const;
    std::unordered_set<Snowflake> GetMembersInGuild(Snowflake guild_id) const;
    // ^ not the same as GetUsersInGuild since users in a guild may include users who do not have retrieved member data

    template<typename Iter>
    std::vector<UserData> GetUsersBulk(Iter begin, Iter end) {
        const int size = std::distance(begin, end);
        if (size == 0) return {};

        std::string query = "SELECT * FROM USERS WHERE id IN (";
        for (int i = 0; i < size; i++) {
            query += "?, ";
        }
        query.resize(query.size() - 2); // chop off extra ", "
        query += ")";

        Statement s(m_db, query.c_str());
        if (!s.OK()) {
            printf("failed to prepare bulk users: %s\n", m_db.ErrStr());
            return {};
        }

        for (int i = 0; begin != end; i++, begin++) {
            s.Bind(i, *begin);
        }

        std::vector<UserData> r;
        r.reserve(size);
        while (s.FetchOne()) {
            r.push_back(GetUserBound(&s));
        }
        printf("fetched %llu\n", r.size());
        return r;
    }

    void AddReaction(const MessageReactionAddObject &data, bool byself);
    void RemoveReaction(const MessageReactionRemoveObject &data, bool byself);

    void ClearGuild(Snowflake id);
    void ClearChannel(Snowflake id);
    void ClearBan(Snowflake guild_id, Snowflake user_id);
    void ClearRecipient(Snowflake channel_id, Snowflake user_id);
    void ClearRole(Snowflake id);

    std::unordered_set<Snowflake> GetChannels() const;
    std::unordered_set<Snowflake> GetGuilds() const;

    void ClearAll();

    void BeginTransaction();
    void EndTransaction();

private:
    class Database {
    public:
        Database(const char *path);
        ~Database();

        int Close();
        int StartTransaction();
        int EndTransaction();
        int Execute(const char *command);
        int Error() const;
        bool OK() const;
        const char *ErrStr() const;
        int SetError(int err);
        sqlite3 *obj();

    private:
        sqlite3 *m_db;
        int m_err = SQLITE_OK;
        mutable char m_err_scratch[256] { 0 };

        // stupid shit i dont like to allow closing properly
        using type_signal_close = sigc::signal<void>;
        type_signal_close m_signal_close;

    public:
        type_signal_close signal_close();
    };

    class Statement {
    public:
        Statement() = delete;
        Statement(const Statement &other) = delete;
        Statement(Database &db, const char *command);
        ~Statement();
        Statement &operator=(Statement &other) = delete;

        [[nodiscard]] bool OK() const;

        int Bind(int index, Snowflake id);
        int Bind(int index, const char *str, size_t len = -1);
        int Bind(int index, const std::string &str);
        int Bind(int index);

        template<typename T>
        int Bind(int index, std::optional<T> opt) {
            if (opt.has_value())
                return Bind(index, opt.value());
            else
                return Bind(index);
        }

        template<typename Iter>
        int BindIDsAsJSON(int index, Iter start, Iter end) {
            std::vector<Snowflake> x;
            for (Iter it = start; it != end; it++) {
                x.push_back((*it).ID);
            }
            return Bind(index, nlohmann::json(x).dump());
        }

        template<typename T>
        int BindAsJSONArray(int index, const std::optional<T> &obj) {
            if (obj.has_value())
                return Bind(index, nlohmann::json(obj.value()).dump());
            else
                return Bind(index, std::string("[]"));
        }

        template<typename T>
        int BindAsJSON(int index, const T &obj) {
            return Bind(index, nlohmann::json(obj).dump());
        }

        template<typename T>
        inline typename std::enable_if<std::is_enum<T>::value, int>::type
        Bind(int index, T val) {
            return Bind(index, static_cast<typename std::underlying_type<T>::type>(val));
        }

        template<typename T>
        typename std::enable_if<std::is_integral<T>::value, int>::type
        Bind(int index, T val) {
            return m_db->SetError(sqlite3_bind_int64(m_stmt, index, val));
        }

        template<typename T>
        int BindAsJSON(int index, const std::optional<T> &obj) {
            if (obj.has_value())
                return Bind(index, nlohmann::json(obj.value()).dump());
            else
                return Bind(index);
        }

        template<typename T>
        typename std::enable_if<std::is_integral<T>::value>::type
        Get(int index, T &out) const {
            out = static_cast<T>(sqlite3_column_int64(m_stmt, index));
        }

        void Get(int index, Snowflake &out) const;
        void Get(int index, std::string &out) const;

        template<typename T>
        void GetJSON(int index, std::optional<T> &out) const {
            if (IsNull(index))
                out = std::nullopt;
            else {
                std::string stuff;
                Get(index, stuff);
                if (stuff == "")
                    out = std::nullopt;
                else
                    out = nlohmann::json::parse(stuff).get<T>();
            }
        }

        template<typename T>
        void GetJSON(int index, T &out) const {
            std::string stuff;
            Get(index, stuff);
            nlohmann::json::parse(stuff).get_to(out);
        }

        template<typename T>
        void Get(int index, std::optional<T> &out) const {
            if (IsNull(index))
                out = std::nullopt;
            else {
                T tmp;
                Get(index, tmp);
                out = std::optional<T>(std::move(tmp));
            }
        }

        template<typename T>
        inline typename std::enable_if<std::is_enum<T>::value, void>::type
        Get(int index, T &val) const {
            typename std::underlying_type<T>::type tmp;
            Get(index, tmp);
            val = static_cast<T>(tmp);
        }

        template<typename T>
        void GetIDOnlyStructs(int index, std::optional<std::vector<T>> &out) const {
            out.emplace();
            std::string str;
            Get(index, str);
            for (const auto &id : nlohmann::json::parse(str))
                out->emplace_back().ID = id.get<Snowflake>();
        }

        template<typename T, typename OutputIt>
        void GetArray(int index, OutputIt first) const {
            std::string str;
            Get(index, str);
            for (const auto &id : nlohmann::json::parse(str))
                *first++ = id.get<T>();
        }

        [[nodiscard]] bool IsNull(int index) const;
        int Step();
        bool Insert();
        bool FetchOne();
        int Reset();

        sqlite3_stmt *obj();

    private:
        Database *m_db;
        sqlite3_stmt *m_stmt;
    };

    UserData GetUserBound(Statement *stmt) const;
    Message GetMessageBound(std::unique_ptr<Statement> &stmt) const;
    static RoleData GetRoleBound(std::unique_ptr<Statement> &stmt);

    void SetMessageInteractionPair(Snowflake message_id, const MessageInteractionData &interaction);

    bool CreateTables();
    bool CreateStatements();

    bool m_ok = true;

    std::filesystem::path m_db_path;
    Database m_db;
#define STMT(x) mutable std::unique_ptr<Statement> m_stmt_##x
    STMT(set_guild);
    STMT(get_guild);
    STMT(get_guild_ids);
    STMT(clr_guild);
    STMT(set_chan);
    STMT(get_chan);
    STMT(get_chan_ids);
    STMT(clr_chan);
    STMT(set_msg);
    STMT(get_msg);
    STMT(set_msg_ref);
    STMT(get_last_msgs);
    STMT(set_user);
    STMT(get_user);
    STMT(set_member);
    STMT(get_member);
    STMT(set_role);
    STMT(get_role);
    STMT(get_guild_roles);
    STMT(set_emoji);
    STMT(get_emoji);
    STMT(set_perm);
    STMT(get_perm);
    STMT(set_ban);
    STMT(get_ban);
    STMT(get_bans);
    STMT(clr_ban);
    STMT(set_interaction);
    STMT(set_member_roles);
    STMT(get_member_roles);
    STMT(clr_member_roles);
    STMT(set_guild_emoji);
    STMT(get_guild_emojis);
    STMT(clr_guild_emoji);
    STMT(set_guild_feature);
    STMT(get_guild_features);
    STMT(get_guild_chans);
    STMT(set_thread);
    STMT(get_threads);
    STMT(get_active_threads);
    STMT(get_messages_before);
    STMT(get_pins);
    STMT(set_emoji_role);
    STMT(get_emoji_roles);
    STMT(set_mention);
    STMT(get_mentions);
    STMT(set_role_mention);
    STMT(get_role_mentions);
    STMT(set_attachment);
    STMT(get_attachments);
    STMT(set_recipient);
    STMT(get_recipients);
    STMT(clr_recipient);
    STMT(add_reaction);
    STMT(sub_reaction);
    STMT(get_reactions);
    STMT(get_chan_ids_parent);
    STMT(get_guild_member_ids);
    STMT(clr_role);
    STMT(get_guild_owner);
    STMT(set_webhook_msg);
    STMT(get_webhook_msg);
#undef STMT
};