from __future__ import annotations from collections import defaultdict from dataclasses import dataclass from datetime import date from decimal import Decimal from typing import Any, Mapping from uuid import UUID from sqlalchemy import and_, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import aliased from app.db.models import ( AttributeDefinition, AttributeDefinitionMember, AttributeDefinitionSet, ContentAttribute, ContentItem, ) # ============================================================================= # DOMAIN EXCEPTIONS # ============================================================================= class ContentAttributeError(Exception): """ Base exception for content reconstruction failures. """ class ContentNotFoundError(ContentAttributeError): """ Requested content item does not exist. """ class ContentDefinitionSetError(ContentAttributeError): """ Content item and attribute values do not belong to a consistent attribute definition set. """ class AttributeHierarchyError(ContentAttributeError): """ Stored attribute hierarchy is structurally invalid. """ class AttributeValueError(ContentAttributeError): """ Stored scalar/object value does not conform to its definition. """ class AttributeCycleError(ContentAttributeError): """ A cycle was detected in the value hierarchy. """ class DuplicateScalarAttributeError(ContentAttributeError): """ A non-multivalue attribute has multiple values beneath the same parent. """ class DuplicateAttributeCodeError(ContentAttributeError): """ Two different definitions resolve to the same local JSON code beneath the same parent. """ class InvalidAttributeKeyError(ContentAttributeError): """ Canonical attribute_key cannot be mapped to the expected definition set. """ # ============================================================================= # CONSTANTS # ============================================================================= DEFINITION_KIND_SCALAR = "scalar" DEFINITION_KIND_OBJECT = "object" DATA_TYPE_TEXT = "text" DATA_TYPE_RICH_TEXT = "rich_text" DATA_TYPE_NUMBER = "number" DATA_TYPE_BOOLEAN = "boolean" DATA_TYPE_DATE = "date" DATA_TYPE_JSON = "json" DATA_TYPE_MEDIA = "media" SUPPORTED_DATA_TYPES = { DATA_TYPE_TEXT, DATA_TYPE_RICH_TEXT, DATA_TYPE_NUMBER, DATA_TYPE_BOOLEAN, DATA_TYPE_DATE, DATA_TYPE_JSON, DATA_TYPE_MEDIA, } # ============================================================================= # INTERNAL DTOs # ============================================================================= @dataclass(frozen=True, slots=True) class DefinitionSetInfo: """ Minimal definition-set information required during reconstruction. """ id: UUID code: str attribute_prefix_code: str attribute_prefix_name: str @dataclass(frozen=True, slots=True) class AttributeValueRow: """ Normalized representation of: content_attributes JOIN attribute_definitions LEFT JOIN parent content_attributes LEFT JOIN attribute_definition_members The builder works only against these normalized rows. """ id: UUID content_id: UUID attribute_definition_id: UUID attribute_definition_set_id: UUID | None parent_attribute_value_id: UUID | None # Full persistent machine identity. # # Example: # M0002_CT0001.regional_anatomy.structures attribute_key: str # Local JSON-facing key. # # Example: # structures attribute_code: str attribute_label: str definition_kind: str data_type: str | None is_root: bool is_multivalue: bool # Definition-level ordering. definition_sort_order: int # Contextual ordering under an object definition. member_sort_order: int | None # Ordering of repeated actual values. value_sort_order: int value_text: str | None value_number: Decimal | None value_boolean: bool | None value_date: date | None value_json: Any | None media_asset_id: UUID | None # ============================================================================= # PUBLIC BUILDER # ============================================================================= class ContentJsonBuilder: """ Reconstructs typed-EAV content into nested JSON. Supports: - definition-set scoped content - scalar attributes - multivalue scalar attributes - nested object attributes - multivalue objects - arbitrary practical N-level hierarchy - typed value conversion - contextual member ordering - deterministic output - cycle detection - malformed hierarchy detection - historical/deactivated definition readability --------------------------------------------------------------------------- IMPORTANT DESIGN RULE --------------------------------------------------------------------------- AttributeDefinition.is_active is intentionally NOT used when reading existing content values. Deactivation means: "do not use this definition for new content/editing" It must NOT mean: "hide historical values already stored against this definition" Otherwise deactivating a definition would make existing persisted content silently disappear from reconstructed JSON. """ def __init__( self, session: AsyncSession, *, max_depth: int = 32, ) -> None: if max_depth < 1: raise ValueError( "max_depth must be >= 1" ) self._session = session self._max_depth = max_depth # ========================================================================= # PUBLIC API # ========================================================================= async def build_content_json( self, content_id: UUID, ) -> dict[str, Any]: """ Build the complete application-facing content JSON. Raises: ContentNotFoundError ContentDefinitionSetError InvalidAttributeKeyError AttributeHierarchyError AttributeCycleError AttributeValueError DuplicateScalarAttributeError DuplicateAttributeCodeError """ content = await self._load_content( content_id ) definition_set = ( await self._load_definition_set_for_content( content ) ) rows = await self._load_attribute_rows( content_id=content_id, definition_set=definition_set, ) self._validate_definition_set_consistency( content=content, definition_set=definition_set, rows=rows, ) attributes = self._build_attributes( rows ) return { "id": str(content.id), "source_key": ( content.source_key ), "content_kind": ( self._enum_value( content.content_kind ) ), "definition_set": ( { "id": str( definition_set.id ), "code": ( definition_set.code ), "attribute_prefix_code": ( definition_set.attribute_prefix_code ), "attribute_prefix_name": ( definition_set.attribute_prefix_name ), } if definition_set else None ), "title": content.title, "slug": content.slug, "summary": content.summary, "status": ( self._enum_value( content.status ) ), "is_active": ( content.is_active ), "default_language": ( content.default_language ), "version_no": ( content.version_no ), "published_at": ( content.published_at.isoformat() if content.published_at else None ), "created_at": ( content.created_at.isoformat() if content.created_at else None ), "updated_at": ( content.updated_at.isoformat() if content.updated_at else None ), "metadata": self._json_safe( content.metadata_json or {} ), "attributes": attributes, } async def build_attributes_only( self, content_id: UUID, ) -> dict[str, Any]: """ Reconstruct only the dynamic attributes object. """ content = await self._load_content( content_id ) definition_set = ( await self._load_definition_set_for_content( content ) ) rows = await self._load_attribute_rows( content_id=content_id, definition_set=definition_set, ) self._validate_definition_set_consistency( content=content, definition_set=definition_set, rows=rows, ) return self._build_attributes( rows ) # ========================================================================= # CONTENT LOADING # ========================================================================= async def _load_content( self, content_id: UUID, ) -> ContentItem: stmt = ( select(ContentItem) .where( ContentItem.id == content_id ) ) result = await self._session.execute( stmt ) content = ( result.scalar_one_or_none() ) if content is None: raise ContentNotFoundError( f"Content item not found: " f"{content_id}" ) return content # ========================================================================= # DEFINITION SET LOADING # ========================================================================= async def _load_definition_set_for_content( self, content: ContentItem, ) -> DefinitionSetInfo | None: """ Resolve the definition set directly from: content_items.attribute_definition_set_id This is intentionally NOT inferred from: - metadata - content_kind - attribute keys """ definition_set_id = ( content.attribute_definition_set_id ) if definition_set_id is None: return None stmt = ( select( AttributeDefinitionSet.id, AttributeDefinitionSet.code, AttributeDefinitionSet.attribute_prefix_code, AttributeDefinitionSet.attribute_prefix_name, ) .where( AttributeDefinitionSet.id == definition_set_id ) ) result = await self._session.execute( stmt ) row = ( result.mappings() .one_or_none() ) if row is None: raise ContentDefinitionSetError( "Content references a missing " "attribute definition set. " f"content_id={content.id}, " f"definition_set_id=" f"{definition_set_id}" ) return DefinitionSetInfo( id=row["id"], code=row["code"], attribute_prefix_code=( row[ "attribute_prefix_code" ] ), attribute_prefix_name=( row[ "attribute_prefix_name" ] ), ) # ========================================================================= # ATTRIBUTE ROW LOADING # ========================================================================= async def _load_attribute_rows( self, *, content_id: UUID, definition_set: DefinitionSetInfo | None, ) -> list[AttributeValueRow]: """ Load the complete value tree in ONE SQL query. Important: AttributeDefinition.is_active is deliberately not filtered. ParentAttributeValue is joined so that nested child definitions can resolve their contextual member relationship: parent definition -> attribute_definition_members -> child definition """ ParentAttributeValue = aliased( ContentAttribute, name="parent_attribute_value", ) stmt = ( select( # ------------------------------------------------------------- # Actual value identity # ------------------------------------------------------------- ContentAttribute.id, ContentAttribute.content_id, ContentAttribute .attribute_definition_id, ContentAttribute .parent_attribute_value_id, # ------------------------------------------------------------- # Definition identity # ------------------------------------------------------------- AttributeDefinition .attribute_definition_set_id, AttributeDefinition .attribute_key, AttributeDefinition .attribute_label, AttributeDefinition .definition_kind, AttributeDefinition .data_type, AttributeDefinition .is_root, AttributeDefinition .is_multivalue, AttributeDefinition .sort_order .label( "definition_sort_order" ), # ------------------------------------------------------------- # Contextual parent-member ordering # ------------------------------------------------------------- AttributeDefinitionMember .sort_order .label( "member_sort_order" ), # ------------------------------------------------------------- # Actual repeated-value ordering # ------------------------------------------------------------- ContentAttribute .sort_order .label( "value_sort_order" ), # ------------------------------------------------------------- # Typed storage # ------------------------------------------------------------- ContentAttribute .value_text, ContentAttribute .value_number, ContentAttribute .value_boolean, ContentAttribute .value_date, ContentAttribute .value_json, ContentAttribute .media_asset_id, ) # ------------------------------------------------------------- # Definition # ------------------------------------------------------------- .join( AttributeDefinition, AttributeDefinition.id == ContentAttribute .attribute_definition_id, ) # ------------------------------------------------------------- # Parent value # # NULL for root attributes. # ------------------------------------------------------------- .outerjoin( ParentAttributeValue, ParentAttributeValue.id == ContentAttribute .parent_attribute_value_id, ) # ------------------------------------------------------------- # Contextual member relationship # ------------------------------------------------------------- .outerjoin( AttributeDefinitionMember, and_( AttributeDefinitionMember .parent_attribute_definition_id == ParentAttributeValue .attribute_definition_id, AttributeDefinitionMember .child_attribute_definition_id == ContentAttribute .attribute_definition_id, ), ) .where( ContentAttribute.content_id == content_id ) .order_by( ContentAttribute .parent_attribute_value_id .asc() .nulls_first(), AttributeDefinitionMember .sort_order .asc() .nulls_first(), AttributeDefinition .sort_order .asc(), ContentAttribute .sort_order .asc(), ContentAttribute .id .asc(), ) ) result = await self._session.execute( stmt ) normalized_rows: list[ AttributeValueRow ] = [] for row in result.mappings(): attribute_key = str( row["attribute_key"] ) attribute_code = ( self._derive_attribute_code( attribute_key=attribute_key, definition_set=definition_set, ) ) # Nested values must correspond to an explicit # attribute_definition_members edge. Root rows legitimately # have no member_sort_order. if ( row["parent_attribute_value_id"] is not None and row["member_sort_order"] is None ): raise AttributeHierarchyError( "Nested attribute value has no matching " "attribute_definition_members relationship. " f"value_id={row['id']}, " f"attribute={attribute_key!r}, " f"parent_value_id={row['parent_attribute_value_id']}" ) normalized_rows.append( AttributeValueRow( id=row["id"], content_id=row[ "content_id" ], attribute_definition_id=row[ "attribute_definition_id" ], attribute_definition_set_id=row[ "attribute_definition_set_id" ], parent_attribute_value_id=row[ "parent_attribute_value_id" ], attribute_key=( attribute_key ), attribute_code=( attribute_code ), attribute_label=row[ "attribute_label" ], definition_kind=row[ "definition_kind" ], data_type=row[ "data_type" ], is_root=row[ "is_root" ], is_multivalue=row[ "is_multivalue" ], definition_sort_order=row[ "definition_sort_order" ], member_sort_order=row[ "member_sort_order" ], value_sort_order=row[ "value_sort_order" ], value_text=row[ "value_text" ], value_number=row[ "value_number" ], value_boolean=row[ "value_boolean" ], value_date=row[ "value_date" ], value_json=row[ "value_json" ], media_asset_id=row[ "media_asset_id" ], ) ) return normalized_rows # ========================================================================= # CANONICAL KEY → JSON CODE # ========================================================================= @staticmethod def _derive_attribute_code( *, attribute_key: str, definition_set: DefinitionSetInfo | None, ) -> str: """ Convert: M0001_CT0002.regional_anatomy.structures to: structures The prefix is still validated so malformed/cross-set keys fail early. """ if not attribute_key: raise InvalidAttributeKeyError( "attribute_key cannot be empty" ) if definition_set is not None: expected_prefix = ( definition_set .attribute_prefix_code + "." ) if not attribute_key.startswith( expected_prefix ): raise InvalidAttributeKeyError( "Attribute key does not belong " "to the content definition set. " f"attribute_key={attribute_key!r}, " f"expected_prefix=" f"{expected_prefix!r}" ) code = ( attribute_key .rsplit(".", 1)[-1] .strip() ) if not code: raise InvalidAttributeKeyError( "Unable to derive local code from " f"attribute_key={attribute_key!r}" ) return code # ========================================================================= # DEFINITION SET VALIDATION # ========================================================================= @staticmethod def _validate_definition_set_consistency( *, content: ContentItem, definition_set: DefinitionSetInfo | None, rows: list[AttributeValueRow], ) -> None: expected_definition_set_id = ( content .attribute_definition_set_id ) if expected_definition_set_id is None: if rows: raise ContentDefinitionSetError( "Content contains attribute values " "but attribute_definition_set_id " "is NULL. " f"content_id={content.id}" ) return if definition_set is None: raise ContentDefinitionSetError( "Content has an attribute_definition_set_id " "but the definition set could not be loaded. " f"content_id={content.id}" ) if ( definition_set.id != expected_definition_set_id ): raise ContentDefinitionSetError( "Resolved definition set does not " "match content. " f"content_id={content.id}" ) for row in rows: if ( row.attribute_definition_set_id != expected_definition_set_id ): raise ContentDefinitionSetError( "Attribute value belongs to an " "unexpected definition set. " f"content_id={content.id}, " f"attribute_key=" f"{row.attribute_key!r}, " f"expected=" f"{expected_definition_set_id}, " f"actual=" f"{row.attribute_definition_set_id}" ) # ========================================================================= # TREE CONSTRUCTION # ========================================================================= def _build_attributes( self, rows: list[AttributeValueRow], ) -> dict[str, Any]: if not rows: return {} # --------------------------------------------------------------------- # Fast node lookup # --------------------------------------------------------------------- row_by_id: dict[ UUID, AttributeValueRow, ] = {} for row in rows: if row.id in row_by_id: raise AttributeHierarchyError( "Duplicate content attribute row id " f"encountered: {row.id}" ) row_by_id[row.id] = row # --------------------------------------------------------------------- # Parent → children adjacency map # --------------------------------------------------------------------- children_by_parent: dict[ UUID | None, list[AttributeValueRow], ] = defaultdict(list) for row in rows: parent_id = ( row.parent_attribute_value_id ) if parent_id is not None: parent = row_by_id.get( parent_id ) if parent is None: raise AttributeHierarchyError( "Attribute value references " "a parent that does not belong " "to the loaded content tree. " f"child_id={row.id}, " f"parent_id={parent_id}" ) if ( parent.content_id != row.content_id ): raise AttributeHierarchyError( "Parent and child attribute " "values belong to different " "content items." ) if ( parent.definition_kind != DEFINITION_KIND_OBJECT ): raise AttributeHierarchyError( "Scalar value is being used " "as a hierarchy parent. " f"parent_id={parent.id}, " f"parent_attribute=" f"{parent.attribute_key!r}" ) children_by_parent[ parent_id ].append(row) # --------------------------------------------------------------------- # Deterministic ordering # --------------------------------------------------------------------- for child_rows in ( children_by_parent.values() ): child_rows.sort( key=self._attribute_sort_key ) roots = children_by_parent.get( None, [], ) # Root rows must actually reference root definitions. for root in roots: if not root.is_root: raise AttributeHierarchyError( "Child-only attribute definition " "is stored at content root. " f"attribute={root.attribute_key!r}, " f"value_id={root.id}" ) result: dict[str, Any] = {} self._populate_object( output=result, rows=roots, children_by_parent=( children_by_parent ), visited_path=frozenset(), depth=0, ) return result @staticmethod def _attribute_sort_key( row: AttributeValueRow, ) -> tuple[ int, int, str, str, ]: """ Root: attribute_definitions.sort_order Child: attribute_definition_members.sort_order Repeated instances: content_attributes.sort_order """ if ( row.parent_attribute_value_id is not None and row.member_sort_order is not None ): structural_order = ( row.member_sort_order ) else: structural_order = ( row.definition_sort_order ) return ( structural_order, row.value_sort_order, row.attribute_code, str(row.id), ) def _populate_object( self, *, output: dict[str, Any], rows: list[AttributeValueRow], children_by_parent: Mapping[ UUID | None, list[AttributeValueRow], ], visited_path: frozenset[UUID], depth: int, ) -> None: """ Materialize one JSON object level. Multiple rows having the same local definition code are grouped together and interpreted using `is_multivalue`. """ self._validate_depth( depth ) grouped: dict[ str, list[AttributeValueRow], ] = defaultdict(list) ordered_codes: list[str] = [] for row in rows: code = row.attribute_code if code not in grouped: ordered_codes.append( code ) grouped[code].append( row ) for code in ordered_codes: group = grouped[code] self._validate_definition_consistency( rows=group, attribute_code=code, ) first = group[0] if first.is_multivalue: output[code] = [ self._build_node( row=row, children_by_parent=( children_by_parent ), visited_path=( visited_path ), depth=depth + 1, ) for row in group ] continue if len(group) > 1: raise DuplicateScalarAttributeError( "Non-multivalue attribute " "contains multiple instances. " f"attribute_code={code!r}, " f"attribute_key=" f"{first.attribute_key!r}, " f"count={len(group)}" ) output[code] = ( self._build_node( row=first, children_by_parent=( children_by_parent ), visited_path=( visited_path ), depth=depth + 1, ) ) def _build_node( self, *, row: AttributeValueRow, children_by_parent: Mapping[ UUID | None, list[AttributeValueRow], ], visited_path: frozenset[UUID], depth: int, ) -> Any: self._validate_depth( depth ) if row.id in visited_path: raise AttributeCycleError( "Cycle detected in content " "attribute value hierarchy. " f"value_id={row.id}, " f"attribute=" f"{row.attribute_key!r}" ) current_path = ( visited_path | frozenset( {row.id} ) ) # --------------------------------------------------------------------- # Scalar # --------------------------------------------------------------------- if ( row.definition_kind == DEFINITION_KIND_SCALAR ): children = ( children_by_parent.get( row.id, [], ) ) if children: raise AttributeHierarchyError( "Scalar attribute unexpectedly " "contains child values. " f"attribute=" f"{row.attribute_key!r}, " f"value_id={row.id}" ) return self._extract_scalar_value( row ) # --------------------------------------------------------------------- # Object # --------------------------------------------------------------------- if ( row.definition_kind == DEFINITION_KIND_OBJECT ): self._validate_object_container( row ) child_rows = ( children_by_parent.get( row.id, [], ) ) nested: dict[str, Any] = {} self._populate_object( output=nested, rows=child_rows, children_by_parent=( children_by_parent ), visited_path=( current_path ), depth=depth, ) return nested raise AttributeValueError( "Unsupported attribute " "definition_kind. " f"attribute=" f"{row.attribute_key!r}, " f"definition_kind=" f"{row.definition_kind!r}" ) # ========================================================================= # SCALAR VALUE EXTRACTION # ========================================================================= def _extract_scalar_value( self, row: AttributeValueRow, ) -> Any: """ Convert typed PostgreSQL storage into JSON-compatible Python values. """ data_type = row.data_type if ( data_type not in SUPPORTED_DATA_TYPES ): raise AttributeValueError( "Unsupported data type " f"{data_type!r} for " f"{row.attribute_key!r}" ) self._validate_scalar_column_exclusivity( row ) # --------------------------------------------------------------------- # text / rich_text # --------------------------------------------------------------------- if data_type in { DATA_TYPE_TEXT, DATA_TYPE_RICH_TEXT, }: if row.value_text is None: raise AttributeValueError( f"{row.attribute_key!r} " "requires value_text" ) return row.value_text # --------------------------------------------------------------------- # number # --------------------------------------------------------------------- if data_type == DATA_TYPE_NUMBER: if row.value_number is None: raise AttributeValueError( f"{row.attribute_key!r} " "requires value_number" ) return self._serialize_decimal( row.value_number ) # --------------------------------------------------------------------- # boolean # --------------------------------------------------------------------- if data_type == DATA_TYPE_BOOLEAN: if row.value_boolean is None: raise AttributeValueError( f"{row.attribute_key!r} " "requires value_boolean" ) return row.value_boolean # --------------------------------------------------------------------- # date # --------------------------------------------------------------------- if data_type == DATA_TYPE_DATE: if row.value_date is None: raise AttributeValueError( f"{row.attribute_key!r} " "requires value_date" ) return ( row.value_date .isoformat() ) # --------------------------------------------------------------------- # json # --------------------------------------------------------------------- if data_type == DATA_TYPE_JSON: if row.value_json is None: raise AttributeValueError( f"{row.attribute_key!r} " "requires value_json" ) return self._json_safe(row.value_json) # --------------------------------------------------------------------- # media # --------------------------------------------------------------------- if data_type == DATA_TYPE_MEDIA: if row.media_asset_id is None: raise AttributeValueError( f"{row.attribute_key!r} " "requires media_asset_id" ) return str( row.media_asset_id ) raise AttributeValueError( f"Unhandled data_type: " f"{data_type!r}" ) # ========================================================================= # STRUCTURAL VALIDATION # ========================================================================= @staticmethod def _validate_definition_consistency( *, rows: list[AttributeValueRow], attribute_code: str, ) -> None: """ Rows grouped beneath the same parent/local code must all refer to the same logical definition. Example allowed: quality = "Wiry" quality = "Slippery" Both must reference the exact same definition id. """ if not rows: return reference = rows[0] for row in rows[1:]: if ( row.attribute_definition_id != reference.attribute_definition_id ): raise DuplicateAttributeCodeError( "Same local attribute code " "resolves to multiple definitions " "beneath the same parent. " f"code={attribute_code!r}, " f"definition_a=" f"{reference.attribute_key!r}, " f"definition_b=" f"{row.attribute_key!r}" ) if ( row.attribute_definition_set_id != reference .attribute_definition_set_id ): raise AttributeHierarchyError( "Grouped attribute values " "belong to different " "definition sets. " f"code={attribute_code!r}" ) if ( row.definition_kind != reference.definition_kind ): raise AttributeHierarchyError( "Inconsistent definition_kind " f"for {reference.attribute_key!r}" ) if ( row.data_type != reference.data_type ): raise AttributeHierarchyError( "Inconsistent data_type " f"for {reference.attribute_key!r}" ) if ( row.is_multivalue != reference.is_multivalue ): raise AttributeHierarchyError( "Inconsistent is_multivalue " f"for {reference.attribute_key!r}" ) @staticmethod def _validate_object_container( row: AttributeValueRow, ) -> None: """ Object/container rows carry structure only. They must not contain any scalar typed value. """ populated = ( row.value_text, row.value_number, row.value_boolean, row.value_date, row.value_json, row.media_asset_id, ) if any( value is not None for value in populated ): raise AttributeValueError( "Object attribute contains " "a scalar value. " f"attribute=" f"{row.attribute_key!r}, " f"value_id={row.id}" ) @staticmethod def _validate_scalar_column_exclusivity( row: AttributeValueRow, ) -> None: """ Scalar definitions must have exactly ONE physical value column set. """ populated = [ row.value_text is not None, row.value_number is not None, row.value_boolean is not None, row.value_date is not None, row.value_json is not None, row.media_asset_id is not None, ] populated_count = sum( populated ) if populated_count != 1: raise AttributeValueError( "Scalar attribute must have " "exactly one typed value populated. " f"attribute=" f"{row.attribute_key!r}, " f"value_id={row.id}, " f"populated_columns=" f"{populated_count}" ) def _validate_depth( self, depth: int, ) -> None: if depth > self._max_depth: raise AttributeHierarchyError( "Maximum attribute hierarchy " f"depth {self._max_depth} exceeded" ) # ========================================================================= # SERIALIZATION HELPERS # ========================================================================= @staticmethod def _serialize_decimal( value: Decimal, ) -> int | float: """ Convert Decimal into JSON-compatible numeric output. Examples: Decimal("10.000000") -> 10 Decimal("10.500000") -> 10.5 """ if ( value == value.to_integral_value() ): return int(value) return float(value) @classmethod def _json_safe( cls, value: Any, ) -> Any: """ Convert supported Python/SQLAlchemy-facing values into JSON-safe primitives without allowing ORM infrastructure objects to leak into the API response. Supported conversions: - UUID -> str - Decimal -> int/float - date -> ISO-8601 string - Enum-like -> .value - Mapping -> recursively converted dict - list/tuple -> recursively converted list - primitives -> unchanged """ if value is None: return None if isinstance(value, UUID): return str(value) if isinstance(value, Decimal): return cls._serialize_decimal(value) if isinstance(value, date): return value.isoformat() if hasattr(value, "value") and not isinstance( value, (str, bytes, bytearray), ): enum_value = getattr(value, "value", None) if enum_value is not None: return cls._json_safe(enum_value) if isinstance(value, Mapping): return { str(key): cls._json_safe(item) for key, item in value.items() } if isinstance(value, (list, tuple)): return [ cls._json_safe(item) for item in value ] if isinstance( value, ( str, int, float, bool, ), ): return value raise AttributeValueError( "Encountered non-JSON-serializable value while " f"building content JSON: type={type(value)!r}" ) @staticmethod def _enum_value( value: Any, ) -> Any: """ Support both native strings and Python Enum-backed SQLAlchemy fields. """ if value is None: return None if hasattr( value, "value", ): return value.value return value