Files
beavergram/backend/src/userbot/modules/profiles/repository.py
T

67 lines
2.0 KiB
Python

import asyncpg
from userbot.modules.profiles.parse import ProfileFields
_GET_PEER = """
SELECT first_name, last_name, username, phone, photo_unique_id, is_deleted_account
FROM peers
WHERE account_id = $1 AND peer_id = $2
"""
_UPSERT_PEER = """
INSERT INTO peers
(account_id, peer_id, first_name, last_name, username, phone,
photo_unique_id, is_deleted_account, raw, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, now())
ON CONFLICT (account_id, peer_id) DO UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
username = EXCLUDED.username,
phone = EXCLUDED.phone,
photo_unique_id = EXCLUDED.photo_unique_id,
is_deleted_account = EXCLUDED.is_deleted_account,
raw = EXCLUDED.raw,
updated_at = now()
"""
_INSERT_HISTORY = """
INSERT INTO peer_history
(account_id, peer_id, observed_at, first_name, last_name, username, phone,
photo_unique_id, is_deleted_account, raw)
VALUES ($1, $2, now(), $3, $4, $5, $6, $7, $8, $9::jsonb)
ON CONFLICT DO NOTHING
"""
async def get_peer(
pool: asyncpg.Pool, account_id: int, peer_id: int
) -> ProfileFields | None:
row = await pool.fetchrow(_GET_PEER, account_id, peer_id)
if row is None:
return None
return ProfileFields(
first_name=row["first_name"],
last_name=row["last_name"],
username=row["username"],
phone=row["phone"],
photo_unique_id=row["photo_unique_id"],
is_deleted_account=row["is_deleted_account"],
)
async def write_profile(
pool: asyncpg.Pool, account_id: int, peer_id: int, fields: ProfileFields, raw: str
) -> None:
args = (
fields.first_name,
fields.last_name,
fields.username,
fields.phone,
fields.photo_unique_id,
fields.is_deleted_account,
raw,
)
async with pool.acquire() as conn, conn.transaction():
await conn.execute(_UPSERT_PEER, account_id, peer_id, *args)
await conn.execute(_INSERT_HISTORY, account_id, peer_id, *args)