1
0
mirror of synced 2024-12-22 09:45:53 +01:00
artemis/titles/cxb/schema/profile.py

79 lines
2.6 KiB
Python
Raw Normal View History

from typing import Optional, Dict, List
from sqlalchemy import Table, Column, UniqueConstraint, PrimaryKeyConstraint, and_
from sqlalchemy.types import Integer, String, TIMESTAMP, Boolean, JSON
from sqlalchemy.schema import ForeignKey
from sqlalchemy.sql import func, select
from sqlalchemy.dialects.mysql import insert
from core.data.schema import BaseData, metadata
profile = Table(
"cxb_profile",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade"), nullable=False),
Column("version", Integer, nullable=False),
Column("index", Integer, nullable=False),
Column("data", JSON, nullable=False),
UniqueConstraint("user", "index", name="cxb_profile_uk"),
2023-03-09 17:38:58 +01:00
mysql_charset="utf8mb4",
)
2023-03-09 17:38:58 +01:00
class CxbProfileData(BaseData):
2024-01-09 20:42:17 +01:00
async def put_profile(
2023-03-09 17:38:58 +01:00
self, user_id: int, version: int, index: int, data: JSON
) -> Optional[int]:
sql = insert(profile).values(
2023-03-09 17:38:58 +01:00
user=user_id, version=version, index=index, data=data
)
2023-03-09 17:38:58 +01:00
conflict = sql.on_duplicate_key_update(index=index, data=data)
2024-01-09 20:42:17 +01:00
result = await self.execute(conflict)
if result is None:
2023-03-09 17:38:58 +01:00
self.logger.error(
f"{__name__} failed to update! user: {user_id}, index: {index}, data: {data}"
)
return None
2023-03-09 17:38:58 +01:00
return result.lastrowid
2024-01-09 20:42:17 +01:00
async def get_profile(self, aime_id: int, version: int) -> Optional[List[Dict]]:
"""
Given a game version and either a profile or aime id, return the profile
"""
2023-03-09 17:38:58 +01:00
sql = profile.select(
and_(profile.c.version == version, profile.c.user == aime_id)
)
2024-01-09 20:42:17 +01:00
result = await self.execute(sql)
2023-03-09 17:38:58 +01:00
if result is None:
return None
return result.fetchall()
2024-01-09 20:42:17 +01:00
async def get_profile_index(
2023-03-09 17:38:58 +01:00
self, index: int, aime_id: int = None, version: int = None
) -> Optional[Dict]:
"""
Given a game version and either a profile or aime id, return the profile
"""
if aime_id is not None and version is not None and index is not None:
2023-03-09 17:38:58 +01:00
sql = profile.select(
and_(
profile.c.version == version,
profile.c.user == aime_id,
2023-03-09 17:38:58 +01:00
profile.c.index == index,
)
)
else:
2023-03-09 17:38:58 +01:00
self.logger.error(
f"get_profile: Bad arguments!! aime_id {aime_id} version {version}"
)
return None
2023-03-09 17:38:58 +01:00
2024-01-09 20:42:17 +01:00
result = await self.execute(sql)
2023-03-09 17:38:58 +01:00
if result is None:
return None
return result.fetchone()