-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
2555 lines (2347 loc) · 95.8 KB
/
Copy pathdb.js
File metadata and controls
2555 lines (2347 loc) · 95.8 KB
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { Pool } = require('pg');
const logger = require('./utils/logger');
const poolConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
database: process.env.DB_DATABASE_NAME,
password: process.env.DB_PASSWORD,
ssl: { rejectUnauthorized: false },
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
};
const pool = new Pool(poolConfig);
pool.on('error', (err) => {
logger.error('[DB Pool] Unexpected error on idle client', err);
});
const executeQuery = async (query, params) => {
const client = await pool.connect();
try {
const result = await client.query(query, params);
return result;
} catch (err) {
logger.error('[DB] Query error:', err);
throw err;
} finally {
client.release();
}
};
const closePool = async () => {
await pool.end();
logger.info('[DB Pool] Connection pool closed');
};
// Officials application queries (moved from interactionHandler.js to use pool)
const findOfficialApplication = async (discordId) => {
const result = await executeQuery(
'SELECT * FROM official_applications WHERE discord_id = $1',
[discordId]
);
return result.rows;
};
const insertOfficialApplication = async (discordId, username, inGameUsername, agreedToRules, understandsConsequences, applicationUrl) => {
await executeQuery(
`INSERT INTO official_applications (discord_id, discord_username, in_game_username, agreed_to_rules, understands_consequences, application_url, submitted_at)
VALUES ($1, $2, $3, $4, $5, $6, NOW())`,
[discordId, username, inGameUsername, agreedToRules, understandsConsequences, applicationUrl]
);
};
const deleteOfficialApplication = async (discordId) => {
await executeQuery(
'DELETE FROM official_applications WHERE discord_id = $1',
[discordId]
);
};
// Analytics events: local mirror of everything sent to Mixpanel, so metrics
// can be queried directly without Mixpanel read access.
const ensureAnalyticsEventsTable = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS analytics_events (
id BIGSERIAL PRIMARY KEY,
event_name TEXT NOT NULL,
user_id TEXT NOT NULL,
properties JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
await executeQuery(`
CREATE INDEX IF NOT EXISTS idx_analytics_events_name_time
ON analytics_events (event_name, created_at)
`);
};
const insertAnalyticsEvent = async (eventName, userId, properties = {}) => {
await executeQuery(
`INSERT INTO analytics_events (event_name, user_id, properties)
VALUES ($1, $2, $3)`,
[eventName, String(userId), JSON.stringify(properties)]
);
};
// FF Official application queries
const ensureFfOfficialApplicationsTable = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS ff_official_applications (
discord_id TEXT PRIMARY KEY,
discord_username TEXT NOT NULL,
in_game_username TEXT NOT NULL,
applicant_role TEXT NOT NULL,
officiating_duration TEXT NOT NULL,
understands_rules BOOLEAN NOT NULL,
motivation TEXT NOT NULL,
stats_link TEXT NOT NULL,
application_url TEXT NOT NULL,
submitted_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
};
const findFfOfficialApplication = async (discordId) => {
const result = await executeQuery(
'SELECT * FROM ff_official_applications WHERE discord_id = $1',
[discordId]
);
return result.rows;
};
const insertFfOfficialApplication = async (params) => {
const {
discordId,
username,
inGameUsername,
currentRole,
officiatingDuration,
understandsRules,
motivation,
statsLink,
applicationUrl,
} = params;
await executeQuery(
`INSERT INTO ff_official_applications
(discord_id, discord_username, in_game_username, applicant_role, officiating_duration, understands_rules, motivation, stats_link, application_url, submitted_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NOW())`,
[discordId, username, inGameUsername, currentRole, officiatingDuration, understandsRules, motivation, statsLink, applicationUrl]
);
};
const deleteFfOfficialApplication = async (discordId) => {
await executeQuery(
'DELETE FROM ff_official_applications WHERE discord_id = $1',
[discordId]
);
};
const ensureBugSquasherApplicationsTable = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS community_bug_squasher_applications (
discord_id TEXT PRIMARY KEY,
discord_username TEXT NOT NULL,
requirements_aware BOOLEAN NOT NULL,
no_guarantee_aware BOOLEAN NOT NULL,
tos_aware BOOLEAN NOT NULL,
motivation TEXT NOT NULL,
value_add TEXT NOT NULL,
application_url TEXT NOT NULL,
submitted_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
};
const findBugSquasherApplication = async (discordId) => {
const result = await executeQuery(
'SELECT * FROM community_bug_squasher_applications WHERE discord_id = $1',
[discordId]
);
return result.rows;
};
const insertBugSquasherApplication = async (params) => {
const {
discordId,
username,
requirementsAware,
noGuaranteeAware,
tosAware,
motivation,
valueAdd,
applicationUrl,
} = params;
await executeQuery(
`INSERT INTO community_bug_squasher_applications
(discord_id, discord_username, requirements_aware, no_guarantee_aware, tos_aware, motivation, value_add, application_url, submitted_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())`,
[discordId, username, requirementsAware, noGuaranteeAware, tosAware, motivation, valueAdd, applicationUrl]
);
};
const deleteBugSquasherApplication = async (discordId) => {
await executeQuery(
'DELETE FROM community_bug_squasher_applications WHERE discord_id = $1',
[discordId]
);
};
const ensureEmhApplicationsTable = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS emh_applications (
discord_id TEXT PRIMARY KEY,
discord_username TEXT NOT NULL,
ingame_name TEXT NOT NULL,
hosting_duration TEXT NOT NULL,
rules_read BOOLEAN NOT NULL,
motivation TEXT NOT NULL,
youtube_link TEXT NOT NULL,
application_url TEXT NOT NULL,
submitted_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
};
const findEmhApplication = async (discordId) => {
const result = await executeQuery(
'SELECT * FROM emh_applications WHERE discord_id = $1',
[discordId]
);
return result.rows;
};
const insertEmhApplication = async (params) => {
const {
discordId,
username,
ingameName,
hostingDuration,
rulesRead,
motivation,
youtubeLink,
applicationUrl,
} = params;
await executeQuery(
`INSERT INTO emh_applications
(discord_id, discord_username, ingame_name, hosting_duration, rules_read, motivation, youtube_link, application_url, submitted_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())`,
[discordId, username, ingameName, hostingDuration, rulesRead, motivation, youtubeLink, applicationUrl]
);
};
const deleteEmhApplication = async (discordId) => {
await executeQuery(
'DELETE FROM emh_applications WHERE discord_id = $1',
[discordId]
);
};
const ensureCdtApplicationsTable = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS cdt_applications (
discord_id TEXT PRIMARY KEY,
discord_username TEXT NOT NULL,
ingame_name TEXT NOT NULL,
challenge_history TEXT NOT NULL,
no_ai BOOLEAN NOT NULL,
motivation TEXT NOT NULL,
portfolio_link TEXT NOT NULL,
application_url TEXT NOT NULL,
submitted_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
};
const findCdtApplication = async (discordId) => {
const result = await executeQuery(
'SELECT * FROM cdt_applications WHERE discord_id = $1',
[discordId]
);
return result.rows;
};
const insertCdtApplication = async (params) => {
const {
discordId,
username,
ingameName,
challengeHistory,
noAi,
motivation,
portfolioLink,
applicationUrl,
} = params;
await executeQuery(
`INSERT INTO cdt_applications
(discord_id, discord_username, ingame_name, challenge_history, no_ai, motivation, portfolio_link, application_url, submitted_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())`,
[discordId, username, ingameName, challengeHistory, noAi, motivation, portfolioLink, applicationUrl]
);
};
const deleteCdtApplication = async (discordId) => {
await executeQuery(
'DELETE FROM cdt_applications WHERE discord_id = $1',
[discordId]
);
};
// CDT published designs. Files live in S3 under cdt-designs/<id>/v<version>/
// so leads can swap them without touching the public forum post; downloads are
// tracked one row per unique user per design.
const ensureCdtDesignTables = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS cdt_designs (
design_id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
category TEXT NOT NULL,
description TEXT NOT NULL,
designer_id TEXT NOT NULL,
credit_name TEXT NOT NULL,
file_version INTEGER NOT NULL DEFAULT 1,
forum_thread_id TEXT NOT NULL DEFAULT '',
approved_by TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
await executeQuery(`
CREATE TABLE IF NOT EXISTS cdt_design_downloads (
design_id INTEGER NOT NULL REFERENCES cdt_designs(design_id) ON DELETE CASCADE,
discord_id TEXT NOT NULL,
downloaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (design_id, discord_id)
)
`);
};
const insertCdtDesign = async (params) => {
const {
title,
category,
description,
designerId,
creditName,
approvedBy,
} = params;
const result = await executeQuery(
`INSERT INTO cdt_designs
(title, category, description, designer_id, credit_name, approved_by)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING design_id`,
[title, category, description, designerId, creditName, approvedBy]
);
return result.rows[0].design_id;
};
const getCdtDesign = async (designId) => {
const result = await executeQuery(
'SELECT * FROM cdt_designs WHERE design_id = $1',
[designId]
);
return result.rows[0] || null;
};
const updateCdtDesign = async (designId, fields) => {
const columns = {
title: 'title',
description: 'description',
creditName: 'credit_name',
fileVersion: 'file_version',
forumThreadId: 'forum_thread_id',
};
const sets = [];
const values = [];
for (const [key, column] of Object.entries(columns)) {
if (fields[key] !== undefined) {
values.push(fields[key]);
sets.push(`${column} = $${values.length}`);
}
}
if (sets.length === 0) {
return;
}
values.push(designId);
await executeQuery(
`UPDATE cdt_designs SET ${sets.join(', ')}, updated_at = NOW() WHERE design_id = $${values.length}`,
values
);
};
// Compare-and-set so two leads updating the same design's files concurrently
// cannot both commit; the loser cleans up its uploaded prefix.
const commitCdtFileVersion = async (designId, fromVersion, toVersion) => {
const result = await executeQuery(
`UPDATE cdt_designs SET file_version = $3, updated_at = NOW()
WHERE design_id = $1 AND file_version = $2`,
[designId, fromVersion, toVersion]
);
return result.rowCount > 0;
};
const deleteCdtDesign = async (designId) => {
await executeQuery(
'DELETE FROM cdt_designs WHERE design_id = $1',
[designId]
);
};
const searchCdtDesigns = async (query) => {
const result = await executeQuery(
`SELECT design_id, title, category FROM cdt_designs
WHERE title ILIKE $1
ORDER BY created_at DESC
LIMIT 25`,
[`%${query}%`]
);
return result.rows;
};
const recordCdtDownload = async (designId, discordId) => {
await executeQuery(
`INSERT INTO cdt_design_downloads (design_id, discord_id)
VALUES ($1, $2)
ON CONFLICT (design_id, discord_id) DO NOTHING`,
[designId, discordId]
);
};
// Every published design with its thread and unique-download count, ordered so
// the first row is the Most Downloaded candidate (ties go to the older design).
const cdtTagStats = async () => {
const result = await executeQuery(
`SELECT d.design_id, d.forum_thread_id, COUNT(dl.discord_id)::int AS downloads
FROM cdt_designs d
LEFT JOIN cdt_design_downloads dl ON dl.design_id = d.design_id
WHERE d.forum_thread_id <> ''
GROUP BY d.design_id
ORDER BY downloads DESC, d.created_at ASC`
);
return result.rows;
};
const cdtDownloadStats = async () => {
const result = await executeQuery(
`SELECT d.design_id, d.title, d.category, d.credit_name,
COUNT(dl.discord_id)::int AS downloads
FROM cdt_designs d
LEFT JOIN cdt_design_downloads dl ON dl.design_id = d.design_id
GROUP BY d.design_id
ORDER BY downloads DESC, d.created_at DESC
LIMIT 20`
);
return result.rows;
};
// Game ideas metrics (durable tracking of forum threads + thread messages)
const ensureGameIdeasTables = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS game_ideas_threads (
thread_id TEXT PRIMARY KEY,
starter_id TEXT,
name TEXT,
url TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
await executeQuery(`
CREATE TABLE IF NOT EXISTS game_ideas_messages (
message_id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
author_id TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
await executeQuery(
'CREATE INDEX IF NOT EXISTS idx_game_ideas_threads_created_at ON game_ideas_threads (created_at)'
).catch(() => {});
await executeQuery(
'CREATE INDEX IF NOT EXISTS idx_game_ideas_messages_created_at ON game_ideas_messages (created_at)'
).catch(() => {});
await executeQuery(
'CREATE INDEX IF NOT EXISTS idx_game_ideas_messages_author ON game_ideas_messages (author_id)'
).catch(() => {});
};
const insertGameIdeasThread = async ({ threadId, starterId, name, url, createdAt }) => {
await executeQuery(
`INSERT INTO game_ideas_threads (thread_id, starter_id, name, url, created_at)
VALUES ($1, $2, $3, $4, COALESCE($5, NOW()))
ON CONFLICT (thread_id) DO NOTHING`,
[threadId, starterId || null, name || null, url || null, createdAt || null]
);
};
const insertGameIdeasMessage = async ({ messageId, threadId, authorId, createdAt }) => {
await executeQuery(
`INSERT INTO game_ideas_messages (message_id, thread_id, author_id, created_at)
VALUES ($1, $2, $3, COALESCE($4, NOW()))
ON CONFLICT (message_id) DO NOTHING`,
[messageId, threadId, authorId, createdAt || null]
);
};
const getGameIdeasSummary = async (start, end) => {
const result = await executeQuery(
`SELECT
(SELECT COUNT(*) FROM game_ideas_threads WHERE created_at >= $1 AND created_at <= $2) AS thread_count,
(SELECT COUNT(*) FROM game_ideas_messages WHERE created_at >= $1 AND created_at <= $2) AS message_count,
(SELECT COUNT(DISTINCT author_id) FROM game_ideas_messages WHERE created_at >= $1 AND created_at <= $2) AS unique_participants`,
[start, end]
);
const row = result.rows[0] || {};
return {
threadCount: parseInt(row.thread_count, 10) || 0,
messageCount: parseInt(row.message_count, 10) || 0,
uniqueParticipants: parseInt(row.unique_participants, 10) || 0,
};
};
const fetchGameIdeasThreadsInRange = async (start, end) => {
const result = await executeQuery(
`SELECT thread_id, starter_id, name, url, created_at
FROM game_ideas_threads
WHERE created_at >= $1 AND created_at <= $2
ORDER BY created_at ASC`,
[start, end]
);
return result.rows;
};
// Top-5 community poll: post catalog (poll_posts) + per-user ranked picks (poll_votes).
const ensurePollTables = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS poll_posts (
thread_id TEXT NOT NULL,
board TEXT NOT NULL,
title TEXT,
url TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (thread_id, board)
)
`);
await executeQuery(
'CREATE INDEX IF NOT EXISTS idx_poll_posts_board ON poll_posts (board)'
).catch(() => {});
// When Ballhead posted the "add this to your Top 5" nudge in the post's thread;
// NULL means never nudged. Not swallowed like the index creations, because the
// nudge job selects on this column and would fail silently every run without it.
await executeQuery(
'ALTER TABLE poll_posts ADD COLUMN IF NOT EXISTS promoted_at TIMESTAMPTZ'
);
await executeQuery(`
CREATE TABLE IF NOT EXISTS poll_votes (
user_id TEXT NOT NULL,
board TEXT NOT NULL,
thread_id TEXT NOT NULL,
position SMALLINT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (user_id, board, thread_id),
UNIQUE (user_id, board, position)
)
`);
await executeQuery(
'CREATE INDEX IF NOT EXISTS idx_poll_votes_board_thread ON poll_votes (board, thread_id)'
).catch(() => {});
};
// A new board row inherits the thread's existing promoted_at. Nudges are posted
// once per thread, so a post that gains or swaps a board tag after being nudged
// must not look un-nudged again just because its row is new.
const upsertPollPost = async ({ threadId, board, title, url, createdAt }) => {
await executeQuery(
`INSERT INTO poll_posts (thread_id, board, title, url, created_at, promoted_at)
VALUES ($1, $2, $3, $4, COALESCE($5, NOW()),
(SELECT MAX(promoted_at) FROM poll_posts WHERE thread_id = $1))
ON CONFLICT (thread_id, board) DO UPDATE
SET title = EXCLUDED.title, url = EXCLUDED.url`,
[threadId, board, title || null, url || null, createdAt || null]
);
};
// Remove any board rows for this thread that are not in the given list.
// boards = [] removes every row for the thread (e.g. thread deleted or de-tagged).
const deletePollPostBoardsExcept = async (threadId, boards) => {
await executeQuery(
'DELETE FROM poll_posts WHERE thread_id = $1 AND NOT (board = ANY($2::text[]))',
[threadId, boards]
);
};
const searchPollPosts = async (board, query, limit = 25) => {
const q = (query || '').trim();
const result = await executeQuery(
`SELECT thread_id, title, url
FROM poll_posts
WHERE board = $1 AND ($2 = '' OR title ILIKE '%' || $2 || '%')
ORDER BY (title ILIKE $2 || '%') DESC, created_at DESC
LIMIT $3`,
[board, q, limit]
);
return result.rows;
};
const getPollPostBoards = async (threadId) => {
const result = await executeQuery(
'SELECT board FROM poll_posts WHERE thread_id = $1',
[threadId]
);
return result.rows.map((r) => r.board);
};
const getPollPostCount = async () => {
const result = await executeQuery('SELECT COUNT(*) AS n FROM poll_posts');
return parseInt(result.rows[0]?.n, 10) || 0;
};
// Newest posts that have never had the Top 5 nudge posted in them. Grouped by
// thread because a post tagged both Gameplay and Skins has one row per board but
// only ever gets one nudge.
const getUnpromotedPollPosts = async (limit, maxAgeDays) => {
const result = await executeQuery(
`SELECT thread_id, array_agg(board) AS boards, MIN(created_at) AS created_at
FROM poll_posts
WHERE created_at > NOW() - make_interval(days => $2)
GROUP BY thread_id
HAVING COUNT(promoted_at) = 0
ORDER BY MIN(created_at) DESC
LIMIT $1`,
[limit, maxAgeDays]
);
return result.rows;
};
const markPollPostPromoted = async (threadId) => {
await executeQuery(
'UPDATE poll_posts SET promoted_at = NOW() WHERE thread_id = $1',
[threadId]
);
};
const getUserBoardList = async (userId, board) => {
const result = await executeQuery(
`SELECT v.thread_id, p.title, p.url
FROM poll_votes v
LEFT JOIN poll_posts p ON p.thread_id = v.thread_id AND p.board = v.board
WHERE v.user_id = $1 AND v.board = $2
ORDER BY v.position ASC`,
[userId, board]
);
return result.rows;
};
// Rewrite a user's whole list for one board in a single transaction: the list is
// small (<=5) and rewriting avoids fiddly position-swap SQL and the UNIQUE(position)
// races that piecemeal updates would hit.
const saveUserBoardList = async (userId, board, threadIds) => {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('DELETE FROM poll_votes WHERE user_id = $1 AND board = $2', [userId, board]);
for (let i = 0; i < threadIds.length; i++) {
await client.query(
'INSERT INTO poll_votes (user_id, board, thread_id, position) VALUES ($1, $2, $3, $4)',
[userId, board, threadIds[i], i + 1]
);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
};
const getLeaderboard = async (board, limit = 10) => {
const result = await executeQuery(
`SELECT v.thread_id, p.title, p.url,
SUM(6 - v.position) AS points,
COUNT(*) AS voters
FROM poll_votes v
JOIN poll_posts p ON p.thread_id = v.thread_id AND p.board = v.board
WHERE v.board = $1
GROUP BY v.thread_id, p.title, p.url
ORDER BY points DESC, voters DESC, MIN(p.created_at) ASC
LIMIT $2`,
[board, limit]
);
return result.rows;
};
// Program role snapshots (durable "roles they had" record for moderation alerts)
// Captures the program roles a member currently holds so that, after a ban or
// leave, we can still tell whether the moderated user was a program member.
const ensureProgramRoleSnapshotTable = async () => {
await executeQuery(`
CREATE TABLE IF NOT EXISTS program_role_snapshots (
user_id TEXT PRIMARY KEY,
role_ids TEXT[] NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
};
const upsertProgramRoleSnapshot = async (userId, roleIds) => {
await executeQuery(
`INSERT INTO program_role_snapshots (user_id, role_ids, updated_at)
VALUES ($1, $2, NOW())
ON CONFLICT (user_id) DO UPDATE SET role_ids = EXCLUDED.role_ids, updated_at = NOW()`,
[userId, roleIds]
);
};
const getProgramRoleSnapshot = async (userId) => {
const result = await executeQuery(
'SELECT user_id, role_ids, updated_at FROM program_role_snapshots WHERE user_id = $1',
[userId]
);
const row = result.rows[0];
if (!row) {
return null;
}
return { userId: row.user_id, roleIds: row.role_ids || [], updatedAt: row.updated_at };
};
// League queries (moved from interactionHandler.js to use pool)
const findLeagueApplication = async (applicationMessageId) => {
const result = await executeQuery(
'SELECT * FROM "League Applications" WHERE application_message_id = $1',
[applicationMessageId]
);
return result.rows;
};
// Atomic claim: only a still-Pending application transitions, so a double
// click or a deny/approve race resolves to exactly one winner. Returns true
// when this call made the transition.
const updateLeagueApplicationApproval = async (messageId, reviewerId) => {
const result = await executeQuery(
`UPDATE "League Applications"
SET review_status = 'Approved', is_approved = TRUE, reviewed_date = NOW(), reviewed_by = $1
WHERE application_message_id = $2 AND review_status = 'Pending'
RETURNING application_message_id`,
[reviewerId, messageId]
);
return result.rows.length > 0;
};
const updateLeagueApplicationDenial = async (messageId, denialReason, reviewerId) => {
const result = await executeQuery(
`UPDATE "League Applications"
SET review_status = 'Denied', denial_reason = $1, reviewed_date = NOW(), reviewed_by = $2
WHERE application_message_id = $3 AND review_status = 'Pending'
RETURNING application_message_id`,
[denialReason, reviewerId, messageId]
);
return result.rows.length > 0;
};
// Compensating revert for a failed approval: puts a claimed application back
// to Pending so the reviewer can retry, mirroring the compensating deletes
// used when an ops-card post fails after an insert.
const revertLeagueApplicationToPending = async (messageId) => {
await executeQuery(
`UPDATE "League Applications"
SET review_status = 'Pending', is_approved = FALSE, reviewed_date = NULL, reviewed_by = NULL
WHERE application_message_id = $1 AND review_status = 'Approved'`,
[messageId]
);
};
const findActiveLeague = async (key, value) => {
const validKeys = ['server_id', 'owner_id'];
if (!validKeys.includes(key)) {
throw new Error(`Invalid key: ${key}`);
}
// Disbanded leagues are soft-deleted: they keep their owner_id/server_id but
// must not count as an existing league, otherwise the registration guards
// wrongly block a user (or server) whose only league was disbanded.
// No tier filter: one league per owner, whatever its tier. Everything else
// in the system (fetchLeaguesByOwner(...)[0]) assumes that invariant.
const query = `SELECT * FROM "Active Leagues" WHERE ${key} = $1 AND league_status <> 'Disbanded'`;
const result = await executeQuery(query, [value]);
return result.rows;
};
const findActiveLeagueByOwnerAndName = async (ownerId, leagueName) => {
const result = await executeQuery(
'SELECT * FROM "Active Leagues" WHERE owner_id = $1 AND league_name = $2',
[ownerId, leagueName]
);
return result.rows;
};
const insertActiveLeague = async (params) => {
await executeQuery(
`INSERT INTO "Active Leagues"
(owner_id, owner_discord_name, league_name, server_name, server_id, member_count, server_owner_id, league_type, league_status, approval_date, is_sponsored, league_invite, server_icon, server_banner, vanity_url, server_description, server_features, owner_profile_picture)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'Active', NOW(), $9, $10, $11, $12, $13, $14, $15, $16)`,
params
);
};
// Server metadata params may be null (invite could not be resolved at approval
// time); COALESCE keeps the existing values so a failed fetch can never
// overwrite good data with placeholders.
const updateActiveLeague = async (params) => {
await executeQuery(
`UPDATE "Active Leagues" SET
league_type = $1, approval_date = NOW(),
server_id = COALESCE($2, server_id),
server_name = COALESCE($3, server_name),
member_count = COALESCE($4, member_count),
server_icon = COALESCE($5, server_icon),
server_banner = COALESCE($6, server_banner),
vanity_url = COALESCE($7, vanity_url),
server_description = COALESCE($8, server_description),
server_features = COALESCE($9, server_features),
owner_profile_picture = COALESCE($10, owner_profile_picture)
WHERE owner_id = $11 AND league_name = $12`,
params
);
};
// LFG queries (moved from interactionHandler.js to use pool)
const ensureLfgTable = async () => {
await executeQuery(`CREATE TABLE IF NOT EXISTS lfg_queues (
thread_id TEXT PRIMARY KEY,
queue_key TEXT NOT NULL,
queue_name TEXT NOT NULL,
size INTEGER NOT NULL,
status TEXT NOT NULL,
participants TEXT[] NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`);
// Add columns that may not exist on older tables
const columns = [
{ name: 'description', type: 'TEXT' },
{ name: 'lobby_display_name', type: 'TEXT' },
{ name: 'lobby_id', type: 'TEXT' },
{ name: 'play_type', type: 'TEXT' },
{ name: 'play_rules', type: 'TEXT' },
{ name: 'region', type: 'TEXT' },
];
for (const col of columns) {
await executeQuery(
`ALTER TABLE lfg_queues ADD COLUMN IF NOT EXISTS ${col.name} ${col.type}`
).catch(() => {});
}
};
const findLfgParticipantQueues = async (userId, excludeKey) => {
const result = await executeQuery(
'SELECT thread_id, queue_key, queue_name, size, participants FROM lfg_queues WHERE $1 = ANY(participants) AND queue_key <> $2',
[userId, excludeKey]
);
return result.rows;
};
const updateLfgParticipants = async (threadId, participants) => {
await executeQuery(
`UPDATE lfg_queues
SET participants = COALESCE($1::text[], ARRAY[]::text[]),
updated_at = NOW(),
status = CASE
WHEN array_length(COALESCE($1::text[], ARRAY[]::text[]),1) IS NULL
OR array_length(COALESCE($1::text[], ARRAY[]::text[]),1) < size
THEN 'waiting'
ELSE 'ready'
END
WHERE thread_id = $2`,
[participants, threadId]
);
};
const findLfgQueueByKey = async (key) => {
const result = await executeQuery(
`SELECT queue_key, queue_name, size,
COALESCE(description,'') AS description,
COALESCE(lobby_display_name,'') AS lobby_display_name
FROM lfg_queues
WHERE queue_key = $1
ORDER BY updated_at DESC
LIMIT 1`,
[key]
);
if (!result.rows[0]) return null;
const row = result.rows[0];
return { key: row.queue_key, name: row.queue_name, size: row.size, description: row.description, lobby_display_name: row.lobby_display_name };
};
const findLfgQueueByThreadId = async (threadId) => {
const result = await executeQuery(
`SELECT queue_key, queue_name, size,
COALESCE(description,'') AS description,
COALESCE(lobby_display_name,'') AS lobby_display_name
FROM lfg_queues
WHERE thread_id = $1
LIMIT 1`,
[threadId]
);
if (!result.rows[0]) return null;
const row = result.rows[0];
return { key: row.queue_key, name: row.queue_name, size: row.size, description: row.description, lobby_display_name: row.lobby_display_name };
};
const loadAllLfgParticipants = async () => {
const result = await executeQuery(
'SELECT queue_key, participants FROM lfg_queues'
);
return result.rows;
};
const findLfgParticipantsByKey = async (key) => {
const result = await executeQuery(
'SELECT participants FROM lfg_queues WHERE queue_key = $1 ORDER BY updated_at DESC LIMIT 1',
[key]
);
return result.rows[0]?.participants || [];
};
const upsertLfgQueue = async (threadId, queueDef, participants, status) => {
await executeQuery(
`INSERT INTO lfg_queues(thread_id, queue_key, queue_name, size, status, participants, updated_at)
VALUES($1,$2,$3,$4,$5,$6,NOW())
ON CONFLICT (thread_id) DO UPDATE SET queue_key=EXCLUDED.queue_key, queue_name=EXCLUDED.queue_name, size=EXCLUDED.size, status=EXCLUDED.status, participants=EXCLUDED.participants, updated_at=NOW()`,
[threadId, queueDef.key, queueDef.name, queueDef.size, status, participants]
);
};
const insertCommandUsage = async (command_name, user_id, channel_id, server_id, timestamp) => {
const query = `
INSERT INTO command_usage (command_name, user_id, channel_id, server_id, timestamp)
VALUES ($1, $2, $3, $4, $5)
`;
await executeQuery(query, [command_name, user_id, channel_id, server_id, timestamp]);
};
const insertSquadApplication = async (member_display_name, member_object, member_squad_name, message_url, user_id, squad_type) => {
const query = `
INSERT INTO squad_applications_data (member_display_name, member_object, member_squad_name, message_url, user_id, squad_type)
VALUES ($1, $2, $3, $4, $5, $6)
`;
await executeQuery(query, [member_display_name, member_object, member_squad_name, message_url, user_id, squad_type]);
};
const fetchCommandUsageData = async () => {
const query = 'SELECT * FROM command_usage';
const result = await executeQuery(query);
return result.rows;
};
const fetchSquadApplications = async () => {
const query = 'SELECT * FROM squad_applications_data';
const result = await executeQuery(query);
return result.rows;
};
const fetchSquadApplicationByMessageUrl = async (message_url) => {
const query = 'SELECT * FROM squad_applications_data WHERE message_url = $1';
const result = await executeQuery(query, [message_url]);
return result.rows[0];
};
const deleteSquadApplicationById = async (id) => {
const query = 'DELETE FROM squad_applications_data WHERE id = $1';
const result = await executeQuery(query, [id]);
return result.rowCount > 0;
};
const ensureInvitesSchema = async () => {
// Historically this table only ever existed in prod; the CREATE brings it
// under code management so fresh environments work (2026-08).
await executeQuery(`
CREATE TABLE IF NOT EXISTS invites (
id SERIAL PRIMARY KEY,
command_user_id TEXT NOT NULL,
invited_member_id TEXT NOT NULL,
squad_name TEXT NOT NULL,
squad_type TEXT,
invite_status TEXT NOT NULL DEFAULT 'Pending',
message_id TEXT,
tracking_message_id TEXT,
squad_id INTEGER,
expires_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
)
`);
await executeQuery(
'ALTER TABLE invites ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ'
).catch(() => {});
await executeQuery(
'ALTER TABLE invites ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW()'
).catch(() => {});
await executeQuery(
'ALTER TABLE invites ADD COLUMN IF NOT EXISTS squad_id INTEGER'
).catch(() => {});
};
const insertInvite = async (command_user_id, invited_member_id, squad_name, message_id, tracking_message_id, squad_type, expiresAt, squadId = null) => {
const query = `
INSERT INTO invites (command_user_id, invited_member_id, squad_name, invite_status, message_id, tracking_message_id, squad_type, expires_at, created_at, squad_id)
VALUES ($1, $2, $3, 'Pending', $4, $5, $6, $7, NOW(), $8)
`;
await executeQuery(query, [command_user_id, invited_member_id, squad_name, message_id, tracking_message_id, squad_type, expiresAt || null, squadId]);
};
const fetchExpiredPendingInvites = async () => {
const result = await executeQuery(
'SELECT * FROM invites WHERE invite_status = \'Pending\' AND expires_at IS NOT NULL AND expires_at <= NOW()'
);
return result.rows;
};
const deleteInvite = async (message_id) => {
const query = 'DELETE FROM invites WHERE message_id = $1';
const result = await executeQuery(query, [message_id]);