avoid multiple SQL queries by using ON CONFLICT

This commit is contained in:
leander committed 2026-10-24 04:48:49 +02:00
1 parent 5214d8ce31
commit 5e7a78e7fa
2 files changed
+11 -16

No files matched your search

+8 -12
View File
@@ -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)
+3 -4
View File
@@ -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),
)