Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

4.2 KB
Raw Blame
from django.db import models
from django.utils import timezone

from posthog.models.utils import UUIDTModel

from .event_definition import EventDefinition


class SchemaPropertyType(models.TextChoices):
    """Property types supported in schema definitions (includes Object for TypeScript generation)"""

    Datetime = "DateTime", "DateTime"
    String = "String", "String"
    Numeric = "Numeric", "Numeric"
    Boolean = "Boolean", "Boolean"
    Object = "Object", "Object"
    Array = "Array", "Array"


class SchemaPropertyGroup(UUIDTModel):
    """
    A reusable group of properties that defines a schema.
    Can be attached to multiple events via EventSchema.
    """

    team = models.ForeignKey(
        "posthog.Team",
        on_delete=models.CASCADE,
        related_name="schema_property_groups",
        related_query_name="schema_property_group",
    )
    project = models.ForeignKey("posthog.Project", on_delete=models.CASCADE, null=True, related_name="+")
    name = models.CharField(max_length=400)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(
        "posthog.User",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="created_schema_property_groups",
    )

    class Meta:
        db_table = "posthog_schemapropertygroup"
        indexes = [
            models.Index(fields=["team", "name"], name="schema_pg_team_name_idx"),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=["team", "name"],
                name="unique_schema_property_group_team_name",
            )
        ]

    def __str__(self) -> str:
        return f"{self.name} / {self.team.name}"


class SchemaPropertyGroupProperty(UUIDTModel):
    """
    Individual property within a property group.
    Defines the expected name, type, and whether it's required.
    """

    property_group = models.ForeignKey(
        SchemaPropertyGroup,
        on_delete=models.CASCADE,
        related_name="properties",
        related_query_name="property",
    )
    name = models.CharField(max_length=400)
    property_type = models.CharField(max_length=50, choices=SchemaPropertyType)
    is_required = models.BooleanField(default=False)
    is_optional_in_types = models.BooleanField(default=False)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "posthog_schemapropertygroupproperty"
        indexes = [
            models.Index(
                fields=["property_group", "name"],
                name="schema_pgp_group_name_idx",
            ),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=["property_group", "name"],
                name="unique_property_group_property_name",
            ),
        ]
        ordering = ["name"]

    def __str__(self) -> str:
        required_str = " (required)" if self.is_required else ""
        return f"{self.name} ({self.property_type}){required_str} / {self.property_group.name}"


class EventSchema(UUIDTModel):
    """
    Associates a property group with an event definition.
    Defines which property groups an event should have.
    """

    event_definition = models.ForeignKey(
        EventDefinition,
        on_delete=models.CASCADE,
        related_name="schemas",
        related_query_name="schema",
    )
    property_group = models.ForeignKey(
        SchemaPropertyGroup,
        on_delete=models.CASCADE,
        related_name="event_schemas",
        related_query_name="event_schema",
    )
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "posthog_eventschema"
        constraints = [
            models.UniqueConstraint(
                fields=["event_definition", "property_group"],
                name="unique_event_schema",
            )
        ]

    def __str__(self) -> str:
        return f"{self.event_definition.name} → {self.property_group.name}"