from sqlalchemy import Column, ForeignKey, Integer, String, DateTime from sqlalchemy.orm import relationship from datetime import datetime from database import Base class User(Base): # This defines the name of the table in the database. # Here, the class User is mapped to a table called users. __tablename__ = "users" # __table_args__ = {'extend_existing': True} # This line defines a column called id in the users table. # Integer: The data type of this column is an integer. # primary_key=True: This makes the id column the primary key # for the users table, meaning each row will have a unique id. # index=True: This creates an index on the id column, making # lookups by id faster. id = Column(Integer, primary_key=True, index=True) # This line defines a column called username. username = Column(String, unique=True, index=True) # This establishes a relationship between the User model # and a related model called Message. # relationship("Message"): This creates a one-to-many relationship between User and Message. # It indicates that each user can have many associated messages # (the relationship is “one user to many messages”). # back_populates="user": This specifies that the relationship is bidirectional, # meaning the Message model will also have a corresponding relationship with User. # The back_populates="user" part tells SQLAlchemy to link the relationship on the # Message side back to the user field, creating a mutual relationship. messages = relationship("Message", back_populates="user") # TODO: Implement the Message SQLAlchemy model. Message should have a primary key, # a message attribute to store the content of messages, a type, AI or Human, # depending on if it is a user question or an AI response, a timestamp to # order by time and a user attribute to get the user instance associated # with the message. We also need a user_id that will use the User.id # attribute as a foreign key. class Message(Base): __tablename__ = "messages" # __table_args__ = {'extend_existing': True} id = Column(Integer, primary_key=True, index=True) user_id = Column(Integer, ForeignKey("users.id"), nullable=False) message = Column(String, nullable=False) type = Column(String, nullable=False) timestamp = Column(DateTime, default=datetime.now(), nullable=False) user = relationship("User", back_populates="messages")