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.

19.1 KB
Raw Blame
# Generated by Django 4.2.29 on 2026-03-19 13:21

import django.db.models.deletion
import django.contrib.postgres.fields
from django.conf import settings
from django.db import migrations, models

import posthog.models.utils

MODELS_TO_MOVE = [
    "survey",
    "surveyresponsearchive",
]


def _move_content_types(apps, schema_editor, from_label, to_label):
    """Move ContentTypes between apps, handling duplicates idempotently.

    If the target (app_label, model) already exists (e.g., Django auto-created
    it before migration ran, or a prior failed attempt), merges permissions
    onto the target and deletes the source to avoid unique constraint violations.
    """
    db_alias = schema_editor.connection.alias
    ContentType = apps.get_model("contenttypes", "ContentType")
    Permission = apps.get_model("auth", "Permission")

    for model_name in MODELS_TO_MOVE:
        source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()
        target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()

        if source and target:
            Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)
            source.delete(using=db_alias)
        elif source:
            source.app_label = to_label
            source.save(using=db_alias)


def update_content_types(apps, schema_editor):
    _move_content_types(apps, schema_editor, "posthog", "surveys")


def reverse_content_types(apps, schema_editor):
    _move_content_types(apps, schema_editor, "surveys", "posthog")


class Migration(migrations.Migration):
    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("posthog", "1062_migrate_links_models"),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.CreateModel(
                    name="Survey",
                    fields=[
                        (
                            "id",
                            models.UUIDField(
                                default=posthog.models.utils.UUIDT,
                                editable=False,
                                primary_key=True,
                                serialize=False,
                            ),
                        ),
                        ("name", models.CharField(max_length=400)),
                        ("description", models.TextField(blank=True)),
                        (
                            "type",
                            models.CharField(
                                choices=[
                                    ("popover", "popover"),
                                    ("widget", "widget"),
                                    ("external_survey", "external survey"),
                                    ("api", "api"),
                                ],
                                max_length=40,
                            ),
                        ),
                        ("conditions", models.JSONField(blank=True, null=True)),
                        (
                            "questions",
                            models.JSONField(
                                blank=True,
                                help_text='\n        The `array` of questions included in the survey. Each question must conform to one of the defined question types: Basic, Link, Rating, or Multiple Choice.\n\n        Basic (open-ended question)\n        - `id`: The question ID\n        - `type`: `open`\n        - `question`: The text of the question.\n        - `description`: Optional description of the question.\n        - `descriptionContentType`: Content type of the description (`html` or `text`).\n        - `optional`: Whether the question is optional (`boolean`).\n        - `buttonText`: Text displayed on the submit button.\n        - `branching`: Branching logic for the question. See branching types below for details.\n\n        Link (a question with a link)\n        - `id`: The question ID\n        - `type`: `link`\n        - `question`: The text of the question.\n        - `description`: Optional description of the question.\n        - `descriptionContentType`: Content type of the description (`html` or `text`).\n        - `optional`: Whether the question is optional (`boolean`).\n        - `buttonText`: Text displayed on the submit button.\n        - `link`: The URL associated with the question.\n        - `branching`: Branching logic for the question. See branching types below for details.\n\n        Rating (a question with a rating scale)\n        - `id`: The question ID\n        - `type`: `rating`\n        - `question`: The text of the question.\n        - `description`: Optional description of the question.\n        - `descriptionContentType`: Content type of the description (`html` or `text`).\n        - `optional`: Whether the question is optional (`boolean`).\n        - `buttonText`: Text displayed on the submit button.\n        - `display`: Display style of the rating (`number` or `emoji`).\n        - `scale`: The scale of the rating (`number`).\n        - `lowerBoundLabel`: Label for the lower bound of the scale.\n        - `upperBoundLabel`: Label for the upper bound of the scale.\n        - `isNpsQuestion`: Whether the question is an NPS rating.\n        - `branching`: Branching logic for the question. See branching types below for details.\n\n        Multiple choice\n        - `id`: The question ID\n        - `type`: `single_choice` or `multiple_choice`\n        - `question`: The text of the question.\n        - `description`: Optional description of the question.\n        - `descriptionContentType`: Content type of the description (`html` or `text`).\n        - `optional`: Whether the question is optional (`boolean`).\n        - `buttonText`: Text displayed on the submit button.\n        - `choices`: An array of choices for the question.\n        - `shuffleOptions`: Whether to shuffle the order of the choices (`boolean`).\n        - `hasOpenChoice`: Whether the question allows an open-ended response (`boolean`).\n        - `branching`: Branching logic for the question. See branching types below for details.\n\n        Branching logic can be one of the following types:\n\n        Next question: Proceeds to the next question\n        ```json\n        {\n            "type": "next_question"\n        }\n        ```\n\n        End: Ends the survey, optionally displaying a confirmation message.\n        ```json\n        {\n            "type": "end"\n        }\n        ```\n\n        Response-based: Branches based on the response values. Available for the `rating` and `single_choice` question types.\n        ```json\n        {\n            "type": "response_based",\n            "responseValues": {\n                "responseKey": "value"\n            }\n        }\n        ```\n\n        Specific question: Proceeds to a specific question by index.\n        ```json\n        {\n            "type": "specific_question",\n            "index": 2\n        }\n        ```\n\n        Translations: Each question can include inline translations.\n        - `translations`: Object mapping language codes to translated fields.\n        - Language codes: Any string - allows customers to use their own language keys (e.g., "es", "es-MX", "english", "french")\n        - Translatable fields: `question`, `description`, `buttonText`, `choices`, `lowerBoundLabel`, `upperBoundLabel`, `link`\n\n        Example with translations:\n        ```json\n        {\n            "id": "uuid",\n            "type": "rating",\n            "question": "How satisfied are you?",\n            "lowerBoundLabel": "Not satisfied",\n            "upperBoundLabel": "Very satisfied",\n            "translations": {\n                "es": {\n                    "question": "¿Qué tan satisfecho estás?",\n                    "lowerBoundLabel": "No satisfecho",\n                    "upperBoundLabel": "Muy satisfecho"\n                },\n                "fr": {\n                    "question": "Dans quelle mesure êtes-vous satisfait?"\n                }\n            }\n        }\n        ```\n        ',
                                null=True,
                            ),
                        ),
                        ("appearance", models.JSONField(blank=True, null=True)),
                        ("created_at", models.DateTimeField(auto_now_add=True)),
                        ("start_date", models.DateTimeField(null=True)),
                        ("end_date", models.DateTimeField(null=True)),
                        ("updated_at", models.DateTimeField(auto_now=True)),
                        ("archived", models.BooleanField(default=False)),
                        ("responses_limit", models.PositiveIntegerField(null=True)),
                        (
                            "response_sampling_start_date",
                            models.DateTimeField(blank=True, null=True),
                        ),
                        (
                            "response_sampling_interval_type",
                            models.CharField(
                                blank=True,
                                choices=[("day", "day"), ("week", "week"), ("month", "month")],
                                default="week",
                                max_length=6,
                                null=True,
                            ),
                        ),
                        (
                            "response_sampling_interval",
                            models.PositiveIntegerField(blank=True, null=True),
                        ),
                        (
                            "response_sampling_limit",
                            models.PositiveIntegerField(blank=True, null=True),
                        ),
                        (
                            "response_sampling_daily_limits",
                            models.JSONField(blank=True, null=True),
                        ),
                        ("iteration_count", models.PositiveIntegerField(null=True)),
                        ("iteration_frequency_days", models.PositiveIntegerField(null=True)),
                        (
                            "iteration_start_dates",
                            django.contrib.postgres.fields.ArrayField(
                                base_field=models.DateTimeField(null=True),
                                blank=True,
                                default=None,
                                null=True,
                                size=None,
                            ),
                        ),
                        ("current_iteration", models.PositiveIntegerField(null=True)),
                        ("current_iteration_start_date", models.DateTimeField(null=True)),
                        (
                            "schedule",
                            models.CharField(
                                blank=True,
                                choices=[
                                    ("once", "once"),
                                    ("recurring", "recurring"),
                                    ("always", "always"),
                                ],
                                default="once",
                                max_length=40,
                                null=True,
                            ),
                        ),
                        (
                            "enable_partial_responses",
                            models.BooleanField(default=False, null=True),
                        ),
                        ("enable_iframe_embedding", models.BooleanField(default=False)),
                        ("headline_summary", models.TextField(blank=True, null=True)),
                        (
                            "headline_response_count",
                            models.PositiveIntegerField(blank=True, null=True),
                        ),
                        ("question_summaries", models.JSONField(blank=True, null=True)),
                        ("form_content", models.JSONField(blank=True, null=True)),
                        ("translations", models.JSONField(blank=True, null=True)),
                        (
                            "is_publicly_shareable",
                            models.BooleanField(
                                blank=True,
                                help_text="Allow this survey to be accessed via public URL (https://app.posthog.com/surveys/[survey_id]) without authentication",
                                null=True,
                            ),
                        ),
                        ("actions", models.ManyToManyField(to="posthog.action")),
                        (
                            "created_by",
                            models.ForeignKey(
                                null=True,
                                on_delete=django.db.models.deletion.SET_NULL,
                                related_name="surveys",
                                related_query_name="survey",
                                to=settings.AUTH_USER_MODEL,
                            ),
                        ),
                        (
                            "internal_response_sampling_flag",
                            models.ForeignKey(
                                blank=True,
                                null=True,
                                on_delete=django.db.models.deletion.SET_NULL,
                                related_name="surveys_internal_response_sampling_flag",
                                related_query_name="surveys_internal_response_sampling_flag",
                                to="posthog.featureflag",
                            ),
                        ),
                        (
                            "internal_targeting_flag",
                            models.ForeignKey(
                                blank=True,
                                null=True,
                                on_delete=django.db.models.deletion.SET_NULL,
                                related_name="surveys_internal_targeting_flag",
                                related_query_name="survey_internal_targeting_flag",
                                to="posthog.featureflag",
                            ),
                        ),
                        (
                            "linked_flag",
                            models.ForeignKey(
                                blank=True,
                                null=True,
                                on_delete=django.db.models.deletion.SET_NULL,
                                related_name="surveys_linked_flag",
                                related_query_name="survey_linked_flag",
                                to="posthog.featureflag",
                            ),
                        ),
                        (
                            "linked_insight",
                            models.ForeignKey(
                                blank=True,
                                null=True,
                                on_delete=django.db.models.deletion.SET_NULL,
                                related_name="surveys_linked_insight",
                                related_query_name="survey_linked_insight",
                                to="posthog.insight",
                            ),
                        ),
                        (
                            "targeting_flag",
                            models.ForeignKey(
                                blank=True,
                                null=True,
                                on_delete=django.db.models.deletion.SET_NULL,
                                related_name="surveys_targeting_flag",
                                related_query_name="survey_targeting_flag",
                                to="posthog.featureflag",
                            ),
                        ),
                        (
                            "team",
                            models.ForeignKey(
                                on_delete=django.db.models.deletion.CASCADE,
                                related_name="surveys",
                                related_query_name="survey",
                                to="posthog.team",
                            ),
                        ),
                    ],
                    options={
                        "db_table": "posthog_survey",
                    },
                ),
                migrations.CreateModel(
                    name="SurveyResponseArchive",
                    fields=[
                        (
                            "id",
                            models.UUIDField(
                                default=posthog.models.utils.uuid7,
                                editable=False,
                                primary_key=True,
                                serialize=False,
                            ),
                        ),
                        (
                            "response_uuid",
                            models.UUIDField(help_text="UUID of the ClickHouse event representing the survey response"),
                        ),
                        ("archived_at", models.DateTimeField(auto_now_add=True)),
                        (
                            "survey",
                            models.ForeignKey(
                                on_delete=django.db.models.deletion.CASCADE,
                                related_name="response_archives",
                                related_query_name="response_archive",
                                to="surveys.survey",
                            ),
                        ),
                        (
                            "team",
                            models.ForeignKey(
                                on_delete=django.db.models.deletion.CASCADE,
                                related_name="survey_response_archives",
                                related_query_name="survey_response_archive",
                                to="posthog.team",
                            ),
                        ),
                    ],
                    options={
                        "db_table": "posthog_surveyresponsearchive",
                        "indexes": [
                            models.Index(fields=["survey", "team"], name="posthog_sur_survey__f78fc7_idx"),
                            models.Index(
                                fields=["team", "response_uuid"],
                                name="posthog_sur_team_id_2c59a2_idx",
                            ),
                        ],
                    },
                ),
                migrations.AddConstraint(
                    model_name="surveyresponsearchive",
                    constraint=models.UniqueConstraint(
                        fields=("team", "response_uuid"),
                        name="unique_archived_response_per_team",
                    ),
                ),
                migrations.AddConstraint(
                    model_name="survey",
                    constraint=models.UniqueConstraint(fields=("team", "name"), name="unique survey name for team"),
                ),
            ],
            database_operations=[],
        ),
        migrations.RunPython(update_content_types, reverse_content_types),
    ]