from datetime import datetime from typing import Optional from sqlalchemy import String, DateTime, ForeignKey, func, Index from sqlalchemy.orm import Mapped, mapped_column, relationship from app.database import Base class Record(Base): __tablename__ = "records" id: Mapped[int] = mapped_column(primary_key=True) table_id: Mapped[int] = mapped_column( ForeignKey("tables.id", ondelete="CASCADE"), nullable=False, index=True ) created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=True) updated_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=func.now()) updated_at: Mapped[datetime] = mapped_column( DateTime, default=func.now(), onupdate=func.now() ) # Relationships table = relationship("Table", back_populates="records") created_by_user = relationship( "User", back_populates="created_records", foreign_keys=[created_by] ) updated_by_user = relationship( "User", back_populates="updated_records", foreign_keys=[updated_by] ) cell_values = relationship( "CellValue", back_populates="record", cascade="all, delete-orphan" ) comments = relationship( "Comment", back_populates="record", cascade="all, delete-orphan" ) attachments = relationship( "Attachment", back_populates="record", cascade="all, delete-orphan" ) __table_args__ = (Index("idx_records_table", "table_id"),) def __repr__(self): return f"" class CellValue(Base): __tablename__ = "cell_values" id: Mapped[int] = mapped_column(primary_key=True) record_id: Mapped[int] = mapped_column( ForeignKey("records.id", ondelete="CASCADE"), nullable=False, index=True ) column_id: Mapped[int] = mapped_column( ForeignKey("columns.id", ondelete="CASCADE"), nullable=False, index=True ) value: Mapped[Optional[str]] = mapped_column(String, nullable=True) updated_at: Mapped[datetime] = mapped_column( DateTime, default=func.now(), onupdate=func.now() ) # Relationships record = relationship("Record", back_populates="cell_values") column = relationship("Column", back_populates="cell_values") __table_args__ = ( Index("idx_cell_values_record", "record_id"), Index("idx_cell_values_column", "column_id"), ) def __repr__(self): return f""