linkedin2/utils/clients.py

44 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.exc import IntegrityError
from model.database import Client
async def upsert_client(db: AsyncSession, user_id: str, user_login: str, user_nicename: str, user_email: str, phone: str, json_data: str):
# Проверяем, существует ли клиент с таким логином или email
async with db.begin():
result = await db.execute(
select(Client).filter((Client.id == user_id))# | (Client.user_email == user_email))
)
client = result.scalars().first() # Получаем первый результат или None
if client:
# Если клиент существует, обновляем его данные
client.user_nicename = user_nicename
client.phone = phone
client.json_data = json_data
# Можно добавить другие поля для обновления
try:
await db.commit() # Применяем изменения в базе данных
await db.refresh(client) # Обновляем объект в Python
return client
except IntegrityError:
await db.rollback() # В случае ошибки откатываем изменения
raise
else:
# Если клиента нет, создаем нового
new_client = Client(
user_login=user_login,
user_nicename=user_nicename,
user_email=user_email,
json_data=json_data,
)
db.add(new_client)
try:
await db.commit() # Сохраняем нового клиента в базе данных
await db.refresh(new_client) # Обновляем объект в Python
return new_client
except IntegrityError:
await db.rollback() # В случае ошибки откатываем изменения
raise