FastAPI-Users on pgdorm — Zero SQLAlchemy, Zero greenlet, 1-RTT OAuth2 & JWT#
← Proving Grounds · FastAPI-Users on GitHub ↗ · Tests: tests/cases/fastapi_users/
The Problem#
FastAPI-Users (MIT) is the standard batteries-included authentication library for FastAPI, but its default PostgreSQL adapter (fastapi-users-db-sqlalchemy) drags in sqlalchemy[asyncio], greenlet, AsyncSession, expire_on_commit=False, and lazy="joined" relationship traps (results.unique().scalar_one_or_none(), MissingGreenlet during Pydantic serialization, and 3-RTT session.refresh() + commit() + session.refresh() on OAuth account links).
pgdorm drops directly into FastAPI-Users' BaseUserDatabase protocol via PgdormUserDatabase — implementing all 8/8 BaseUserDatabase methods on two slot-backed pg.Table models (AuthUser and OAuthAccount) with zero wrapper dataclasses, zero SQLAlchemy, and zero greenlet.
Direct Slot-Backed Models (Zero Wrapper Boilerplate)#
With strict_pk=False, AuthUser and OAuthAccount satisfy FastAPI-Users' UserOAuthProtocol and OAuthAccountProtocol directly — no _to_user() mapping layer and no __dict__ overhead:
class AuthUser(pg.Table, strict_pk=False):
id: pg.Col[UUID] = pg.pk()
email: pg.Col[str] = pg.col(unique=True)
hashed_password: pg.Col[str] = pg.col()
is_active: pg.Col[bool] = pg.col(default=True)
is_superuser: pg.Col[bool] = pg.col(default=False)
is_verified: pg.Col[bool] = pg.col(default=False)
@property
def oauth_accounts(self) -> list[OAuthAccount]:
return _OAUTH_ACCOUNTS.setdefault(self.id, [])
@oauth_accounts.setter
def oauth_accounts(self, value: list[OAuthAccount]) -> None:
_OAUTH_ACCOUNTS[self.id] = value
class OAuthAccount(pg.Table, strict_pk=False):
id: pg.Col[UUID] = pg.pk()
user_id: pg.Col[UUID] = pg.fk(AuthUser.id, on_delete=pg.enums.OnDelete.CASCADE)
oauth_name: pg.Col[str] = pg.col()
access_token: pg.Col[str] = pg.col()
expires_at: pg.Col[int | None] = pg.col(default=None)
refresh_token: pg.Col[str | None] = pg.col(default=None)
account_id: pg.Col[str] = pg.col()
account_email: pg.Col[str] = pg.col()
Before vs After: 1-RTT OAuth Link (add_oauth_account)#
Before (fastapi-users-db-sqlalchemy — 3 RTTs)#
# Upstream SQLAlchemy adapter: 3 network round trips per OAuth link
async def add_oauth_account(self, user: UOAP, create_dict: dict[str, Any]) -> UOAP:
await self.session.refresh(user) # RTT 1: reload user + joined accounts
oauth_account = self.oauth_account_table(**create_dict)
self.session.add(oauth_account)
user.oauth_accounts.append(oauth_account)
self.session.add(user)
await self.session.commit() # RTT 2: INSERT + COMMIT
await self.session.refresh(user) # RTT 3: reload user + joined accounts
return user
After (pgdorm — 1 RTT via tx.pipeline(commit=True))#
async def add_oauth_account( # ty: ignore[incompatible-method-override]
self, user: AuthUser, create_dict: dict[str, Any]
) -> AuthUser:
self.calls.append("add_oauth_account")
expires_raw = create_dict.get("expires_at")
refresh_raw = create_dict.get("refresh_token")
account = OAuthAccount(
id=create_dict.get("id") or uuid4(),
user_id=user.id,
oauth_name=str(create_dict["oauth_name"]),
access_token=str(create_dict["access_token"]),
expires_at=int(expires_raw) if expires_raw is not None else None,
refresh_token=str(refresh_raw) if refresh_raw is not None else None,
account_id=str(create_dict["account_id"]),
account_email=str(create_dict["account_email"]),
)
async with self._pool.transaction() as tx, tx.pipeline(commit=True) as pipe:
pipe.add(pg.insert(OAuthAccount).values(account))
accounts_handle = pipe.add(
pg.select(OAuthAccount)
.where(OAuthAccount.user_id == user.id)
.order_by(OAuthAccount.oauth_name.asc(), OAuthAccount.account_id.asc())
)
user.oauth_accounts = accounts_handle.all()
return user
What crosses the wire (1 Sync, tr.rtts == 1):
-- Frame 1: BEGIN (lazy, fused)
-- Frame 2: INSERT INTO "oauth_account" (...) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
-- Frame 3: SELECT "id", "user_id", "oauth_name", ... FROM "oauth_account"
-- WHERE "user_id" = $1 ORDER BY "oauth_name" ASC, "account_id" ASC
-- Frame 4: COMMIT + single Sync ==> 1 RTT (verified via TelemetryHook)
Before vs After: 1-RTT OAuth Lookup (No AsyncSession, No greenlet, No .unique())#
Before (fastapi-users-db-sqlalchemy)#
# Requires sqlalchemy[asyncio] + greenlet + expire_on_commit=False.
# Forgetting .unique() on joined eager loads crashes at runtime;
# touching an unloaded relationship in Pydantic raises MissingGreenlet.
async def get_by_oauth_account(self, oauth: str, account_id: str) -> UP | None:
statement = (
select(self.user_table)
.join(self.oauth_account_table)
.where(self.oauth_account_table.oauth_name == oauth)
.where(self.oauth_account_table.account_id == account_id)
)
results = await self.session.execute(statement)
return results.unique().scalar_one_or_none()
After (pgdorm — 4-Line Typed JOIN, 1 RTT)#
async def get_by_oauth_account(self, oauth: str, account_id: str) -> AuthUser | None:
self.calls.append("get_by_oauth_account")
return await self._pool.one_or_none(
pg.select(AuthUser)
.join(OAuthAccount)
.where((OAuthAccount.oauth_name == oauth) & (OAuthAccount.account_id == account_id))
)
No AsyncSession, no greenlet, no .unique(), and no MissingGreenlet — just a single prepared JOIN backed by auto_index_fk = True on oauth_account(user_id).
The Adoption Ladder#
| Status | Rung | Today | Blocked by |
|---|---|---|---|
| ✅ | Audit the live schema | 2 tables; left untouched: nothing | — |
| ✅ | Bind models to the live schema, zero DDL | 0 planned DDL operations | — |
| ✅ | Build a fresh database from the models alone | 2 DDL ops applied cleanly | — |
| ✅ | Assimilate onto pgdorm conventions | 2 tables assimilated cleanly (0 residual ops) | — |
| ✅ | Run real FastAPI-Users auth, JWT & OAuth2 on pgdorm | All 8/8 BaseUserDatabase methods, 5 JWT endpoints & 1-RTT OAuth2 verified end-to-end | — |