convert Moderation to sqlite3 (and rename it to Aurora) #12

Merged
cswimr merged 16 commits from sqlite3 into main 2023-12-28 05:22:52 -05:00
2 changed files with 27 additions and 27 deletions
Showing only changes of commit 910601a269 - Show all commits

View file

@ -576,19 +576,19 @@ class Aurora(commands.Cog):
cursor = database.cursor() cursor = database.cursor()
query = f"""SELECT * query = f"""SELECT *
FROM {interaction.guild.id} FROM moderation_{interaction.guild.id}
ORDER BY moderation_id DESC;""" ORDER BY moderation_id DESC;"""
cursor.execute(query) cursor.execute(query)
results = cursor.fetchall() results = cursor.fetchall()
try: try:
filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"{interaction.guild.id}.json" filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"moderation_{interaction.guild.id}.json"
with open(filename, "w", encoding="utf-8") as f: with open(filename, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2) json.dump(results, f, indent=2)
await interaction.followup.send(file=discord.File(filename, f"{interaction.guild.id}.json"), ephemeral=ephemeral) await interaction.followup.send(file=discord.File(filename, f"moderation_{interaction.guild.id}.json"), ephemeral=ephemeral)
os.remove(filename) os.remove(filename)
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
@ -601,19 +601,19 @@ class Aurora(commands.Cog):
if target: if target:
query = f"""SELECT * query = f"""SELECT *
FROM {interaction.guild.id} FROM moderation_{interaction.guild.id}
WHERE target_id = ? WHERE target_id = ?
ORDER BY moderation_id DESC;""" ORDER BY moderation_id DESC;"""
cursor.execute(query, (target.id,)) cursor.execute(query, (target.id,))
elif moderator: elif moderator:
query = f"""SELECT * query = f"""SELECT *
FROM {interaction.guild.id} FROM moderation_{interaction.guild.id}
WHERE moderator_id = ? WHERE moderator_id = ?
ORDER BY moderation_id DESC;""" ORDER BY moderation_id DESC;"""
cursor.execute(query, (moderator.id,)) cursor.execute(query, (moderator.id,))
else: else:
query = f"""SELECT * query = f"""SELECT *
FROM {interaction.guild.id} FROM moderation_{interaction.guild.id}
ORDER BY moderation_id DESC;""" ORDER BY moderation_id DESC;"""
cursor.execute(query) cursor.execute(query)
@ -695,14 +695,14 @@ class Aurora(commands.Cog):
database = connect() database = connect()
cursor = database.cursor() cursor = database.cursor()
query_1 = f"SELECT * FROM {interaction.guild.id} WHERE moderation_id = ?;" query_1 = f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ?;"
cursor.execute(query_1, (case,)) cursor.execute(query_1, (case,))
result_1 = cursor.fetchone() result_1 = cursor.fetchone()
if result_1 is None or case == 0: if result_1 is None or case == 0:
await interaction.response.send_message(content=f"There is no moderation with a case number of {case}.", ephemeral=True) await interaction.response.send_message(content=f"There is no moderation with a case number of {case}.", ephemeral=True)
return return
query_2 = f"SELECT * FROM {interaction.guild.id} WHERE moderation_id = ? AND resolved = 0;" query_2 = f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ? AND resolved = 0;"
cursor.execute(query_2, (case,)) cursor.execute(query_2, (case,))
result_2 = cursor.fetchone() result_2 = cursor.fetchone()
if result_2 is None: if result_2 is None:
@ -755,9 +755,9 @@ class Aurora(commands.Cog):
except discord.NotFound: except discord.NotFound:
pass pass
resolve_query = f"UPDATE `{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?"
else: else:
resolve_query = f"UPDATE `{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?"
cursor.execute(resolve_query, (json.dumps(changes), interaction.user.id, reason, case_dict['moderation_id'])) cursor.execute(resolve_query, (json.dumps(changes), interaction.user.id, reason, case_dict['moderation_id']))
database.commit() database.commit()
@ -802,7 +802,7 @@ class Aurora(commands.Cog):
if case_dict: if case_dict:
if export: if export:
if export.value == 'file' or len(str(case_dict)) > 1800: if export.value == 'file' or len(str(case_dict)) > 1800:
filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"{interaction.guild.id}_case_{case}.json" filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"moderation_{interaction.guild.id}_case_{case}.json"
with open(filename, "w", encoding="utf-8") as f: with open(filename, "w", encoding="utf-8") as f:
json.dump(case_dict, f, indent=2) json.dump(case_dict, f, indent=2)
@ -812,7 +812,7 @@ class Aurora(commands.Cog):
else: else:
content = f"Case #{case:,} exported." content = f"Case #{case:,} exported."
await interaction.response.send_message(content=content, file=discord.File(filename, f"{interaction.guild.id}_case_{case}.json"), ephemeral=ephemeral) await interaction.response.send_message(content=content, file=discord.File(filename, f"moderation_{interaction.guild.id}_case_{case}.json"), ephemeral=ephemeral)
os.remove(filename) os.remove(filename)
return return
@ -914,10 +914,10 @@ class Aurora(commands.Cog):
cursor = database.cursor() cursor = database.cursor()
if parsed_time: if parsed_time:
update_query = f"UPDATE `{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s" update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s"
cursor.execute(update_query, (json.dumps(changes), reason, parsed_time, end_timestamp, case)) cursor.execute(update_query, (json.dumps(changes), reason, parsed_time, end_timestamp, case))
else: else:
update_query = f"UPDATE `{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s" update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s"
cursor.execute(update_query, (json.dumps(changes), reason, case)) cursor.execute(update_query, (json.dumps(changes), reason, case))
database.commit() database.commit()
@ -941,7 +941,7 @@ class Aurora(commands.Cog):
for guild in guilds: for guild in guilds:
if not await self.bot.cog_disabled_in_guild(self, guild): if not await self.bot.cog_disabled_in_guild(self, guild):
tempban_query = f"SELECT target_id, moderation_id FROM {guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'TEMPBAN' AND expired = 0" tempban_query = f"SELECT target_id, moderation_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'TEMPBAN' AND expired = 0"
try: try:
cursor.execute(tempban_query, (time.time(),)) cursor.execute(tempban_query, (time.time(),))
@ -966,10 +966,10 @@ class Aurora(commands.Cog):
except [discord.errors.NotFound, discord.errors.Forbidden, discord.errors.HTTPException] as e: except [discord.errors.NotFound, discord.errors.Forbidden, discord.errors.HTTPException] as e:
print(f"Failed to unban {user.name}#{user.discriminator} ({user.id}) from {guild.name} ({guild.id})\n{e}") print(f"Failed to unban {user.name}#{user.discriminator} ({user.id}) from {guild.name} ({guild.id})\n{e}")
expiry_query = f"UPDATE `{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')" expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')"
cursor.execute(expiry_query, (time.time(),)) cursor.execute(expiry_query, (time.time(),))
blacklist_query = f"SELECT target_id, moderation_id, role_id FROM {guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0" blacklist_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0"
try: try:
cursor.execute(blacklist_query, (time.time(),)) cursor.execute(blacklist_query, (time.time(),))
result = cursor.fetchall() result = cursor.fetchall()

