from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, DateTime, Date, Float from sqlalchemy.orm import relationship, declarative_base from sqlalchemy.ext.mutable import MutableDict from sqlalchemy.dialects.postgresql import ARRAY, JSONB from sqlalchemy.ext.mutable import MutableList from datetime import datetime Base = declarative_base() # userposts table depends on username and pins as a foreign key, so we define them first here for # it to use as a dependency, otherwise if the userposts table is attempted to be # created first we would have tables not found error class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) username = Column(String, unique=True, index=True, nullable=False) email = Column(String, unique=True, index=True, nullable=False) hashed_password = Column(String, nullable=False) dob = Column(Date, nullable=False) country_of_origin = Column(String, nullable=False) followers = Column(MutableList.as_mutable(ARRAY(String)), default=[]) following = Column(MutableList.as_mutable(ARRAY(String)), default=[]) bio = Column(String, nullable=True) profile_picture = Column(String, nullable=True) pins = relationship("Pin", back_populates="users") posts = relationship("UserPost", back_populates="user", cascade="all, delete") class Pin(Base): __tablename__ = "pins" id = Column(Integer, primary_key=True, index=True) pin_name = Column(String, nullable=False) username = Column(String, ForeignKey("users.username"), nullable=False) x = Column(Float, nullable=False) # long y = Column(Float, nullable=False) # lat description = Column(String, nullable=True) # optional category = Column(String, nullable=True) # optional public = Column(Boolean, default=False) created_at = Column(DateTime, default=datetime.utcnow) users = relationship("User", back_populates="pins") posts = relationship("UserPost", back_populates="pin", cascade="all, delete") class UserPost(Base): __tablename__ = "user_posts" id = Column(Integer, primary_key=True, index=True, autoincrement=True) username = Column(String, ForeignKey("users.username", ondelete="CASCADE"), nullable=False) image_url = Column(String, nullable=False) # image as url, Amazon S3 description = Column(String, nullable=True) tags = Column(String, nullable=True) public = Column(Boolean, default=False) pin_id = Column(Integer, ForeignKey("pins.id", ondelete="SET NULL"), nullable=False) likes = Column(Integer, default=0) comments = Column(MutableDict.as_mutable(JSONB), default={}) created_at = Column(DateTime, default=datetime.utcnow) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) pin = relationship("Pin", back_populates="posts") user = relationship("User", back_populates="posts")