Skip to content

Commit 89d188e

Browse files
committed
chore(database): move current (dev) database schema to new one
1 parent 323d595 commit 89d188e

File tree

8 files changed

+182
-320
lines changed

8 files changed

+182
-320
lines changed

src/db/botinfo.ts

Lines changed: 1 addition & 124 deletions
Original file line numberDiff line numberDiff line change
@@ -1,124 +1 @@
1-
import type { PoolClient, QueryResult } from "pg";
2-
import type { dbBotInfo } from "../types/database";
3-
4-
import { pool } from "../utils/database";
5-
6-
export async function updateBotInfo(
7-
guilds_total: number = 0,
8-
channels_tracked: number = 0,
9-
total_members: number = 0,
10-
): Promise<void> {
11-
const query = `
12-
INSERT INTO bot_info (guilds_total, channels_tracked, total_members, time)
13-
VALUES ($1, $2, $3, NOW())
14-
ON CONFLICT (time) DO UPDATE
15-
SET guilds_total = EXCLUDED.guilds_total,
16-
channels_tracked = EXCLUDED.channels_tracked,
17-
total_members = EXCLUDED.total_members;
18-
`;
19-
20-
try {
21-
const client = await pool.connect();
22-
23-
await client.query(query, [
24-
guilds_total,
25-
channels_tracked,
26-
total_members,
27-
]);
28-
29-
client.release();
30-
31-
console.log("Bot info updated successfully");
32-
} catch (err) {
33-
console.error("Error updating bot info:", err);
34-
}
35-
}
36-
37-
export async function getBotInfo() {
38-
const query = `SELECT * FROM bot_info`;
39-
40-
try {
41-
const client: PoolClient = await pool.connect();
42-
const result: QueryResult<any> = await client.query(query);
43-
44-
client.release();
45-
46-
return result.rows[0] as dbBotInfo;
47-
} catch (err) {
48-
console.error("Error getting bot info:", err);
49-
50-
return null;
51-
}
52-
}
53-
54-
export async function updateBotInfoNotifications(
55-
platform: "youtube" | "bluesky" | "twitch",
56-
) {
57-
const query = `
58-
INSERT INTO bot_info_notifications (date, total_${platform})
59-
VALUES (CURRENT_DATE, 1)
60-
ON CONFLICT (date) DO UPDATE
61-
SET total_${platform} = bot_info_notifications.total_${platform} + 1;
62-
`;
63-
64-
try {
65-
const client: PoolClient = await pool.connect();
66-
67-
await client.query(query, [platform]);
68-
69-
client.release();
70-
71-
console.log(`Bot info notifications updated for ${platform}`);
72-
} catch (err) {
73-
console.error(
74-
`Error updating bot info notifications for ${platform}:`,
75-
err,
76-
);
77-
}
78-
}
79-
80-
export async function getBotInfoNotifications() {
81-
const query = `SELECT * FROM bot_info_notifications`;
82-
83-
try {
84-
const client: PoolClient = await pool.connect();
85-
const result: QueryResult<any> = await client.query(query);
86-
87-
client.release();
88-
89-
return result.rows;
90-
} catch (err) {
91-
console.error("Error getting bot info notifications:", err);
92-
93-
return [];
94-
}
95-
}
96-
97-
export async function updateBotInfoNotificationsTimings(
98-
channel_id: string,
99-
time_ms: number,
100-
): Promise<void> {
101-
const query = `
102-
INSERT INTO bot_info_notifications_timings (time, channel_id, time_ms)
103-
VALUES (NOW(), $1, $2)
104-
ON CONFLICT (time, channel_id) DO UPDATE
105-
SET time_ms = EXCLUDED.time_ms;
106-
`;
107-
108-
try {
109-
const client: PoolClient = await pool.connect();
110-
111-
await client.query(query, [channel_id, time_ms]);
112-
113-
client.release();
114-
115-
console.log(
116-
`Bot info notifications timings updated for channel ${channel_id}`,
117-
);
118-
} catch (err) {
119-
console.error(
120-
`Error updating bot info notifications timings for channel ${channel_id}:`,
121-
err,
122-
);
123-
}
124-
}
1+
// Rewriting

src/db/cron.ts

Lines changed: 0 additions & 22 deletions
This file was deleted.

