64 lines
1.6 KiB
Python
64 lines
1.6 KiB
Python
"""User repository for database operations."""
|
|
|
|
from uuid import UUID
|
|
|
|
import asyncpg
|
|
|
|
|
|
class UserRepository:
|
|
"""Database operations for users."""
|
|
|
|
def __init__(self, conn: asyncpg.Connection) -> None:
|
|
self.conn = conn
|
|
|
|
async def create(
|
|
self,
|
|
user_id: UUID,
|
|
email: str,
|
|
password_hash: str,
|
|
) -> dict:
|
|
"""Create a new user."""
|
|
row = await self.conn.fetchrow(
|
|
"""
|
|
INSERT INTO users (id, email, password_hash)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id, email, created_at
|
|
""",
|
|
user_id,
|
|
email,
|
|
password_hash,
|
|
)
|
|
return dict(row)
|
|
|
|
async def get_by_id(self, user_id: UUID) -> dict | None:
|
|
"""Get user by ID."""
|
|
row = await self.conn.fetchrow(
|
|
"""
|
|
SELECT id, email, password_hash, created_at
|
|
FROM users
|
|
WHERE id = $1
|
|
""",
|
|
user_id,
|
|
)
|
|
return dict(row) if row else None
|
|
|
|
async def get_by_email(self, email: str) -> dict | None:
|
|
"""Get user by email."""
|
|
row = await self.conn.fetchrow(
|
|
"""
|
|
SELECT id, email, password_hash, created_at
|
|
FROM users
|
|
WHERE email = $1
|
|
""",
|
|
email,
|
|
)
|
|
return dict(row) if row else None
|
|
|
|
async def exists_by_email(self, email: str) -> bool:
|
|
"""Check if user exists by email."""
|
|
result = await self.conn.fetchval(
|
|
"SELECT EXISTS(SELECT 1 FROM users WHERE email = $1)",
|
|
email,
|
|
)
|
|
return result
|