Files
resolutionflow/backend/app/models/account.py
chihlasm 974e86a502 fix: resolve circular FK between users and accounts on registration
Account.owner_id and User.account_id are both NOT NULL, creating a
circular dependency that prevents inserting either row first. Fix by:
1. Making owner_id nullable (set immediately after user creation)
2. Creating Account before User, then setting owner_id after flush
3. Removing NOT NULL enforcement on owner_id in migration 020

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 02:55:53 -05:00

39 lines
2.4 KiB
Python

import uuid
from datetime import datetime, timezone
from typing import Optional, TYPE_CHECKING
from sqlalchemy import String, DateTime, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import UUID
from app.core.database import Base
if TYPE_CHECKING:
from app.models.user import User
from app.models.subscription import Subscription
from app.models.tree import Tree
from app.models.category import TreeCategory
from app.models.tag import TreeTag
from app.models.step_category import StepCategory
from app.models.step_library import StepLibrary
class Account(Base):
__tablename__ = "accounts"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name: Mapped[str] = mapped_column(String(255), nullable=False)
display_code: Mapped[str] = mapped_column(String(8), unique=True, nullable=False)
owner_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="RESTRICT"), nullable=True)
stripe_customer_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
# Relationships
owner: Mapped["User"] = relationship("User", foreign_keys=[owner_id], back_populates="owned_account")
users: Mapped[list["User"]] = relationship("User", foreign_keys="[User.account_id]", back_populates="account")
subscription: Mapped[Optional["Subscription"]] = relationship("Subscription", back_populates="account", uselist=False)
trees: Mapped[list["Tree"]] = relationship("Tree", foreign_keys="[Tree.account_id]", back_populates="account")
categories: Mapped[list["TreeCategory"]] = relationship("TreeCategory", foreign_keys="[TreeCategory.account_id]", back_populates="account")
tags: Mapped[list["TreeTag"]] = relationship("TreeTag", foreign_keys="[TreeTag.account_id]", back_populates="account")
step_categories: Mapped[list["StepCategory"]] = relationship("StepCategory", foreign_keys="[StepCategory.account_id]", back_populates="account")
step_library: Mapped[list["StepLibrary"]] = relationship("StepLibrary", foreign_keys="[StepLibrary.account_id]", back_populates="account")