acupedia-api/app/db/models/content.py

886 lines
46 KiB
Python

from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from typing import Any
from uuid import UUID
from sqlalchemy import (
ARRAY,
BigInteger,
Boolean,
CheckConstraint,
Computed,
Date,
DateTime,
ForeignKey,
Index,
Integer,
Numeric,
PrimaryKeyConstraint,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.dialects.postgresql import JSONB, TSVECTOR, UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base import Base
from app.db.schemas import AUTH_SCHEMA, COMMERCE_SCHEMA, CONTENT_SCHEMA, PLATFORM_SCHEMA
from app.db.enums import (
ATTRIBUTE_VALUE_TYPE_ENUM,
BILLING_PERIOD_ENUM,
CONTENT_KIND_ENUM,
DEVICE_REQUEST_STATUS_ENUM,
ENTITLEMENT_STATUS_ENUM,
MEDIA_KIND_ENUM,
MODULE_STATUS_ENUM,
NOTIFICATION_DELIVERY_ENUM,
PAYMENT_STATUS_ENUM,
PLAN_TYPE_ENUM,
RECORD_STATUS_ENUM,
SUBSCRIPTION_STATUS_ENUM,
AttributeValueType,
BillingPeriod,
ContentKind,
DeviceRequestStatus,
EntitlementStatus,
MediaKind,
ModuleStatus,
NotificationDelivery,
PaymentStatus,
PlanType,
RecordStatus,
SubscriptionStatus,
)
# =============================================================================
# CONTENT MODELS
# =============================================================================
class AttributeDefinitionSet(Base):
__tablename__ = "attribute_definition_sets"
__table_args__ = (
UniqueConstraint("code", name="uq_attribute_definition_sets_code"),
UniqueConstraint("attribute_prefix_code", name="uq_attribute_definition_sets_prefix_code"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
code: Mapped[str] = mapped_column(Text, nullable=False)
name: Mapped[str] = mapped_column(Text, nullable=False)
attribute_prefix_code: Mapped[str] = mapped_column(Text, nullable=False)
attribute_prefix_name: Mapped[str] = mapped_column(Text, nullable=False)
content_kind: Mapped[ContentKind | None] = mapped_column(CONTENT_KIND_ENUM)
description: Mapped[str | None] = mapped_column(Text)
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
content_items: Mapped[list["ContentItem"]] = relationship(back_populates="attribute_definition_set", cascade="all, delete-orphan", passive_deletes=True)
attribute_definitions: Mapped[list["AttributeDefinition"]] = relationship(back_populates="attribute_definition_set", cascade="all, delete-orphan", passive_deletes=True)
presentation_contracts: Mapped[list["TemplatePresentationContract"]] = relationship(
back_populates="attribute_definition_set",
cascade="all, delete-orphan",
passive_deletes=True,
order_by="TemplatePresentationContract.client_type, TemplatePresentationContract.version_no.desc()",
)
class TemplatePresentationContract(Base):
__tablename__ = "template_presentation_contracts"
__table_args__ = (
UniqueConstraint(
"attribute_definition_set_id",
"client_type",
"version_no",
name="uq_template_presentation_contract_version",
),
CheckConstraint("length(btrim(client_type)) > 0", name="ck_template_presentation_client_type"),
CheckConstraint("presentation_mode in ('collection', 'single')", name="ck_template_presentation_mode"),
CheckConstraint("version_no > 0", name="ck_template_presentation_version"),
CheckConstraint("length(btrim(detail_renderer)) > 0", name="ck_template_presentation_detail_renderer"),
CheckConstraint(
"collection_renderer is null or length(btrim(collection_renderer)) > 0",
name="ck_template_presentation_collection_renderer",
),
CheckConstraint(
"collection_item_renderer is null or length(btrim(collection_item_renderer)) > 0",
name="ck_template_presentation_collection_item_renderer",
),
CheckConstraint(
"presentation_mode <> 'collection' or (collection_renderer is not null and collection_item_renderer is not null)",
name="ck_template_presentation_collection_requirements",
),
CheckConstraint(
"presentation_mode <> 'single' or (collection_renderer is null and collection_item_renderer is null)",
name="ck_template_presentation_single_requirements",
),
CheckConstraint("jsonb_typeof(metadata) = 'object'", name="ck_template_presentation_metadata_object"),
Index(
"uq_template_presentation_active_client",
"attribute_definition_set_id",
"client_type",
unique=True,
postgresql_where=text("is_active = true"),
),
Index(
"idx_template_presentation_definition_set",
"attribute_definition_set_id",
"client_type",
"is_active",
text("version_no desc"),
),
Index("idx_template_presentation_client_active", "client_type", "is_active"),
Index(
"idx_template_presentation_metadata_gin",
"metadata",
postgresql_using="gin",
postgresql_ops={"metadata": "jsonb_path_ops"},
),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
attribute_definition_set_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.attribute_definition_sets.id", ondelete="CASCADE"),
nullable=False,
)
client_type: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'mobile'"))
presentation_mode: Mapped[str] = mapped_column(Text, nullable=False)
collection_renderer: Mapped[str | None] = mapped_column(Text)
collection_item_renderer: Mapped[str | None] = mapped_column(Text)
detail_renderer: Mapped[str] = mapped_column(Text, nullable=False)
version_no: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("1"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
attribute_definition_set: Mapped[AttributeDefinitionSet] = relationship(back_populates="presentation_contracts")
attribute_presentations: Mapped[list["TemplateAttributePresentation"]] = relationship(
back_populates="presentation_contract",
cascade="all, delete-orphan",
passive_deletes=True,
order_by="TemplateAttributePresentation.attribute_definition_id",
)
class ContentItem(Base):
__tablename__ = "content_items"
__table_args__ = (
UniqueConstraint("slug", name="uq_content_items_slug"),
CheckConstraint("version_no > 0", name="ck_content_items_version"),
Index("uq_content_items_source_key", "source_key", unique=True, postgresql_where=text("source_key is not null")),
Index("idx_content_items_definition_set", "attribute_definition_set_id"),
Index("idx_content_items_slug", "slug"),
Index("idx_content_items_metadata_gin", "metadata", postgresql_using="gin", postgresql_ops={"metadata": "jsonb_path_ops"}),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
attribute_definition_set_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.attribute_definition_sets.id", ondelete="CASCADE"), nullable=False)
content_kind: Mapped[ContentKind | None] = mapped_column(CONTENT_KIND_ENUM)
title: Mapped[str] = mapped_column(Text, nullable=False)
slug: Mapped[str] = mapped_column(Text, nullable=False)
summary: Mapped[str | None] = mapped_column(Text)
source_key: Mapped[str | None] = mapped_column(Text)
status: Mapped[RecordStatus] = mapped_column(RECORD_STATUS_ENUM, nullable=False, server_default=text("'draft'"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
sort_title: Mapped[str] = mapped_column(Text, Computed("lower(title)", persisted=True))
default_language: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'en'"))
created_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="RESTRICT"))
updated_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="RESTRICT"))
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
version_no: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("1"))
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
attribute_definition_set: Mapped[AttributeDefinitionSet] = relationship(back_populates="content_items")
creator: Mapped[AppUser | None] = relationship(
"AppUser", foreign_keys=[created_by], back_populates="created_content_items"
)
updater: Mapped[AppUser | None] = relationship(
"AppUser", foreign_keys=[updated_by], back_populates="updated_content_items"
)
translations: Mapped[list["ContentTranslation"]] = relationship(back_populates="content", cascade="all, delete-orphan", passive_deletes=True)
attributes: Mapped[list["ContentAttribute"]] = relationship(back_populates="content", cascade="all, delete-orphan", passive_deletes=True, foreign_keys="ContentAttribute.content_id")
media_links: Mapped[list["ContentMedia"]] = relationship(back_populates="content", cascade="all, delete-orphan", passive_deletes=True)
class ContentTranslation(Base):
__tablename__ = "content_translations"
__table_args__ = (UniqueConstraint("content_id", "language_code", name="uq_content_translation"), {"schema": CONTENT_SCHEMA})
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
content_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.content_items.id", ondelete="CASCADE"), nullable=False)
language_code: Mapped[str] = mapped_column(Text, nullable=False)
title: Mapped[str] = mapped_column(Text, nullable=False)
summary: Mapped[str | None] = mapped_column(Text)
body_json: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, server_default=text("'{}'::jsonb"))
is_machine_translated: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
translated_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="SET NULL"))
reviewed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
content: Mapped[ContentItem] = relationship(back_populates="translations")
translator: Mapped[AppUser | None] = relationship(foreign_keys=[translated_by])
class Tag(Base):
__tablename__ = "tags"
__table_args__ = (
UniqueConstraint("slug", name="uq_tags_slug"),
UniqueConstraint("code", name="uq_tags_code"),
Index("idx_tags_slug", "slug"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
name: Mapped[str | None] = mapped_column(Text)
slug: Mapped[str | None] = mapped_column(Text)
code: Mapped[str | None] = mapped_column(Text)
label: Mapped[str | None] = mapped_column(Text)
description: Mapped[str | None] = mapped_column(Text)
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
class ContentTag(Base):
__tablename__ = "content_tags"
__table_args__ = (
UniqueConstraint("content_id", "tag_id"),
Index("idx_content_tags_content", "content_id"),
Index("idx_content_tags_tag", "tag_id"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
content_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.content_items.id", ondelete="CASCADE"), nullable=False)
tag_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.tags.id", ondelete="CASCADE"), nullable=False)
content: Mapped[ContentItem] = relationship()
tag: Mapped[Tag] = relationship()
class MediaAsset(Base):
__tablename__ = "media_assets"
__table_args__ = (
Index("uq_media_assets_storage_key", "storage_key", unique=True),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
media_kind: Mapped[MediaKind | None] = mapped_column(MEDIA_KIND_ENUM)
file_name: Mapped[str | None] = mapped_column(Text)
file_path: Mapped[str | None] = mapped_column(Text)
original_filename: Mapped[str | None] = mapped_column(Text)
storage_key: Mapped[str | None] = mapped_column(Text)
mime_type: Mapped[str | None] = mapped_column(Text)
file_size: Mapped[int | None] = mapped_column(BigInteger)
file_size_bytes: Mapped[int | None] = mapped_column(BigInteger)
width: Mapped[int | None] = mapped_column(Integer)
width_px: Mapped[int | None] = mapped_column(Integer)
height: Mapped[int | None] = mapped_column(Integer)
height_px: Mapped[int | None] = mapped_column(Integer)
duration: Mapped[int | None] = mapped_column(Integer)
duration_seconds: Mapped[Decimal | None] = mapped_column(Numeric(12, 2))
alt_text: Mapped[str | None] = mapped_column(Text)
status: Mapped[str | None] = mapped_column(Text)
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
class ContentMedia(Base):
"""Association between content and canonical media assets.
The latest schema intentionally uses a single media_asset_id FK. The older
media_id compatibility column is no longer part of the authoritative DDL.
"""
__tablename__ = "content_media"
__table_args__ = (
UniqueConstraint("content_id", "media_asset_id", name="uq_content_media_content_asset"),
UniqueConstraint(
"content_id",
"media_asset_id",
"usage_type",
name="uq_content_media_content_asset_usage",
),
CheckConstraint("media_role in ('primary', 'gallery')", name="ck_content_media_role"),
CheckConstraint("sort_order >= 1", name="ck_content_media_sort_order"),
CheckConstraint("btrim(usage_type) <> ''", name="ck_content_media_usage_type_nonempty"),
Index("ix_content_media_content_sort", "content_id", "sort_order"),
Index("ix_content_media_content_usage", "content_id", "usage_type"),
Index(
"uq_content_media_one_primary",
"content_id",
unique=True,
postgresql_where=text("media_role = 'primary'"),
),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
content_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.content_items.id", ondelete="CASCADE"),
nullable=False,
)
media_asset_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.media_assets.id", ondelete="RESTRICT"),
nullable=False,
)
media_role: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'gallery'")
)
usage_type: Mapped[str] = mapped_column(Text, nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("1"))
alt_text: Mapped[str | None] = mapped_column(Text)
caption: Mapped[str | None] = mapped_column(Text)
metadata_json: Mapped[dict[str, Any]] = mapped_column(
"metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb")
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
content: Mapped[ContentItem] = relationship(back_populates="media_links")
media_asset: Mapped[MediaAsset] = relationship(foreign_keys=[media_asset_id])
class AttributeDefinition(Base):
__tablename__ = "attribute_definitions"
__table_args__ = (
CheckConstraint("definition_kind in ('scalar', 'object')", name="ck_attribute_definition_kind"),
CheckConstraint("data_type is null or data_type in ('text','rich_text','number','boolean','date','json','media')", name="ck_attribute_definition_data_type"),
CheckConstraint("definition_kind <> 'scalar' or data_type is not null", name="ck_attribute_definition_scalar_type"),
CheckConstraint("definition_kind <> 'object' or data_type is null", name="ck_attribute_definition_object_type"),
CheckConstraint("sort_order >= 0", name="ck_attribute_definition_sort_order"),
CheckConstraint("allowed_values is null or jsonb_typeof(allowed_values) = 'array'", name="ck_attribute_definition_allowed_values"),
CheckConstraint("definition_kind <> 'object' or allowed_values is null", name="ck_attribute_definition_object_allowed_values"),
Index("uq_attribute_definition_set_key", "attribute_definition_set_id", "attribute_key", unique=True, postgresql_where=text("attribute_definition_set_id is not null")),
# Retained to mirror schema.sql exactly. In the current DDL the FK column
# is NOT NULL, so this partial index is presently unreachable by data.
Index(
"uq_attribute_definition_unscoped_key",
"attribute_key",
unique=True,
postgresql_where=text("attribute_definition_set_id is null"),
),
Index("idx_attribute_definitions_set", "attribute_definition_set_id", "sort_order"),
Index("idx_attribute_definitions_set_active", "attribute_definition_set_id", "sort_order", postgresql_where=text("is_active = true")),
Index("idx_attribute_definitions_set_root", "attribute_definition_set_id", "sort_order", postgresql_where=text("is_active = true and is_root = true")),
Index("idx_attribute_definitions_set_filterable", "attribute_definition_set_id", "sort_order", postgresql_where=text("is_active = true and is_filterable = true")),
Index("idx_attribute_definitions_set_searchable", "attribute_definition_set_id", "sort_order", postgresql_where=text("is_active = true and is_searchable = true")),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
attribute_definition_set_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.attribute_definition_sets.id", ondelete="CASCADE"), nullable=False)
content_kind: Mapped[ContentKind | None] = mapped_column(CONTENT_KIND_ENUM)
attribute_key: Mapped[str] = mapped_column(Text, nullable=False)
attribute_label: Mapped[str] = mapped_column(Text, nullable=False)
data_type: Mapped[str | None] = mapped_column(Text)
definition_kind: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'scalar'"))
is_root: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
description: Mapped[str | None] = mapped_column(Text)
is_required: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
is_searchable: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
is_filterable: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
is_multivalue: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
allowed_values: Mapped[list[Any] | None] = mapped_column(JSONB)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
attribute_definition_set: Mapped[AttributeDefinitionSet] = relationship(back_populates="attribute_definitions")
parent_memberships: Mapped[list["AttributeDefinitionMember"]] = relationship(foreign_keys="AttributeDefinitionMember.child_attribute_definition_id", back_populates="child_definition")
child_memberships: Mapped[list["AttributeDefinitionMember"]] = relationship(foreign_keys="AttributeDefinitionMember.parent_attribute_definition_id", back_populates="parent_definition", cascade="all, delete-orphan", passive_deletes=True)
values: Mapped[list["ContentAttribute"]] = relationship(back_populates="definition", foreign_keys="ContentAttribute.attribute_definition_id")
presentation_overrides: Mapped[list["TemplateAttributePresentation"]] = relationship(
back_populates="attribute_definition",
cascade="all, delete-orphan",
passive_deletes=True,
)
class TemplateAttributePresentation(Base):
"""Per-template, per-client, per-attribute presentation override.
Client and template/version scope are inherited from presentation_contract.
Absence of a row means the effective empty behavior is HIDE.
"""
__tablename__ = "template_attribute_presentations"
__table_args__ = (
UniqueConstraint(
"template_presentation_contract_id",
"attribute_definition_id",
name="uq_template_attribute_presentation_contract_attribute",
),
CheckConstraint(
"empty_behavior in ('hide', 'show')",
name="ck_template_attribute_presentation_empty_behavior",
),
CheckConstraint(
"empty_text is null or length(btrim(empty_text)) > 0",
name="ck_template_attribute_presentation_empty_text",
),
CheckConstraint(
"empty_behavior = 'show' or empty_text is null",
name="ck_template_attribute_presentation_empty_text_behavior",
),
CheckConstraint(
"jsonb_typeof(metadata) = 'object'",
name="ck_template_attribute_presentation_metadata_object",
),
Index(
"idx_template_attribute_presentations_contract",
"template_presentation_contract_id",
),
Index(
"idx_template_attribute_presentations_attribute",
"attribute_definition_id",
),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
template_presentation_contract_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.template_presentation_contracts.id", ondelete="CASCADE"),
nullable=False,
)
attribute_definition_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.attribute_definitions.id", ondelete="CASCADE"),
nullable=False,
)
empty_behavior: Mapped[str] = mapped_column(
Text,
nullable=False,
server_default=text("'hide'"),
)
empty_text: Mapped[str | None] = mapped_column(Text)
metadata_json: Mapped[dict[str, Any]] = mapped_column(
"metadata",
JSONB,
nullable=False,
server_default=text("'{}'::jsonb"),
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=text("now()"),
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=text("now()"),
)
presentation_contract: Mapped[TemplatePresentationContract] = relationship(
back_populates="attribute_presentations"
)
attribute_definition: Mapped[AttributeDefinition] = relationship(
back_populates="presentation_overrides"
)
class AttributeDefinitionMember(Base):
__tablename__ = "attribute_definition_members"
__table_args__ = (
UniqueConstraint("parent_attribute_definition_id", "child_attribute_definition_id", name="uq_attribute_definition_member"),
CheckConstraint("parent_attribute_definition_id <> child_attribute_definition_id", name="ck_attribute_definition_member_no_self"),
CheckConstraint("sort_order >= 0", name="ck_attribute_definition_member_sort_order"),
Index("idx_attribute_definition_members_parent", "parent_attribute_definition_id", "sort_order"),
Index("idx_attribute_definition_members_child", "child_attribute_definition_id"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
parent_attribute_definition_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.attribute_definitions.id", ondelete="CASCADE"), nullable=False)
child_attribute_definition_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.attribute_definitions.id", ondelete="RESTRICT"), nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_required: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
parent_definition: Mapped[AttributeDefinition] = relationship(foreign_keys=[parent_attribute_definition_id], back_populates="child_memberships")
child_definition: Mapped[AttributeDefinition] = relationship(foreign_keys=[child_attribute_definition_id], back_populates="parent_memberships")
class ContentAttribute(Base):
__tablename__ = "content_attributes"
__table_args__ = (
CheckConstraint("sort_order >= 0", name="ck_content_attributes_sort_order"),
Index("uq_content_attribute_top_level", "content_id", "attribute_definition_id", "sort_order", unique=True, postgresql_where=text("parent_attribute_value_id is null")),
Index("uq_content_attribute_child", "content_id", "parent_attribute_value_id", "attribute_definition_id", "sort_order", unique=True, postgresql_where=text("parent_attribute_value_id is not null")),
Index("idx_content_attributes_content", "content_id"),
Index("idx_content_attributes_definition", "attribute_definition_id"),
Index("idx_content_attributes_parent", "parent_attribute_value_id", postgresql_where=text("parent_attribute_value_id is not null")),
Index("idx_content_attributes_text", "attribute_definition_id", "value_text", postgresql_where=text("value_text is not null")),
Index("idx_content_attributes_number", "attribute_definition_id", "value_number", postgresql_where=text("value_number is not null")),
Index("idx_content_attributes_boolean", "attribute_definition_id", "value_boolean", postgresql_where=text("value_boolean is not null")),
Index("idx_content_attributes_date", "attribute_definition_id", "value_date", postgresql_where=text("value_date is not null")),
Index("idx_content_attributes_json", "value_json", postgresql_using="gin", postgresql_ops={"value_json": "jsonb_path_ops"}, postgresql_where=text("value_json is not null")),
Index("idx_content_attributes_media", "media_asset_id", postgresql_where=text("media_asset_id is not null")),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
content_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.content_items.id", ondelete="CASCADE"), nullable=False)
attribute_definition_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.attribute_definitions.id", ondelete="RESTRICT"), nullable=False)
parent_attribute_value_id: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.content_attributes.id", ondelete="CASCADE"))
value_text: Mapped[str | None] = mapped_column(Text)
value_number: Mapped[Decimal | None] = mapped_column(Numeric(18, 6))
value_boolean: Mapped[bool | None] = mapped_column(Boolean)
value_date: Mapped[date | None] = mapped_column(Date)
value_json: Mapped[Any | None] = mapped_column(JSONB)
media_asset_id: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.media_assets.id", ondelete="RESTRICT"))
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
content: Mapped[ContentItem] = relationship(back_populates="attributes", foreign_keys=[content_id])
definition: Mapped[AttributeDefinition] = relationship(back_populates="values", foreign_keys=[attribute_definition_id])
media_asset: Mapped[MediaAsset | None] = relationship(foreign_keys=[media_asset_id])
parent: Mapped["ContentAttribute | None"] = relationship(remote_side="ContentAttribute.id", foreign_keys=[parent_attribute_value_id], back_populates="children")
children: Mapped[list["ContentAttribute"]] = relationship(back_populates="parent", cascade="all, delete-orphan", passive_deletes=True)
class Module(Base):
__tablename__ = "modules"
__table_args__ = (
UniqueConstraint("slug", name="uq_modules_slug"),
Index(
"uq_modules_code",
"code",
unique=True,
postgresql_where=text("code is not null"),
),
CheckConstraint("preview_item_limit >= 0", name="ck_modules_preview_limit"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
code: Mapped[str | None] = mapped_column(Text)
name: Mapped[str] = mapped_column(Text, nullable=False)
slug: Mapped[str] = mapped_column(Text, nullable=False)
description: Mapped[str | None] = mapped_column(Text)
thumbnail_media_asset_id: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.media_assets.id", ondelete="SET NULL"))
status: Mapped[ModuleStatus] = mapped_column(MODULE_STATUS_ENUM, nullable=False, server_default=text("'draft'"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
preview_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
preview_item_limit: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
release_version: Mapped[str | None] = mapped_column(Text)
expected_release_date: Mapped[date | None] = mapped_column(Date)
release_notes: Mapped[str | None] = mapped_column(Text)
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
created_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="RESTRICT"))
updated_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="RESTRICT"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
thumbnail_media_asset: Mapped[MediaAsset | None] = relationship(
"MediaAsset", foreign_keys=[thumbnail_media_asset_id]
)
creator: Mapped[AppUser | None] = relationship(
"AppUser", foreign_keys=[created_by], back_populates="created_modules"
)
updater: Mapped[AppUser | None] = relationship(
"AppUser", foreign_keys=[updated_by], back_populates="updated_modules"
)
class ModuleContent(Base):
__tablename__ = "module_contents"
__table_args__ = (PrimaryKeyConstraint("module_id", "content_id"), {"schema": CONTENT_SCHEMA})
module_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.modules.id", ondelete="CASCADE"), nullable=False)
content_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.content_items.id", ondelete="CASCADE"), nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_highlighted: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
created_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id"))
module: Mapped[Module] = relationship("Module", foreign_keys=[module_id])
content: Mapped[ContentItem] = relationship("ContentItem", foreign_keys=[content_id])
creator: Mapped[AppUser | None] = relationship("AppUser", foreign_keys=[created_by])
class ModuleTag(Base):
__tablename__ = "module_tags"
__table_args__ = (PrimaryKeyConstraint("module_id", "tag_id"), {"schema": CONTENT_SCHEMA})
module_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.modules.id", ondelete="CASCADE"), nullable=False)
tag_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.tags.id", ondelete="CASCADE"), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
module: Mapped[Module] = relationship()
tag: Mapped[Tag] = relationship()
class SearchFacetDefinition(Base):
__tablename__ = "search_facet_definitions"
__table_args__ = (
UniqueConstraint("code", name="uq_search_facet_definitions_code"),
CheckConstraint(
"control_type in ('typeahead','typeahead_multi','single_select','multi_select')",
name="ck_search_facet_control_type",
),
CheckConstraint(
"value_source in ('projected','controlled')",
name="ck_search_facet_value_source",
),
Index("ix_search_facet_definitions_active_sort", "is_active", "category", "sort_order"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
code: Mapped[str] = mapped_column(Text, nullable=False)
label: Mapped[str] = mapped_column(Text, nullable=False)
category: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'General'"))
description: Mapped[str | None] = mapped_column(Text)
control_type: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'typeahead_multi'")
)
allow_multiple_values: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("true")
)
value_source: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'projected'")
)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
metadata_json: Mapped[dict[str, Any]] = mapped_column(
"metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb")
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
values: Mapped[list["SearchFacetValue"]] = relationship(
back_populates="facet", cascade="all, delete-orphan", passive_deletes=True
)
mappings: Mapped[list["SearchFacetMapping"]] = relationship(
back_populates="facet", cascade="all, delete-orphan", passive_deletes=True
)
projected_values: Mapped[list["ContentSearchFacet"]] = relationship(
back_populates="facet", cascade="all, delete-orphan", passive_deletes=True
)
class SearchFacetValue(Base):
__tablename__ = "search_facet_values"
__table_args__ = (
UniqueConstraint("facet_id", "value_key", name="uq_search_facet_values_key"),
Index("ix_search_facet_values_lookup", "facet_id", "is_active", "label"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
facet_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.search_facet_definitions.id", ondelete="CASCADE"),
nullable=False,
)
value_key: Mapped[str] = mapped_column(Text, nullable=False)
label: Mapped[str] = mapped_column(Text, nullable=False)
aliases: Mapped[list[Any]] = mapped_column(
JSONB, nullable=False, server_default=text("'[]'::jsonb")
)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
metadata_json: Mapped[dict[str, Any]] = mapped_column(
"metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb")
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
facet: Mapped[SearchFacetDefinition] = relationship(back_populates="values")
class SearchFacetMapping(Base):
__tablename__ = "search_facet_mappings"
__table_args__ = (
CheckConstraint(
"mapping_strategy in ('auto','scalar','multivalue','content_ref_label')",
name="ck_search_facet_mapping_strategy",
),
CheckConstraint("weight > 0", name="ck_search_facet_mapping_weight"),
Index(
"uq_search_facet_mapping_identity",
"facet_id",
"attribute_definition_id",
text("coalesce(module_id, '00000000-0000-0000-0000-000000000000'::uuid)"),
text("coalesce(content_kind, '')"),
unique=True,
),
Index(
"ix_search_facet_mappings_attribute",
"attribute_definition_id",
postgresql_where=text("is_active = true"),
),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
facet_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.search_facet_definitions.id", ondelete="CASCADE"),
nullable=False,
)
attribute_definition_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.attribute_definitions.id", ondelete="CASCADE"),
nullable=False,
)
module_id: Mapped[UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.modules.id", ondelete="CASCADE")
)
# Intentionally TEXT: schema.sql defines this projection constraint as text,
# not content_kind_enum.
content_kind: Mapped[str | None] = mapped_column(Text)
mapping_strategy: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'auto'")
)
weight: Mapped[Decimal] = mapped_column(
Numeric(8, 4), nullable=False, server_default=text("1.0")
)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
metadata_json: Mapped[dict[str, Any]] = mapped_column(
"metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb")
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
facet: Mapped[SearchFacetDefinition] = relationship(back_populates="mappings")
attribute_definition: Mapped[AttributeDefinition] = relationship()
module: Mapped[Module | None] = relationship()
projected_values: Mapped[list["ContentSearchFacet"]] = relationship(
back_populates="mapping", cascade="all, delete-orphan", passive_deletes=True
)
class ContentSearchDocument(Base):
__tablename__ = "content_search_documents"
__table_args__ = (
Index("ix_search_documents_vector", "search_vector", postgresql_using="gin"),
Index("ix_search_documents_template", "template_code"),
{"schema": CONTENT_SCHEMA},
)
content_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.content_items.id", ondelete="CASCADE"),
primary_key=True,
)
template_code: Mapped[str] = mapped_column(Text, nullable=False)
search_text: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("''"))
search_vector: Mapped[Any] = mapped_column(TSVECTOR, nullable=False)
indexed_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
content: Mapped[ContentItem] = relationship()
class ContentSearchFacet(Base):
__tablename__ = "content_search_facets"
__table_args__ = (
UniqueConstraint(
"content_id",
"facet_id",
"mapping_id",
"value_key",
name="uq_content_search_facet_projection",
),
Index("ix_content_search_facets_lookup", "facet_id", "value_key", "content_id"),
Index("ix_content_search_facets_content", "content_id", "facet_id"),
Index(
"ix_content_search_facets_label_trgm",
"value_label",
postgresql_using="gin",
postgresql_ops={"value_label": "gin_trgm_ops"},
),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
content_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.content_items.id", ondelete="CASCADE"),
nullable=False,
)
facet_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.search_facet_definitions.id", ondelete="CASCADE"),
nullable=False,
)
mapping_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.search_facet_mappings.id", ondelete="CASCADE"),
nullable=False,
)
value_key: Mapped[str] = mapped_column(Text, nullable=False)
value_label: Mapped[str] = mapped_column(Text, nullable=False)
value_text: Mapped[str | None] = mapped_column(Text)
value_number: Mapped[Decimal | None] = mapped_column(Numeric)
source_attribute_definition_id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey(f"{CONTENT_SCHEMA}.attribute_definitions.id", ondelete="CASCADE"),
nullable=False,
)
source_value: Mapped[Any | None] = mapped_column(JSONB)
indexed_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
content: Mapped[ContentItem] = relationship()
facet: Mapped[SearchFacetDefinition] = relationship(back_populates="projected_values")
mapping: Mapped[SearchFacetMapping] = relationship(back_populates="projected_values")
source_attribute_definition: Mapped[AttributeDefinition] = relationship()