From 5e7a78e7fad1399d212ff673b1df5acc1b70a80d Mon Sep 17 00:00:00 2001 From: Leander Furumo Date: Sat, 24 Oct 2026 04:48:49 +0200 Subject: [PATCH] avoid multiple SQL queries by using ON CONFLICT --- src/cogs/birthday.py | 20 ++++++++------------ src/cogs/social_credit.py | 7 +++---- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/cogs/birthday.py b/src/cogs/birthday.py index 30b8bdb..9fda735 100644 --- a/src/cogs/birthday.py +++ b/src/cogs/birthday.py @@ -3,7 +3,6 @@ import random from datetime import datetime import discord -import psycopg2 from dateutil.relativedelta import relativedelta from discord import app_commands from discord.ext import commands @@ -223,17 +222,14 @@ class Birthday(commands.Cog): birthday (datetime): The birthday of the user """ - try: - self.cursor.execute( - """ - INSERT INTO birthdays (discord_id, birthday) - VALUES (%s, %s) - """, - (user_id, birthday), - ) - except psycopg2.errors.UniqueViolation: - self.bot.db_connection.rollback() - self.cursor.execute("UPDATE birthdays SET birthday = %s WHERE discord_id = %s", (birthday, user_id)) + self.cursor.execute( + """ + INSERT INTO birthdays (discord_id, birthday) + VALUES (%s, %s) + ON CONFLICT (discord_id) DO UPDATE SET birthday = EXCLUDED.birthday + """, + (user_id, birthday), + ) @app_commands.checks.bot_has_permissions(embed_links=True) @app_commands.checks.cooldown(1, 5) diff --git a/src/cogs/social_credit.py b/src/cogs/social_credit.py index 5028e6e..9dc63b6 100644 --- a/src/cogs/social_credit.py +++ b/src/cogs/social_credit.py @@ -65,9 +65,7 @@ class SocialCredit(commands.Cog): async def wrapper(*args, **kwargs): self = args[0] - self.cursor.execute("SELECT user_id FROM social_credit WHERE user_id = %s", (args[1],)) - if not self.cursor.fetchone(): - self.add_citizen(args[1]) + self.add_citizen(args[1]) await func(*args, **kwargs) return wrapper @@ -88,7 +86,7 @@ class SocialCredit(commands.Cog): def add_citizen(self, user_id: int): """ - Adds a user to the database + Adds a user to the database if they aren't already in it Parameters ---------- @@ -100,6 +98,7 @@ class SocialCredit(commands.Cog): INSERT INTO social_credit (user_id, credit_score) VALUES (%s, %s) + ON CONFLICT (user_id) DO NOTHING """, (user_id, self.START_POINTS), )