View file

@ -30,12 +30,12 @@ async def create_guild_table(guild: Guild):
cursor = database.cursor() cursor = database.cursor()
try: try:
cursor.execute(f"SELECT * FROM `{guild.id}`") cursor.execute(f"SELECT * FROM `moderation_{guild.id}`")
logger.debug("SQLite Table exists for server %s (%s)", guild.name, guild.id) logger.debug("SQLite Table exists for server %s (%s)", guild.name, guild.id)
except sqlite3.OperationalError: except sqlite3.OperationalError:
query = f""" query = f"""
CREATE TABLE `{guild.id}` ( CREATE TABLE `moderation_{guild.id}` (
moderation_id INTEGER PRIMARY KEY, moderation_id INTEGER PRIMARY KEY,
timestamp INTEGER NOT NULL, timestamp INTEGER NOT NULL,
moderation_type TEXT NOT NULL, moderation_type TEXT NOT NULL,
@ -56,17 +56,17 @@ async def create_guild_table(guild: Guild):
""" """
cursor.execute(query) cursor.execute(query)
index_query_1 = "CREATE INDEX idx_target_id ON {}(target_id);" index_query_1 = "CREATE INDEX idx_target_id ON moderation_{}(target_id);"
cursor.execute(index_query_1.format(guild.id)) cursor.execute(index_query_1.format(guild.id))
index_query_2 = "CREATE INDEX idx_moderator_id ON {}(moderator_id);" index_query_2 = "CREATE INDEX idx_moderator_id ON moderation_{}(moderator_id);"
cursor.execute(index_query_2.format(guild.id)) cursor.execute(index_query_2.format(guild.id))
index_query_3 = "CREATE INDEX idx_moderation_id ON {}(moderation_id);" index_query_3 = "CREATE INDEX idx_moderation_id ON moderation_{}(moderation_id);"
cursor.execute(index_query_3.format(guild.id)) cursor.execute(index_query_3.format(guild.id))
insert_query = f""" insert_query = f"""
INSERT INTO `{guild.id}` INSERT INTO `moderation_{guild.id}`
(moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata) (moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""" """
@ -93,7 +93,7 @@ async def create_guild_table(guild: Guild):
database.commit() database.commit()
logger.debug( logger.debug(
"SQLite Table (%s) created for %s (%s)", "SQLite Table (moderation_%s) created for %s (%s)",
guild.id, guild.id,
guild.name, guild.name,
guild.id, guild.id,
@ -157,7 +157,7 @@ async def mysql_log(
moderation_id = await get_next_case_number(guild_id=guild_id, cursor=cursor) moderation_id = await get_next_case_number(guild_id=guild_id, cursor=cursor)
sql = f"INSERT INTO `{guild_id}` (moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" sql = f"INSERT INTO `moderation_{guild_id}` (moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
val = ( val = (
moderation_id, moderation_id,
timestamp, timestamp,
@ -184,7 +184,7 @@ async def mysql_log(
database.close() database.close()
logger.debug( logger.debug(
"Row inserted into %s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", "Row inserted into moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
guild_id, guild_id,
moderation_id, moderation_id,
timestamp, timestamp,
@ -212,7 +212,7 @@ async def fetch_case(moderation_id: int, guild_id: str) -> dict:
database = connect() database = connect()
cursor = database.cursor() cursor = database.cursor()
query = f"SELECT * FROM {guild_id} WHERE moderation_id = ?;" query = f"SELECT * FROM moderation_{guild_id} WHERE moderation_id = ?;"
cursor.execute(query, (moderation_id,)) cursor.execute(query, (moderation_id,))
result = cursor.fetchone() result = cursor.fetchone()