"""Справочник званий: чтение, создание, изменение, удаление.""" from __future__ import annotations from typing import Any from common.db.pool import get_pool async def list_titles() -> list[dict[str, Any]]: """Все звания с количеством игроков, у которых они стоят.""" async with get_pool().connection() as conn: cur = await conn.execute( """ SELECT t.id_title, t.title, t.price, t.visible, (SELECT count(*) FROM bot.de_users AS d WHERE d.id_title = t.id_title) AS used FROM bot.titles AS t ORDER BY t.price DESC, t.id_title """ ) return await cur.fetchall() async def create_title(title: str, price: int, visible: bool) -> int: async with get_pool().connection() as conn: cur = await conn.execute( "INSERT INTO bot.titles (title, price, visible) VALUES (%s, %s, %s) RETURNING id_title", (title, price, visible), ) row = await cur.fetchone() return int(row["id_title"]) async def update_title(title_id: int, title: str, price: int, visible: bool) -> bool: async with get_pool().connection() as conn: cur = await conn.execute( "UPDATE bot.titles SET title = %s, price = %s, visible = %s WHERE id_title = %s", (title, price, visible, title_id), ) return bool(cur.rowcount) async def delete_title(title_id: int) -> bool: async with get_pool().connection() as conn: cur = await conn.execute("DELETE FROM bot.titles WHERE id_title = %s", (title_id,)) return bool(cur.rowcount) async def usage_count(title_id: int) -> int: async with get_pool().connection() as conn: cur = await conn.execute( "SELECT count(*) AS total FROM bot.de_users WHERE id_title = %s", (title_id,), ) row = await cur.fetchone() return int(row["total"]) if row else 0