geo/backend/app/models/competitor.py

50 lines
1.5 KiB
Python

import uuid
from datetime import datetime
from sqlalchemy import String, DateTime, func, JSON, ForeignKey
from sqlalchemy import Uuid
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.types import TypeDecorator
from app.database import Base
class JSONType(TypeDecorator):
"""A JSON type that uses JSONB on PostgreSQL and JSON on other databases."""
impl = JSON
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == "postgresql":
return dialect.type_descriptor(JSONB())
return dialect.type_descriptor(JSON())
class Competitor(Base):
__tablename__ = "competitors"
id: Mapped[uuid.UUID] = mapped_column(
Uuid(as_uuid=True),
primary_key=True,
default=uuid.uuid4,
)
brand_id: Mapped[uuid.UUID] = mapped_column(
Uuid(as_uuid=True),
ForeignKey("brands.id", ondelete="CASCADE"),
nullable=False,
)
name: Mapped[str] = mapped_column(String(50), nullable=False)
aliases: Mapped[list] = mapped_column(JSONType, default=list, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
nullable=False,
)
brand: Mapped["Brand"] = relationship("Brand", back_populates="competitors")
# Import at bottom to avoid circular import
from app.models.brand import Brand # noqa: E402, F401