from datetime import datetime from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, UniqueConstraint from app.database import Base class UserCollection(Base): __tablename__ = "user_collections" id = Column(Integer, primary_key=True, index=True) user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) title = Column(String(200), nullable=False) created_at = Column(DateTime, default=datetime.utcnow) # When it was last opened or added to. Null means never since this was # recorded, which is not the same claim as "never used". last_used_at = Column(DateTime, nullable=True) class UserCollectionQuestion(Base): __tablename__ = "user_collection_questions" __table_args__ = (UniqueConstraint("collection_id", "question_id", name="uq_collection_question"),) id = Column(Integer, primary_key=True, index=True) collection_id = Column(Integer, ForeignKey("user_collections.id", ondelete="CASCADE"), nullable=False) question_id = Column(Integer, ForeignKey("questions.id", ondelete="CASCADE"), nullable=False) class UserCollectionArticle(Base): """An article put aside into a library. Its own table rather than a nullable `article_id` beside `question_id` on the row above: that shape allows a row with both, or with neither, and every read then has to say which kind it is looking at. Two tables, one unique constraint each, and a library is the union of them. """ __tablename__ = "user_collection_articles" __table_args__ = (UniqueConstraint("collection_id", "article_id", name="uq_collection_article"),) id = Column(Integer, primary_key=True, index=True) collection_id = Column(Integer, ForeignKey("user_collections.id", ondelete="CASCADE"), nullable=False) article_id = Column(Integer, ForeignKey("articles.id", ondelete="CASCADE"), nullable=False)