src/db/db.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { drizzle } from "drizzle-orm/node-postgres";
2+
import { Pool } from "pg";
3+
4+
import { config } from "../config";
5+
6+
import * as schema from "./schema";
7+
8+
const pool = new Pool({
9+
connectionString: config.databaseUrl,
10+
});
11+
12+
export const db = drizzle(pool, { schema });

src/db/discord.ts

Lines changed: 88 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,70 @@
1+
import { eq, and } from "drizzle-orm";
2+
13
import { Platform } from "../types/types";
2-
import { pool } from "../utils/database";
4+
5+
import { db } from "./db";
6+
import {
7+
dbGuildYouTubeSubscriptionsTable,
8+
dbGuildTwitchSubscriptionsTable,
9+
} from "./schema";
310

411
export async function checkIfGuildIsTrackingUserAlready(
512
platform: Platform,
613
userId: string,
714
guildId: string,
8-
): Promise<{ success: boolean; data: any[] | null }> {
15+
): Promise<
16+
| {
17+
success: true;
18+
data:
19+
| (typeof dbGuildYouTubeSubscriptionsTable.$inferSelect)[]
20+
| (typeof dbGuildTwitchSubscriptionsTable.$inferSelect)[]
21+
| null;
22+
}
23+
| { success: false; data: null }
24+
> {
925
console.log(
1026
`Checking if guild ${guildId} is tracking user ${userId} on platform ${platform}`,
1127
);
1228

13-
let query: string | null = null;
14-
15-
if (platform === Platform.YouTube) {
16-
query = `
17-
SELECT * FROM guild_youtube_subscriptions
18-
WHERE youtube_channel_id = $1 AND guild_id = $2
19-
`;
20-
} else if (platform === Platform.Twitch) {
21-
query = `
22-
SELECT * FROM guild_twitch_subscriptions
23-
WHERE twitch_user_id = $1 AND guild_id = $2
24-
`;
25-
}
26-
27-
if (!query) {
28-
console.error("Invalid platform provided for tracking check.");
29-
30-
return { success: false, data: null };
31-
}
32-
3329
try {
34-
const client = await pool.connect();
35-
const result = await client.query(query, [userId, guildId]);
36-
37-
client.release();
38-
39-
if (result.rows.length > 0) {
40-
return { success: true, data: result.rows };
30+
let result: any[] = [];
31+
32+
if (platform === Platform.YouTube) {
33+
result = await db
34+
.select()
35+
.from(dbGuildYouTubeSubscriptionsTable)
36+
.where(
37+
and(
38+
eq(
39+
dbGuildYouTubeSubscriptionsTable.youtubeChannelId,
40+
userId,
41+
),
42+
eq(dbGuildYouTubeSubscriptionsTable.guildId, guildId),
43+
),
44+
);
45+
} else if (platform === Platform.Twitch) {
46+
result = await db
47+
.select()
48+
.from(dbGuildTwitchSubscriptionsTable)
49+
.where(
50+
and(
51+
eq(
52+
dbGuildTwitchSubscriptionsTable.twitchChannelId,
53+
userId,
54+
),
55+
eq(dbGuildTwitchSubscriptionsTable.guildId, guildId),
56+
),
57+
);
4158
} else {
42-
return { success: true, data: null };
59+
console.error("Invalid platform provided for tracking check.");
60+
61+
return { success: false, data: null };
4362
}
63+
64+
return {
65+
success: true,
66+
data: result.length > 0 ? result : null,
67+
};
4468
} catch (error) {
4569
console.error("Error checking if guild is tracking user:", error);
4670

@@ -65,60 +89,44 @@ export async function discordAddGuildTrackingUser(
6589
`Adding guild ${guildId} tracking for user ${platformUserId} on platform ${platform}`,
6690
);
6791

68-
let query: string | null = null;
69-
let params: any[] = [];
70-
71-
if (platform === Platform.YouTube) {
72-
if (
73-
youtubeTrackVideos === undefined ||
74-
youtubeTrackVideos === null ||
75-
youtubeTrackShorts === undefined ||
76-
youtubeTrackShorts === null ||
77-
youtubeTrackLive === undefined ||
78-
youtubeTrackLive === null
79-
) {
80-
console.error(
81-
"YouTube tracking options must be provided for YouTube subscriptions.",
82-
);
92+
try {
93+
if (platform === Platform.YouTube) {
94+
if (
95+
youtubeTrackVideos == null ||
96+
youtubeTrackShorts == null ||
97+
youtubeTrackLive == null
98+
) {
99+
console.error(
100+
"YouTube tracking options must be provided for YouTube subscriptions.",
101+
);
102+
103+
return { success: false, data: [] };
104+
}
105+
106+
await db.insert(dbGuildYouTubeSubscriptionsTable).values({
107+
youtubeChannelId: platformUserId,
108+
guildId,
109+
notificationChannelId: guildChannelId,
110+
notificationRoleId: roleId,
111+
isDm,
112+
trackVideos: youtubeTrackVideos,
113+
trackShorts: youtubeTrackShorts,
114+
trackStreams: youtubeTrackLive,
115+
});
116+
} else if (platform === Platform.Twitch) {
117+
await db.insert(dbGuildTwitchSubscriptionsTable).values({
118+
twitchChannelId: platformUserId,
119+
guildId,
120+
notificationChannelId: guildChannelId,
121+
notificationRoleId: roleId,
122+
isDm,
123+
});
124+
} else {
125+
console.error("Invalid platform provided.");
83126

84127
return { success: false, data: [] };
85128
}
86129

87-
query = `
88-
INSERT INTO guild_youtube_subscriptions (
89-
youtube_channel_id, guild_id, notification_channel_id, notification_role_id, is_dm,
90-
track_videos, track_shorts, track_streams
91-
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
92-
`;
93-
params = [
94-
platformUserId,
95-
guildId,
96-
guildChannelId,
97-
roleId,
98-
isDm,
99-
youtubeTrackVideos ?? false,
100-
youtubeTrackShorts ?? false,
101-
youtubeTrackLive ?? false,
102-
];
103-
} else if (platform === Platform.Twitch) {
104-
query = `
105-
INSERT INTO guild_twitch_subscriptions (
106-
twitch_channel_id, guild_id, notification_channel_id, notification_role_id, is_dm
107-
) VALUES ($1, $2, $3, $4, $5)
108-
`;
109-
params = [platformUserId, guildId, guildChannelId, roleId, isDm];
110-
}
111-
112-
if (!query) {
113-
return { success: false, data: [] };
114-
}
115-
116-
try {
117-
const client = await pool.connect();
118-
119-
await client.query(query, params);
120-
client.release();
121-
122130
return { success: true, data: [] };
123131
} catch (error) {
124132
console.error("Error adding guild tracking user:", error);

src/db/schema.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
// To make it easier to work with the database, disable prettier for this file
1+
// To make it easier to work with the database, disable prettier and some eslint rules for this file
2+
/* eslint-disable no-inline-comments */
23
/* eslint-disable prettier/prettier */
34
import { pgTable, serial, text, boolean, timestamp, decimal, unique, index, pgEnum, jsonb, integer } from "drizzle-orm/pg-core";
45

@@ -19,6 +20,8 @@ export const dbBlueskyTable = pgTable("bluesky", {
1920

2021
export const dbYouTubeTable = pgTable("youtube", {
2122
youtubeChannelId: text("youtube_channel_id").primaryKey(),
23+
youtubeChannelName: text("youtube_channel_name").notNull().default(""),
24+
latestAllId: text("latest_all_id"), // For verification and optimisation purposes
2225
latestVideoId: text("latest_video_id"),
2326
latestVideoIdUpdated: timestamp("latest_video_id_updated"),
2427
latestShortId: text("latest_short_id"),
@@ -34,6 +37,7 @@ export const dbYouTubeTable = pgTable("youtube", {
3437
export const dbTwitchTable = pgTable("twitch", {
3538
twitchChannelId: text("twitch_channel_id").primaryKey(),
3639
twitchChannelIsLive: boolean("twitch_channel_is_live").notNull().default(false),
40+
twitchChannelName: text("twitch_channel_name").notNull().default(""),
3741
}, (table) => [
3842
index("idx_twitch_channel_id").on(table.twitchChannelId),
3943
]);
@@ -110,11 +114,11 @@ export const dbBotInfoNotificationsTable = pgTable("bot_info_notifications", {
110114
// });
111115

112116
export const dbAuditLogsEventTypeEnum = pgEnum("event_type", [
113-
"subscription_created",
114-
"subscription_deleted",
115-
"notification_sent",
116-
"guild_joined",
117-
"guild_left",
117+
"subscription_created",
118+
"subscription_deleted",
119+
"notification_sent",
120+
"guild_joined",
121+
"guild_left",
118122
]);
119123

120124
export const dbAuditLogsSuccessTypeEnum = pgEnum("audit_log_success", [

0 commit comments

Comments
 (0)