61 lines
2.3 KiB
Python
61 lines
2.3 KiB
Python
import uuid
|
|
from datetime import datetime
|
|
from typing import TYPE_CHECKING
|
|
|
|
from sqlalchemy import Column, String, Boolean, DateTime, ForeignKey, Text, TypeDecorator
|
|
from sqlalchemy.orm import relationship, Mapped, mapped_column
|
|
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
|
|
|
|
from fastapi_users.db import SQLAlchemyBaseUserTableUUID
|
|
|
|
from database import Base
|
|
|
|
if TYPE_CHECKING:
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
|
|
# GUID type that works with both SQLite and PostgreSQL
|
|
class GUID(TypeDecorator):
|
|
"""Platform-independent GUID type that uses CHAR(36) on SQLite and UUID on PostgreSQL."""
|
|
impl = String(36)
|
|
cache_ok = True
|
|
|
|
def process_bind_param(self, value, dialect):
|
|
if value is None:
|
|
return value
|
|
if isinstance(value, uuid.UUID):
|
|
return str(value)
|
|
return value
|
|
|
|
def process_result_value(self, value, dialect):
|
|
if value is None:
|
|
return value
|
|
if not isinstance(value, uuid.UUID):
|
|
return uuid.UUID(value)
|
|
return value
|
|
|
|
class User(SQLAlchemyBaseUserTableUUID, Base):
|
|
__allow_unmapped__ = True
|
|
# FastAPI-Users requires these fields for full functionality
|
|
is_superuser: bool = Column(Boolean, default=False, nullable=False)
|
|
is_verified: bool = Column(Boolean, default=False, nullable=False)
|
|
|
|
url_lists: Mapped[list["URLList"]] = relationship("URLList", back_populates="owner", cascade="all, delete-orphan")
|
|
|
|
class URLList(Base):
|
|
__tablename__ = "url_lists"
|
|
__allow_unmapped__ = True
|
|
|
|
id: Mapped[uuid.UUID] = mapped_column(GUID(), primary_key=True, default=uuid.uuid4)
|
|
name: Mapped[str] = mapped_column(String(100), index=True)
|
|
urls: Mapped[str] = mapped_column(Text)
|
|
unique_slug: Mapped[str] = mapped_column(String(50), unique=True, index=True)
|
|
is_public: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
|
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
|
|
|
owner_id: Mapped[uuid.UUID] = mapped_column(GUID(), ForeignKey("user.id"))
|
|
owner: Mapped["User"] = relationship("User", back_populates="url_lists")
|
|
|
|
def __repr__(self):
|
|
return f"<URLList(name='{self.name}', unique_slug='{self.unique_slug}')>"
|