Skip to content

Commit

Permalink
refactor: use raw query to make pulling slightly faster on average
Browse files Browse the repository at this point in the history
This new method may be slower for large amounts of items,
but it's unlikely we'll run into that.
  • Loading branch information
AstreaTSS committed Nov 5, 2024
1 parent 5f70433 commit f012ca6
Showing 1 changed file with 18 additions and 19 deletions.
37 changes: 18 additions & 19 deletions exts/gacha/gacha_cmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,27 @@

import asyncio
import importlib
import random
from collections import defaultdict

import interactions as ipy
import tansy
import typing_extensions as typing
from prisma.types import PrismaGachaItemScalarFieldKeys

import common.fuzzy as fuzzy
import common.help_tools as help_tools
import common.models as models
import common.utils as utils

if typing.TYPE_CHECKING:
from prisma.types import PrismaGachaItemWhereInput
QUERY_GACHA_ROLL = (
f"SELECT {', '.join(typing.get_args(PrismaGachaItemScalarFieldKeys))} FROM" # noqa: S608
" thiagachaitems WHERE guild_id = $1 AND amount != 0 ORDER BY RANDOM() LIMIT 1;"
)
QUERY_GACHA_ROLL_NO_DUPS = (
f"SELECT {', '.join(typing.get_args(PrismaGachaItemScalarFieldKeys))} FROM" # noqa: S608
" thiagachaitems WHERE guild_id = $1 AND amount != 0 AND id NOT IN (SELECT item_id"
" FROM thiagachaitemtoplayer WHERE player_id = $2) ORDER BY RANDOM() LIMIT 1;"
)


class GachaCommands(utils.Extension):
Expand Down Expand Up @@ -66,25 +73,17 @@ async def gacha_roll(self, ctx: utils.THIASlashContext) -> None:
" do so."
)

where: PrismaGachaItemWhereInput = {}
if config.gacha.draw_duplicates:
where = {"guild_id": ctx.guild.id, "amount": {"not": 0}}
item = await models.GachaItem.prisma().query_first(
QUERY_GACHA_ROLL, ctx.guild.id
)
else:
where = {
"guild_id": ctx.guild.id,
"amount": {"not": 0},
"players": {"none": {"player_id": player.id}},
}

item_count = await models.GachaItem.prisma().count(where=where)
if item_count == 0:
raise utils.CustomCheckFailure("There are no items available to roll.")
item = await models.GachaItem.prisma().query_first(
QUERY_GACHA_ROLL_NO_DUPS, ctx.guild.id, player.id
)

item = await models.GachaItem.prisma().find_first_or_raise(
skip=random.randint(0, item_count - 1), # noqa: S311
where=where,
order={"id": "asc"},
)
if item is None:
raise utils.CustomCheckFailure("There are no items available to roll.")

new_count = player.currency_amount - config.gacha.currency_cost
embed = item.embed()
Expand Down

0 comments on commit f012ca6

Please sign in to comment.