To migrate your FastAPI authentication service from the databases library to pure SQLAlchemy while maintaining the same abstraction layer, you'll need to make several changes. This includes updating your database.py to use SQLAlchemy's asynchronous capabilities and modifying your UserRepository to interact with the new setup without altering its existing interface.
Below are the updated database.py and UserRepository files:
1. database.py
We'll replace the databases library with SQLAlchemy's AsyncEngine and AsyncSession. To maintain the same abstraction (Database interface) that your repositories rely on, we'll create a custom Database class that mimics the databases.Database interface using SQLAlchemy's async features.
# src/database.py
from uuid import uuid4
from sqlalchemy import (
ARRAY,
Boolean,
Column,
DateTime,
ForeignKey,
Identity,
Integer,
LargeBinary,
MetaData,
String,
Table,
create_engine,
func,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.schema import ForeignKeyConstraint
from src.config import settings
from src.constants import DB_NAMING_CONVENTION
DATABASE_URL = str(settings.DATABASE_URL).replace("postgresql://", "postgresql+asyncpg://")
# Create an asynchronous engine
engine: AsyncEngine = create_async_engine(
DATABASE_URL,
echo=settings.ENVIRONMENT.is_development,
future=True,
)
# Create a configured "AsyncSession" class
AsyncSessionLocal = sessionmaker(
bind=engine, class_=AsyncSession, expire_on_commit=False
)
metadata = MetaData(naming_convention=DB_NAMING_CONVENTION)
# Define your tables as before
auth_user = Table(
"auth_user",
metadata,
Column("id", Integer, Identity()),
Column("uuid", UUID(as_uuid=True), unique=True, primary_key=True, default=uuid4),
Column("name", String, nullable=True),
Column("email", String, unique=True, nullable=True),
Column("apple_id", String, unique=True, nullable=True),
Column("google_id", String, unique=True, nullable=True),
Column("wallet_address", String, unique=True, nullable=True),
Column("created_at", DateTime, server_default=func.now(), nullable=False),
Column("updated_at", DateTime, onupdate=func.now()),
Column("last_active_at", DateTime, nullable=True),
Column("is_admin", Boolean, server_default="false", nullable=False),
)
client_application = Table(
"client_application",
metadata,
Column("client_id", UUID(as_uuid=True), unique=True, primary_key=True, default=uuid4),
Column("client_secret", LargeBinary, nullable=False),
Column("client_name", String, nullable=False),
Column("redirect_uris", ARRAY(String)),
)
discord = Table(
"discord",
metadata,
Column("uuid", UUID(as_uuid=True), unique=True, primary_key=True, default=uuid4),
Column(
"user_uuid",
UUID(as_uuid=True),
ForeignKey("auth_user.uuid", ondelete="CASCADE"),
nullable=False,
unique=True,
),
Column("id", String, nullable=False, unique=True),
Column("user_name", String, nullable=False),
)
twitter = Table(
"twitter",
metadata,
Column("uuid", UUID(as_uuid=True), unique=True, primary_key=True, default=uuid4),
Column(
"user_uuid",
UUID(as_uuid=True),
ForeignKey("auth_user.uuid", ondelete="CASCADE"),
nullable=False,
unique=True,
),
Column("id", String, nullable=False, unique=True),
Column("name", String, nullable=True),
Column("user_name", String, nullable=False),
Column("profile_image_url", String, nullable=True),
)
# Custom Database class to mimic databases.Database interface
class Database:
def __init__(self, session_factory):
self._session_factory = session_factory
async def fetch_one(self, query, values=None):
async with self._session_factory() as session:
result = await session.execute(query)
return result.fetchone()
async def fetch_all(self, query, values=None):
async with self._session_factory() as session:
result = await session.execute(query)
return result.fetchall()
async def execute(self, query, values=None):
async with self._session_factory() as session:
try:
result = await session.execute(query)
await session.commit()
return result
except Exception as e:
await session.rollback()
raise e
async def execute_many(self, query, values_list):
async with self._session_factory() as session:
try:
await session.execute(query, values_list)
await session.commit()
except Exception as e:
await session.rollback()
raise e
async def connect(self):
# No action needed for SQLAlchemy
pass
async def disconnect(self):
await engine.dispose()
# Instantiate the custom Database
database = Database(AsyncSessionLocal)
Explanation:
-
Async Engine and Session:
- Engine: We use
create_async_engine with postgresql+asyncpg dialect for asynchronous operations.
- SessionMaker: Configured with
AsyncSession to handle session creation.
-
Table Definitions:
- Remain largely unchanged except for minor adjustments like setting
UUID(as_uuid=True) to ensure UUID fields are handled correctly.
-
Custom Database Class:
- Methods: Implements
fetch_one, fetch_all, execute, and execute_many to mirror the databases.Database interface.
- Session Management: Each method creates a new
AsyncSession, executes the query, and handles committing or rolling back transactions as necessary.
- Connect/Disconnect: The
connect method is a no-op since SQLAlchemy manages connections implicitly. The disconnect method disposes of the engine.
-
Instantiation:
- The
database instance is created using the custom Database class, ensuring your repositories can interact with it as before.
2. UserRepository
Now, update the UserRepository to work with the new Database class. Fortunately, since the custom Database class mirrors the databases.Database interface, minimal changes are required. Specifically, you need to ensure that the repository uses asynchronous sessions correctly.
# src/user/repositories/user_repository.py
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy import insert, select
from sqlalchemy.exc import SQLAlchemyError
from src.database import auth_user, database
from src.exceptions import UserRepositoryError
from src.user.models import User
__all__ = ["UserRepository"]
class UserRepository:
def __init__(self, db: database.__class__ = database):
self._db = db
self._write_fields = [
"name",
"email",
"is_admin",
"apple_id",
"google_id",
"wallet_address",
"last_active_at",
]
self._read_fields = [
"id",
"uuid",
"name",
"email",
"is_admin",
"apple_id",
"google_id",
"wallet_address",
"created_at",
"updated_at",
"last_active_at",
]
async def _get(self, filters: Dict[str, Any]) -> Optional[User]:
select_query = select(auth_user)
for field, value in filters.items():
if field in self._read_fields:
select_query = select_query.where(getattr(auth_user.c, field) == value)
try:
row = await self._db.fetch_one(select_query)
except SQLAlchemyError:
raise UserRepositoryError
if row:
return self._to_object(row)
return None
async def _get_batch(self, ids: List[Any], filters: Dict[str, Any]) -> List[User]:
select_query = select(auth_user).where(auth_user.c.uuid.in_(ids))
for field, value in filters.items():
if field in self._read_fields:
select_query = select_query.where(getattr(auth_user.c, field) == value)
try:
rows = await self._db.fetch_all(select_query)
except SQLAlchemyError:
raise UserRepositoryError
if rows:
users = [self._to_object(row) for row in rows]
return users
return []
async def _update(self, user: User, fields: Optional[List[str]] = None) -> None:
if not fields:
fields = self._write_fields
if fields:
valid_fields = {field for field in fields if field in self._write_fields}
update_values = user.model_dump(include=valid_fields)
if update_values:
update_query = (
auth_user.update()
.values(update_values)
.where(auth_user.c.uuid == user.uuid)
)
try:
await self._db.execute(update_query)
except SQLAlchemyError:
raise UserRepositoryError
async def _create(self, values: Dict[str, Any]) -> User:
insert_values = {
key: value for key, value in values.items() if key in self._write_fields
}
insert_values.update({"uuid": uuid.uuid4(), "created_at": datetime.utcnow()})
insert_query = insert(auth_user).values(insert_values).returning(auth_user)
try:
row = await self._db.fetch_one(insert_query)
if not row:
raise UserRepositoryError
except SQLAlchemyError:
raise UserRepositoryError
return self._to_object(row)
async def get_by_uuid(self, user_uuid: uuid.UUID) -> Optional[User]:
filters = {"uuid": user_uuid}
return await self._get(filters)
async def get_by_email(self, email: str) -> Optional[User]:
filters = {"email": email.lower()}
return await self._get(filters)
async def get_by_wallet_address(self, wallet_address: str) -> Optional[User]:
filters = {"wallet_address": wallet_address}
return await self._get(filters)
async def get_by_apple_id(self, apple_id: str) -> Optional[User]:
filters = {"apple_id": apple_id}
return await self._get(filters)
async def get_by_google_id(self, google_id: str) -> Optional[User]:
filters = {"google_id": google_id}
return await self._get(filters)
async def get_batch_by_uuid(self, user_uuids: List[uuid.UUID]) -> List[User]:
return await self._get_batch(ids=user_uuids, filters={})
async def set_email(self, user: User, email: str) -> None:
user.email = email
await self._update(user, fields=["email"])
async def set_name(self, user: User, name: str) -> None:
user.name = name
await self._update(user, fields=["name"])
async def set_google_id(self, user: User, google_id: str) -> None:
user.google_id = google_id
await self._update(user, fields=["google_id"])
async def set_apple_id(self, user: User, apple_id: str) -> None:
user.apple_id = apple_id
await self._update(user, fields=["apple_id"])
async def set_wallet_address(self, user: User, wallet_address: str) -> None:
user.wallet_address = wallet_address
await self._update(user, fields=["wallet_address"])
async def set_activity_date(self, user: User, activity_date: datetime) -> None:
user.last_active_at = activity_date
await self._update(user, fields=["last_active_at"])
async def create_with_email(self, email: str) -> User:
values = {"email": email.lower()}
return await self._create(values)
async def create_with_google(self, google_id: str, email: str) -> User:
values = {"google_id": google_id, "email": email.lower()}
return await self._create(values)
async def create_with_apple(self, apple_id: str, email: str) -> User:
values = {"apple_id": apple_id, "email": email.lower()}
return await self._create(values)
async def create_with_wallet(self, wallet_address: str) -> User:
values = {"wallet_address": wallet_address}
return await self._create(values)
@classmethod
def _to_object(cls, row) -> User:
return User(
id=row["id"],
uuid=row["uuid"],
name=row["name"],
email=row["email"],
is_admin=row["is_admin"],
apple_id=row["apple_id"],
google_id=row["google_id"],
wallet_address=row["wallet_address"],
created_at=row["created_at"],
updated_at=row["updated_at"],
last_active_at=row["last_active_at"],
)
Explanation:
-
Initialization:
- The
UserRepository now accepts an instance of the custom Database class. By default, it uses the database instance created in database.py.
-
Database Operations:
- All database operations (
fetch_one, fetch_all, execute) are performed using the methods provided by the custom Database class, which internally uses SQLAlchemy's AsyncSession.
-
Error Handling:
- Exceptions are caught and re-raised as
UserRepositoryError to maintain consistency.
-
Data Transformation:
- The
_to_object method converts SQLAlchemy result rows into User model instances as before.
-
No Changes Needed in Repository Usage:
- Since the
Database interface remains the same, you don't need to modify any other parts of your codebase that depend on UserRepository.
3. Application Startup and Shutdown
Ensure that your FastAPI application properly initializes and disposes of the database connection. Update your main application file (e.g., main.py) as follows:
# src/main.py
from fastapi import FastAPI
from src.database import database
from src.user.repositories.user_repository import UserRepository
app = FastAPI()
# Initialize repositories
user_repository = UserRepository(db=database)
@app.on_event("startup")
async def startup():
await database.connect()
# You can also create tables here if not using migrations
# from src.database import metadata, engine
# async with engine.begin() as conn:
# await conn.run_sync(metadata.create_all)
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
# Include your routers and other setup
Explanation:
-
Startup Event:
- Calls
database.connect(), which is essentially a no-op in our custom Database class but can be used to perform any initialization if needed.
-
Shutdown Event:
- Disposes of the SQLAlchemy engine to gracefully close all connections.
4. Additional Considerations
-
Migrations:
- If you're using Alembic for database migrations, ensure it's configured to work with the asynchronous engine. Update your
alembic.ini and migration scripts accordingly.
-
Session Management:
- The custom
Database class handles session creation and disposal for each operation. If you need more granular control over transactions, consider integrating SQLAlchemy's transaction management into your repository methods.
-
Dependency Injection:
- If you're using dependency injection for repositories, ensure that the new
database instance is correctly provided to your repositories.
5. Summary
By replacing the databases library with SQLAlchemy's asynchronous capabilities and creating a custom Database class that mimics the databases.Database interface, you can maintain the same abstraction layer in your repositories. This approach minimizes changes to your repository code and ensures compatibility with newer versions of SQLAlchemy.
This setup leverages the full power of SQLAlchemy's async features, providing better performance and more control over your database interactions without sacrificing the architectural integrity of your application.