: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(demo): guard against unapplied migrations (#60894)
Raúl Negrón-Otero15d57631e799
diff --git a/posthog/health.py b/posthog/health.pyindex b17dc1eebb16..d8adebe92dea 100644--- a/posthog/health.py+++ b/posthog/health.py@@ -193,6 +193,18 @@ def is_postgres_connected(db_alias=DEFAULT_DB_ALIAS) -> bool:return True+def get_pending_postgres_migrations() -> list[str]:+ """+ Return the `app_label.name` of every migration the running code knows about+ that has not yet been applied to the default database. Empty list means up to date.++ Does not swallow errors — callers decide how to treat an unreachable database.+ """+ executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])+ plan = executor.migration_plan(executor.loader.graph.leaf_nodes())+ return [f"{migration.app_label}.{migration.name}" for migration, _backwards in plan]++def are_postgres_migrations_uptodate() -> bool:"""Check that all migrations that the running version of the code knows about@@ -201,14 +213,11 @@ def are_postgres_migrations_uptodate() -> bool:Returns `True` if so, `False` otherwise"""try:- executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])- plan = executor.migration_plan(executor.loader.graph.leaf_nodes())+ return not get_pending_postgres_migrations()except Exception:logger.debug("postgres_migrations_check_failure", exc_info=True)return False- return not plan-def is_clickhouse_connected() -> bool:"""diff --git a/posthog/management/commands/generate_demo_data.py b/posthog/management/commands/generate_demo_data.pyindex 1ad509e34983..223c7357b4d7 100644--- a/posthog/management/commands/generate_demo_data.py+++ b/posthog/management/commands/generate_demo_data.py@@ -10,13 +10,15 @@ from urllib.parse import quotefrom django.conf import settingsfrom django.core import exceptions-from django.core.management.base import BaseCommand+from django.core.management.base import BaseCommand, CommandError+from django.db.utils import OperationalErrorfrom posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIESfrom posthog.demo.dashboard_template_seeds import seed_dev_dashboard_templatesfrom posthog.demo.matrix import Matrix, MatrixManagerfrom posthog.demo.products.hedgebox import HedgeboxMatrixfrom posthog.demo.products.spikegpt import SpikeGPTMatrix+from posthog.health import get_pending_postgres_migrationsfrom posthog.management.commands.sync_feature_flags_from_api import sync_feature_flags_from_apifrom posthog.models import Userfrom posthog.models.file_system.user_product_list import UserProductList@@ -64,6 +66,11 @@ class Command(BaseCommand):help="Number of clusters (default: 500)",)parser.add_argument("--dry-run", action="store_true", help="Don't save simulation results")+ parser.add_argument(+ "--skip-migration-check",+ action="store_true",+ help="Skip the pre-flight check for unapplied Postgres migrations",+ )parser.add_argument("--team-id",type=int,@@ -121,6 +128,20 @@ class Command(BaseCommand):def handle(self, *args, **options):timer = monotonic()++ if not options.get("skip_migration_check"):+ try:+ pending = get_pending_postgres_migrations()+ except OperationalError:+ pending = [] # DB unreachable — let the normal flow surface the connection error+ if pending:+ raise CommandError(+ f"{len(pending)} unapplied Postgres migration(s) (e.g. {pending[0]}). "+ "The dev database schema is behind the code, so demo data generation would fail. "+ "Run `python manage.py migrate` (or `hogli migrations:sync`) first, "+ "or pass --skip-migration-check to bypass."+ )+seed = options.get("seed") or secrets.token_hex(16)now = options.get("now") or dt.datetime.now(dt.UTC)existing_team_id = options.get("team_id")