74 lines
2.1 KiB
Python
74 lines
2.1 KiB
Python
from typing import Optional
|
|
from datetime import datetime, timezone
|
|
from enum import Enum
|
|
|
|
from sqlalchemy import insert, select
|
|
from sqlalchemy.ext.asyncio import AsyncConnection
|
|
|
|
from api.db.tables.account import account_keyring_table
|
|
|
|
from api.schemas.account.account_keyring import AccountKeyring
|
|
from api.schemas.endpoints.account_keyring import AccountKeyringUpdate, StatusKey, TypeKey
|
|
|
|
|
|
|
|
async def get_key_id(connection: AsyncConnection, key_id: str) -> Optional[AccountKeyring]:
|
|
"""
|
|
Получает key по key_id.
|
|
"""
|
|
query = (
|
|
select(account_keyring_table)
|
|
.where(account_keyring_table.c.key_id == key_id)
|
|
)
|
|
|
|
user_db_cursor = await connection.execute(query)
|
|
user_db = user_db_cursor.one_or_none()
|
|
|
|
if not user_db:
|
|
return None
|
|
|
|
user_data = {
|
|
column.name: (getattr(user_db, column.name).name if isinstance(
|
|
getattr(user_db, column.name), Enum) else getattr(user_db, column.name))
|
|
for column in account_keyring_table.columns
|
|
}
|
|
|
|
return AccountKeyring.model_validate(user_data)
|
|
|
|
|
|
async def update_key_id(connection: AsyncConnection, update_values, key) -> Optional[AccountKeyring]:
|
|
"""
|
|
Вносит изменеия в нужное поле таблицы account_keyring_table.
|
|
"""
|
|
await connection.execute(
|
|
account_keyring_table.update()
|
|
.where(account_keyring_table.c.key_id == key.key_id)
|
|
.values(**update_values)
|
|
)
|
|
|
|
await connection.commit()
|
|
|
|
|
|
async def create_key(connection: AsyncConnection, key: AccountKeyring, key_id:int) -> Optional[AccountKeyring]:
|
|
"""
|
|
Создает нове поле в таблице account_keyring_table).
|
|
"""
|
|
query = insert(account_keyring_table).values(
|
|
owner_id = key.owner_id,
|
|
key_type= key.key_type.value,
|
|
key_id= key_id,
|
|
key_value= key.key_value,
|
|
created_at= datetime.now(timezone.utc),
|
|
expiry= key.expiry,
|
|
status= key.status.value
|
|
)
|
|
|
|
key.created_at= datetime.now(timezone.utc)
|
|
key.key_id= key_id
|
|
|
|
await connection.execute(query)
|
|
|
|
await connection.commit()
|
|
|
|
return key
|